Search in sources :

Example 46 with HttpException

use of org.apache.commons.httpclient.HttpException in project zm-mailbox by Zimbra.

the class SaveDocument method fetchMimePart.

private Doc fetchMimePart(OperationContext octxt, AuthToken authtoken, ItemId itemId, String partId, String name, String ct, String description) throws ServiceException {
    String accountId = itemId.getAccountId();
    Account acct = Provisioning.getInstance().get(AccountBy.id, accountId);
    if (Provisioning.onLocalServer(acct)) {
        Mailbox mbox = MailboxManager.getInstance().getMailboxByAccount(acct);
        Message msg = mbox.getMessageById(octxt, itemId.getId());
        try {
            return new Doc(Mime.getMimePart(msg.getMimeMessage(), partId), name, ct);
        } catch (MessagingException e) {
            throw ServiceException.RESOURCE_UNREACHABLE("can't fetch mime part msgId=" + itemId + ", partId=" + partId, e);
        } catch (IOException e) {
            throw ServiceException.RESOURCE_UNREACHABLE("can't fetch mime part msgId=" + itemId + ", partId=" + partId, e);
        }
    }
    String url = UserServlet.getRestUrl(acct) + "?auth=co&id=" + itemId + "&part=" + partId;
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    GetMethod get = new GetMethod(url);
    authtoken.encode(client, get, false, acct.getAttr(ZAttrProvisioning.A_zimbraMailHost));
    try {
        int statusCode = HttpClientUtil.executeMethod(client, get);
        if (statusCode != HttpStatus.SC_OK) {
            throw ServiceException.RESOURCE_UNREACHABLE("can't fetch remote mime part", null, new InternalArgument(ServiceException.URL, url, Argument.Type.STR));
        }
        Header ctHeader = get.getResponseHeader("Content-Type");
        ContentType contentType = new ContentType(ctHeader.getValue());
        return new Doc(get.getResponseBodyAsStream(), contentType, name, ct, description);
    } catch (HttpException e) {
        throw ServiceException.PROXY_ERROR(e, url);
    } catch (IOException e) {
        throw ServiceException.RESOURCE_UNREACHABLE("can't fetch remote mime part", e, new InternalArgument(ServiceException.URL, url, Argument.Type.STR));
    }
}
Also used : Account(com.zimbra.cs.account.Account) Message(com.zimbra.cs.mailbox.Message) ContentType(com.zimbra.common.mime.ContentType) MessagingException(javax.mail.MessagingException) InternalArgument(com.zimbra.common.service.ServiceException.InternalArgument) IOException(java.io.IOException) Mailbox(com.zimbra.cs.mailbox.Mailbox) Header(org.apache.commons.httpclient.Header) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) HttpException(org.apache.commons.httpclient.HttpException)

Example 47 with HttpException

use of org.apache.commons.httpclient.HttpException in project zm-mailbox by Zimbra.

the class TestWsdlServlet method doWsdlServletRequest.

String doWsdlServletRequest(String wsdlUrl, boolean admin, int expectedCode) throws Exception {
    Server localServer = Provisioning.getInstance().getLocalServer();
    String protoHostPort;
    if (admin)
        protoHostPort = "https://localhost:" + localServer.getIntAttr(Provisioning.A_zimbraAdminPort, 0);
    else
        protoHostPort = "http://localhost:" + localServer.getIntAttr(Provisioning.A_zimbraMailPort, 0);
    String url = protoHostPort + wsdlUrl;
    HttpClient client = new HttpClient();
    HttpMethod method = new GetMethod(url);
    try {
        int respCode = HttpClientUtil.executeMethod(client, method);
        int statusCode = method.getStatusCode();
        String statusLine = method.getStatusLine().toString();
        ZimbraLog.test.debug("respCode=" + respCode);
        ZimbraLog.test.debug("statusCode=" + statusCode);
        ZimbraLog.test.debug("statusLine=" + statusLine);
        assertTrue("Response code", respCode == expectedCode);
        assertTrue("Status code", statusCode == expectedCode);
        Header[] respHeaders = method.getResponseHeaders();
        for (int i = 0; i < respHeaders.length; i++) {
            String header = respHeaders[i].toString();
            ZimbraLog.test.debug("ResponseHeader:" + header);
        }
        String respBody = method.getResponseBodyAsString();
        // ZimbraLog.test.debug("Response Body:" + respBody);
        return respBody;
    } catch (HttpException e) {
        fail("Unexpected HttpException" + e);
        throw e;
    } catch (IOException e) {
        fail("Unexpected IOException" + e);
        throw e;
    } finally {
        method.releaseConnection();
    }
}
Also used : Server(com.zimbra.cs.account.Server) Header(org.apache.commons.httpclient.Header) 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)

