Example usage for org.apache.commons.httpclient HttpMethod getPath

List of usage examples for org.apache.commons.httpclient HttpMethod getPath

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod getPath.

Prototype

public abstract String getPath();

Source Link

Usage

From source file:ir.keloud.android.lib.common.KeloudClient.java

@Override
public int executeMethod(HttpMethod method) throws IOException, HttpException {
    try { // just to log 
        boolean customRedirectionNeeded = false;

        try {/*  w ww .ja  va2  s .c o m*/
            method.setFollowRedirects(mFollowRedirects);
        } catch (Exception e) {
            /*
             if (mFollowRedirects) 
               Log_OC.d(TAG, "setFollowRedirects failed for " + method.getName() 
            + " method, custom redirection will be used if needed");
            */
            customRedirectionNeeded = mFollowRedirects;
        }

        // Update User Agent
        HttpParams params = method.getParams();
        String userAgent = KeloudClientManagerFactory.getUserAgent();
        params.setParameter(HttpMethodParams.USER_AGENT, userAgent);

        Log_OC.d(TAG + " #" + mInstanceNumber, "REQUEST " + method.getName() + " " + method.getPath());

        //           logCookiesAtRequest(method.getRequestHeaders(), "before");
        //           logCookiesAtState("before");

        int status = super.executeMethod(method);

        if (customRedirectionNeeded) {
            status = patchRedirection(status, method);
        }

        //           logCookiesAtRequest(method.getRequestHeaders(), "after");
        //           logCookiesAtState("after");
        //           logSetCookiesAtResponse(method.getResponseHeaders());

        return status;

    } catch (IOException e) {
        Log_OC.d(TAG + " #" + mInstanceNumber, "Exception occurred", e);
        throw e;
    }
}

From source file:com.twinsoft.convertigo.beans.connectors.HttpConnector.java

