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.hono.service.AbstractProtocolAdapterBase.java

private Future<String> getGatewayId(final String tenantId, final String deviceId,
        final Device authenticatedDevice) {

    final Future<String> result = Future.future();
    if (authenticatedDevice == null) {
        result.complete(null);//from www . j av a2  s.c om
    } else if (tenantId.equals(authenticatedDevice.getTenantId())) {
        if (deviceId.equals(authenticatedDevice.getDeviceId())) {
            result.complete(null);
        } else {
            result.complete(authenticatedDevice.getDeviceId());
        }
    } else {
        result.fail(new ClientErrorException(HttpURLConnection.HTTP_FORBIDDEN,
                "cannot publish data for device of other tenant"));
    }
    return result;
}

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

public void authenticate(IProgressMonitor monitor) throws CoreException {
    if (loggedIn || (!hasAuthenticationCredentials() && !hasHTTPAuthenticationCredentials())) {
        return;//from  ww  w .j ava2  s.  c  om
    }

    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.oclc.os.SRW.SRWServlet.java

/**
 * respond to the ?list command.//from   w w  w . ja  v  a 2 s .  co m
 * if enableList is set, we list the engine config. If it isnt, then an
 * error is written out
 * @param response
 * @throws AxisFault, IOException
 */
protected void processListRequest(HttpServletResponse response) throws AxisFault, IOException {
    AxisEngine engine = getEngine();
    if (enableList) {
        Document doc = Admin.listConfig(engine);
        if (doc != null) {
            response.setContentType("text/xml");
            PrintWriter writer = response.getWriter();
            XMLUtils.DocumentToWriter(doc, writer);
            writer.close();
        } else {
            //error code is 404
            response.setStatus(HttpURLConnection.HTTP_NOT_FOUND);
            response.setContentType("text/html");
            PrintWriter writer = response.getWriter();
            writer.println("<h2>" + Messages.getMessage("error00") + "</h2>");
            writer.println("<p>" + Messages.getMessage("noDeploy00") + "</p>");
            writer.close();
        }
    } else {
        // list not enable, return error
        //error code is, what, 401
        response.setStatus(HttpURLConnection.HTTP_FORBIDDEN);
        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();
        writer.println("<h2>" + Messages.getMessage("error00") + "</h2>");
        writer.println("<p><i>?list</i> " + Messages.getMessage("disabled00") + "</p>");
        writer.close();
    }
}

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

public void publishComments(String reviewId, int patchSetId, final String message,
        final Set<ApprovalCategoryValue.Id> approvals, IProgressMonitor monitor) throws GerritException {
    final PatchSet.Id id = new PatchSet.Id(new Change.Id(id(reviewId)), patchSetId);
    ReviewInput reviewInput = new ReviewInput(message);
    Map<String, CommentInfo[]> drafts = listDrafts(id, monitor);
    Map<String, CommentInput[]> comments = convert(drafts);
    if (!comments.isEmpty()) {
        reviewInput.setComments(comments);
    }//  w  w w.  j a v a2 s.c  om
    reviewInput.setApprovals(approvals);
    final String uri = "/a/changes/" + id.getParentKey().get() + "/revisions/" + id.get() + "/review"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    executePostRestRequest(uri, reviewInput, ReviewInfo.class, new ErrorHandler() {

        @Override
        public void handleError(HttpMethodBase method) throws GerritException {
            if (method.getStatusCode() == HttpURLConnection.HTTP_FORBIDDEN) {
                String msg = getResponseBodyAsString(method);
                if (msg.startsWith("Applying label") && msg.endsWith("is restricted")) { //$NON-NLS-1$ //$NON-NLS-2$
                    throw new GerritException(msg);
                }
            }
        }

        private String getResponseBodyAsString(HttpMethodBase method) {
            try {
                String msg = method.getResponseBodyAsString();
                return msg.trim();
            } catch (IOException e) {
                // ignore
            }
            return null;
        }
    }, monitor);
}

From source file:org.apache.hadoop.fs.http.server.TestHttpFSServer.java

@Test
@TestDir/*from   w  w w.java 2 s . c  om*/
@TestJetty
@TestHdfs
public void testDelegationTokenOperations() throws Exception {
    createHttpFSServer(true);

    URL url = new URL(TestJettyHelper.getJettyURL(), "/webhdfs/v1/?op=GETHOMEDIRECTORY");
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode());

    AuthenticationToken token = new AuthenticationToken("u", "p",
            new KerberosDelegationTokenAuthenticationHandler().getType());
    token.setExpires(System.currentTimeMillis() + 100000000);
    SignerSecretProvider secretProvider = StringSignerSecretProviderCreator.newStringSignerSecretProvider();
    Properties secretProviderProps = new Properties();
    secretProviderProps.setProperty(AuthenticationFilter.SIGNATURE_SECRET, "secret");
    secretProvider.init(secretProviderProps, null, -1);
    Signer signer = new Signer(secretProvider);
    String tokenSigned = signer.sign(token.toString());

    url = new URL(TestJettyHelper.getJettyURL(), "/webhdfs/v1/?op=GETHOMEDIRECTORY");
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestProperty("Cookie", AuthenticatedURL.AUTH_COOKIE + "=" + tokenSigned);
    Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());

    url = new URL(TestJettyHelper.getJettyURL(), "/webhdfs/v1/?op=GETDELEGATIONTOKEN");
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestProperty("Cookie", AuthenticatedURL.AUTH_COOKIE + "=" + tokenSigned);
    Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());

    JSONObject json = (JSONObject) new JSONParser().parse(new InputStreamReader(conn.getInputStream()));
    json = (JSONObject) json.get(DelegationTokenAuthenticator.DELEGATION_TOKEN_JSON);
    String tokenStr = (String) json.get(DelegationTokenAuthenticator.DELEGATION_TOKEN_URL_STRING_JSON);

    url = new URL(TestJettyHelper.getJettyURL(), "/webhdfs/v1/?op=GETHOMEDIRECTORY&delegation=" + tokenStr);
    conn = (HttpURLConnection) url.openConnection();
    Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());

    url = new URL(TestJettyHelper.getJettyURL(), "/webhdfs/v1/?op=RENEWDELEGATIONTOKEN&token=" + tokenStr);
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("PUT");
    Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, conn.getResponseCode());

    url = new URL(TestJettyHelper.getJettyURL(), "/webhdfs/v1/?op=RENEWDELEGATIONTOKEN&token=" + tokenStr);
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("PUT");
    conn.setRequestProperty("Cookie", AuthenticatedURL.AUTH_COOKIE + "=" + tokenSigned);
    Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());

    url = new URL(TestJettyHelper.getJettyURL(), "/webhdfs/v1/?op=CANCELDELEGATIONTOKEN&token=" + tokenStr);
    conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("PUT");
    Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());

    url = new URL(TestJettyHelper.getJettyURL(), "/webhdfs/v1/?op=GETHOMEDIRECTORY&delegation=" + tokenStr);
    conn = (HttpURLConnection) url.openConnection();
    Assert.assertEquals(HttpURLConnection.HTTP_FORBIDDEN, conn.getResponseCode());
}

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

