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

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

Introduction

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

Prototype

int SC_FORBIDDEN

To view the source code for org.apache.commons.httpclient HttpStatus SC_FORBIDDEN.

Click Source Link

Document

<tt>403 Forbidden</tt> (HTTP/1.0 - RFC 1945)

Usage

From source file:com.sun.faban.harness.webclient.ResultAction.java

/**
 * This method is responsible for uploading the runs to repository.
 * @param uploadSet/*  w  w w  .  j  a va2s.c  om*/
 * @param replaceSet
 * @return HashSet
 * @throws java.io.IOException
 */
public static HashSet<String> uploadRuns(String[] runIds, HashSet<File> uploadSet, HashSet<String> replaceSet)
        throws IOException {
    // 3. Upload the run
    HashSet<String> duplicates = new HashSet<String>();

    // Prepare run id set for cross checking.
    HashSet<String> runIdSet = new HashSet<String>(runIds.length);
    for (String runId : runIds) {
        runIdSet.add(runId);
    }

    // Prepare the parts for the request.
    ArrayList<Part> params = new ArrayList<Part>();
    params.add(new StringPart("host", Config.FABAN_HOST));
    for (String replaceId : replaceSet) {
        params.add(new StringPart("replace", replaceId));
    }
    for (File jarFile : uploadSet) {
        params.add(new FilePart("jarfile", jarFile));
    }
    Part[] parts = new Part[params.size()];
    parts = params.toArray(parts);

    // Send the request for each reposotory.
    for (URL repository : Config.repositoryURLs) {
        URL repos = new URL(repository, "/controller/uploader/upload_runs");
        PostMethod post = new PostMethod(repos.toString());
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));

        HttpClient client = new HttpClient();
        client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        int status = client.executeMethod(post);

        if (status == HttpStatus.SC_FORBIDDEN)
            logger.warning("Server denied permission to upload run !");
        else if (status == HttpStatus.SC_NOT_ACCEPTABLE)
            logger.warning("Run origin error!");
        else if (status != HttpStatus.SC_CREATED)
            logger.warning(
                    "Server responded with status code " + status + ". Status code 201 (SC_CREATED) expected.");
        for (File jarFile : uploadSet) {
            jarFile.delete();
        }

        String response = post.getResponseBodyAsString();

        if (status == HttpStatus.SC_CREATED) {

            StringTokenizer t = new StringTokenizer(response.trim(), "\n");
            while (t.hasMoreTokens()) {
                String duplicateRun = t.nextToken().trim();
                if (duplicateRun.length() > 0)
                    duplicates.add(duplicateRun.trim());
            }

            for (Iterator<String> iter = duplicates.iterator(); iter.hasNext();) {
                String runId = iter.next();
                if (!runIdSet.contains(runId)) {
                    logger.warning("Unexpected archive response from " + repos + ": " + runId);
                    iter.remove();
                }
            }
        } else {
            logger.warning("Message from repository: " + response);
        }
    }
    return duplicates;
}

From source file:davmail.exchange.ews.EWSMethod.java