private byte[] executeMethod(HttpMethod method, final Context context)
        throws IOException, URIException, MalformedURLException, EngineException {
    Header[] requestHeaders, responseHeaders = null;
    byte[] result = null;
    String contents = null;/*from  w  ww .java 2 s.  c om*/
    int statuscode = -1;

    if (!context.requestedObject.runningThread.bContinue)
        return null;

    Engine.logBeans
            .debug("(HttpConnector) Executing method - " + method.getName() + "(" + method.getPath() + ")");

    try {
        requestHeaders = method.getRequestHeaders();
        if (Engine.logBeans.isTraceEnabled())
            Engine.logBeans
                    .trace("(HttpConnector) Request headers :\n" + Arrays.asList(requestHeaders).toString());

        statuscode = doExecuteMethod(method, context);

        Engine.logBeans.debug("(HttpConnector) Status: " + method.getStatusLine().toString());

        responseHeaders = method.getResponseHeaders();
        context.setResponseHeaders(responseHeaders);
        if (Engine.logBeans.isTraceEnabled())
            Engine.logBeans
                    .trace("(HttpConnector) Response headers:\n" + Arrays.asList(responseHeaders).toString());

        if (statuscode != -1) {
            InputStream in = method.getResponseBodyAsStream();
            if (in != null) {

                /**
                 * Retrieve response charset if available in responseHeaders
                 */
                charset = null;
                boolean checkGZip = false; // add GZip support #320

                for (int i = 0; i < responseHeaders.length && (charset == null || !checkGZip); i++) {
                    Header head = responseHeaders[i];
                    if (HeaderName.ContentType.is(head)) {
                        context.contentType = head.getValue();
                        HeaderElement[] els = head.getElements();
                        for (int j = 0; j < els.length && charset == null; j++) {
                            NameValuePair nvp = els[j].getParameterByName("charset");
                            if (nvp != null)
                                charset = nvp.getValue();
                        }
                    } else if (HeaderName.ContentEncoding.is(head)) {
                        checkGZip = true;
                        HeaderElement[] els = head.getElements();
                        for (int j = 0; j < els.length; j++)
                            if ("gzip".equals(els[j].getName())) {
                                Engine.logBeans.debug("(HttpConnector) Decode GZip stream");
                                in = new GZIPInputStream(in);
                            }
                    }
                }

                if (context.contentType != null && context.contentType.startsWith("multipart/")
                        && context.requestedObject instanceof AbstractHttpTransaction) {
                    Engine.logBeans.debug("(HttpConnector) Decoding multipart contentType");

                    try {
                        AbstractHttpTransaction transaction = (AbstractHttpTransaction) context.requestedObject;

                        BigMimeMultipart mp = new BigMimeMultipart(new BufferedInputStream(in),
                                context.contentType);

                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        mp.nextPart(bos);
                        result = bos.toByteArray();

                        if (transaction.getAllowDownloadAttachment()) {
                            Document doc = context.outputDocument;
                            Element attInfo = null;

                            File file = File.createTempFile("c8o_", ".part");

                            for (MimePart bp = mp.nextPart(file); bp != null; bp = mp.nextPart(file)) {
                                try {
                                    file.deleteOnExit();

                                    if (attInfo == null) {
                                        Engine.logBeans.debug("(HttpConnector) Saving attachment(s)");

                                        attInfo = doc.createElement("AttachmentInfo");
                                        doc.getDocumentElement().appendChild(attInfo);
                                    }

                                    Element att = doc.createElement("attachment");
                                    attInfo.appendChild(att);

                                    String cid = bp.getContentID();

                                    if (cid != null) {
                                        cid = cid.replaceFirst("^<?(.*?)>?$", "$1");
                                        att.setAttribute("cid", "cid:" + cid);
                                    }

                                    Engine.logBeans.debug("(HttpConnector) Saving the attachment cid: " + cid
                                            + " in file: " + file.getAbsolutePath());

                                    att.setAttribute("filepath", file.getAbsolutePath());

                                    Enumeration<javax.mail.Header> headers = GenericUtils
                                            .cast(bp.getAllHeaders());
                                    while (headers.hasMoreElements()) {
                                        javax.mail.Header header = headers.nextElement();
                                        Element eHeader = doc.createElement("header");
                                        att.appendChild(eHeader);

                                        eHeader.setAttribute("name", header.getName());
                                        eHeader.setAttribute("value", header.getValue());
                                    }
                                } catch (Exception e1) {
                                    Engine.logBeans
                                            .error("(HttpConnector) Failed to retrieve the attachment in "
                                                    + file.getAbsolutePath(), e1);
                                }

                                file = File.createTempFile("c8o_", ".part");
                            }

                            file.delete();
                            in.close();
                        }
                    } catch (Exception e) {
                        Engine.logBeans.error("(HttpConnector) Failed to retrieve attachments", e);
                    }
                } else {
                    result = IOUtils.toByteArray(in);
                    in.close();
                }
            }

            if (Engine.logBeans.isTraceEnabled()) {
                contents = new String((result != null) ? result : new byte[] {});
                Engine.logBeans.trace("(HttpConnector) Response content:\n" + contents);
            }

            String redirectUrl, newuri;
            GetMethod redirectMethod = null;

            // Handles REDIRECTION through Location header
            if ((statuscode == HttpStatus.SC_MOVED_TEMPORARILY)
                    || (statuscode == HttpStatus.SC_MOVED_PERMANENTLY)
                    || (statuscode == HttpStatus.SC_SEE_OTHER)
                    || (statuscode == HttpStatus.SC_TEMPORARY_REDIRECT)) {

                Header location = method.getResponseHeader("Location");
                if (location != null) {
                    newuri = location.getValue();
                    if ((newuri == null) || (newuri.equals(""))) {
                        newuri = "/";
                    }

                    // ignore any data after the ";" character
                    int split = newuri.indexOf(';');
                    if (split != -1) {
                        newuri = newuri.substring(0, split);
                    }

                    redirectUrl = getAbsoluteUrl(method, newuri);
                    Engine.logBeans.debug("(HttpConnector) Redirecting to : " + redirectUrl);
                    redirectMethod = new GetMethod(redirectUrl);

                    // set headers
                    for (int i = 0; i < requestHeaders.length; i++)
                        redirectMethod.setRequestHeader(requestHeaders[i]);

                    referer = redirectUrl.startsWith("http") ? redirectUrl
                            : (hostConfiguration.getHostURL() + redirectUrl);

                    result = executeMethod(redirectMethod, context); // recurse
                } else {
                    Engine.logBeans.debug("(HttpConnector) Invalid redirect!");
                }
            } else {
                /*
                 * String lwContents = contents.toLowerCase(); int index, i,
                 * j, k, z; // Handles REDIRECTION through META Refresh if
                 * (((index = lwContents.indexOf("http-equiv='refresh'")) !=
                 * -1) || ((index =
                 * lwContents.indexOf("http-equiv=\"refresh\"")) != -1)) {
                 * if ((i = lwContents.indexOf("content=", index + 20)) !=
                 * -1) { char c = lwContents.charAt(i+8); if ((j =
                 * lwContents.indexOf("url=", i)) != -1) { if ((k =
                 * lwContents.indexOf(c, j + 1)) != -1) { newuri =
                 * lwContents.substring(j+4, k); redirectUrl =
                 * getAbsoluteUrl(method,newuri);
                 * Engine.logBeans.debug("(HttpConnector) Redirecting to : "
                 * + redirectUrl); redirectMethod = new
                 * GetMethod(redirectUrl);
                 * 
                 * // set headers for (z=0; z<requestHeaders.length; z++)
                 * redirectMethod.setRequestHeader(requestHeaders[z]);
                 * 
                 * referer = redirectUrl; result =
                 * executeMethod(redirectMethod, context); // recurse } } }
                 * } // Handles FRAMESET else if
                 * (lwContents.indexOf("frameset") != -1) {
                 * Engine.logBeans.debug
                 * ("(HttpConnector) Analyzing frameset...");
                 * StringTokenizer st = new StringTokenizer(lwContents);
                 * StringEx newcontents = new StringEx(lwContents); while
                 * (st.hasMoreTokens()) { String token = st.nextToken();
                 * String uri; if (token.startsWith("src=")) { if
                 * ((token.indexOf("\"") != -1) || (token.indexOf("'") !=
                 * -1)) { token = token.substring(5); uri =
                 * token.substring(0,token.length()-1); newuri =
                 * getAbsoluteUrl(method,uri);
                 * Engine.logBeans.trace("(HttpConnector) Replaced uri ("+
                 * uri +") with newuri("+ newuri +")");
                 * 
                 * newcontents.replaceAll(token,newuri); } } }
                 * Engine.logBeans
                 * .trace("(HttpConnector) New response content:\n"+
                 * newcontents); result = newcontents.toString().getBytes();
                 * }
                 */
            }
        }
        //Added by julienda - #3433 - 04/03/2013
        AbstractHttpTransaction abstractHttpTransaction = (AbstractHttpTransaction) context.transaction;

        if (abstractHttpTransaction.getHttpInfo()) {
            Document doc = context.outputDocument;

            //Remove the node HTTPInfo if we have a redirect
            NodeList nodeList = XMLUtils.findElements(context.outputDocument.getDocumentElement(),
                    abstractHttpTransaction.getHttpInfoTagName());
            if (nodeList != null) {
                XMLUtils.removeNodeListContent(nodeList);
            }

            //Parent Element
            httpInfoElement = doc.createElement(abstractHttpTransaction.getHttpInfoTagName());

            //Add requested URL
            Element urlElement = doc.createElement("url");
            urlElement.setTextContent(method.getURI().toString());
            httpInfoElement.appendChild(urlElement);

            //Add status code
            Element httpStatusElement = doc.createElement("status");

            httpStatusElement.setAttribute("code", Integer.toString(statuscode));
            httpStatusElement.setAttribute("text", method.getStatusText());
            httpInfoElement.appendChild(httpStatusElement);

            //We add headers informations

            List<Header> headers = Arrays.asList(requestHeaders);
            if (!headers.isEmpty()) {
                Element httpHeadersElement = doc.createElement("headers");

                for (int i = 0; i < headers.size(); i++) {
                    Element elt = doc.createElement("header");
                    elt.setAttribute("name", headers.get(i).getName());
                    elt.setAttribute("value", headers.get(i).getValue());
                    httpHeadersElement.appendChild(elt);
                }
                httpInfoElement.appendChild(httpHeadersElement);
            }

            // we add response header information
            if (responseHeaders.length != 0) {
                Element httpHeadersElement = doc.createElement("responseHeaders");

                for (int i = 0; i < responseHeaders.length; i++) {
                    Element elt = doc.createElement("header");
                    elt.setAttribute("name", responseHeaders[i].getName());
                    elt.setAttribute("value", responseHeaders[i].getValue());
                    httpHeadersElement.appendChild(elt);
                }
                httpInfoElement.appendChild(httpHeadersElement);
            }

            doc.getDocumentElement().appendChild(httpInfoElement);
        }
    } finally {
        method.releaseConnection();
    }

    return result;
}

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

