Search in sources :

Example 31 with HttpMethod

use of org.apache.commons.httpclient.HttpMethod in project CloudStack-archive by CloudStack-extras.

the class UserCloudAPIExecutor method main.

public static void main(String[] args) {
    // Host
    String host = null;
    // Fully qualified URL with http(s)://host:port
    String apiUrl = null;
    // ApiKey and secretKey as given by your CloudStack vendor
    String apiKey = null;
    String secretKey = null;
    try {
        Properties prop = new Properties();
        prop.load(new FileInputStream("usercloud.properties"));
        // host
        host = prop.getProperty("host");
        if (host == null) {
            System.out.println("Please specify a valid host in the format of http(s)://:/client/api in your usercloud.properties file.");
        }
        // apiUrl
        apiUrl = prop.getProperty("apiUrl");
        if (apiUrl == null) {
            System.out.println("Please specify a valid API URL in the format of command=&param1=&param2=... in your usercloud.properties file.");
        }
        // apiKey
        apiKey = prop.getProperty("apiKey");
        if (apiKey == null) {
            System.out.println("Please specify your API Key as provided by your CloudStack vendor in your usercloud.properties file.");
        }
        // secretKey
        secretKey = prop.getProperty("secretKey");
        if (secretKey == null) {
            System.out.println("Please specify your secret Key as provided by your CloudStack vendor in your usercloud.properties file.");
        }
        if (apiUrl == null || apiKey == null || secretKey == null) {
            return;
        }
        System.out.println("Constructing API call to host = '" + host + "' with API command = '" + apiUrl + "' using apiKey = '" + apiKey + "' and secretKey = '" + secretKey + "'");
        // Step 1: Make sure your APIKey is URL encoded
        String encodedApiKey = URLEncoder.encode(apiKey, "UTF-8");
        // Step 2: URL encode each parameter value, then sort the parameters and apiKey in
        // alphabetical order, and then toLowerCase all the parameters, parameter values and apiKey.
        // Please note that if any parameters with a '&' as a value will cause this test client to fail since we are using
        // '&' to delimit
        // the string
        List<String> sortedParams = new ArrayList<String>();
        sortedParams.add("apikey=" + encodedApiKey.toLowerCase());
        StringTokenizer st = new StringTokenizer(apiUrl, "&");
        String url = null;
        boolean first = true;
        while (st.hasMoreTokens()) {
            String paramValue = st.nextToken();
            String param = paramValue.substring(0, paramValue.indexOf("="));
            String value = URLEncoder.encode(paramValue.substring(paramValue.indexOf("=") + 1, paramValue.length()), "UTF-8");
            if (first) {
                url = param + "=" + value;
                first = false;
            } else {
                url = url + "&" + param + "=" + value;
            }
            sortedParams.add(param.toLowerCase() + "=" + value.toLowerCase());
        }
        Collections.sort(sortedParams);
        System.out.println("Sorted Parameters: " + sortedParams);
        // Step 3: Construct the sorted URL and sign and URL encode the sorted URL with your secret key
        String sortedUrl = null;
        first = true;
        for (String param : sortedParams) {
            if (first) {
                sortedUrl = param;
                first = false;
            } else {
                sortedUrl = sortedUrl + "&" + param;
            }
        }
        System.out.println("sorted URL : " + sortedUrl);
        String encodedSignature = signRequest(sortedUrl, secretKey);
        // Step 4: Construct the final URL we want to send to the CloudStack Management Server
        // Final result should look like:
        // http(s)://://client/api?&apiKey=&signature=
        String finalUrl = host + "?" + url + "&apiKey=" + apiKey + "&signature=" + encodedSignature;
        System.out.println("final URL : " + finalUrl);
        // Step 5: Perform a HTTP GET on this URL to execute the command
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(finalUrl);
        int responseCode = client.executeMethod(method);
        if (responseCode == 200) {
            // SUCCESS!
            System.out.println("Successfully executed command");
        } else {
            // FAILED!
            System.out.println("Unable to execute command with response code: " + responseCode);
        }
    } catch (Throwable t) {
        System.out.println(t);
    }
}
Also used : StringTokenizer(java.util.StringTokenizer) HttpClient(org.apache.commons.httpclient.HttpClient) ArrayList(java.util.ArrayList) GetMethod(org.apache.commons.httpclient.methods.GetMethod) Properties(java.util.Properties) FileInputStream(java.io.FileInputStream) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 32 with HttpMethod

use of org.apache.commons.httpclient.HttpMethod in project intellij-community by JetBrains.

the class YouTrackRepository method getAvailableTaskStates.

@NotNull
@Override
public Set<CustomTaskState> getAvailableTaskStates(@NotNull Task task) throws Exception {
    final HttpMethod method = doREST("/rest/issue/" + task.getId() + "/execute/intellisense?command=" + encodeUrl("state: "), false);
    try {
        final InputStream stream = method.getResponseBodyAsStream();
        final Element element = new SAXBuilder(false).build(stream).getRootElement();
        return ContainerUtil.map2Set(element.getChild("suggest").getChildren("item"), element1 -> {
            final String stateName = element1.getChildText("option");
            return new CustomTaskState(stateName, stateName);
        });
    } finally {
        method.releaseConnection();
    }
}
Also used : SAXBuilder(org.jdom.input.SAXBuilder) InputStream(java.io.InputStream) Element(org.jdom.Element) HttpMethod(org.apache.commons.httpclient.HttpMethod) NotNull(org.jetbrains.annotations.NotNull)

