Example usage for org.apache.commons.httpclient HttpStatus getStatusText

List of usage examples for org.apache.commons.httpclient HttpStatus getStatusText

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpStatus getStatusText.

Prototype

public static String getStatusText(int statusCode) 

Source Link

Document

Get the reason phrase for a particular status code.

Usage

From source file:org.craftercms.cstudio.impl.service.deployment.PublishingManagerImpl.java

@Override
public void deployItemsToTarget(String site, List<PublishingSyncItem> filteredItems,
        PublishingTargetItem target) throws ContentNotFoundForPublishingException, UploadFailedException {
    LOGGER.debug("Start deploying items for site \"{0}\", target \"{1}\", number of items \"{2}\"", site,
            target.getName(), filteredItems.size());
    URL requestUrl = null;/*from ww w .ja  v  a2  s .com*/
    try {
        requestUrl = new URL(target.getServerUrl());
    } catch (MalformedURLException e) {
        LOGGER.error("Invalid server URL for target {0}", target.getName());
        throw new UploadFailedException(site, target.getName(), target.getServerUrl(), e);
    }

    ByteArrayPartSource baps = null;
    PartSource metadataPart = null;
    StringPart stringPart = null;
    FilePart filePart = null;

    int numberOfBuckets = filteredItems.size() / target.getBucketSize() + 1;
    Iterator<PublishingSyncItem> iter = filteredItems.iterator();
    LOGGER.debug("Divide all deployment items into {0} bucket(s) for  target {1}", numberOfBuckets,
            target.getName());
    List<DeploymentEventItem> eventItems = new ArrayList<DeploymentEventItem>();
    for (int bucketIndex = 0; bucketIndex < numberOfBuckets; bucketIndex++) {
        int cntFiles = 0;
        StringBuilder sbDeletedFiles = new StringBuilder();
        List<Part> formParts = new ArrayList<Part>();

        formParts.add(new StringPart(PASSWORD_REQUEST_PARAMETER, target.getPassword()));
        formParts.add(new StringPart(TARGET_REQUEST_PARAMETER, target.getTarget()));
        String siteId = target.getSiteId();
        if (StringUtils.isEmpty(siteId)) {
            siteId = site;
        }
        formParts.add(new StringPart(SITE_REQUEST_PARAMETER, siteId));

        LOGGER.debug("Preparing deployment items (bucket {0}) for target {1}", bucketIndex + 1,
                target.getName());

        int loopSize = (filteredItems.size() - (bucketIndex * target.getBucketSize()) > target.getBucketSize())
                ? target.getBucketSize()
                : filteredItems.size() - bucketIndex * target.getBucketSize();
        for (int j = 0; j < loopSize; j++) {
            if (iter.hasNext()) {

                PublishingSyncItem item = iter.next();
                LOGGER.debug("Parsing \"{0}\" , site \"{1}\"; for publishing on target \"{2}\"", item.getPath(),
                        item.getSite(), target.getName());
                DeploymentEventItem eventItem = new DeploymentEventItem();
                eventItem.setSite(item.getSite());
                eventItem.setPath(item.getPath());
                eventItem.setUser(item.getUser());
                eventItem.setDateTime(new Date());

                if (item.getAction() == PublishingSyncItem.Action.DELETE) {
                    eventItem.setState(DeploymentEventItem.STATE_DELETED);
                    if (sbDeletedFiles.length() > 0) {
                        sbDeletedFiles.append(FILES_SEPARATOR).append(item.getPath());
                    } else {
                        sbDeletedFiles.append(item.getPath());
                    }
                    if (item.getPath().endsWith("/" + _indexFile)) {
                        sbDeletedFiles.append(FILES_SEPARATOR)
                                .append(item.getPath().replace("/" + _indexFile, ""));
                    }
                } else {

                    if (item.getAction() == PublishingSyncItem.Action.NEW) {
                        eventItem.setState(DeploymentEventItem.STATE_NEW);
                    } else if (item.getAction() == PublishingSyncItem.Action.MOVE) {
                        eventItem.setState(DeploymentEventItem.STATE_MOVED);
                    } else {
                        eventItem.setState(DeploymentEventItem.STATE_UPDATED);
                    }

                    LOGGER.debug("Get content for \"{0}\" , site \"{1}\"", item.getPath(), item.getSite());
                    InputStream input = _contentRepository.getContent(site, null, LIVE_ENVIRONMENT,
                            item.getPath());
                    try {
                        if (input == null || input.available() < 0) {
                            if (!_contentRepository.isFolder(site, item.getPath())
                                    && _contentRepository.contentExists(site, item.getPath())) {
                                baps = null;
                                stringPart = null;
                                filePart = null;
                                formParts = null;
                                throw new ContentNotFoundForPublishingException(site, target.getName(),
                                        item.getPath());
                            } else {
                                // Content does not exist - skip deploying file
                                continue;
                            }
                        }
                    } catch (IOException err) {
                        LOGGER.error("Error reading input stream for content at path: " + item.getPath()
                                + " site: " + item.getSite());
                        if (_contentRepository.contentExists(site, item.getPath())) {
                            baps = null;
                            stringPart = null;
                            filePart = null;
                            formParts = null;
                            throw new ContentNotFoundForPublishingException(site, target.getName(),
                                    item.getPath());
                        } else {
                            // Content does not exist - skip deploying file
                            continue;
                        }
                    }
                    String fileName = _contentRepository.getFilename(site, item.getPath());

                    byte[] byteArray = null;

                    try {
                        byteArray = IOUtils.toByteArray(input);
                    } catch (IOException e) {
                        LOGGER.error("Error while converting input stream to byte array", e);
                        baps = null;
                        stringPart = null;
                        filePart = null;
                        formParts = null;
                        if (_contentRepository.contentExists(site, item.getPath())) {
                            throw new ContentNotFoundForPublishingException(site, target.getName(),
                                    item.getPath());
                        } else {
                            // Content does not exist - skip deploying file
                            continue;
                        }
                    } finally {
                        IOUtils.closeQuietly(input);
                        input = null;
                    }
                    baps = new ByteArrayPartSource(fileName, byteArray);

                    LOGGER.debug(
                            "Create http request parameters for \"{0}\" , site \"{1}\"; publishing on target \"{2}\"",
                            item.getPath(), item.getSite(), target.getName());
                    int idx = item.getPath().lastIndexOf("/");
                    String relativePath = item.getPath().substring(0, idx + 1) + fileName;
                    stringPart = new StringPart(CONTENT_LOCATION_REQUEST_PARAMETER + cntFiles, relativePath);
                    formParts.add(stringPart);
                    filePart = new FilePart(CONTENT_FILE_REQUEST_PARAMETER + cntFiles, baps);
                    formParts.add(filePart);
                    if (item.getAction() == PublishingSyncItem.Action.MOVE) {
                        if (item.getOldPath() != null && !item.getOldPath().equalsIgnoreCase(item.getPath())) {
                            LOGGER.debug("Add old path to be deleted for MOVE action (\"{0}\")",
                                    item.getOldPath());
                            eventItem.setOldPath(item.getOldPath());
                            if (sbDeletedFiles.length() > 0) {
                                sbDeletedFiles.append(",").append(item.getOldPath());
                            } else {
                                sbDeletedFiles.append(item.getOldPath());
                            }
                            if (item.getOldPath().endsWith("/" + _indexFile)) {
                                sbDeletedFiles.append(FILES_SEPARATOR)
                                        .append(item.getOldPath().replace("/" + _indexFile, ""));
                            }
                        }
                    }

                    if (target.isSendMetadata()) {
                        LOGGER.debug("Adding meta data for content \"{0}\" site \"{0}\"", item.getPath(),
                                item.getSite());
                        InputStream metadataStream = null;
                        try {
                            metadataStream = _contentRepository.getMetadataStream(site, item.getPath());
                            metadataPart = new ByteArrayPartSource(fileName + ".meta",
                                    IOUtils.toByteArray(metadataStream));
                            formParts.add(
                                    new FilePart(METADATA_FILE_REQUEST_PARAMETER + cntFiles, metadataPart));
                        } catch (IOException e) {
                            LOGGER.error("Error while creating input stream with content metadata", e);
                            baps = null;
                            stringPart = null;
                            filePart = null;
                            formParts = null;
                        } finally {
                            IOUtils.closeQuietly(metadataStream);
                            metadataPart = null;
                        }
                    }
                }
                cntFiles++;
                eventItems.add(eventItem);
            }
        }

        if (sbDeletedFiles.length() > 0) {
            formParts.add(new StringPart(DELETED_FILES_REQUEST_PARAMETER, sbDeletedFiles.toString()));
        }
        LOGGER.debug("Create http request to deploy bucket {0} for target {1}", bucketIndex + 1,
                target.getName());

        PostMethod postMethod = null;
        HttpClient client = null;
        try {

            LOGGER.debug("Create HTTP Post Method");
            postMethod = new PostMethod(requestUrl.toString());
            postMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
            Part[] parts = new Part[formParts.size()];
            for (int i = 0; i < formParts.size(); i++)
                parts[i] = formParts.get(i);
            postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
            client = new HttpClient();

            LOGGER.debug("Execute HTTP POST request \"{0}\"", postMethod.getURI());
            int status = client.executeMethod(postMethod);
            if (status == HttpStatus.SC_OK) {
                LOGGER.info("Successfully deployed bucket number {0} on target {1}", bucketIndex + 1,
                        target.getName());
            } else {
                LOGGER.error(
                        "Deployment failed for bucket number {0} on target {1}. Deployment agent returned status {2}",
                        bucketIndex + 1, target.getName(), HttpStatus.getStatusText(status));
                throw new UploadFailedException(site, target.getName(), target.getServerUrl());
            }
        } catch (HttpException e) {
            LOGGER.error("Publish failed for target {0} due to http protocol exception", target.getName());
            throw new UploadFailedException(site, target.getName(), target.getServerUrl(), e);
        } catch (IOException e) {
            LOGGER.error("Publish failed for target {0} due to I/O (transport) exception", target.getName());
            throw new UploadFailedException(site, target.getName(), target.getServerUrl(), e);
        } finally {
            LOGGER.debug("Release http connection and release resources");
            if (client != null) {
                HttpConnectionManager mgr = client.getHttpConnectionManager();
                if (mgr instanceof SimpleHttpConnectionManager) {
                    ((SimpleHttpConnectionManager) mgr).shutdown();
                }
            }
            if (postMethod != null) {
                postMethod.releaseConnection();
                postMethod = null;
                client = null;
            }
            baps = null;
            stringPart = null;
            filePart = null;
            formParts = null;
        }
    }

    LOGGER.debug("Publishing deployment event for target \"{0}\" with \"{1}\" items.", target.getName(),
            eventItems.size());
    _contentRepository.publishDeployEvent(target.getName(), eventItems);

    LOGGER.info("Deployment successful on target {0}", target.getName());
    LOGGER.debug("Finished deploying items for site \"{0}\", target \"{1}\", number of items \"{2}\"", site,
            target.getName(), filteredItems.size());
}