@Override
protected void buildSessionInfo(HttpMethod method) throws DavMailException {
    // no need to check logon method body
    if (method != null) {
        method.releaseConnection();/*from  w  w w.  j a v  a2  s. co m*/
    }
    boolean directEws = method == null || "/ews/services.wsdl".equalsIgnoreCase(method.getPath());

    // options page is not available in direct EWS mode
    if (!directEws) {
        // retrieve email and alias from options page
        getEmailAndAliasFromOptions();
    }

    if (email == null || alias == null) {
        // OWA authentication failed, get email address from login
        if (userName.indexOf('@') >= 0) {
            // userName is email address
            email = userName;
            alias = userName.substring(0, userName.indexOf('@'));
        } else {
            // userName or domain\\username, rebuild email address
            alias = getAliasFromLogin();
            email = getAliasFromLogin() + getEmailSuffixFromHostname();
        }
    }

    currentMailboxPath = "/users/" + email.toLowerCase();

    // check EWS access
    try {
        checkEndPointUrl("/ews/exchange.asmx");
        // workaround for Exchange bug: send fake request
        internalGetFolder("");
    } catch (IOException e) {
        // first failover: retry with NTLM
        DavGatewayHttpClientFacade.addNTLM(httpClient);
        try {
            checkEndPointUrl("/ews/exchange.asmx");
            // workaround for Exchange bug: send fake request
            internalGetFolder("");
        } catch (IOException e2) {
            LOGGER.debug(e2.getMessage());
            try {
                // failover, try to retrieve EWS url from autodiscover
                checkEndPointUrl(getEwsUrlFromAutoDiscover());
                // workaround for Exchange bug: send fake request
                internalGetFolder("");
            } catch (IOException e3) {
                // autodiscover failed and initial exception was authentication failure => throw original exception
                if (e instanceof DavMailAuthenticationException) {
                    throw (DavMailAuthenticationException) e;
                }
                LOGGER.error(e2.getMessage());
                throw new DavMailAuthenticationException("EXCEPTION_EWS_NOT_AVAILABLE");
            }
        }
    }

    // enable preemptive authentication on non NTLM endpoints
    if (!DavGatewayHttpClientFacade.hasNTLM(httpClient)) {
        httpClient.getParams().setParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, true);
    }

    // direct EWS: get primary smtp email address with ResolveNames
    if (directEws) {
        try {
            ResolveNamesMethod resolveNamesMethod = new ResolveNamesMethod(alias);
            executeMethod(resolveNamesMethod);
            List<EWSMethod.Item> responses = resolveNamesMethod.getResponseItems();
            for (EWSMethod.Item response : responses) {
                if (alias.equalsIgnoreCase(response.get("Name"))) {
                    email = response.get("EmailAddress");
                    currentMailboxPath = "/users/" + email.toLowerCase();
                }
            }
        } catch (IOException e) {
            LOGGER.warn("Unable to get primary email address with ResolveNames", e);
        }
    }

    try {
        folderIdMap = new HashMap<String, String>();
        // load actual well known folder ids
        folderIdMap.put(internalGetFolder(INBOX).folderId.value, INBOX);
        folderIdMap.put(internalGetFolder(CALENDAR).folderId.value, CALENDAR);
        folderIdMap.put(internalGetFolder(CONTACTS).folderId.value, CONTACTS);
        folderIdMap.put(internalGetFolder(SENT).folderId.value, SENT);
        folderIdMap.put(internalGetFolder(DRAFTS).folderId.value, DRAFTS);
        folderIdMap.put(internalGetFolder(TRASH).folderId.value, TRASH);
        folderIdMap.put(internalGetFolder(JUNK).folderId.value, JUNK);
        folderIdMap.put(internalGetFolder(UNSENT).folderId.value, UNSENT);
    } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
        throw new DavMailAuthenticationException("EXCEPTION_EWS_NOT_AVAILABLE");
    }
    LOGGER.debug("Current user email is " + email + ", alias is " + alias + " on " + serverVersion);
}

