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.eclipse.mylyn.internal.bugzilla.core.BugzillaClient.java

public void authenticate(IProgressMonitor monitor) throws CoreException {
    if (loggedIn || (!hasAuthenticationCredentials() && !hasHTTPAuthenticationCredentials())) {
        return;/*w  ww  .jav a  2s.c o m*/
    }

    monitor = Policy.monitorFor(monitor);

    GzipPostMethod postMethod = null;

    try {
        hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor);

        NameValuePair[] formData;

        String loginToken = getBugzillaLoginTokenIfExists(monitor);
        if (loginToken != null) {
            formData = new NameValuePair[3];
            formData[2] = new NameValuePair("Bugzilla_login_token", loginToken); //$NON-NLS-1$
        } else {
            formData = new NameValuePair[2];
        }

        AuthenticationCredentials credentials = location.getCredentials(AuthenticationType.REPOSITORY);
        AuthenticationCredentials httpAuthCredentials = location.getCredentials(AuthenticationType.HTTP);
        if (credentials == null && httpAuthCredentials == null) {
            loggedIn = false;
            throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                    RepositoryStatus.ERROR_REPOSITORY_LOGIN, repositoryUrl.toString(),
                    "Authentication credentials from location missing.")); //$NON-NLS-1$
        }
        if (credentials != null) {
            String password = credentials.getPassword();
            if ("".equals(password) && !hasHTTPAuthenticationCredentials()) { //$NON-NLS-1$
                loggedIn = false;
                throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                        RepositoryStatus.ERROR_EMPTY_PASSWORD, repositoryUrl.toString(),
                        "Empty password not allowed for Authentication credentials.")); //$NON-NLS-1$
            }
            formData[0] = new NameValuePair(IBugzillaConstants.POST_INPUT_BUGZILLA_LOGIN,
                    credentials.getUserName());
            formData[1] = new NameValuePair(IBugzillaConstants.POST_INPUT_BUGZILLA_PASSWORD,
                    credentials.getPassword());
        }
        postMethod = new GzipPostMethod(
                WebUtil.getRequestPath(repositoryUrl.toString() + IBugzillaConstants.URL_POST_LOGIN), true);

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

        if (credentials != null) {
            postMethod.setRequestBody(formData);
        }
        postMethod.setDoAuthentication(true);
        postMethod.setFollowRedirects(false);

        if (httpAuthCredentials != null && httpAuthCredentials.getUserName() != null
                && httpAuthCredentials.getUserName().length() > 0) {
            httpClient.getParams().setAuthenticationPreemptive(true);
        }

        int code = WebUtil.execute(httpClient, hostConfiguration, postMethod, monitor);
        if (code == HttpURLConnection.HTTP_UNAUTHORIZED || code == HttpURLConnection.HTTP_FORBIDDEN) {
            loggedIn = false;
            WebUtil.releaseConnection(postMethod, monitor);
            throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                    RepositoryStatus.ERROR_REPOSITORY_LOGIN, repositoryUrl.toString(),
                    "HTTP authentication failed.")); //$NON-NLS-1$

        } else if (code == HttpURLConnection.HTTP_PROXY_AUTH) {
            loggedIn = false;
            WebUtil.releaseConnection(postMethod, monitor);
            throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                    RepositoryStatus.ERROR_REPOSITORY_LOGIN, repositoryUrl.toString(),
                    "Proxy authentication required")); //$NON-NLS-1$

        } else if (code != HttpURLConnection.HTTP_OK) {
            loggedIn = false;
            WebUtil.releaseConnection(postMethod, monitor);
            throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                    RepositoryStatus.ERROR_NETWORK, "Http error: " + HttpStatus.getStatusText(code))); //$NON-NLS-1$
        }
        if (httpAuthCredentials != null && httpAuthCredentials.getUserName() != null
                && httpAuthCredentials.getUserName().length() > 0) {
            // If httpAuthCredentials are used HttpURLConnection.HTTP_UNAUTHORIZED when the credentials are invalide so we
            // not need to test the cookies.
            // see bug 305267 or https://bugzilla.mozilla.org/show_bug.cgi?id=385606
            loggedIn = true;
            InputStream inputStream = getResponseStream(postMethod, monitor);
            try {
                BufferedReader in = new BufferedReader(
                        new InputStreamReader(inputStream, getCharacterEncoding()));

                try {
                    String errorMessage = extractErrorMessage(in);

                    if (errorMessage != null) {
                        loggedIn = false;
                        throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                                RepositoryStatus.ERROR_REPOSITORY_LOGIN, repositoryUrl.toString(),
                                errorMessage));
                    }
                } finally {
                    inputStream.close();
                }
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } else if (hasAuthenticationCredentials()) {
            for (Cookie cookie : httpClient.getState().getCookies()) {
                if (cookie.getName().equals(COOKIE_BUGZILLA_LOGIN)) {
                    loggedIn = true;
                    break;
                }
            }

            if (!loggedIn) {
                InputStream input = getResponseStream(postMethod, monitor);
                try {
                    throw new CoreException(parseHtmlError(input));
                } finally {
                    input.close();
                }
            }
        } else {
            // anonymous login
            loggedIn = true;
        }
    } catch (IOException e) {
        throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                RepositoryStatus.ERROR_IO, repositoryUrl.toString(), e));
    } finally {
        if (postMethod != null) {
            WebUtil.releaseConnection(postMethod, monitor);
        }
        httpClient.getParams().setAuthenticationPreemptive(false);
    }
}

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

