Example usage for java.net HttpURLConnection HTTP_FORBIDDEN

List of usage examples for java.net HttpURLConnection HTTP_FORBIDDEN

Introduction

In this page you can find the example usage for java.net HttpURLConnection HTTP_FORBIDDEN.

Prototype

int HTTP_FORBIDDEN

To view the source code for java.net HttpURLConnection HTTP_FORBIDDEN.

Click Source Link

Document

HTTP Status-Code 403: Forbidden.

Usage

From source file:org.eclipse.ecf.provider.filetransfer.httpclient4.HttpClientRetrieveFileTransfer.java

private boolean openStreamsForResume() {

    Trace.entering(Activator.PLUGIN_ID, DebugOptions.METHODS_ENTERING, this.getClass(), "openStreamsForResume"); //$NON-NLS-1$
    final String urlString = getRemoteFileURL().toString();
    this.doneFired = false;

    int code = -1;

    try {//from ww w  . ja v a  2s .  c  o  m
        httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, getSocketReadTimeout());
        int connectTimeout = getConnectTimeout();
        httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout);

        setupAuthentication(urlString);

        getMethod = new HttpGet(urlString);
        // Define a CredentialsProvider - found that possibility while debugging in org.apache.commons.httpclient.HttpMethodDirector.processProxyAuthChallenge(HttpMethod)
        // Seems to be another way to select the credentials.
        setResumeRequestHeaderValues();

        Trace.trace(Activator.PLUGIN_ID, "resume=" + urlString); //$NON-NLS-1$

        // Gzip encoding is not an option for resume
        fireConnectStartEvent();
        if (checkAndHandleDone()) {
            return false;
        }

        connectingSockets.clear();
        // Actually execute get and get response code (since redirect is set to true, then
        // redirect response code handled internally
        if (connectJob == null) {
            performConnect(new NullProgressMonitor());
        } else {
            connectJob.schedule();
            connectJob.join();
            connectJob = null;
        }
        if (checkAndHandleDone()) {
            return false;
        }

        code = responseCode;

        responseHeaders = getResponseHeaders();

        Trace.trace(Activator.PLUGIN_ID, "retrieve resp=" + code); //$NON-NLS-1$

        if (code == HttpURLConnection.HTTP_PARTIAL || code == HttpURLConnection.HTTP_OK) {
            getResumeResponseHeaderValues();
            setInputStream(httpResponse.getEntity().getContent());
            this.paused = false;
            fireReceiveResumedEvent();
        } else if (code == HttpURLConnection.HTTP_NOT_FOUND) {
            EntityUtils.consume(httpResponse.getEntity());
            throw new IncomingFileTransferException(NLS.bind("File not found: {0}", urlString), code, //$NON-NLS-1$
                    responseHeaders);
        } else if (code == HttpURLConnection.HTTP_UNAUTHORIZED) {
            EntityUtils.consume(httpResponse.getEntity());
            throw new IncomingFileTransferException(Messages.HttpClientRetrieveFileTransfer_Unauthorized, code,
                    responseHeaders);
        } else if (code == HttpURLConnection.HTTP_FORBIDDEN) {
            EntityUtils.consume(httpResponse.getEntity());
            throw new IncomingFileTransferException("Forbidden", code, responseHeaders); //$NON-NLS-1$
        } else if (code == HttpURLConnection.HTTP_PROXY_AUTH) {
            EntityUtils.consume(httpResponse.getEntity());
            throw new IncomingFileTransferException(Messages.HttpClientRetrieveFileTransfer_Proxy_Auth_Required,
                    code, responseHeaders);
        } else {
            EntityUtils.consume(httpResponse.getEntity());
            throw new IncomingFileTransferException(
                    NLS.bind(Messages.HttpClientRetrieveFileTransfer_ERROR_GENERAL_RESPONSE_CODE,
                            new Integer(code)),
                    code, responseHeaders);
        }
        Trace.exiting(Activator.PLUGIN_ID, DebugOptions.METHODS_EXITING, this.getClass(),
                "openStreamsForResume", Boolean.TRUE); //$NON-NLS-1$
        return true;
    } catch (final Exception e) {
        Trace.catching(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_CATCHING, this.getClass(),
                "openStreamsForResume", e); //$NON-NLS-1$
        if (code == -1) {
            if (!isDone()) {
                setDoneException(e);
            }
        } else {
            setDoneException((e instanceof IncomingFileTransferException) ? e
                    : new IncomingFileTransferException(
                            NLS.bind(Messages.HttpClientRetrieveFileTransfer_EXCEPTION_COULD_NOT_CONNECT,
                                    urlString),
                            e, code, responseHeaders));
        }
        fireTransferReceiveDoneEvent();
        Trace.exiting(Activator.PLUGIN_ID, DebugOptions.METHODS_EXITING, this.getClass(),
                "openStreamsForResume", Boolean.FALSE); //$NON-NLS-1$
        return false;
    }
}

