Search in sources :

Example 16 with HttpException

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

the class StatsImageServlet method doGet.

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    AuthToken authToken = getAdminAuthTokenFromCookie(req, resp);
    if (authToken == null)
        return;
    String imgName = null;
    InputStream is = null;
    boolean imgAvailable = true;
    boolean localServer = false;
    boolean systemWide = false;
    String serverAddr = "";
    String noDefaultImg = req.getParameter("nodef");
    boolean noDefault = false;
    if (noDefaultImg != null && !noDefaultImg.equals("") && noDefaultImg.equals("1")) {
        noDefault = true;
    }
    String reqPath = req.getRequestURI();
    try {
        //check if this is the logger host, otherwise proxy the request to the logger host 
        String serviceHostname = Provisioning.getInstance().getLocalServer().getAttr(Provisioning.A_zimbraServiceHostname);
        String logHost = Provisioning.getInstance().getConfig().getAttr(Provisioning.A_zimbraLogHostname);
        if (!serviceHostname.equalsIgnoreCase(logHost)) {
            StringBuffer url = new StringBuffer("https");
            url.append("://").append(logHost).append(':').append(LC.zimbra_admin_service_port.value());
            url.append(reqPath);
            String queryStr = req.getQueryString();
            if (queryStr != null)
                url.append('?').append(queryStr);
            // create an HTTP client with the same cookies
            HttpState state = new HttpState();
            try {
                state.addCookie(new org.apache.commons.httpclient.Cookie(logHost, ZimbraCookie.COOKIE_ZM_ADMIN_AUTH_TOKEN, authToken.getEncoded(), "/", null, false));
            } catch (AuthTokenException ate) {
                throw ServiceException.PROXY_ERROR(ate, url.toString());
            }
            HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
            client.setState(state);
            GetMethod get = new GetMethod(url.toString());
            try {
                int statusCode = HttpClientUtil.executeMethod(client, get);
                if (statusCode != HttpStatus.SC_OK)
                    throw ServiceException.RESOURCE_UNREACHABLE(get.getStatusText(), null);
                resp.setContentType("image/gif");
                ByteUtil.copy(get.getResponseBodyAsStream(), true, resp.getOutputStream(), false);
                return;
            } catch (HttpException e) {
                throw ServiceException.RESOURCE_UNREACHABLE(get.getStatusText(), e);
            } catch (IOException e) {
                throw ServiceException.RESOURCE_UNREACHABLE(get.getStatusText(), e);
            } finally {
                get.releaseConnection();
            }
        }
    } catch (Exception ex) {
        resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Image not found");
        return;
    }
    try {
        if (reqPath == null || reqPath.length() == 0) {
            resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
            return;
        }
        if (mLog.isDebugEnabled())
            mLog.debug("received request to:(" + reqPath + ")");
        String[] reqParts = reqPath.split("/");
        String reqFilename = reqParts[3];
        imgName = LC.stats_img_folder.value() + File.separator + reqFilename;
        try {
            is = new FileInputStream(imgName);
        } catch (FileNotFoundException ex) {
            //unlikely case - only if the server's files are broken
            if (is != null)
                is.close();
            if (!noDefault) {
                imgName = LC.stats_img_folder.value() + File.separator + IMG_NOT_AVAIL;
                is = new FileInputStream(imgName);
            } else {
                resp.sendError(HttpServletResponse.SC_NOT_FOUND, "Image not found");
                return;
            }
        }
    } catch (Exception ex) {
        if (is != null)
            is.close();
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "FNF image File not found");
        return;
    }
    resp.setContentType("image/gif");
    ByteUtil.copy(is, true, resp.getOutputStream(), false);
}
Also used : HttpState(org.apache.commons.httpclient.HttpState) ServletException(javax.servlet.ServletException) ServiceException(com.zimbra.common.service.ServiceException) AuthTokenException(com.zimbra.cs.account.AuthTokenException) HttpException(org.apache.commons.httpclient.HttpException) AuthTokenException(com.zimbra.cs.account.AuthTokenException) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) AuthToken(com.zimbra.cs.account.AuthToken) HttpException(org.apache.commons.httpclient.HttpException)

Example 17 with HttpException

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

the class FileUploadServlet method fetchRemoteUpload.