public void postAttachment(String bugReportID, String comment, AbstractTaskAttachmentSource source,
        TaskAttribute attachmentAttribute, IProgressMonitor monitor)
        throws HttpException, IOException, CoreException {
    monitor = Policy.monitorFor(monitor);
    String description = source.getDescription();
    String contentType = source.getContentType();
    String filename = source.getName();
    boolean isPatch = false;

    if (attachmentAttribute != null) {
        TaskAttachmentMapper mapper = TaskAttachmentMapper.createFrom(attachmentAttribute);

        if (mapper.getDescription() != null) {
            description = mapper.getDescription();
        }/*from  w w w  . ja  v a 2s.com*/

        if (mapper.getContentType() != null) {
            contentType = mapper.getContentType();
        }

        if (mapper.getFileName() != null) {
            filename = mapper.getFileName();
        }

        if (mapper.isPatch() != null) {
            isPatch = mapper.isPatch();
        }
    }
    Assert.isNotNull(bugReportID);
    Assert.isNotNull(source);
    Assert.isNotNull(contentType);
    if (description == null) {
        throw new CoreException(new Status(IStatus.WARNING, BugzillaCorePlugin.ID_PLUGIN,
                Messages.BugzillaClient_description_required_when_submitting_attachments));
    }

    hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor);
    authenticate(monitor);
    GzipPostMethod postMethod = null;

    try {
        postMethod = new GzipPostMethod(
                WebUtil.getRequestPath(repositoryUrl + IBugzillaConstants.URL_POST_ATTACHMENT_UPLOAD), true);
        // This option causes the client to first
        // check
        // with the server to see if it will in fact receive the post before
        // actually sending the contents.
        postMethod.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
        List<PartBase> parts = new ArrayList<PartBase>();
        parts.add(new StringPart(IBugzillaConstants.POST_INPUT_ACTION, VALUE_ACTION_INSERT,
                getCharacterEncoding()));

        parts.add(new StringPart(IBugzillaConstants.POST_INPUT_BUGID, bugReportID, getCharacterEncoding()));
        if (description != null) {
            parts.add(new StringPart(IBugzillaConstants.POST_INPUT_DESCRIPTION, description,
                    getCharacterEncoding()));
        }
        if (comment != null) {
            parts.add(new StringPart(IBugzillaConstants.POST_INPUT_COMMENT, comment, getCharacterEncoding()));
        }
        parts.add(new BugzillaFilePart(source, filename, contentType, getCharacterEncoding()));

        if (isPatch) {
            parts.add(new StringPart(ATTRIBUTE_ISPATCH, VALUE_ISPATCH));
        } else {
            parts.add(new StringPart(ATTRIBUTE_CONTENTTYPEMETHOD, VALUE_CONTENTTYPEMETHOD_MANUAL));
            parts.add(new StringPart(ATTRIBUTE_CONTENTTYPEENTRY, contentType));
        }
        if (attachmentAttribute != null) {
            Collection<TaskAttribute> attributes = attachmentAttribute.getAttributes().values();
            Iterator<TaskAttribute> itr = attributes.iterator();
            while (itr.hasNext()) {
                TaskAttribute a = itr.next();
                if (a.getId().startsWith(BugzillaAttribute.KIND_FLAG_TYPE) && repositoryConfiguration != null) {
                    List<BugzillaFlag> flags = repositoryConfiguration.getFlags();
                    TaskAttribute requestee = a.getAttribute("requestee"); //$NON-NLS-1$
                    a = a.getAttribute("state"); //$NON-NLS-1$
                    String value = a.getValue();
                    String id = ""; //$NON-NLS-1$
                    if (value.equals(" ")) { //$NON-NLS-1$
                        continue;
                    }
                    String flagname = a.getMetaData().getLabel();
                    BugzillaFlag theFlag = null;
                    for (BugzillaFlag bugzillaFlag : flags) {
                        if (flagname.equals(bugzillaFlag.getName())) {
                            theFlag = bugzillaFlag;
                            break;
                        }
                    }
                    if (theFlag != null) {
                        int flagTypeNumber = theFlag.getFlagId();
                        id = "flag_type-" + flagTypeNumber; //$NON-NLS-1$
                        value = a.getValue();
                        if (value.equals("?") && requestee != null) { //$NON-NLS-1$
                            parts.add(new StringPart("requestee_type-" + flagTypeNumber, //$NON-NLS-1$
                                    requestee.getValue() != null ? requestee.getValue() : "")); //$NON-NLS-1$
                        }
                    }
                    parts.add(new StringPart(id, value != null ? value : "")); //$NON-NLS-1$
                } else if (a.getId().startsWith(BugzillaAttribute.KIND_FLAG)) {
                    TaskAttribute flagnumber = a.getAttribute("number"); //$NON-NLS-1$
                    TaskAttribute requestee = a.getAttribute("requestee"); //$NON-NLS-1$
                    a = a.getAttribute("state"); //$NON-NLS-1$
                    String id = "flag-" + flagnumber.getValue(); //$NON-NLS-1$
                    String value = a.getValue();
                    if (value.equals(" ") || value.equals("")) { //$NON-NLS-1$ //$NON-NLS-2$
                        value = "X"; //$NON-NLS-1$
                    }
                    if (value.equals("?") && requestee != null) { //$NON-NLS-1$
                        parts.add(new StringPart("requestee-" + flagnumber.getValue(), //$NON-NLS-1$
                                requestee.getValue() != null ? requestee.getValue() : "")); //$NON-NLS-1$
                    }
                    parts.add(new StringPart(id, value != null ? value : "")); //$NON-NLS-1$
                }
            }
        }
        String token = null;
        BugzillaVersion bugzillaVersion = null;
        if (repositoryConfiguration != null) {
            bugzillaVersion = repositoryConfiguration.getInstallVersion();
        } else {
            bugzillaVersion = BugzillaVersion.MIN_VERSION;
        }
        if (bugzillaVersion.compareMajorMinorOnly(BugzillaVersion.BUGZILLA_4_0) > 0) {
            token = getTokenInternal(repositoryUrl + ENTER_ATTACHMENT_CGI + bugReportID, monitor);
        }
        if (token != null) {
            parts.add(new StringPart(BugzillaAttribute.TOKEN.getKey(), token));
        }

        postMethod.setRequestEntity(
                new MultipartRequestEntity(parts.toArray(new Part[1]), postMethod.getParams()));
        postMethod.setDoAuthentication(true);
        int status = WebUtil.execute(httpClient, hostConfiguration, postMethod, monitor);
        if (status == HttpStatus.SC_OK) {
            InputStream input = getResponseStream(postMethod, monitor);
            try {
                parsePostResponse(bugReportID, input);
            } finally {
                input.close();
            }

        } else {
            WebUtil.releaseConnection(postMethod, monitor);
            throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                    RepositoryStatus.ERROR_NETWORK, repositoryUrl.toString(), "Http error: " //$NON-NLS-1$
                            + HttpStatus.getStatusText(status)));
            // throw new IOException("Communication error occurred during
            // upload. \n\n"
            // + HttpStatus.getStatusText(status));
        }
    } finally {
        if (postMethod != null) {
            WebUtil.releaseConnection(postMethod, monitor);
        }
    }
}

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