protected void openStreams() throws IncomingFileTransferException {

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

    int code = -1;

    try {//from   w ww. j a  va  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.
        setRequestHeaderValues();

        Trace.trace(Activator.PLUGIN_ID, "retrieve=" + urlString); //$NON-NLS-1$
        // Set request header for possible gzip encoding, but only if
        // 1) The file range specification is null (we want the whole file)
        // 2) The target remote file does *not* end in .gz (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=280205)
        if (getFileRangeSpecification() == null && !targetHasGzSuffix(super.getRemoteFileName())) {
            Trace.trace(Activator.PLUGIN_ID, "Accept-Encoding: gzip,deflate added to request header"); //$NON-NLS-1$

            // Add the interceptors to provide the gzip 
            httpClient.addRequestInterceptor(new RequestAcceptEncoding());
            httpClient.addResponseInterceptor(new ResponseContentEncoding());
        } else {
            Trace.trace(Activator.PLUGIN_ID, "Accept-Encoding NOT added to header"); //$NON-NLS-1$
        }

        fireConnectStartEvent();
        if (checkAndHandleDone()) {
            return;
        }

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

        code = responseCode;

        responseHeaders = getResponseHeaders();

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

        // Check for NTLM proxy in response headers 
        // This check is to deal with bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=252002
        boolean ntlmProxyFound = NTLMProxyDetector.detectNTLMProxy(httpContext);
        if (ntlmProxyFound && !hasForceNTLMProxyOption())
            throw new IncomingFileTransferException(
                    "HttpClient Provider is not configured to support NTLM proxy authentication.", //$NON-NLS-1$
                    HttpClientOptions.NTLM_PROXY_RESPONSE_CODE);

        if (NTLMProxyDetector.detectSPNEGOProxy(httpContext))
            throw new BrowseFileTransferException(
                    "HttpClient Provider does not support the use of SPNEGO proxy authentication."); //$NON-NLS-1$

        if (code == HttpURLConnection.HTTP_PARTIAL || code == HttpURLConnection.HTTP_OK) {
            getResponseHeaderValues();
            setInputStream(httpResponse.getEntity().getContent());
            fireReceiveStartEvent();
        } 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$
        } else if (code == HttpURLConnection.HTTP_UNAUTHORIZED) {
            EntityUtils.consume(httpResponse.getEntity());
            throw new IncomingFileTransferException(Messages.HttpClientRetrieveFileTransfer_Unauthorized, code);
        } else if (code == HttpURLConnection.HTTP_FORBIDDEN) {
            EntityUtils.consume(httpResponse.getEntity());
            throw new IncomingFileTransferException("Forbidden", code); //$NON-NLS-1$
        } else if (code == HttpURLConnection.HTTP_PROXY_AUTH) {
            EntityUtils.consume(httpResponse.getEntity());
            throw new IncomingFileTransferException(Messages.HttpClientRetrieveFileTransfer_Proxy_Auth_Required,
                    code);
        } else {
            Trace.trace(Activator.PLUGIN_ID, EntityUtils.toString(httpResponse.getEntity()));
            //            EntityUtils.consume(httpResponse.getEntity());
            throw new IncomingFileTransferException(
                    NLS.bind(Messages.HttpClientRetrieveFileTransfer_ERROR_GENERAL_RESPONSE_CODE,
                            new Integer(code)),
                    code);
        }
    } catch (final Exception e) {
        Trace.throwing(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_THROWING, this.getClass(), "openStreams", //$NON-NLS-1$
                e);
        if (code == -1) {
            if (!isDone()) {
                setDoneException(e);
            }
            fireTransferReceiveDoneEvent();
        } else {
            IncomingFileTransferException ex = (IncomingFileTransferException) ((e instanceof IncomingFileTransferException)
                    ? e
                    : new IncomingFileTransferException(
                            NLS.bind(Messages.HttpClientRetrieveFileTransfer_EXCEPTION_COULD_NOT_CONNECT,
                                    urlString),
                            e, code));
            throw ex;
        }
    }
    Trace.exiting(Activator.PLUGIN_ID, DebugOptions.METHODS_EXITING, this.getClass(), "openStreams"); //$NON-NLS-1$
}

