Example usage for java.net HttpURLConnection HTTP_PROXY_AUTH

List of usage examples for java.net HttpURLConnection HTTP_PROXY_AUTH

Introduction

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

Prototype

int HTTP_PROXY_AUTH

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

Click Source Link

Document

HTTP Status-Code 407: Proxy Authentication Required.

Usage

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

protected void runRequest() throws Exception {
    Trace.entering(Activator.PLUGIN_ID, DebugOptions.METHODS_ENTERING, this.getClass(), "runRequest"); //$NON-NLS-1$
    setupProxies();//from  www  .j a v a  2s  . c  o  m
    // set timeout
    initHttpClientConnectionManager();

    String urlString = directoryOrFile.toString();
    CredentialsProvider credProvider = new HttpClientProxyCredentialProvider() {

        protected Proxy getECFProxy() {
            return getProxy();
        }

        protected Credentials getNTLMCredentials(Proxy lp) {
            if (hasForceNTLMProxyOption())
                return HttpClientRetrieveFileTransfer.createNTLMCredentials(lp);
            return null;
        }

    };
    // setup authentication
    setupAuthentication(urlString);
    // setup https host and port
    setupHostAndPort(credProvider, urlString);

    headMethod = new HeadMethod(hostConfigHelper.getTargetRelativePath());
    headMethod.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.
    headMethod.getParams().setParameter(CredentialsProvider.PROVIDER, credProvider);
    // set max-age for cache control to 0 for bug https://bugs.eclipse.org/bugs/show_bug.cgi?id=249990
    headMethod.addRequestHeader("Cache-Control", "max-age=0"); //$NON-NLS-1$//$NON-NLS-2$
    headMethod.addRequestHeader("Connection", "Keep-Alive"); //$NON-NLS-1$ //$NON-NLS-2$

    long lastModified = 0;
    long fileLength = -1;
    connectingSockets.clear();
    int code = -1;
    try {
        Trace.trace(Activator.PLUGIN_ID, "browse=" + urlString); //$NON-NLS-1$

        code = httpClient.executeMethod(getHostConfiguration(), headMethod);

        Trace.trace(Activator.PLUGIN_ID, "browse 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(headMethod);
        if (ntlmProxyFound && !hasForceNTLMProxyOption())
            throw new BrowseFileTransferException(
                    "HttpClient Provider is not configured to support NTLM proxy authentication.", //$NON-NLS-1$
                    HttpClientOptions.NTLM_PROXY_RESPONSE_CODE);

        if (code == HttpURLConnection.HTTP_OK) {
            fileLength = headMethod.getResponseContentLength();
            lastModified = getLastModifiedTimeFromHeader();
        } else if (code == HttpURLConnection.HTTP_NOT_FOUND) {
            throw new BrowseFileTransferException(NLS.bind("File not found: {0}", urlString), code); //$NON-NLS-1$
        } else if (code == HttpURLConnection.HTTP_UNAUTHORIZED) {
            throw new BrowseFileTransferException(Messages.HttpClientRetrieveFileTransfer_Unauthorized, code);
        } else if (code == HttpURLConnection.HTTP_FORBIDDEN) {
            throw new BrowseFileTransferException("Forbidden", code); //$NON-NLS-1$
        } else if (code == HttpURLConnection.HTTP_PROXY_AUTH) {
            throw new BrowseFileTransferException(Messages.HttpClientRetrieveFileTransfer_Proxy_Auth_Required,
                    code);
        } else {
            throw new BrowseFileTransferException(
                    NLS.bind(Messages.HttpClientRetrieveFileTransfer_ERROR_GENERAL_RESPONSE_CODE,
                            new Integer(code)),
                    code);
        }
        remoteFiles = new IRemoteFile[1];
        remoteFiles[0] = new URLRemoteFile(lastModified, fileLength, fileID);
    } catch (Exception e) {
        Trace.throwing(Activator.PLUGIN_ID, DebugOptions.EXCEPTIONS_THROWING, this.getClass(), "runRequest", e); //$NON-NLS-1$
        BrowseFileTransferException ex = (BrowseFileTransferException) ((e instanceof BrowseFileTransferException)
                ? e
                : new BrowseFileTransferException(NLS
                        .bind(Messages.HttpClientRetrieveFileTransfer_EXCEPTION_COULD_NOT_CONNECT, urlString),
                        e, code));
        throw ex;
    } finally {
        headMethod.releaseConnection();
    }
}

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 ww  w  . j  a  v 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: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 {/*from  ww  w.  j  a  va2  s  . com*/
        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.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 . ja  v a2  s  . 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.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 {// w w w.  j  a  va 2  s . c  om
        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.eclipse.mylyn.internal.bugzilla.core.BugzillaClient.java

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

    for (int attempt = 0; attempt < 2; attempt++) {
        // force authentication
        authenticate(monitor);/*from   ww w.  ja  v  a2s. c  o  m*/

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

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

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

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

        getMethod.setDoAuthentication(true);

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

    }

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

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

public void authenticate(IProgressMonitor monitor) throws CoreException {
    if (loggedIn || (!hasAuthenticationCredentials() && !hasHTTPAuthenticationCredentials())) {
        return;//from   ww w. ja  v  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

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 ww  .  j a  v  a  2s  . 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$
}