From source file:io.hops.hopsworks.api.jobs.JobService.java

/**
 * Get the job ui for the specified job.
 * This act as a proxy to get the job ui from yarn
 * <p>/* w w w . j a v  a 2 s.  c o m*/
 * @param appId
 * @param param
 * @param sc
 * @param req
 * @return
 */
@GET
@Path("/{appId}/prox/{path: .+}")
@Produces(MediaType.WILDCARD)
@AllowedProjectRoles({ AllowedProjectRoles.DATA_OWNER, AllowedProjectRoles.DATA_SCIENTIST })
public Response getProxy(@PathParam("appId") final String appId, @PathParam("path") final String param,
        @Context SecurityContext sc, @Context HttpServletRequest req) {

    Response response = checkAccessRight(appId);
    if (response != null) {
        return response;
    }
    try {
        String trackingUrl;
        if (param.matches("http([a-zA-Z,:,/,.,0-9,-])+:([0-9])+(.)+")) {
            trackingUrl = param;
        } else {
            trackingUrl = "http://" + param;
        }
        trackingUrl = trackingUrl.replace("@hwqm", "?");
        if (!hasAppAccessRight(trackingUrl)) {
            LOGGER.log(Level.SEVERE, "A user is trying to access an app outside their project!");
            return Response.status(Response.Status.FORBIDDEN).build();
        }
        org.apache.commons.httpclient.URI uri = new org.apache.commons.httpclient.URI(trackingUrl, false);

        HttpClientParams params = new HttpClientParams();
        params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
        HttpClient client = new HttpClient(params);

        final HttpMethod method = new GetMethod(uri.getEscapedURI());
        Enumeration<String> names = req.getHeaderNames();
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            String value = req.getHeader(name);
            if (PASS_THROUGH_HEADERS.contains(name)) {
                //yarn does not send back the js if encoding is not accepted
                //but we don't want to accept encoding for the html because we
                //need to be able to parse it
                if (!name.toLowerCase().equals("accept-encoding") || trackingUrl.contains(".js")) {
                    method.setRequestHeader(name, value);
                }
            }
        }
        String user = req.getRemoteUser();
        if (user != null && !user.isEmpty()) {
            method.setRequestHeader("Cookie", PROXY_USER_COOKIE_NAME + "=" + URLEncoder.encode(user, "ASCII"));
        }

        client.executeMethod(method);
        Response.ResponseBuilder responseBuilder = noCacheResponse
                .getNoCacheResponseBuilder(Response.Status.OK);
        for (Header header : method.getResponseHeaders()) {
            responseBuilder.header(header.getName(), header.getValue());
        }
        //method.getPath().contains("/allexecutors") is needed to replace the links under Executors tab
        //which are in a json response object
        if (method.getResponseHeader("Content-Type") == null
                || method.getResponseHeader("Content-Type").getValue().contains("html")
                || method.getPath().contains("/allexecutors")) {
            final String source = "http://" + method.getURI().getHost() + ":" + method.getURI().getPort();
            if (method.getResponseHeader("Content-Length") == null) {
                responseBuilder.entity(new StreamingOutput() {
                    @Override
                    public void write(OutputStream out) throws IOException, WebApplicationException {
                        Writer writer = new BufferedWriter(new OutputStreamWriter(out));
                        InputStream stream = method.getResponseBodyAsStream();
                        Reader in = new InputStreamReader(stream, "UTF-8");
                        char[] buffer = new char[4 * 1024];
                        String remaining = "";
                        int n;
                        while ((n = in.read(buffer)) != -1) {
                            StringBuilder strb = new StringBuilder();
                            strb.append(buffer, 0, n);
                            String s = remaining + strb.toString();
                            remaining = s.substring(s.lastIndexOf(">") + 1, s.length());
                            s = hopify(s.substring(0, s.lastIndexOf(">") + 1), param, appId, source);
                            writer.write(s);
                        }
                        writer.flush();
                    }
                });
            } else {
                String s = hopify(method.getResponseBodyAsString(), param, appId, source);
                responseBuilder.entity(s);
                responseBuilder.header("Content-Length", s.length());
            }

        } else {
            responseBuilder.entity(new StreamingOutput() {
                @Override
                public void write(OutputStream out) throws IOException, WebApplicationException {
                    InputStream stream = method.getResponseBodyAsStream();
                    org.apache.hadoop.io.IOUtils.copyBytes(stream, out, 4096, true);
                    out.flush();
                }
            });
        }
        return responseBuilder.build();
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, "exception while geting job ui " + e.getLocalizedMessage(), e);
        return noCacheResponse.getNoCacheResponseBuilder(Response.Status.NOT_FOUND).build();
    }

}