From source file:org.eclipse.orion.server.tests.servlets.files.CoreFilesTest.java

/**
 * Tests that we are not allowed to get metadata files
 *///from  ww w  .j av  a  2s  . c  om
@Test
public void testGetForbiddenFiles() throws IOException, SAXException, BackingStoreException {
    //enable global anonymous read
    IEclipsePreferences prefs = InstanceScope.INSTANCE.getNode(ServerConstants.PREFERENCE_SCOPE);
    String oldValue = prefs.get(ServerConstants.CONFIG_FILE_ANONYMOUS_READ, null);
    prefs.put(ServerConstants.CONFIG_FILE_ANONYMOUS_READ, "true");
    prefs.flush();
    try {
        //should not be allowed to get at file root
        WebRequest request = getGetRequest("file/");
        setAuthentication(request);
        WebResponse response = webConversation.getResponse(request);
        assertEquals("Should not be able to get the root", HttpURLConnection.HTTP_FORBIDDEN,
                response.getResponseCode());

        //should not be allowed to access the metadata directory
        request = getGetRequest("file/" + ".metadata");
        setAuthentication(request);
        response = webConversation.getResponse(request);
        assertEquals("Should not be able to get metadata", HttpURLConnection.HTTP_FORBIDDEN,
                response.getResponseCode());

        //should not be allowed to read specific metadata files
        request = getGetRequest(
                "file/" + ".metadata/.plugins/org.eclipse.orion.server.user.securestorage/user_store");
        setAuthentication(request);
        response = webConversation.getResponse(request);
        assertEquals("Should not be able to get metadata", HttpURLConnection.HTTP_FORBIDDEN,
                response.getResponseCode());
    } finally {
        //reset the preference we messed with for the test
        if (oldValue == null)
            prefs.remove(ServerConstants.CONFIG_FILE_ANONYMOUS_READ);
        else
            prefs.put(ServerConstants.CONFIG_FILE_ANONYMOUS_READ, oldValue);
        prefs.flush();
    }
}

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