From source file:org.craftercms.cstudio.share.service.impl.WcmWorkflowServiceImpl.java

private String callRESTService(final String targetURI, final String xmlString) throws Exception {
    String xmlResponseString = "";
    int result = -1;

    //TODO: Use Alfresco Endpoint instead of httpclient

    PostMethod postMethod = null;//from  ww w . j  a v  a 2s  . c o m
    BufferedReader br = null;
    HttpClient httpClient = new HttpClient();

    // PRECONDITIONS
    assert targetURI != null && targetURI.trim().length() > 0 : "path must not be null, empty or blank.";

    // Body
    postMethod = new PostMethod(targetURI);
    postMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);

    // Get the Alfresco Ticket       
    SeamlessAppContext context = SeamlessAppContext.currentApplicationContext();
    String alfTicketCookie = (String) cookieManager.getCookieValue(context.getRequest(),
            this.COOKIE_ALFRESCO_TICKET);

    // Set the Parameter
    //getMethod.setQueryString(new NameValuePair[] {new NameValuePair("formId", formId)});
    postMethod.setQueryString("?xml=" + xmlString + "&" + COOKIE_ALFRESCO_TICKET + "=" + alfTicketCookie);

    try {
        result = httpClient.executeMethod(postMethod);

        if (result == HttpStatus.SC_NOT_IMPLEMENTED) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("The POST method is not implemented by this URI");
                throw new Exception("The POST method is not implemented by this URI");
            }
            // still consume the response body
            xmlResponseString = postMethod.getResponseBodyAsString();
        } else {
            if (result == HttpStatus.SC_OK) {
                br = new BufferedReader(new InputStreamReader(postMethod.getResponseBodyAsStream()));

                String readLine;
                while (((readLine = br.readLine()) != null)) {
                    xmlResponseString = xmlString + readLine;
                }
            } else {
                if (LOGGER.isErrorEnabled()) {
                    LOGGER.error("Push to Alfresco Service Failed: " + HttpStatus.getStatusText(result));
                    throw new Exception("Push to Alfresco Service Failed: " + HttpStatus.getStatusText(result));
                }
            }
        }
    } catch (HttpException he) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Push to Alfresco Service Failed due to HttpException: " + he.getMessage(), he);
            throw he;
        }
    } catch (IOException ie) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("Push to Alfresco Service Failed due to IOException: " + ie.getMessage(), ie);
        }
    } finally {
        postMethod.releaseConnection();
        if (br != null)
            try {
                br.close();
            } catch (Exception fe) {
            }
    }

    return (xmlResponseString);
}