/**
 * calling method must release the connection on the returned PostMethod once finished.
 *
 * @throws CoreException/*  w ww  . jav a  2 s .c o m*/
 */
private GzipPostMethod postFormData(String formUrl, NameValuePair[] formData, IProgressMonitor monitor)
        throws IOException, CoreException {

    GzipPostMethod postMethod = null;
    monitor = Policy.monitorFor(monitor);
    hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor);
    authenticate(monitor);

    postMethod = new GzipPostMethod(WebUtil.getRequestPath(repositoryUrl.toString() + formUrl), true);
    postMethod.setRequestHeader("Content-Type", //$NON-NLS-1$
            "application/x-www-form-urlencoded; charset=" + getCharacterEncoding()); //$NON-NLS-1$

    httpClient.getHttpConnectionManager().getParams().setSoTimeout(WebUtil.getConnectionTimeout());

    postMethod.setRequestBody(formData);
    postMethod.setDoAuthentication(true);
    int status = WebUtil.execute(httpClient, hostConfiguration, postMethod, monitor);
    if (status == HttpStatus.SC_OK) {
        return postMethod;
    } else if (status == HttpStatus.SC_MOVED_TEMPORARILY) {
        String redirectLocation;
        Header locationHeader = postMethod.getResponseHeader("location"); //$NON-NLS-1$
        if (locationHeader != null) {
            redirectLocation = locationHeader.getValue();
            WebUtil.releaseConnection(postMethod, monitor);
            throw new RedirectException(redirectLocation);
        }

    }
    WebUtil.releaseConnection(postMethod, monitor);
    throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
            RepositoryStatus.ERROR_IO, repositoryUrl.toString(), new IOException(
                    "Communication error occurred during upload. \n\n" + HttpStatus.getStatusText(status)))); //$NON-NLS-1$
}

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