From source file:org.openrdf.http.client.HTTPClient.java

public void deleteRepository(String repositoryID) throws HttpException, IOException, RepositoryException {

    HttpMethod method = new DeleteMethod(Protocol.getRepositoryLocation(serverURL, repositoryID));
    setDoAuthentication(method);//  w  w  w.  j  av a2 s.  co m

    try {
        int httpCode = httpClient.executeMethod(method);

        if (httpCode == HttpURLConnection.HTTP_NO_CONTENT) {
            return;
        } else if (httpCode == HttpURLConnection.HTTP_FORBIDDEN) {
            ErrorInfo errInfo = getErrorInfo(method);
            throw new UnauthorizedException(errInfo.getErrorMessage());
        } else {
            ErrorInfo errInfo = getErrorInfo(method);
            throw new RepositoryException("Failed to delete repository: " + errInfo + " (" + httpCode + ")");
        }
    } finally {
        releaseConnection(method);
    }
}

From source file:org.eclipse.mylyn.internal.gerrit.core.client.GerritClient.java

private ChangeDetail submitRest(PatchSet.Id id, IProgressMonitor monitor) throws GerritException {
    final String uri = "/a/changes/" + id.getParentKey().get() + "/revisions/" + id.get() + "/submit"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    executePostRestRequest(uri, new SubmitInput(true), SubmitInfo.class, new ErrorHandler() {
        @Override//from  ww  w  .  j  a v a 2s . c o  m
        public void handleError(HttpMethodBase method) throws GerritException {
            String errorMsg = getResponseBodyAsString(method);
            if (isNotPermitted(method, errorMsg) || isConflict(method)) {
                throw new GerritException(NLS.bind("Cannot submit change: {0}", errorMsg)); //$NON-NLS-1$
            }
        }

        private String getResponseBodyAsString(HttpMethodBase method) {
            try {
                return method.getResponseBodyAsString();
            } catch (IOException e) {
                return null;
            }
        }

        private boolean isNotPermitted(HttpMethodBase method, String msg) {
            return method.getStatusCode() == HttpURLConnection.HTTP_FORBIDDEN
                    && "submit not permitted\n".equals(msg); //$NON-NLS-1$
        }

        private boolean isConflict(HttpMethodBase method) {
            return method.getStatusCode() == HttpURLConnection.HTTP_CONFLICT;
        }
    }, monitor);
    return getChangeDetail(id.getParentKey().get(), monitor);
}

From source file:org.eclipse.ecf.provider.filetransfer.httpclient.HttpClientRetrieveFileTransfer.java

