Search in sources :

Example 31 with HttpException

use of org.apache.commons.httpclient.HttpException in project cloudstack by apache.

the class RegionsApiUtil method makeDomainAPICall.

/**
     * Makes an api call using region service end_point, api command and params
     * Returns Domain object on success
     * @param region
     * @param command
     * @param params
     * @return
     */
protected static RegionDomain makeDomainAPICall(Region region, String command, List<NameValuePair> params) {
    try {
        String url = buildUrl(buildParams(command, params), region);
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(url);
        if (client.executeMethod(method) == 200) {
            InputStream is = method.getResponseBodyAsStream();
            XStream xstream = new XStream(new DomDriver());
            //Translate response to Domain object
            xstream.alias("domain", RegionDomain.class);
            xstream.aliasField("id", RegionDomain.class, "uuid");
            xstream.aliasField("parentdomainid", RegionDomain.class, "parentUuid");
            xstream.aliasField("networkdomain", DomainVO.class, "networkDomain");
            try (ObjectInputStream in = xstream.createObjectInputStream(is)) {
                return (RegionDomain) in.readObject();
            } catch (IOException e) {
                s_logger.error(e.getMessage());
                return null;
            }
        } else {
            return null;
        }
    } catch (HttpException e) {
        s_logger.error(e.getMessage());
        return null;
    } catch (IOException e) {
        s_logger.error(e.getMessage());
        return null;
    } catch (ClassNotFoundException e) {
        s_logger.error(e.getMessage());
        return null;
    }
}
Also used : DomDriver(com.thoughtworks.xstream.io.xml.DomDriver) ObjectInputStream(java.io.ObjectInputStream) InputStream(java.io.InputStream) XStream(com.thoughtworks.xstream.XStream) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException) HttpMethod(org.apache.commons.httpclient.HttpMethod) ObjectInputStream(java.io.ObjectInputStream)

Example 32 with HttpException

use of org.apache.commons.httpclient.HttpException in project cloudstack by apache.

the class RegionsApiUtil method makeUserAccountAPICall.

/**
     * Makes an api call using region service end_point, api command and params
     * Returns UserAccount object on success
     * @param region
     * @param command
     * @param params
     * @return
     */
protected static UserAccount makeUserAccountAPICall(Region region, String command, List<NameValuePair> params) {
    try {
        String url = buildUrl(buildParams(command, params), region);
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(url);
        if (client.executeMethod(method) == 200) {
            InputStream is = method.getResponseBodyAsStream();
            XStream xstream = new XStream(new DomDriver());
            xstream.alias("useraccount", UserAccountVO.class);
            xstream.aliasField("id", UserAccountVO.class, "uuid");
            try (ObjectInputStream in = xstream.createObjectInputStream(is)) {
                return (UserAccountVO) in.readObject();
            } catch (IOException e) {
                s_logger.error(e.getMessage());
                return null;
            }
        } else {
            return null;
        }
    } catch (HttpException e) {
        s_logger.error(e.getMessage());
        return null;
    } catch (IOException e) {
        s_logger.error(e.getMessage());
        return null;
    } catch (ClassNotFoundException e) {
        s_logger.error(e.getMessage());
        return null;
    }
}
Also used : DomDriver(com.thoughtworks.xstream.io.xml.DomDriver) UserAccountVO(com.cloud.user.UserAccountVO) ObjectInputStream(java.io.ObjectInputStream) InputStream(java.io.InputStream) XStream(com.thoughtworks.xstream.XStream) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException) HttpMethod(org.apache.commons.httpclient.HttpMethod) ObjectInputStream(java.io.ObjectInputStream)

Example 33 with HttpException

use of org.apache.commons.httpclient.HttpException in project cloudstack by apache.

the class RegionsApiUtil method makeAccountAPICall.

/**
     * Makes an api call using region service end_point, api command and params
     * Returns Account object on success
     * @param region
     * @param command
     * @param params
     * @return
     */