@Override
public int getStatusCode() {
    if ("ErrorAccessDenied".equals(errorDetail)) {
        return HttpStatus.SC_FORBIDDEN;
    } else if ("ErrorItemNotFound".equals(errorDetail)) {
        return HttpStatus.SC_NOT_FOUND;
    } else {//from w w  w  . j a  v  a 2 s  .  c  om
        return super.getStatusCode();
    }
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Execute Get method, do not follow redirects.
 *
 * @param httpClient      Http client instance
 * @param method          Http method//from w  ww . ja  va2  s  . c  o  m
 * @param followRedirects Follow redirects flag
 * @throws IOException on error
 */
public static void executeGetMethod(HttpClient httpClient, GetMethod method, boolean followRedirects)
        throws IOException {
    // do not follow redirects in expired sessions
    method.setFollowRedirects(followRedirects);
    int status = httpClient.executeMethod(method);
    if ((status == HttpStatus.SC_UNAUTHORIZED || status == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED)
            && acceptsNTLMOnly(method) && !hasNTLM(httpClient)) {
        resetMethod(method);
        LOGGER.debug("Received " + status + " unauthorized at " + method.getURI() + ", retrying with NTLM");
        addNTLM(httpClient);
        status = httpClient.executeMethod(method);
    }
    if (status != HttpStatus.SC_OK && (followRedirects || !isRedirect(status))) {
        LOGGER.warn("GET failed with status " + status + " at " + method.getURI());
        if (status != HttpStatus.SC_NOT_FOUND && status != HttpStatus.SC_FORBIDDEN) {
            LOGGER.warn(method.getResponseBodyAsString());
        }
        throw DavGatewayHttpClientFacade.buildHttpException(method);
    }
    // check for expired session
    if (followRedirects) {
        String queryString = method.getQueryString();
        checkExpiredSession(queryString);
    }
}

From source file:edu.ku.brc.util.WebStoreAttachmentMgr.java

/**
 * @param urlStr//from w w  w. j  av  a 2  s . c  om
 * @param tmpFile
 * @return
 * @throws IOException
 */

private File getFileFromWeb(final String attachLocation, final String mimeType, final Integer scale,
        final byte[] bytes) {
    File dlFile = getDLFileForName((scale == null) ? attachLocation : getScaledFileName(attachLocation, scale));
    try {
        dlFile.createNewFile();
        dlFile.deleteOnExit();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return null;
    }

    boolean success = false;

    if (bytes == null) {
        System.out.println("bytes == null");
    }
    notifyListeners(1);

    GetMethod getMethod = new GetMethod(readURLStr);
    // type=<type>&filename=<fname>&coll=<coll>&disp=<disp>&div=<div>&inst=<inst>
    fillValuesArray();
    getMethod.setQueryString(new NameValuePair[] { new NameValuePair("type", (scale != null) ? "T" : "O"),
            new NameValuePair("scale", "" + scale), new NameValuePair("filename", attachLocation),
            new NameValuePair("token", generateToken(attachLocation)), new NameValuePair("coll", values[0]),
            new NameValuePair("disp", values[1]), new NameValuePair("div", values[2]),
            new NameValuePair("inst", values[3]) });

    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);

    try {
        int status = client.executeMethod(getMethod);
        updateServerTimeDelta(getMethod);
        if (status == HttpStatus.SC_FORBIDDEN) {
            System.out.println(getMethod.getResponseBodyAsString());
        }
        if (status == HttpStatus.SC_OK) {
            InputStream inpStream = getMethod.getResponseBodyAsStream();
            if (inpStream != null) {
                BufferedInputStream in = new BufferedInputStream(inpStream);
                BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(dlFile));

                //long totBytes = 0;
                do {
                    int numBytes = in.read(bytes);
                    if (numBytes == -1) {
                        break;
                    }
                    //totBytes += numBytes;
                    bos.write(bytes, 0, numBytes);

                } while (true);
                //log.debug(String.format("Total Bytes for file: %d %d", totBytes, totBytes / 1024));
                in.close();
                bos.flush();
                bos.close();

                success = true;
            }
        }
    } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        getMethod.releaseConnection();
        notifyListeners(-1);
    }

    if (success) {
        return dlFile;
    } else {
        dlFile.delete();
        return null;
    }
}

From source file:com.motorola.studio.android.localization.translators.GoogleTranslator.java