protected void openStreams() throws IncomingFileTransferException {

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

    int code = -1;

    try {//from w w  w.  jav a 2 s .  c  o  m
        initHttpClientConnectionManager();
        setupAuthentication(urlString);

        CredentialsProvider credProvider = new ECFCredentialsProvider();
        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);
        setRequestHeaderValues();

        Trace.trace(Activator.PLUGIN_ID, "retrieve=" + urlString); //$NON-NLS-1$
        // Set request header for possible gzip encoding, but only if
        // 1) The file range specification is null (we want the whole file)
        // 2) The target remote file does *not* end in .gz (see bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=280205)
        if (getFileRangeSpecification() == null && !targetHasGzSuffix(super.getRemoteFileName())) {
            Trace.trace(Activator.PLUGIN_ID, "Accept-Encoding: gzip added to request header"); //$NON-NLS-1$
            getMethod.setRequestHeader(GzipGetMethod.ACCEPT_ENCODING, GzipGetMethod.CONTENT_ENCODING_ACCEPTED);
        } else {
            Trace.trace(Activator.PLUGIN_ID, "Accept-Encoding NOT added to header"); //$NON-NLS-1$
        }

        fireConnectStartEvent();
        if (checkAndHandleDone()) {
            return;
        }

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

        code = responseCode;

        responseHeaders = getResponseHeaders();

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

        // Check for NTLM proxy in response headers 
        // This check is to deal with bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=252002
        boolean ntlmProxyFound = NTLMProxyDetector.detectNTLMProxy(getMethod);
        if (ntlmProxyFound && !hasForceNTLMProxyOption())
            throw new IncomingFileTransferException(
                    "HttpClient Provider is not configured to support NTLM proxy authentication.", //$NON-NLS-1$
                    HttpClientOptions.NTLM_PROXY_RESPONSE_CODE);

        if (code == HttpURLConnection.HTTP_PARTIAL || code == HttpURLConnection.HTTP_OK) {
            getResponseHeaderValues();
            setInputStream(getMethod.getResponseBodyAsUnzippedStream());
            fireReceiveStartEvent();
        } else if (code == HttpURLConnection.HTTP_NOT_FOUND) {
            getMethod.releaseConnection();
            throw new IncomingFileTransferException(NLS.bind("File not found: {0}", urlString), code); //$NON-NLS-1$
        } else if (code == HttpURLConnection.HTTP_UNAUTHORIZED) {
            getMethod.releaseConnection();
            throw new IncomingFileTransferException(Messages.HttpClientRetrieveFileTransfer_Unauthorized, code);
        } else if (code == HttpURLConnection.HTTP_FORBIDDEN) {
            getMethod.releaseConnection();
            throw new IncomingFileTransferException("Forbidden", code); //$NON-NLS-1$
        } else if (code == HttpURLConnection.HTTP_PROXY_AUTH) {
            getMethod.releaseConnection();
            throw new IncomingFileTransferException(Messages.HttpClientRetrieveFileTransfer_Proxy_Auth_Required,
                    code);
        } else {
            getMethod.releaseConnection();
            throw new IncomingFileTransferException(
                    NLS.bind(Messages.HttpClientRetrieveFileTransfer_ERROR_GENERAL_RESPONSE_CODE,
                            new Integer(code)),
                    code);
        }
    } catch (final Exception e) {
        Trace.throwing(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_THROWING, this.getClass(), "openStreams", //$NON-NLS-1$
                e);
        if (code == -1) {
            if (!isDone()) {
                setDoneException(e);
            }
            fireTransferReceiveDoneEvent();
        } else {
            IncomingFileTransferException ex = (IncomingFileTransferException) ((e instanceof IncomingFileTransferException)
                    ? e
                    : new IncomingFileTransferException(
                            NLS.bind(Messages.HttpClientRetrieveFileTransfer_EXCEPTION_COULD_NOT_CONNECT,
                                    urlString),
                            e, code));
            throw ex;
        }
    }
    Trace.exiting(Activator.PLUGIN_ID, DebugOptions.METHODS_EXITING, this.getClass(), "openStreams"); //$NON-NLS-1$
}

From source file:com.bugclipse.fogbugz.api.client.FogBugzClient.java