protected static RegionAccount makeAccountAPICall(Region region, String command, List<NameValuePair> params) {
    try {
        String url = buildUrl(buildParams(command, params), region);
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(url);
        if (client.executeMethod(method) == 200) {
            InputStream is = method.getResponseBodyAsStream();
            //Translate response to Account object
            XStream xstream = new XStream(new DomDriver());
            xstream.alias("account", RegionAccount.class);
            xstream.alias("user", RegionUser.class);
            xstream.aliasField("id", RegionAccount.class, "uuid");
            xstream.aliasField("name", RegionAccount.class, "accountName");
            xstream.aliasField("accounttype", RegionAccount.class, "type");
            xstream.aliasField("domainid", RegionAccount.class, "domainUuid");
            xstream.aliasField("networkdomain", RegionAccount.class, "networkDomain");
            xstream.aliasField("id", RegionUser.class, "uuid");
            xstream.aliasField("accountId", RegionUser.class, "accountUuid");
            try (ObjectInputStream in = xstream.createObjectInputStream(is)) {
                return (RegionAccount) in.readObject();
            } catch (IOException e) {
                s_logger.error(e.getMessage());
                return null;
            }
        } else {
            return null;
        }
    } catch (HttpException e) {
        s_logger.error(e.getMessage());
        return null;
    } catch (IOException e) {
        s_logger.error(e.getMessage());
        return null;
    } catch (ClassNotFoundException e) {
        s_logger.error(e.getMessage());
        return null;
    }
}
Also used : DomDriver(com.thoughtworks.xstream.io.xml.DomDriver) ObjectInputStream(java.io.ObjectInputStream) InputStream(java.io.InputStream) XStream(com.thoughtworks.xstream.XStream) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException) HttpMethod(org.apache.commons.httpclient.HttpMethod) ObjectInputStream(java.io.ObjectInputStream)

Example 34 with HttpException

use of org.apache.commons.httpclient.HttpException in project openhab1-addons by openhab.

the class Telegram method sendTelegram.

@ActionDoc(text = "Sends a Telegram via Telegram REST API - direct message")
public static boolean sendTelegram(@ParamDoc(name = "group") String group, @ParamDoc(name = "message") String message) {
    if (groupTokens.get(group) == null) {
        logger.error("Bot '{}' not defined, action skipped", group);
        return false;
    }
    String url = String.format(TELEGRAM_URL, groupTokens.get(group).getToken());
    HttpClient client = new HttpClient();
    PostMethod postMethod = new PostMethod(url);
    postMethod.getParams().setContentCharset("UTF-8");
    postMethod.getParams().setSoTimeout(HTTP_TIMEOUT);
    postMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
    NameValuePair[] data = { new NameValuePair("chat_id", groupTokens.get(group).getChatId()), new NameValuePair("text", message) };
    postMethod.setRequestBody(data);
    try {
        int statusCode = client.executeMethod(postMethod);
        if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) {
            return true;
        }
        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("Method failed: {}", postMethod.getStatusLine());
            return false;
        }
        InputStream tmpResponseStream = postMethod.getResponseBodyAsStream();
        Header encodingHeader = postMethod.getResponseHeader("Content-Encoding");
        if (encodingHeader != null) {
            for (HeaderElement ehElem : encodingHeader.getElements()) {
                if (ehElem.toString().matches(".*gzip.*")) {
                    tmpResponseStream = new GZIPInputStream(tmpResponseStream);
                    logger.debug("GZipped InputStream from {}", url);
                } else if (ehElem.toString().matches(".*deflate.*")) {
                    tmpResponseStream = new InflaterInputStream(tmpResponseStream);
                    logger.debug("Deflated InputStream from {}", url);
                }
            }
        }
        String responseBody = IOUtils.toString(tmpResponseStream);
        if (!responseBody.isEmpty()) {
            logger.debug(responseBody);
        }
    } catch (HttpException e) {
        logger.error("Fatal protocol violation: {}", e.toString());
        return false;
    } catch (IOException e) {
        logger.error("Fatal transport error: {}", e.toString());
        return false;
    } finally {
        postMethod.releaseConnection();
    }
    return true;
}
Also used : NameValuePair(org.apache.commons.httpclient.NameValuePair) PostMethod(org.apache.commons.httpclient.methods.PostMethod) GZIPInputStream(java.util.zip.GZIPInputStream) InflaterInputStream(java.util.zip.InflaterInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) ImageInputStream(javax.imageio.stream.ImageInputStream) InputStream(java.io.InputStream) HeaderElement(org.apache.commons.httpclient.HeaderElement) InflaterInputStream(java.util.zip.InflaterInputStream) DefaultHttpMethodRetryHandler(org.apache.commons.httpclient.DefaultHttpMethodRetryHandler) IOException(java.io.IOException) GZIPInputStream(java.util.zip.GZIPInputStream) Header(org.apache.commons.httpclient.Header) HttpClient(org.apache.commons.httpclient.HttpClient) HttpException(org.apache.commons.httpclient.HttpException) ActionDoc(org.openhab.core.scriptengine.action.ActionDoc)

Example 35 with HttpException

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

the class TestClientWithAPI method executeEventsAndBilling.