From source file:davmail.exchange.ExchangeSession.java

protected String getAbsoluteUri(HttpMethod method, String path) throws URIException {
    URI uri = method.getURI();/*  ww w.ja va 2 s . c  om*/
    if (path != null) {
        // reset query string
        uri.setQuery(null);
        if (path.startsWith("/")) {
            // path is absolute, replace method path
            uri.setPath(path);
        } else if (path.startsWith("http://") || path.startsWith("https://")) {
            return path;
        } else {
            // relative path, build new path
            String currentPath = method.getPath();
            int end = currentPath.lastIndexOf('/');
            if (end >= 0) {
                uri.setPath(currentPath.substring(0, end + 1) + path);
            } else {
                throw new URIException(uri.getURI());
            }
        }
    }
    return uri.getURI();
}

From source file:davmail.exchange.dav.DavExchangeSession.java

/**
 * Exchange 2003: get mailPath from welcome page
 *
 * @param method current http method//w ww  .j a v  a  2 s .  c o  m
 * @return mail path from body
 */
protected String getMailpathFromWelcomePage(HttpMethod method) {
    String welcomePageMailPath = null;
    // get user mail URL from html body (multi frame)
    BufferedReader mainPageReader = null;
    try {
        mainPageReader = new BufferedReader(new InputStreamReader(method.getResponseBodyAsStream()));
        //noinspection StatementWithEmptyBody
        String line;
        while ((line = mainPageReader.readLine()) != null && line.toLowerCase().indexOf(BASE_HREF) == -1) {
        }
        if (line != null) {
            // Exchange 2003
            int start = line.toLowerCase().indexOf(BASE_HREF) + BASE_HREF.length();
            int end = line.indexOf('\"', start);
            String mailBoxBaseHref = line.substring(start, end);
            URL baseURL = new URL(mailBoxBaseHref);
            welcomePageMailPath = URIUtil.decode(baseURL.getPath());
            LOGGER.debug("Base href found in body, mailPath is " + welcomePageMailPath);
        }
    } catch (IOException e) {
        LOGGER.error("Error parsing main page at " + method.getPath(), e);
    } finally {
        if (mainPageReader != null) {
            try {
                mainPageReader.close();
            } catch (IOException e) {
                LOGGER.error("Error parsing main page at " + method.getPath());
            }
        }
        method.releaseConnection();
    }
    return welcomePageMailPath;
}