Example 48 with HttpException

use of org.apache.commons.httpclient.HttpException in project zm-mailbox by Zimbra.

the class MailboxTestUtil method cleanupIndexStore.

public static void cleanupIndexStore(Mailbox mbox) {
    IndexStore index = mbox.index.getIndexStore();
    if (index instanceof ElasticSearchIndex) {
        String key = mbox.getAccountId();
        String indexUrl = String.format("%s%s/", LC.zimbra_index_elasticsearch_url_base.value(), key);
        HttpMethod method = new DeleteMethod(indexUrl);
        try {
            ElasticSearchConnector connector = new ElasticSearchConnector();
            int statusCode = connector.executeMethod(method);
            if (statusCode == HttpStatus.SC_OK) {
                boolean ok = connector.getBooleanAtJsonPath(new String[] { "ok" }, false);
                boolean acknowledged = connector.getBooleanAtJsonPath(new String[] { "acknowledged" }, false);
                if (!ok || !acknowledged) {
                    ZimbraLog.index.debug("Delete index status ok=%b acknowledged=%b", ok, acknowledged);
                }
            } else {
                String error = connector.getStringAtJsonPath(new String[] { "error" });
                if (error != null && error.startsWith("IndexMissingException")) {
                    ZimbraLog.index.debug("Unable to delete index for key=%s.  Index is missing", key);
                } else {
                    ZimbraLog.index.error("Problem deleting index for key=%s error=%s", key, error);
                }
            }
        } catch (HttpException e) {
            ZimbraLog.index.error("Problem Deleting index with key=" + key, e);
        } catch (IOException e) {
            ZimbraLog.index.error("Problem Deleting index with key=" + key, e);
        }
    }
}
Also used : DeleteMethod(org.apache.commons.httpclient.methods.DeleteMethod) ElasticSearchConnector(com.zimbra.cs.index.elasticsearch.ElasticSearchConnector) HttpException(org.apache.commons.httpclient.HttpException) ElasticSearchIndex(com.zimbra.cs.index.elasticsearch.ElasticSearchIndex) IOException(java.io.IOException) IndexStore(com.zimbra.cs.index.IndexStore) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 49 with HttpException

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

the class RegionsApiUtil method makeAPICall.

/**
     * Makes an api call using region service end_point, api command and params
     * @param region
     * @param command
     * @param params
     * @return True, if api is successful
     */
protected static boolean makeAPICall(Region region, String command, List<NameValuePair> params) {
    try {
        String apiParams = buildParams(command, params);
        String url = buildUrl(apiParams, region);
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod(url);
        if (client.executeMethod(method) == 200) {
            return true;
        } else {
            return false;
        }
    } catch (HttpException e) {
        s_logger.error(e.getMessage());
        return false;
    } catch (IOException e) {
        s_logger.error(e.getMessage());
        return false;
    }
}
Also used : 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)

Example 50 with HttpException

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

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=" + s_account.get();
    s_logger.info("Getting events for the account " + s_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=" + s_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