private HeadMethod connectHead(String requestURL, IProgressMonitor monitor) throws IOException, CoreException {
    hostConfiguration = WebUtil.createHostConfiguration(httpClient, location, monitor);
    for (int attempt = 0; attempt < 2; attempt++) {
        // force authentication
        authenticate(monitor);//from   w  w  w .  j av  a  2  s.co m

        HeadMethod headMethod = new HeadMethod(WebUtil.getRequestPath(requestURL));
        if (requestURL.contains(QUERY_DELIMITER)) {
            headMethod.setQueryString(requestURL.substring(requestURL.indexOf(QUERY_DELIMITER)));
        }

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

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

        //         headMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new BugzillaRetryHandler());
        headMethod.setDoAuthentication(true);

        int code;
        try {
            code = WebUtil.execute(httpClient, hostConfiguration, headMethod, monitor);
        } catch (IOException e) {
            //            ignore the response
            WebUtil.releaseConnection(headMethod, monitor);
            throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                    RepositoryStatus.ERROR_IO, repositoryUrl.toString(), e));
        }

        if (code == HttpURLConnection.HTTP_OK) {
            return headMethod;
        } else if (code == HttpURLConnection.HTTP_UNAUTHORIZED || code == HttpURLConnection.HTTP_FORBIDDEN) {
            //            ignore the response
            WebUtil.releaseConnection(headMethod, monitor);
            loggedIn = false;
            authenticate(monitor);
        } else if (code == HttpURLConnection.HTTP_PROXY_AUTH) {
            loggedIn = false;
            //            ignore the response
            WebUtil.releaseConnection(headMethod, monitor);
            throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                    RepositoryStatus.ERROR_REPOSITORY_LOGIN, repositoryUrl.toString(),
                    "Proxy authentication required")); //$NON-NLS-1$
        } else {
            //            ignore the response
            WebUtil.releaseConnection(headMethod, monitor);
            throw new CoreException(new BugzillaStatus(IStatus.ERROR, BugzillaCorePlugin.ID_PLUGIN,
                    RepositoryStatus.ERROR_NETWORK, "Http error: " + HttpStatus.getStatusText(code))); //$NON-NLS-1$
            // throw new IOException("HttpClient connection error response
            // code: " + code);
        }
    }

    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.gerrit.core.GerritConnector.java