From source file:org.craftercms.studio.impl.v1.deployment.SyncTargetDeployer.java

@Override
public void deployFiles(String site, List<String> paths, List<String> deletedFiles)
        throws ContentNotFoundForPublishingException, UploadFailedException {
    logger.debug("Start deploying items for site \"{0}\", target \"{1}\", number of items \"{2}\"", site,
            endpointConfig.getName(), paths.size());
    URL requestUrl = null;/*  w ww.  j  a v  a  2s . com*/
    try {
        requestUrl = new URL(endpointConfig.getServerUrl());
    } catch (MalformedURLException e) {
        logger.error("Invalid server URL for target {0}", endpointConfig.getName());
        throw new UploadFailedException(site, endpointConfig.getName(), endpointConfig.getServerUrl(), e);
    }

    ByteArrayPartSource baps = null;
    PartSource metadataPart = null;
    StringPart stringPart = null;
    FilePart filePart = null;

    // TODO: implement reactor version of deployment events
    int cntFiles = 0;
    StringBuilder sbDeletedFiles = new StringBuilder();
    List<Part> formParts = new ArrayList<Part>();

    formParts.add(new StringPart(PASSWORD_REQUEST_PARAMETER, endpointConfig.getPassword()));
    formParts.add(new StringPart(TARGET_REQUEST_PARAMETER, endpointConfig.getTarget()));
    String siteId = endpointConfig.getSiteId();
    if (StringUtils.isEmpty(siteId)) {
        siteId = site;
    }
    formParts.add(new StringPart(SITE_REQUEST_PARAMETER, siteId));

    logger.debug("Preparing deployment items for target {0}", endpointConfig.getName());
    for (String path : paths) {
        logger.debug("Parsing \"{0}\" , site \"{1}\"; for publishing on target \"{2}\"", path, site,
                endpointConfig.getName());
        logger.debug("Get content for \"{0}\" , site \"{1}\", environment \"{2}\"", path, site, environment);
        File file = new File(getDestinationPath(site, path, environment));
        InputStream input = null;
        try {
            input = FileUtils.openInputStream(file);
            if (input == null || input.available() < 0) {
                if (file.exists() && !file.isDirectory()) {
                    baps = null;
                    stringPart = null;
                    filePart = null;
                    formParts = null;
                    throw new ContentNotFoundForPublishingException(site, endpointConfig.getName(), path);
                } else {
                    // Content does not exist - skip deploying file
                    continue;
                }
            }
        } catch (IOException err) {
            logger.error("Error reading input stream from envirnoment store for content at path: " + path
                    + " site: " + site + " environment: " + environment);
            if (!file.exists()) {
                logger.error("File expected, but does not exist at path: " + file.getAbsolutePath());
            }
            continue;
        }
        String fileName = file.getName();

        byte[] byteArray = null;

        try {
            byteArray = IOUtils.toByteArray(input);
        } catch (IOException e) {
            logger.error("Error while converting input stream to byte array", e);
            baps = null;
            stringPart = null;
            filePart = null;
            formParts = null;
        } finally {
            IOUtils.closeQuietly(input);
            input = null;
        }
        baps = new ByteArrayPartSource(fileName, byteArray);

        logger.debug("Create http request parameters for \"{0}\" , site \"{1}\"; publishing on target \"{2}\"",
                path, site, endpointConfig.getName());
        int idx = path.lastIndexOf("/");
        String relativePath = path.substring(0, idx + 1) + fileName;
        stringPart = new StringPart(CONTENT_LOCATION_REQUEST_PARAMETER + cntFiles, relativePath);
        formParts.add(stringPart);
        filePart = new FilePart(CONTENT_FILE_REQUEST_PARAMETER + cntFiles, baps);
        formParts.add(filePart);
        /*
        if (item.getAction() == PublishingSyncItem.Action.MOVE) {
        if (item.getOldPath() != null && !item.getOldPath().equalsIgnoreCase(item.getPath())) {
            LOGGER.debug("Add old path to be deleted for MOVE action (\"{0}\")", item.getOldPath());
            eventItem.setOldPath(item.getOldPath());
            if (sbDeletedFiles.length() > 0) {
                sbDeletedFiles.append(",").append(item.getOldPath());
            } else {
                sbDeletedFiles.append(item.getOldPath());
            }
            if (item.getOldPath().endsWith("/" + _indexFile)) {
                sbDeletedFiles.append(FILES_SEPARATOR).append(item.getOldPath().replace("/" + _indexFile, ""));
            }
        }
        }*/
        cntFiles++;

        // TODO: implement metadata transfer
    }

    for (int i = 0; i < deletedFiles.size(); i++) {
        if (i > 0) {
            sbDeletedFiles.append(FILES_SEPARATOR);
        }
        sbDeletedFiles.append(deletedFiles.get(i));
    }

    if (sbDeletedFiles.length() > 0) {
        formParts.add(new StringPart(DELETED_FILES_REQUEST_PARAMETER, sbDeletedFiles.toString()));
    }
    logger.debug("Create http request to deploy content for target {0} ({1})", endpointConfig.getName(),
            endpointConfig.getTarget());
    PostMethod postMethod = null;
    HttpClient client = null;
    try {
        logger.debug("Create HTTP Post Method");
        postMethod = new PostMethod(requestUrl.toString());
        postMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
        Part[] parts = new Part[formParts.size()];
        for (int i = 0; i < formParts.size(); i++)
            parts[i] = formParts.get(i);
        postMethod.setRequestEntity(new MultipartRequestEntity(parts, postMethod.getParams()));
        client = new HttpClient();

        logger.debug("Execute HTTP POST request \"{0}\"", postMethod.getURI());
        int status = client.executeMethod(postMethod);
        if (status == HttpStatus.SC_OK) {
            logger.info("Successfully deployed on target {0}", endpointConfig.getName());
        } else {
            logger.error("Deployment failed for on target {1}. Deployment agent returned status {2}",
                    endpointConfig.getName(), HttpStatus.getStatusText(status));
            throw new UploadFailedException(site, endpointConfig.getName(), endpointConfig.getServerUrl());
        }
    } catch (HttpException e) {
        logger.error("Publish failed for target {0} due to http protocol exception", endpointConfig.getName());
        throw new UploadFailedException(site, endpointConfig.getName(), endpointConfig.getServerUrl(), e);
    } catch (IOException e) {
        logger.error("Publish failed for target {0} due to I/O (transport) exception",
                endpointConfig.getName());
        throw new UploadFailedException(site, endpointConfig.getName(), endpointConfig.getServerUrl(), e);
    } finally {
        logger.debug("Release http connection and release resources");
        if (client != null) {
            HttpConnectionManager mgr = client.getHttpConnectionManager();
            if (mgr instanceof SimpleHttpConnectionManager) {
                ((SimpleHttpConnectionManager) mgr).shutdown();
            }
        }
        if (postMethod != null) {
            postMethod.releaseConnection();
            postMethod = null;
            client = null;
        }
        baps = null;
        stringPart = null;
        filePart = null;
        formParts = null;
    }

    //LOGGER.debug("Publishing deployment event for target \"{0}\" with \"{1}\" items.", target.getName(), 0/*eventItems.size()*/);
    //contentRepository.publishDeployEvent(target.getName(), eventItems);

    logger.info("Deployment successful on target {0}", endpointConfig.getName());
    logger.debug("Finished deploying items for site \"{0}\", target \"{1}\", number of items \"{2}\"", site,
            endpointConfig.getName(), paths.size());
}