private void authenticate()
        throws FogBugzClientException, HttpException, IOException, MarshalException, ValidationException {
    // WebClientUtil.setupHttpClient(httpClient, proxy, repositoryUrl, null,
    // null);//from  w w  w.j  a  va  2  s .c  o m
    if (!hasAuthenticationCredentials()) {
        throw new FogBugzClientException("No authentication credentials!");
    }

    // try standard basic/digest authentication first
    Credentials credentials = new UsernamePasswordCredentials(username, password);
    httpClient.getState().setCredentials(
            new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM), credentials);

    GetMethod method = new GetMethod(WebClientUtil
            .getRequestPath(repositoryUrl + "/api.asp?cmd=logon&email=" + username + "&password=" + password));
    method.setFollowRedirects(false);
    int code;
    try {
        httpClient.getParams().setAuthenticationPreemptive(true);
        code = httpClient.executeMethod(method);
        if (code == HttpURLConnection.HTTP_UNAUTHORIZED || code == HttpURLConnection.HTTP_FORBIDDEN) {
            throw new FogBugzClientException("Session might have expired!");
        }
        Response r = unmarshalResponse(method);
        authenticated = true;
        token = r.getToken();
    } finally {
        method.releaseConnection();
        httpClient.getParams().setAuthenticationPreemptive(false);
    }

    // the expected return code is a redirect, anything else is suspicious
    if (code == HttpURLConnection.HTTP_OK) {
        // try form-based authentication via AccountManagerPlugin as a
        // fall-back
        // authenticateAccountManager(httpClient);
    }

    // validateAuthenticationState(httpClient);

    // success since no exception was thrown

}

From source file:org.apache.hadoop.security.token.delegation.web.TestWebDelegationToken.java

@Test
public void testProxyUser() throws Exception {
    final Server jetty = createJettyServer();
    Context context = new Context();
    context.setContextPath("/foo");
    jetty.setHandler(context);/*from www  . ja  v a  2s.c  om*/
    context.addFilter(new FilterHolder(PseudoDTAFilter.class), "/*", 0);
    context.addServlet(new ServletHolder(UserServlet.class), "/bar");

    try {
        jetty.start();
        final URL url = new URL(getJettyURL() + "/foo/bar");

        // proxyuser using raw HTTP, verifying doAs is case insensitive
        String strUrl = String.format("%s?user.name=%s&doas=%s", url.toExternalForm(), FOO_USER, OK_USER);
        HttpURLConnection conn = (HttpURLConnection) new URL(strUrl).openConnection();
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
        List<String> ret = IOUtils.readLines(conn.getInputStream());
        Assert.assertEquals(1, ret.size());
        Assert.assertEquals(OK_USER, ret.get(0));
        strUrl = String.format("%s?user.name=%s&DOAS=%s", url.toExternalForm(), FOO_USER, OK_USER);
        conn = (HttpURLConnection) new URL(strUrl).openConnection();
        Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
        ret = IOUtils.readLines(conn.getInputStream());
        Assert.assertEquals(1, ret.size());
        Assert.assertEquals(OK_USER, ret.get(0));

        UserGroupInformation ugi = UserGroupInformation.createRemoteUser(FOO_USER);
        ugi.doAs(new PrivilegedExceptionAction<Void>() {
            @Override
            public Void run() throws Exception {
                DelegationTokenAuthenticatedURL.Token token = new DelegationTokenAuthenticatedURL.Token();
                DelegationTokenAuthenticatedURL aUrl = new DelegationTokenAuthenticatedURL();

                // proxyuser using authentication handler authentication
                HttpURLConnection conn = aUrl.openConnection(url, token, OK_USER);
                Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
                List<String> ret = IOUtils.readLines(conn.getInputStream());
                Assert.assertEquals(1, ret.size());
                Assert.assertEquals(OK_USER, ret.get(0));

                // unauthorized proxy user using authentication handler authentication
                conn = aUrl.openConnection(url, token, FAIL_USER);
                Assert.assertEquals(HttpURLConnection.HTTP_FORBIDDEN, conn.getResponseCode());

                // proxy using delegation token authentication
                aUrl.getDelegationToken(url, token, FOO_USER);

                UserGroupInformation ugi = UserGroupInformation.getCurrentUser();
                ugi.addToken(token.getDelegationToken());
                token = new DelegationTokenAuthenticatedURL.Token();

                // requests using delegation token as auth do not honor doAs
                conn = aUrl.openConnection(url, token, OK_USER);
                Assert.assertEquals(HttpURLConnection.HTTP_OK, conn.getResponseCode());
                ret = IOUtils.readLines(conn.getInputStream());
                Assert.assertEquals(1, ret.size());
                Assert.assertEquals(FOO_USER, ret.get(0));

                return null;
            }
        });
    } finally {
        jetty.stop();
    }
}