private static void checkStatusCode(int statusCode, String response) throws HttpException {
    switch (statusCode) {
    case HttpStatus.SC_OK:
        //do nothing
        break;/*  w  ww .  j av  a2  s.com*/
    case HttpStatus.SC_BAD_REQUEST:
        throw new HttpException(NLS.bind(TranslateNLS.GoogleTranslator_ErrorMessageExecutingRequest,
                getErrorMessage(response)));

    case HttpStatus.SC_REQUEST_URI_TOO_LONG:
        throw new HttpException(TranslateNLS.GoogleTranslator_Error_QueryTooBig);

    case HttpStatus.SC_FORBIDDEN:
        throw new HttpException(NLS.bind(TranslateNLS.GoogleTranslator_ErrorMessageNoValidTranslationReturned,
                getErrorMessage(response)));

    default:
        throw new HttpException(NLS.bind(TranslateNLS.GoogleTranslator_Error_HTTPRequestError,
                new Object[] { statusCode, getErrorMessage(response) }));

    }
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Build Http Exception from methode status
 *
 * @param method Http Method//from   w ww. j a  va  2  s  . c o  m
 * @return Http Exception
 */
public static HttpException buildHttpException(HttpMethod method) {
    int status = method.getStatusCode();
    StringBuilder message = new StringBuilder();
    message.append(status).append(' ').append(method.getStatusText());
    try {
        message.append(" at ").append(method.getURI().getURI());
        if (method instanceof CopyMethod || method instanceof MoveMethod) {
            message.append(" to ").append(method.getRequestHeader("Destination"));
        }
    } catch (URIException e) {
        message.append(method.getPath());
    }
    // 440 means forbidden on Exchange
    if (status == 440) {
        return new LoginTimeoutException(message.toString());
    } else if (status == HttpStatus.SC_FORBIDDEN) {
        return new HttpForbiddenException(message.toString());
    } else if (status == HttpStatus.SC_NOT_FOUND) {
        return new HttpNotFoundException(message.toString());
    } else if (status == HttpStatus.SC_PRECONDITION_FAILED) {
        return new HttpPreconditionFailedException(message.toString());
    } else if (status == HttpStatus.SC_INTERNAL_SERVER_ERROR) {
        return new HttpServerErrorException(message.toString());
    } else {
        return new HttpException(message.toString());
    }
}

From source file:edu.unc.lib.dl.fedora.ManagementClient.java

public String upload(File file, boolean retry) {
    String result = null;//w  ww  .j  av  a2s .  c  o m
    String uploadURL = this.getFedoraContextUrl() + "/upload";
    PostMethod post = new PostMethod(uploadURL);
    post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, false);
    log.debug("Uploading file with forwarded groups: " + GroupsThreadStore.getGroupString());
    post.addRequestHeader(HttpClientUtil.FORWARDED_GROUPS_HEADER, GroupsThreadStore.getGroupString());
    try {
        log.debug("Uploading to " + uploadURL);
        Part[] parts = { new FilePart("file", file) };
        post.setRequestEntity(new MultipartRequestEntity(parts, post.getParams()));
        int status = httpClient.executeMethod(post);

        StringWriter sw = new StringWriter();
        try (InputStream in = post.getResponseBodyAsStream(); PrintWriter pw = new PrintWriter(sw)) {
            int b;
            while ((b = in.read()) != -1) {
                pw.write(b);
            }
        }

        switch (status) {
        case HttpStatus.SC_OK:
        case HttpStatus.SC_CREATED:
        case HttpStatus.SC_ACCEPTED:
            result = sw.toString().trim();
            log.info("Upload complete, response=" + result);
            break;
        case HttpStatus.SC_FORBIDDEN:
            log.warn("Authorization to Fedora failed, attempting to reestablish connection.");
            try {
                this.initializeConnections();
                return upload(file, false);
            } catch (Exception e) {
                log.error("Failed to reestablish connection to Fedora", e);
            }
            break;
        case HttpStatus.SC_SERVICE_UNAVAILABLE:
            throw new FedoraTimeoutException("Fedora service unavailable, upload failed");
        default:
            log.warn("Upload failed, response=" + HttpStatus.getStatusText(status));
            log.debug(sw.toString().trim());
            break;
        }
    } catch (ServiceException ex) {
        throw ex;
    } catch (Exception ex) {
        throw new ServiceException(ex);
    } finally {
        post.releaseConnection();
    }
    return result;
}

From source file:com.zimbra.cs.service.UserServlet.java