private static Upload fetchRemoteUpload(String accountId, String uploadId, AuthToken authtoken) throws ServiceException {
    // check if we have fetched the Upload from the remote server previously
    String localUploadId = null;
    synchronized (mProxiedUploadIds) {
        localUploadId = mProxiedUploadIds.get(uploadId);
    }
    if (localUploadId != null) {
        synchronized (mPending) {
            Upload up = mPending.get(localUploadId);
            if (up != null)
                return up;
        }
    }
    // the first half of the upload id is the server id where it lives
    Server server = Provisioning.getInstance().get(Key.ServerBy.id, getUploadServerId(uploadId));
    String url = AccountUtil.getBaseUri(server);
    if (url == null)
        return null;
    String hostname = server.getServiceHostname();
    url += ContentServlet.SERVLET_PATH + ContentServlet.PREFIX_PROXY + '?' + ContentServlet.PARAM_UPLOAD_ID + '=' + uploadId + '&' + ContentServlet.PARAM_EXPUNGE + "=true";
    // create an HTTP client with auth cookie to fetch the file from the remote ContentServlet
    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    GetMethod get = new GetMethod(url);
    authtoken.encode(client, get, false, hostname);
    try {
        // fetch the remote item
        int statusCode = HttpClientUtil.executeMethod(client, get);
        if (statusCode != HttpStatus.SC_OK)
            return null;
        // metadata is encoded in the response's HTTP headers
        Header ctHeader = get.getResponseHeader("Content-Type");
        String contentType = ctHeader == null ? "text/plain" : ctHeader.getValue();
        Header cdispHeader = get.getResponseHeader("Content-Disposition");
        String filename = cdispHeader == null ? "unknown" : new ContentDisposition(cdispHeader.getValue()).getParameter("filename");
        // store the fetched upload along with original uploadId
        Upload up = saveUpload(get.getResponseBodyAsStream(), filename, contentType, accountId);
        synchronized (mProxiedUploadIds) {
            mProxiedUploadIds.put(uploadId, up.uuid);
        }
        return up;
    } catch (HttpException e) {
        throw ServiceException.PROXY_ERROR(e, url);
    } catch (IOException e) {
        throw ServiceException.RESOURCE_UNREACHABLE("can't fetch remote upload", e, new InternalArgument(ServiceException.URL, url, Argument.Type.STR));
    } finally {
        get.releaseConnection();
    }
}
Also used : Server(com.zimbra.cs.account.Server) Header(org.apache.commons.httpclient.Header) ContentDisposition(com.zimbra.common.mime.ContentDisposition) HttpClient(org.apache.commons.httpclient.HttpClient) InternalArgument(com.zimbra.common.service.ServiceException.InternalArgument) GetMethod(org.apache.commons.httpclient.methods.GetMethod) ServletFileUpload(org.apache.commons.fileupload.servlet.ServletFileUpload) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException)

Example 18 with HttpException

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

the class TestPreAuthServlet method testPreAuthAccountNotActive.

public void testPreAuthAccountNotActive() throws Exception {
    String user = "user1";
    Account acct = TestUtil.getAccount(user);
    Provisioning prov = Provisioning.getInstance();
    Map<String, Object> attrs = new HashMap<String, Object>();
    attrs.put(Provisioning.A_zimbraAccountStatus, "maintenance");
    prov.modifyAttrs(acct, attrs);
    System.out.println("Before the test:");
    System.out.println(Provisioning.A_zimbraAccountStatus + ": " + acct.getAttr(Provisioning.A_zimbraAccountStatus));
    System.out.println();
    String preAuthKey = setUpDomain();
    String preAuthUrl = genPreAuthUrl(preAuthKey, user, false, false);
    System.out.println("preAuthKey=" + preAuthKey);
    System.out.println("preAuth=" + preAuthUrl);
    Server localServer = Provisioning.getInstance().getLocalServer();
    String protoHostPort = "http://localhost:" + localServer.getIntAttr(Provisioning.A_zimbraMailPort, 0);
    String url = protoHostPort + preAuthUrl;
    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();
        System.out.println("respCode=" + respCode);
        System.out.println("statusCode=" + statusCode);
        System.out.println("statusLine=" + statusLine);
        assertEquals(400, statusCode);
    } catch (HttpException e) {
        throw e;
    } catch (IOException e) {
        throw e;
    } finally {
        method.releaseConnection();
    }
    //revert account status back to active
    attrs = new HashMap<String, Object>();
    attrs.put(Provisioning.A_zimbraAccountStatus, "active");
    prov.modifyAttrs(acct, attrs);
    System.out.println("After the test:");
    System.out.println(Provisioning.A_zimbraAccountStatus + ": " + acct.getAttr(Provisioning.A_zimbraAccountStatus));
    System.out.println();
}
Also used : Account(com.zimbra.cs.account.Account) Server(com.zimbra.cs.account.Server) HashMap(java.util.HashMap) IOException(java.io.IOException) Provisioning(com.zimbra.cs.account.Provisioning) HttpClient(org.apache.commons.httpclient.HttpClient) GetMethod(org.apache.commons.httpclient.methods.GetMethod) HttpException(org.apache.commons.httpclient.HttpException) HttpMethod(org.apache.commons.httpclient.HttpMethod)