Status toStatus(TaskRepository repository, String qualifier, Exception e) {
    if (StringUtils.isEmpty(qualifier)) {
        qualifier = ""; //$NON-NLS-1$
    } else if (!StringUtils.endsWith(qualifier, ": ")) { //$NON-NLS-1$
        qualifier += ": "; //$NON-NLS-1$
    }/*from   w w w .ja v  a 2s .c o m*/
    if (e instanceof GerritHttpException) {
        int code = ((GerritHttpException) e).getResponseCode();
        return createErrorStatus(repository, qualifier + HttpStatus.getStatusText(code));
    } else if (e instanceof GerritLoginException) {
        if (repository != null) {
            return RepositoryStatus.createLoginError(repository.getUrl(), GerritCorePlugin.PLUGIN_ID);
        } else {
            return createErrorStatus(null, qualifier + "Unknown Host"); //$NON-NLS-1$
        }
    } else if (e instanceof UnknownHostException) {
        return createErrorStatus(repository, qualifier + "Unknown Host"); //$NON-NLS-1$
    } else if (e instanceof GerritException && e.getCause() != null) {
        Throwable cause = e.getCause();
        if (cause instanceof Exception) {
            return toStatus(repository, qualifier, (Exception) cause);
        }
    } else if (e instanceof GerritException && e.getMessage() != null) {
        return createErrorStatus(repository,
                NLS.bind("{0}Gerrit connection issue: {1}", qualifier, e.getMessage())); //$NON-NLS-1$
    }
    String message = NLS.bind("{0}Unexpected error while connecting to Gerrit: {1}", qualifier, e.getMessage()); //$NON-NLS-1$
    if (repository != null) {
        return RepositoryStatus.createStatus(repository, IStatus.ERROR, GerritCorePlugin.PLUGIN_ID, message);
    } else {
        return createErrorStatus(repository, message);
    }
}

From source file:org.elasticsearch.hadoop.rest.commonshttp.CommonsHttpTransport.java

@Override
public Response execute(Request request) throws IOException {
    HttpMethod http = null;/*from   w  w w  .  j a  va 2 s .  c  om*/

    switch (request.method()) {
    case DELETE:
        http = new DeleteMethodWithBody();
        break;
    case HEAD:
        http = new HeadMethod();
        break;
    case GET:
        http = (request.body() == null ? new GetMethod() : new GetMethodWithBody());
        break;
    case POST:
        http = new PostMethod();
        break;
    case PUT:
        http = new PutMethod();
        break;

    default:
        throw new EsHadoopTransportException("Unknown request method " + request.method());
    }

    CharSequence uri = request.uri();
    if (StringUtils.hasText(uri)) {
        http.setURI(new URI(escapeUri(uri.toString(), settings.getNetworkSSLEnabled()), false));
    }
    // NB: initialize the path _after_ the URI otherwise the path gets reset to /
    http.setPath(prefixPath(request.path().toString()));

    try {
        // validate new URI
        uri = http.getURI().toString();
    } catch (URIException uriex) {
        throw new EsHadoopTransportException("Invalid target URI " + request, uriex);
    }

    CharSequence params = request.params();
    if (StringUtils.hasText(params)) {
        http.setQueryString(params.toString());
    }

    ByteSequence ba = request.body();
    if (ba != null && ba.length() > 0) {
        if (!(http instanceof EntityEnclosingMethod)) {
            throw new IllegalStateException(String.format("Method %s cannot contain body - implementation bug",
                    request.method().name()));
        }
        EntityEnclosingMethod entityMethod = (EntityEnclosingMethod) http;
        entityMethod.setRequestEntity(new BytesArrayRequestEntity(ba));
        entityMethod.setContentChunked(false);
    }

    // when tracing, log everything
    if (log.isTraceEnabled()) {
        log.trace(String.format("Tx %s[%s]@[%s][%s] w/ payload [%s]", proxyInfo, request.method().name(),
                httpInfo, request.path(), request.body()));
    }

    long start = System.currentTimeMillis();
    try {
        client.executeMethod(http);
    } finally {
        stats.netTotalTime += (System.currentTimeMillis() - start);
    }

    if (log.isTraceEnabled()) {
        Socket sk = ReflectionUtils.invoke(GET_SOCKET, conn, (Object[]) null);
        String addr = sk.getLocalAddress().getHostAddress();
        log.trace(String.format("Rx %s@[%s] [%s-%s] [%s]", proxyInfo, addr, http.getStatusCode(),
                HttpStatus.getStatusText(http.getStatusCode()), http.getResponseBodyAsString()));
    }

    // the request URI is not set (since it is retried across hosts), so use the http info instead for source
    return new SimpleResponse(http.getStatusCode(), new ResponseInputStream(http), httpInfo);
}

From source file:org.fcrepo.client.FedoraClient.java

/**
 * Upload the given file to Fedora's upload interface via HTTP POST.
 *
 * @return the temporary id which can then be passed to API-M requests as a
 *         URL. It will look like uploaded://123
 *//*from   w w w  .  jav  a2s. c o m*/