From source file:org.crosswire.common.util.WebResource.java

/**
 * Determine the size of this WebResource.
 * <p>Note that the http client may read the entire file to determine this.</p>
 *
 * @return the size of the file/*from w w  w .  j  a  va 2s. c  o  m*/
 */
public int getSize() {
    HttpMethod method = new HeadMethod(uri.getPath());

    try {
        // Execute the method.
        int status = client.executeMethod(method);
        if (status == HttpStatus.SC_OK) {
            return new HttpURLConnection(method, NetUtil.toURL(uri)).getContentLength();
        }
        String reason = HttpStatus.getStatusText(status);
        Reporter.informUser(this, Msg.MISSING_FILE, new Object[] { reason + ':' + uri.getPath() });
    } catch (IOException e) {
        return 0;
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
    return 0;
}

From source file:org.cytoscape.cpath2.internal.CPathProtocol.java

private void checkHttpStatusCode(int statusCode) throws CPathException {
    if (statusCode != 200) {
        throw new CPathException(CPathException.ERROR_HTTP,
                "HTTP Status Code:  " + statusCode + ":  " + HttpStatus.getStatusText(statusCode) + ".");
    }/*from w w w .j av a 2 s.c  om*/
}

From source file:org.eclipse.buckminster.jnlp.MaterializationUtils.java

/**
 * Checks HTTP response code and throws JNLPException if there is a problem
 * /*from   w  ww  .  j  av a 2 s .  c om*/
 * @param connection
 * @throws JNLPException
 * @throws IOException
 */
public static void checkConnection(int status, String originalURL) throws JNLPException {
    if (status != HttpStatus.SC_OK) {
        String errorCode;

        switch (status) {
        case HttpStatus.SC_FORBIDDEN:

            errorCode = ERROR_CODE_403_EXCEPTION;
            break;

        case HttpStatus.SC_NOT_FOUND:

            errorCode = ERROR_CODE_404_EXCEPTION;
            break;

        case HttpStatus.SC_INTERNAL_SERVER_ERROR:

            errorCode = ERROR_CODE_500_EXCEPTION;
            break;

        default:
            errorCode = ERROR_CODE_REMOTE_IO_EXCEPTION;
            break;
        }

        throw new JNLPException(Messages.cannot_read_materialization_specification, errorCode,
                BuckminsterException.fromMessage("%s - %s", originalURL, HttpStatus.getStatusText(status))); //$NON-NLS-1$
    }
}

From source file:org.eclipse.buckminster.jnlp.p2.MaterializationUtils.java

/**
 * Checks HTTP response code and throws JNLPException if there is a problem
 * //from   ww w. j  a va2  s. c om
 * @param connection
 * @throws JNLPException
 * @throws IOException
 */
public static void checkConnection(int status, String originalURL) throws JNLPException {
    if (status != HttpStatus.SC_OK) {
        String errorCode;

        switch (status) {
        case HttpStatus.SC_FORBIDDEN:

            errorCode = ERROR_CODE_403_EXCEPTION;
            break;

        case HttpStatus.SC_NOT_FOUND:

            errorCode = ERROR_CODE_404_EXCEPTION;
            break;

        case HttpStatus.SC_INTERNAL_SERVER_ERROR:

            errorCode = ERROR_CODE_500_EXCEPTION;
            break;

        default:
            errorCode = ERROR_CODE_REMOTE_IO_EXCEPTION;
            break;
        }

        throw new JNLPException("Cannot read materialization specification", errorCode,
                BuckminsterException.fromMessage("%s - %s", originalURL, HttpStatus.getStatusText(status)));
    }
}

From source file:org.eclipse.mylyn.commons.net.http.CommonHttpClient3.java

protected boolean needsReauthentication(int code, IProgressMonitor monitor) throws IOException {
    final AuthenticationType authenticationType;
    if (code == HttpStatus.SC_UNAUTHORIZED || code == HttpStatus.SC_FORBIDDEN) {
        authenticationType = AuthenticationType.HTTP;
    } else if (code == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
        authenticationType = AuthenticationType.PROXY;
    } else {/*w w  w . j a  va2s  .  c  o m*/
        return false;
    }

    try {
        location.requestCredentials(authenticationType, null, monitor);
    } catch (UnsupportedRequestException e) {
        IOException ioe = new IOException(HttpStatus.getStatusText(code));
        ioe.initCause(e);
        throw ioe;
    } catch (UnsupportedOperationException e) {
        IOException ioe = new IOException(HttpStatus.getStatusText(code));
        ioe.initCause(e);
        throw ioe;
    }

    return true;
}

From source file:org.eclipse.mylyn.internal.bugzilla.core.BugzillaClient.java

private GzipGetMethod connectInternal(String requestURL, boolean gzip, IProgressMonitor monitor,
        String eTagValue) throws IOException, CoreException {
    monitor = Policy.monitorFor(monitor);
    hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor);

    for (int attempt = 0; attempt < 2; attempt++) {
        // force authentication
        authenticate(monitor);/*w w  w  .  j  a va2s  .  c  o  m*/

        GzipGetMethod getMethod = new GzipGetMethod(WebUtil.getRequestPath(requestURL), gzip);
        if (requestURL.contains(QUERY_DELIMITER)) {
            getMethod.setQueryString(requestURL.substring(requestURL.indexOf(QUERY_DELIMITER)));
        }

        getMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=" //$NON-NLS-1$ //$NON-NLS-2$
                + getCharacterEncoding());

        if (eTagValue != null && eTagValue.compareTo("") != 0) { //$NON-NLS-1$
            getMethod.setRequestHeader("If-None-Match", eTagValue); //$NON-NLS-1$
        }
        // Resolves bug#195113
        httpClient.getParams().setParameter("http.protocol.single-cookie-header", true); //$NON-NLS-1$

        // WARNING!! Setting browser compatibility breaks Bugzilla
        // authentication
        // getMethod.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        // getMethod.getParams().setCookiePolicy(CookiePolicy.RFC_2109);

        getMethod.setDoAuthentication(true);

        int code;
        try {
            code = WebUtil.execute(httpClient, hostConfiguration, getMethod, monitor);
        } catch (IOException e) {
            WebUtil.releaseConnection(getMethod, monitor);
            throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                    RepositoryStatus.ERROR_IO, repositoryUrl.toString(), e));
        }
        switch (code) {
        case HttpURLConnection.HTTP_OK:
            return getMethod;
        case HttpURLConnection.HTTP_NOT_MODIFIED:
            WebUtil.releaseConnection(getMethod, monitor);
            throw new CoreException(new Status(IStatus.WARNING, BugzillaCorePlugin.ID_PLUGIN, "Not changed")); //$NON-NLS-1$
        case HttpURLConnection.HTTP_UNAUTHORIZED:
        case HttpURLConnection.HTTP_FORBIDDEN:
            // login or reauthenticate due to an expired session
            loggedIn = false;
            WebUtil.releaseConnection(getMethod, monitor);
            authenticate(monitor);
            break;
        case HttpURLConnection.HTTP_PROXY_AUTH:
            loggedIn = false;
            WebUtil.releaseConnection(getMethod, monitor);
            throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                    RepositoryStatus.ERROR_REPOSITORY_LOGIN, repositoryUrl.toString(),
                    "Proxy authentication required")); //$NON-NLS-1$
        case HttpURLConnection.HTTP_INTERNAL_ERROR:
            loggedIn = false;
            InputStream stream = getResponseStream(getMethod, monitor);
            ByteArrayOutputStream ou = new ByteArrayOutputStream(1024);
            transferData(stream, ou);
            WebUtil.releaseConnection(getMethod, monitor);
            throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                    RepositoryStatus.ERROR_NETWORK, repositoryUrl.toString(), "Error = 500")); //$NON-NLS-1$
        default:
            WebUtil.releaseConnection(getMethod, monitor);
            throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                    RepositoryStatus.ERROR_NETWORK, "Http error: " + HttpStatus.getStatusText(code))); //$NON-NLS-1$
        }

    }

    throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
            RepositoryStatus.ERROR_REPOSITORY_LOGIN, "All connection attempts to " + repositoryUrl.toString() //$NON-NLS-1$
                    + " failed. Please verify connection and authentication information.")); //$NON-NLS-1$
}