From source file:davmail.exchange.ExchangeSession.java

/**
 * Create an exchange session for the given URL.
 * The session is established for given userName and password
 *
 * @param url      Exchange url/* w  ww . j  a  v  a2 s .c  o  m*/
 * @param userName user login name
 * @param password user password
 * @throws IOException on error
 */
public ExchangeSession(String url, String userName, String password) throws IOException {
    this.userName = userName;
    try {
        httpClient = DavGatewayHttpClientFacade.getInstance(url);
        // set private connection pool
        DavGatewayHttpClientFacade.createMultiThreadedHttpConnectionManager(httpClient);
        boolean isBasicAuthentication = isBasicAuthentication(httpClient, url);
        // clear cookies created by authentication test
        httpClient.getState().clearCookies();

        // The user may have configured an OTP pre-auth username. It is processed
        // so early because OTP pre-auth may disappear in the Exchange LAN and this
        // helps the user to not change is account settings in mail client at each network change.
        if (preAuthUsername == null) {
            // Searches for the delimiter in configured username for the pre-auth user. 
            // The double-quote is not allowed inside email addresses anyway.
            int doubleQuoteIndex = this.userName.indexOf('"');
            if (doubleQuoteIndex > 0) {
                preAuthUsername = this.userName.substring(0, doubleQuoteIndex);
                this.userName = this.userName.substring(doubleQuoteIndex + 1);
            } else {
                // No doublequote: the pre-auth user is the full username, or it is not used at all.
                preAuthUsername = this.userName;
            }
        }

        DavGatewayHttpClientFacade.setCredentials(httpClient, userName, password);

        // get webmail root url
        // providing credentials
        // manually follow redirect
        HttpMethod method = DavGatewayHttpClientFacade.executeFollowRedirects(httpClient, url);

        if (!this.isAuthenticated()) {
            if (isBasicAuthentication) {
                int status = method.getStatusCode();

                if (status == HttpStatus.SC_UNAUTHORIZED) {
                    method.releaseConnection();
                    throw new DavMailAuthenticationException("EXCEPTION_AUTHENTICATION_FAILED");
                } else if (status != HttpStatus.SC_OK) {
                    method.releaseConnection();
                    throw DavGatewayHttpClientFacade.buildHttpException(method);
                }
                // workaround for basic authentication on /exchange and form based authentication at /owa
                if ("/owa/auth/logon.aspx".equals(method.getPath())) {
                    method = formLogin(httpClient, method, userName, password);
                }
            } else {
                method = formLogin(httpClient, method, userName, password);
            }
        }

        // avoid 401 roundtrips, only if NTLM is disabled and basic authentication enabled
        if (isBasicAuthentication && !DavGatewayHttpClientFacade.hasNTLM(httpClient)) {
            httpClient.getParams().setParameter(HttpClientParams.PREEMPTIVE_AUTHENTICATION, true);
        }

        buildSessionInfo(method);

    } catch (DavMailAuthenticationException exc) {
        LOGGER.error(exc.getMessage());
        throw exc;
    } catch (UnknownHostException exc) {
        BundleMessage message = new BundleMessage("EXCEPTION_CONNECT", exc.getClass().getName(),
                exc.getMessage());
        ExchangeSession.LOGGER.error(message);
        throw new DavMailException("EXCEPTION_DAVMAIL_CONFIGURATION", message);
    } catch (WebdavNotAvailableException exc) {
        throw exc;
    } catch (IOException exc) {
        LOGGER.error(BundleMessage.formatLog("EXCEPTION_EXCHANGE_LOGIN_FAILED", exc));
        throw new DavMailException("EXCEPTION_EXCHANGE_LOGIN_FAILED", exc);
    }
    LOGGER.debug("Session " + this + " created");
}