private boolean openStreamsForResume() {

    Trace.entering(Activator.PLUGIN_ID, DebugOptions.METHODS_ENTERING, this.getClass(), "openStreamsForResume"); //$NON-NLS-1$
    final String urlString = getRemoteFileURL().toString();
    this.doneFired = false;

    int code = -1;

    try {//  w  w w  .  j a v a2 s.c  om
        initHttpClientConnectionManager();

        CredentialsProvider credProvider = new ECFCredentialsProvider();
        setupAuthentication(urlString);

        setupHostAndPort(credProvider, urlString);

        getMethod = new GzipGetMethod(hostConfigHelper.getTargetRelativePath());
        getMethod.addRequestHeader("Connection", "Keep-Alive"); //$NON-NLS-1$ //$NON-NLS-2$
        getMethod.setFollowRedirects(true);
        // Define a CredentialsProvider - found that possibility while debugging in org.apache.commons.httpclient.HttpMethodDirector.processProxyAuthChallenge(HttpMethod)
        // Seems to be another way to select the credentials.
        getMethod.getParams().setParameter(CredentialsProvider.PROVIDER, credProvider);
        setResumeRequestHeaderValues();

        Trace.trace(Activator.PLUGIN_ID, "resume=" + urlString); //$NON-NLS-1$

        // Gzip encoding is not an option for resume
        fireConnectStartEvent();
        if (checkAndHandleDone()) {
            return false;
        }

        connectingSockets.clear();
        // Actually execute get and get response code (since redirect is set to true, then
        // redirect response code handled internally
        if (connectJob == null) {
            performConnect(new NullProgressMonitor());
        } else {
            connectJob.schedule();
            connectJob.join();
            connectJob = null;
        }
        if (checkAndHandleDone()) {
            return false;
        }

        code = responseCode;

        responseHeaders = getResponseHeaders();

        Trace.trace(Activator.PLUGIN_ID, "retrieve resp=" + code); //$NON-NLS-1$

        if (code == HttpURLConnection.HTTP_PARTIAL || code == HttpURLConnection.HTTP_OK) {
            getResumeResponseHeaderValues();
            setInputStream(getMethod.getResponseBodyAsUnzippedStream());
            this.paused = false;
            fireReceiveResumedEvent();
        } else if (code == HttpURLConnection.HTTP_NOT_FOUND) {
            getMethod.releaseConnection();
            throw new IncomingFileTransferException(NLS.bind("File not found: {0}", urlString), code, //$NON-NLS-1$
                    responseHeaders);
        } else if (code == HttpURLConnection.HTTP_UNAUTHORIZED) {
            getMethod.releaseConnection();
            throw new IncomingFileTransferException(Messages.HttpClientRetrieveFileTransfer_Unauthorized, code,
                    responseHeaders);
        } else if (code == HttpURLConnection.HTTP_FORBIDDEN) {
            getMethod.releaseConnection();
            throw new IncomingFileTransferException("Forbidden", code, responseHeaders); //$NON-NLS-1$
        } else if (code == HttpURLConnection.HTTP_PROXY_AUTH) {
            getMethod.releaseConnection();
            throw new IncomingFileTransferException(Messages.HttpClientRetrieveFileTransfer_Proxy_Auth_Required,
                    code, responseHeaders);
        } else {
            getMethod.releaseConnection();
            throw new IncomingFileTransferException(
                    NLS.bind(Messages.HttpClientRetrieveFileTransfer_ERROR_GENERAL_RESPONSE_CODE,
                            new Integer(code)),
                    code, responseHeaders);
        }
        Trace.exiting(Activator.PLUGIN_ID, DebugOptions.METHODS_EXITING, this.getClass(),
                "openStreamsForResume", Boolean.TRUE); //$NON-NLS-1$
        return true;
    } catch (final Exception e) {
        Trace.catching(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_CATCHING, this.getClass(),
                "openStreamsForResume", e); //$NON-NLS-1$
        if (code == -1) {
            if (!isDone()) {
                setDoneException(e);
            }
        } else {
            setDoneException((e instanceof IncomingFileTransferException) ? e
                    : new IncomingFileTransferException(
                            NLS.bind(Messages.HttpClientRetrieveFileTransfer_EXCEPTION_COULD_NOT_CONNECT,
                                    urlString),
                            e, code, responseHeaders));
        }
        fireTransferReceiveDoneEvent();
        Trace.exiting(Activator.PLUGIN_ID, DebugOptions.METHODS_EXITING, this.getClass(),
                "openStreamsForResume", Boolean.FALSE); //$NON-NLS-1$
        return false;
    }
}

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.  ja  v  a2 s. c om

        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$
}