From source file:org.eclipse.mylyn.internal.bugzilla.core.BugzillaClient.java

private String getBugzillaLoginTokenIfExists(IProgressMonitor monitor) throws CoreException {
    String loginToken = null;//from  w w w . j  a  v a  2 s .  c  o  m
    GzipPostMethod getMethod = new GzipPostMethod(
            WebUtil.getRequestPath(repositoryUrl.toString()) + "/index.cgi", //$NON-NLS-1$
            true);
    try {
        getMethod.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=" //$NON-NLS-1$ //$NON-NLS-2$
                + getCharacterEncoding());

        getMethod.setDoAuthentication(true);
        getMethod.setFollowRedirects(false);
        httpClient.getState().clearCookies();
        // for Bugzilla > 4.4.2 but not 4.5, 4.5.1 or 4.5.2 we need first the Bugzilla_login_request_cookie
        int code = WebUtil.execute(httpClient, hostConfiguration, getMethod, monitor);
        WebUtil.releaseConnection(getMethod, monitor);
        if (code != HttpURLConnection.HTTP_OK) {
            loggedIn = false;
            throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                    RepositoryStatus.ERROR_NETWORK, "Http error: " + HttpStatus.getStatusText(code))); //$NON-NLS-1$
        }

        // for Bugzilla > 4.4.2 but not 4.5, 4.5.1 or 4.5.2 we now  do the real authentication
        code = WebUtil.execute(httpClient, hostConfiguration, getMethod, monitor);
        if (code != HttpURLConnection.HTTP_OK) {
            loggedIn = false;
            throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                    RepositoryStatus.ERROR_NETWORK, "Http error: " + HttpStatus.getStatusText(code))); //$NON-NLS-1$
        }
        InputStream is = getResponseStream(getMethod, monitor);
        String result = getStringFromInputStream(is);
        if (result.lastIndexOf(INPUT_TYPE_HIDDEN_NAME_BUGZILLA_LOGIN_TOKEN) != -1) {
            int index = result.lastIndexOf(INPUT_TYPE_HIDDEN_NAME_BUGZILLA_LOGIN_TOKEN);
            String loginTokenAndRest = result.substring(index);
            int valueStart = loginTokenAndRest.indexOf("value=\"") + 7; //$NON-NLS-1$
            int valueEnd = loginTokenAndRest.indexOf("\">"); //$NON-NLS-1$
            loginToken = loginTokenAndRest.substring(valueStart, valueEnd);
        }
    } catch (IOException e) {
        throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                RepositoryStatus.ERROR_IO, repositoryUrl.toString(), e));
    } finally {
        WebUtil.releaseConnection(getMethod, monitor);
    }
    return loginToken;
}