public String uploadFile(File file) throws IOException {
    PostMethod post = null;
    try {
        // prepare the post method
        post = new PostMethod(getUploadURL());
        post.setDoAuthentication(true);
        post.getParams().setParameter("Connection", "Keep-Alive");

        // chunked encoding is not required by the Fedora server,
        // but makes uploading very large files possible
        post.setContentChunked(true);

        // add the file part
        Part[] parts = { new FilePart("file", file) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

        // execute and get the response
        int responseCode = getHttpClient().executeMethod(post);
        String body = null;
        try {
            body = post.getResponseBodyAsString();
        } catch (Exception e) {
            logger.warn("Error reading response body", e);
        }
        if (body == null) {
            body = "[empty response body]";
        }
        body = body.trim();
        if (responseCode != HttpStatus.SC_CREATED) {
            throw new IOException("Upload failed: " + HttpStatus.getStatusText(responseCode) + ": "
                    + replaceNewlines(body, " "));
        } else {
            return replaceNewlines(body, "");
        }
    } finally {
        if (post != null) {
            post.releaseConnection();
        }
    }
}

From source file:org.fenixedu.academic.ui.struts.action.publico.candidacies.GenericCandidaciesDA.java

public ActionForward deleteFile(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws IOException {
    final GenericApplication application = getDomainObject(request, "applicationExternalId");
    final String confirmationCode = (String) getFromRequest(request, "confirmationCode");
    final GenericApplicationFile file = getDomainObject(request, "fileExternalId");
    if (application != null && confirmationCode != null && application.getConfirmationCode() != null
            && application.getConfirmationCode().equals(confirmationCode) && file != null
            && file.getGenericApplication() == application) {
        FenixFramework.atomic(() -> file.delete());
    } else {/*from  w  ww.j av  a  2s.co  m*/
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().write(HttpStatus.getStatusText(HttpStatus.SC_BAD_REQUEST));
        response.getWriter().close();
    }
    return confirmEmail(mapping, form, request, response);
}

From source file:org.geosdi.geoplatform.publish.HttpUtilsLocal.java

/**
 * Performs an HTTP GET on the given URL.
 * <BR>Basic auth is used if both username and pw are not null.
 *
 * @param url The URL where to connect to.
 * @param username Basic auth credential. No basic auth if null.
 * @param pw Basic auth credential. No basic auth if null.
 * @return The HTTP response as a String if the HTTP response code was 200 (OK).
 * @throws MalformedURLException//from   w ww.j  av a  2  s  .c  o  m
 */
public static String get(String url, String username, String pw) throws MalformedURLException {

    GetMethod httpMethod = null;
    try {
        HttpClient client = new HttpClient();
        setAuth(client, url, username, pw);
        httpMethod = new GetMethod(url);
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        int status = client.executeMethod(httpMethod);
        if (status == HttpStatus.SC_OK) {
            InputStream is = httpMethod.getResponseBodyAsStream();
            String response = IOUtils.toString(is);
            if (response.trim().length() == 0) { // sometime gs rest fails
                LOGGER.warn("ResponseBody is empty");
                return null;
            } else {
                return response;
            }
        } else {
            LOGGER.info("(" + status + ") " + HttpStatus.getStatusText(status) + " -- " + url);
        }
    } catch (ConnectException e) {
        LOGGER.info("Couldn't connect to [" + url + "]");
    } catch (IOException e) {
        LOGGER.info("Error talking to [" + url + "]", e);
    } finally {
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }

    return null;
}

From source file:org.geoserver.security.iride.service.policy.handler.IridePolicyRequestHandler.java

/**
 *
 * @param serverURL//w  w  w.j av a 2s  . com
 * @param params
 * @return
 * @throws IOException
 */
public String handleRequest(String serverURL, Map<String, Object> params) throws IOException {
    final String requestXml = this.createPolicyRequestXml(params);
    final HttpMethod requestHttpMethod = this.createPolicyRequestMethod(requestXml, serverURL);

    String result = "";
    try {
        final int responseCode = this.getHttpClient().executeMethod(requestHttpMethod);
        final String responseXml = requestHttpMethod.getResponseBodyAsString();

        if (responseCode == HttpStatus.SC_OK) {
            result = responseXml;
        } else {
            LOGGER.warn("IRIDE error response code: {} {}", responseCode,
                    HttpStatus.getStatusText(responseCode));
        }

        LOGGER.trace("IRIDE SOAP response: " + responseXml);

        return result;
    } finally {
        requestHttpMethod.releaseConnection();
    }
}