private static int executeEventsAndBilling(String server, String developerServer) throws HttpException, IOException {
    // test steps:
    // - get all the events in the system for all users in the system
    // - generate all the usage records in the system
    // - get all the usage records in the system
    // -----------------------------
    // GET EVENTS
    // -----------------------------
    String url = server + "?command=listEvents&page=1&pagesize=100&&account=" + _account.get();
    s_logger.info("Getting events for the account " + _account.get());
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    int responseCode = client.executeMethod(method);
    s_logger.info("get events response code: " + responseCode);
    if (responseCode == 200) {
        InputStream is = method.getResponseBodyAsStream();
        Map<String, List<String>> eventDescriptions = getMultipleValuesFromXML(is, new String[] { "description" });
        List<String> descriptionText = eventDescriptions.get("description");
        if (descriptionText == null) {
            s_logger.info("no events retrieved...");
        } else {
            for (String text : descriptionText) {
                s_logger.info("event: " + text);
            }
        }
    } else {
        s_logger.error("list events failed with error code: " + responseCode + ". Following URL was sent: " + url);
        return responseCode;
    }
    // -------------------------------------------------------------------------------------
    // GENERATE USAGE RECORDS (note: typically this is done infrequently)
    // -------------------------------------------------------------------------------------
    DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
    Date currentDate = new Date();
    String endDate = dateFormat.format(currentDate);
    s_logger.info("Generating usage records from September 1st till " + endDate);
    // generate
    url = server + "?command=generateUsageRecords&startdate=2009-09-01&enddate=" + endDate;
    // all usage record till today
    client = new HttpClient();
    method = new GetMethod(url);
    responseCode = client.executeMethod(method);
    s_logger.info("generate usage records response code: " + responseCode);
    if (responseCode == 200) {
        InputStream is = method.getResponseBodyAsStream();
        Map<String, String> successStr = getSingleValueFromXML(is, new String[] { "success" });
        s_logger.info("successfully generated usage records? " + successStr.get("success"));
    } else {
        s_logger.error("generate usage records failed with error code: " + responseCode + ". Following URL was sent: " + url);
        return responseCode;
    }
    // Sleeping for a 2 minutes before getting a usage records from the database
    try {
        Thread.sleep(120000);
    } catch (Exception ex) {
        s_logger.error(ex);
    }
    // --------------------------------
    // GET USAGE RECORDS
    // --------------------------------
    url = server + "?command=listUsageRecords&startdate=2009-09-01&enddate=" + endDate + "&account=" + _account.get() + "&domaindid=1";
    s_logger.info("Getting all usage records with request: " + url);
    client = new HttpClient();
    method = new GetMethod(url);
    responseCode = client.executeMethod(method);
    s_logger.info("get usage records response code: " + responseCode);
    if (responseCode == 200) {
        InputStream is = method.getResponseBodyAsStream();
        Map<String, List<String>> usageRecValues = getMultipleValuesFromXML(is, new String[] { "description", "usage" });
        if ((usageRecValues.containsKey("description") == true) && (usageRecValues.containsKey("usage") == true)) {
            List<String> descriptions = usageRecValues.get("description");
            List<String> usages = usageRecValues.get("usage");
            for (int i = 0; i < descriptions.size(); i++) {
                String desc = descriptions.get(i);
                String usage = "";
                if (usages != null) {
                    if (i < usages.size()) {
                        usage = ", usage: " + usages.get(i);
                    }
                }
                s_logger.info("desc: " + desc + usage);
            }
        }
    } else {
        s_logger.error("list usage records failed with error code: " + responseCode + ". Following URL was sent: " + url);
        return responseCode;
    }
    return responseCode;
}
Also used : InputStream(java.io.InputStream) Date(java.util.Date) CloudRuntimeException(com.cloud.utils.exception.CloudRuntimeException) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) HttpClient(org.apache.commons.httpclient.HttpClient) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) GetMethod(org.apache.commons.httpclient.methods.GetMethod) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) List(java.util.List) SimpleDateFormat(java.text.SimpleDateFormat) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Aggregations

HttpException (org.apache.commons.httpclient.HttpException)62 IOException (java.io.IOException)55 HttpClient (org.apache.commons.httpclient.HttpClient)35 GetMethod (org.apache.commons.httpclient.methods.GetMethod)32 HttpMethod (org.apache.commons.httpclient.HttpMethod)22 InputStream (java.io.InputStream)16 Header (org.apache.commons.httpclient.Header)12 PostMethod (org.apache.commons.httpclient.methods.PostMethod)12 DefaultHttpMethodRetryHandler (org.apache.commons.httpclient.DefaultHttpMethodRetryHandler)10 UsernamePasswordCredentials (org.apache.commons.httpclient.UsernamePasswordCredentials)8 DeleteMethod (org.apache.commons.httpclient.methods.DeleteMethod)6 Test (org.junit.Test)5 ServiceException (com.zimbra.common.service.ServiceException)4 Server (com.zimbra.cs.account.Server)4 ByteArrayInputStream (java.io.ByteArrayInputStream)4 Date (java.util.Date)4 HashMap (java.util.HashMap)4 MultipartRequestEntity (org.apache.commons.httpclient.methods.multipart.MultipartRequestEntity)4 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)4 XStream (com.thoughtworks.xstream.XStream)3