Example 19 with HttpException

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

the class ElasticSearchIndex method getDocCount.

public int getDocCount() {
    refreshIndexIfNecessary();
    String url = String.format("%s%s/docs/", indexUrl, "_stats");
    GetMethod method = new GetMethod(ElasticSearchConnector.actualUrl(url));
    try {
        ElasticSearchConnector connector = new ElasticSearchConnector();
        int statusCode = connector.executeMethod(method);
        if (statusCode == HttpStatus.SC_OK) {
            int cnt = connector.getIntAtJsonPath(new String[] { "_all", "total", "docs", "count" }, 0);
            return cnt;
        }
    } catch (HttpException e) {
        ZimbraLog.index.error("Problem getting stats for index %s", url, e);
    } catch (IOException e) {
        ZimbraLog.index.error("Problem getting stats for index %s", url, e);
    }
    return 0;
}
Also used : GetMethod(org.apache.commons.httpclient.methods.GetMethod) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException)

Example 20 with HttpException

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

the class ElasticSearchIndex method initializeIndex.

private void initializeIndex() {
    if (haveMappingInfo) {
        return;
    }
    if (!refreshIndexIfNecessary()) {
        try {
            ElasticSearchConnector connector = new ElasticSearchConnector();
            JSONObject mappingInfo = createMappingInfo();
            PutMethod putMethod = new PutMethod(ElasticSearchConnector.actualUrl(indexUrl));
            putMethod.setRequestEntity(new StringRequestEntity(mappingInfo.toString(), MimeConstants.CT_APPLICATION_JSON, MimeConstants.P_CHARSET_UTF8));
            int statusCode = connector.executeMethod(putMethod);
            if (statusCode == HttpStatus.SC_OK) {
                haveMappingInfo = true;
                // Sometimes searches don't seem to honor mapping info.  Try to force it
                refreshIndexIfNecessary();
            } else {
                ZimbraLog.index.error("Problem Setting mapping information for index with key=%s httpstatus=%d", key, statusCode);
            }
        } catch (HttpException e) {
            ZimbraLog.index.error("Problem Getting mapping information for index with key=" + key, e);
        } catch (IOException e) {
            ZimbraLog.index.error("Problem Getting mapping information for index with key=" + key, e);
        } catch (JSONException e) {
            ZimbraLog.index.error("Problem Setting mapping information for index with key=" + key, e);
        }
    }
}
Also used : StringRequestEntity(org.apache.commons.httpclient.methods.StringRequestEntity) JSONObject(org.json.JSONObject) PutMethod(org.apache.commons.httpclient.methods.PutMethod) JSONException(org.json.JSONException) HttpException(org.apache.commons.httpclient.HttpException) IOException(java.io.IOException)

Aggregations

HttpException (org.apache.commons.httpclient.HttpException)61 IOException (java.io.IOException)55 HttpClient (org.apache.commons.httpclient.HttpClient)34 GetMethod (org.apache.commons.httpclient.methods.GetMethod)31 HttpMethod (org.apache.commons.httpclient.HttpMethod)22 InputStream (java.io.InputStream)15 Header (org.apache.commons.httpclient.Header)12 PostMethod (org.apache.commons.httpclient.methods.PostMethod)12 DefaultHttpMethodRetryHandler (org.apache.commons.httpclient.DefaultHttpMethodRetryHandler)9 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