From source file:davmail.exchange.ExchangeSession.java

protected HttpMethod postLogonMethod(HttpClient httpClient, HttpMethod logonMethod, String userName,
        String password) throws IOException {

    setAuthFormFields(logonMethod, httpClient, password);

    // add exchange 2010 PBack cookie in compatibility mode
    httpClient.getState()/*from  w w w.  ja  v  a2 s  . co m*/
            .addCookie(new Cookie(httpClient.getHostConfiguration().getHost(), "PBack", "0", "/", null, false));

    logonMethod = DavGatewayHttpClientFacade.executeFollowRedirects(httpClient, logonMethod);

    // test form based authentication
    checkFormLoginQueryString(logonMethod);

    // workaround for post logon script redirect
    if (!isAuthenticated()) {
        // try to get new method from script based redirection
        logonMethod = buildLogonMethod(httpClient, logonMethod);

        if (otpPreAuthFound && otpPreAuthRetries < MAX_OTP_RETRIES) {
            // A OTP pre-auth page has been found, it is needed to restart the login process.
            // This applies to both the case the user entered a good OTP code (the usual login process
            // takes place) and the case the user entered a wrong OTP code (another code will be asked to him).
            // The user has up to MAX_OTP_RETRIES chances to input a valid OTP key.
            return postLogonMethod(httpClient, logonMethod, userName, password);
        }

        if (logonMethod != null) {
            // if logonMethod is not null, try to follow redirection
            logonMethod = DavGatewayHttpClientFacade.executeFollowRedirects(httpClient, logonMethod);
            checkFormLoginQueryString(logonMethod);
            // also check cookies
            if (!isAuthenticated()) {
                throwAuthenticationFailed();
            }
        } else {
            // authentication failed
            throwAuthenticationFailed();
        }
    }

    // check for language selection form
    if (logonMethod != null && "/owa/languageselection.aspx".equals(logonMethod.getPath())) {
        // need to submit form
        logonMethod = submitLanguageSelectionForm(logonMethod);
    }
    return logonMethod;
}