private static Pair<Header[], HttpMethod> doHttpOp(ZAuthToken authToken, HttpMethod method)
        throws ServiceException {
    // create an HTTP client with the same cookies
    String url = "";
    String hostname = "";
    try {// ww  w . j a v  a2 s  .c om
        url = method.getURI().toString();
        hostname = method.getURI().getHost();
    } catch (IOException e) {
        log.warn("can't parse target URI", e);
    }

    HttpClient client = ZimbraHttpConnectionManager.getInternalHttpConnMgr().newHttpClient();
    Map<String, String> cookieMap = authToken.cookieMap(false);
    if (cookieMap != null) {
        HttpState state = new HttpState();
        for (Map.Entry<String, String> ck : cookieMap.entrySet()) {
            state.addCookie(new org.apache.commons.httpclient.Cookie(hostname, ck.getKey(), ck.getValue(), "/",
                    null, false));
        }
        client.setState(state);
        client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
    }

    if (method instanceof PutMethod) {
        long contentLength = ((PutMethod) method).getRequestEntity().getContentLength();
        if (contentLength > 0) {
            int timeEstimate = Math.max(10000, (int) (contentLength / 100)); // 100kbps in millis
            // cannot set connection time using our ZimbrahttpConnectionManager,
            // see comments in ZimbrahttpConnectionManager.
            // actually, length of the content to Put should not be a factor for
            // establishing a connection, only read time out matter, which we set
            // client.getHttpConnectionManager().getParams().setConnectionTimeout(timeEstimate);

            method.getParams().setSoTimeout(timeEstimate);
        }
    }

    try {
        int statusCode = HttpClientUtil.executeMethod(client, method);
        if (statusCode == HttpStatus.SC_NOT_FOUND || statusCode == HttpStatus.SC_FORBIDDEN)
            throw MailServiceException.NO_SUCH_ITEM(-1);
        else if (statusCode != HttpStatus.SC_OK && statusCode != HttpStatus.SC_CREATED
                && statusCode != HttpStatus.SC_NO_CONTENT)
            throw ServiceException.RESOURCE_UNREACHABLE(method.getStatusText(), null,
                    new ServiceException.InternalArgument(HTTP_URL, url, ServiceException.Argument.Type.STR),
                    new ServiceException.InternalArgument(HTTP_STATUS_CODE, statusCode,
                            ServiceException.Argument.Type.NUM));

        List<Header> headers = new ArrayList<Header>(Arrays.asList(method.getResponseHeaders()));
        headers.add(new Header("X-Zimbra-Http-Status", "" + statusCode));
        return new Pair<Header[], HttpMethod>(headers.toArray(new Header[0]), method);
    } catch (HttpException e) {
        throw ServiceException.RESOURCE_UNREACHABLE("HttpException while fetching " + url, e);
    } catch (IOException e) {
        throw ServiceException.RESOURCE_UNREACHABLE("IOException while fetching " + url, e);
    }
}

From source file:opendap.bes.dap4Responders.FileAccess.java

public void sendNormativeRepresentation(HttpServletRequest req, HttpServletResponse response) throws Exception {

    String requestedResourceId = ReqInfo.getLocalUrl(req);

    String resourceID = getResourceId(requestedResourceId, false);

    BesApi besApi = getBesApi();/*  w  w  w . jav  a 2 s. c  o m*/

    ResourceInfo dsi = new BESResource(resourceID, besApi);
    if (dsi.sourceExists()) {
        if (!dsi.isNode()) {
            if (dsi.sourceIsAccesible()) {
                if (dsi.isDataset()) {
                    if (allowDirectDataSourceAccess()) {
                        sendDatasetFile(resourceID, response);

                    } else {
                        log.warn("respondToHttpGetRequest() - Sending Access Denied for resource: "
                                + Scrub.completeURL(resourceID));
                        sendDirectAccessDenied(req, response);
                    }
                } else {
                    String errMsg = "Unable to locate BES resource: " + Scrub.completeURL(resourceID);
                    log.info("respondToHttpGetRequest() - {}", errMsg);
                    sendHttpErrorResponse(HttpStatus.SC_NOT_FOUND, errMsg, "docs", response);
                }
            } else {
                String errMsg = "BES data source {} is not accessible." + Scrub.completeURL(resourceID);
                log.info("respondToHttpGetRequest() - {}", errMsg);
                sendHttpErrorResponse(HttpStatus.SC_NOT_FOUND, errMsg, "docs", response);
            }

        } else {
            String errMsg = "You may not downloadJobOutput nodes/directories, only files."
                    + Scrub.completeURL(resourceID);
            log.info("respondToHttpGetRequest() - {}", errMsg);
            sendHttpErrorResponse(HttpStatus.SC_FORBIDDEN, errMsg, "docs", response);
        }

    } else {
        String errMsg = "Unable to locate BES resource: " + Scrub.completeURL(resourceID);
        log.info("matches() - {}", errMsg);
        sendHttpErrorResponse(HttpStatus.SC_NOT_FOUND, errMsg, "docs", response);
    }

}