Example 33 with HttpMethod

use of org.apache.commons.httpclient.HttpMethod in project intellij-community by JetBrains.

the class YouTrackRepository method checkVersion.

private void checkVersion() throws Exception {
    HttpMethod method = doREST("/rest/workflow/version", false);
    try {
        InputStream stream = method.getResponseBodyAsStream();
        Element element = new SAXBuilder(false).build(stream).getRootElement();
        final boolean timeTrackingAvailable = element.getName().equals("version") && VersionComparatorUtil.compare(element.getChildText("version"), "4.1") >= 0;
        if (!timeTrackingAvailable) {
            throw new Exception("Time tracking is not supported in this version of Youtrack");
        }
    } finally {
        method.releaseConnection();
    }
}
Also used : SAXBuilder(org.jdom.input.SAXBuilder) InputStream(java.io.InputStream) Element(org.jdom.Element) HttpMethod(org.apache.commons.httpclient.HttpMethod) JDOMException(org.jdom.JDOMException)

Example 34 with HttpMethod

use of org.apache.commons.httpclient.HttpMethod in project intellij-community by JetBrains.

the class YouTrackRepository method doREST.

HttpMethod doREST(String request, boolean post) throws Exception {
    HttpClient client = login(new PostMethod(getUrl() + "/rest/user/login"));
    String uri = getUrl() + request;
    HttpMethod method = post ? new PostMethod(uri) : new GetMethod(uri);
    configureHttpMethod(method);
    int status = client.executeMethod(method);
    if (status == 400) {
        InputStream string = method.getResponseBodyAsStream();
        Element element = new SAXBuilder(false).build(string).getRootElement();
        TaskUtil.prettyFormatXmlToLog(LOG, element);
        if ("error".equals(element.getName())) {
            throw new Exception(element.getText());
        }
    }
    return method;
}
Also used : SAXBuilder(org.jdom.input.SAXBuilder) PostMethod(org.apache.commons.httpclient.methods.PostMethod) InputStream(java.io.InputStream) HttpClient(org.apache.commons.httpclient.HttpClient) Element(org.jdom.Element) GetMethod(org.apache.commons.httpclient.methods.GetMethod) HttpMethod(org.apache.commons.httpclient.HttpMethod) JDOMException(org.jdom.JDOMException)

Example 35 with HttpMethod

use of org.apache.commons.httpclient.HttpMethod in project intellij-community by JetBrains.

the class PivotalTrackerRepository method setTaskState.

@Override
public void setTaskState(@NotNull Task task, @NotNull TaskState state) throws Exception {
    final String realId = getRealId(task.getId());
    if (realId == null)
        return;
    final String stateName;
    switch(state) {
        case IN_PROGRESS:
            stateName = "started";
            break;
        case RESOLVED:
            stateName = "finished";
            break;
        // may add some others in future
        default:
            return;
    }
    String url = API_URL + "/projects/" + myProjectId + "/stories/" + realId;
    url += "?" + encodeUrl("story[current_state]") + "=" + encodeUrl(stateName);
    LOG.info("Updating issue state by id: " + url);
    final HttpMethod method = doREST(url, HTTPMethod.PUT);
    final InputStream stream = method.getResponseBodyAsStream();
    final Element element = new SAXBuilder(false).build(stream).getRootElement();
    if (!element.getName().equals("story")) {
        if (element.getName().equals("errors")) {
            throw new Exception(extractErrorMessage(element));
        } else {
            // unknown error, probably our fault
            LOG.warn("Error setting state for: " + url + ", HTTP status code: " + method.getStatusCode());
            throw new Exception(String.format("Cannot set state '%s' for issue.", stateName));
        }
    }
}
Also used : SAXBuilder(org.jdom.input.SAXBuilder) InputStream(java.io.InputStream) Element(org.jdom.Element) HttpMethod(org.apache.commons.httpclient.HttpMethod) ParseException(java.text.ParseException)

Aggregations

HttpMethod (org.apache.commons.httpclient.HttpMethod)151 HttpClient (org.apache.commons.httpclient.HttpClient)99 GetMethod (org.apache.commons.httpclient.methods.GetMethod)95 InputStream (java.io.InputStream)61 IOException (java.io.IOException)43 ArrayList (java.util.ArrayList)30 HttpException (org.apache.commons.httpclient.HttpException)28 Map (java.util.Map)24 Test (org.junit.Test)23 Element (org.w3c.dom.Element)22 HashMap (java.util.HashMap)20 PostMethod (org.apache.commons.httpclient.methods.PostMethod)19 Header (org.apache.commons.httpclient.Header)17 List (java.util.List)14 NameValuePair (org.apache.commons.httpclient.NameValuePair)13 NodeList (org.w3c.dom.NodeList)12 FileInputStream (java.io.FileInputStream)10 HttpTest (org.apache.sling.commons.testing.integration.HttpTest)10 SAXBuilder (org.jdom.input.SAXBuilder)10 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)9