From source file:org.alfresco.encryption.DefaultEncryptionUtils.java

/**
 * {@inheritDoc}/*from  w ww.  j  av a  2  s .c  o m*/
 */
@Override
public void setRequestAuthentication(HttpMethod method, byte[] message) throws IOException {
    long requestTimestamp = System.currentTimeMillis();

    // add MAC header
    byte[] mac = macUtils.generateMAC(KeyProvider.ALIAS_SOLR,
            new MACInput(message, requestTimestamp, getLocalIPAddress()));

    if (logger.isDebugEnabled()) {
        logger.debug("Setting MAC " + Arrays.toString(mac) + " on HTTP request " + method.getPath());
        logger.debug("Setting timestamp " + requestTimestamp + " on HTTP request " + method.getPath());
    }

    setRequestMac(method, mac);

    // prevent replays
    setRequestTimestamp(method, requestTimestamp);
}

From source file:org.alfresco.rest.api.tests.client.AuthenticatedHttp.java

/**
 * Execute the given method, authenticated as the given user using Basic Authentication.
 * @param method method to execute/*  w w w  .  jav  a 2  s . c  o  m*/
 * @param userName name of user to authenticate (note: if null then attempts to run with no authentication - eq. Quick/Shared Link test)
 * @param callback called after http-call is executed. When callback returns, the 
 *  response stream is closed, so all respose-related operations should be done in the callback. Can be null.
 * @return result returned by the callback or null if no callback is given.
 */
private <T extends Object> T executeWithBasicAuthentication(HttpMethod method, String userName, String password,
        HttpRequestCallback<T> callback) {
    try {
        HttpState state = new HttpState();

        if (userName != null) {
            state.setCredentials(new AuthScope(null, AuthScope.ANY_PORT),
                    new UsernamePasswordCredentials(userName, password));
        }

        httpProvider.getHttpClient().executeMethod(null, method, state);

        if (callback != null) {
            return callback.onCallSuccess(method);
        }

        // No callback used, return null
        return null;
    } catch (Throwable t) {
        boolean handled = false;

        // Delegate to callback to handle error. If not available, throw exception
        if (callback != null) {
            handled = callback.onError(method, t);
        }

        if (!handled) {
            throw new RuntimeException("Error while executing HTTP-call (" + method.getPath() + ")", t);
        }

        return null;
    } finally {
        method.releaseConnection();
    }
}