Example usage for org.apache.http.client.methods HttpRequestBase setURI

List of usage examples for org.apache.http.client.methods HttpRequestBase setURI

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpRequestBase setURI.

Prototype

public void setURI(final URI uri) 

Source Link

Usage

From source file:com.groupon.odo.bmp.http.BrowserMobHttpClient.java

private BrowserMobHttpResponse execute(BrowserMobHttpRequest req, int depth) {
    if (depth >= MAX_REDIRECT) {
        throw new IllegalStateException("Max number of redirects (" + MAX_REDIRECT + ") reached");
    }//w  ww .j  ava2s . com

    RequestCallback callback = req.getRequestCallback();

    HttpRequestBase method = req.getMethod();
    String verificationText = req.getVerificationText();
    String url = method.getURI().toString();

    // save the browser and version if it's not yet been set
    if (har != null && har.getLog().getBrowser() == null) {
        Header[] uaHeaders = method.getHeaders("User-Agent");
        if (uaHeaders != null && uaHeaders.length > 0) {
            String userAgent = uaHeaders[0].getValue();
            try {
                // note: this doesn't work for 'Fandango/4.5.1 CFNetwork/548.1.4 Darwin/11.0.0'
                ReadableUserAgent uai = PARSER.parse(userAgent);
                String browser = uai.getName();
                String version = uai.getVersionNumber().toVersionString();
                har.getLog().setBrowser(new HarNameVersion(browser, version));
            } catch (Exception e) {
                LOG.warn("Failed to parse user agent string", e);
            }
        }
    }

    // process any rewrite requests
    boolean rewrote = false;
    String newUrl = url;
    for (RewriteRule rule : rewriteRules) {
        Matcher matcher = rule.match.matcher(newUrl);
        newUrl = matcher.replaceAll(rule.replace);
        rewrote = true;
    }

    if (rewrote) {
        try {
            method.setURI(new URI(newUrl));
            url = newUrl;
        } catch (URISyntaxException e) {
            LOG.warn("Could not rewrite url to %s", newUrl);
        }
    }

    // handle whitelist and blacklist entries
    int mockResponseCode = -1;
    synchronized (this) {
        // guard against concurrent modification of whitelistEntry
        if (whitelistEntry != null) {
            boolean found = false;
            for (Pattern pattern : whitelistEntry.patterns) {
                if (pattern.matcher(url).matches()) {
                    found = true;
                    break;
                }
            }

            if (!found) {
                mockResponseCode = whitelistEntry.responseCode;
            }
        }
    }

    if (blacklistEntries != null) {
        for (BlacklistEntry blacklistEntry : blacklistEntries) {
            if (blacklistEntry.pattern.matcher(url).matches()) {
                mockResponseCode = blacklistEntry.responseCode;
                break;
            }
        }
    }

    if (!additionalHeaders.isEmpty()) {
        // Set the additional headers
        for (Map.Entry<String, String> entry : additionalHeaders.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            method.removeHeaders(key);
            method.addHeader(key, value);
        }
    }

    String charSet = "UTF-8";
    String responseBody = null;

    InputStream is = null;
    int statusCode = -998;
    long bytes = 0;
    boolean gzipping = false;
    boolean contentMatched = true;
    OutputStream os = req.getOutputStream();
    if (os == null) {
        os = new CappedByteArrayOutputStream(1024 * 1024); // MOB-216 don't buffer more than 1 MB
    }
    if (verificationText != null) {
        contentMatched = false;
    }

    // link the object up now, before we make the request, so that if we get cut off (ie: favicon.ico request and browser shuts down)
    // we still have the attempt associated, even if we never got a response
    HarEntry entry = new HarEntry(harPageRef);

    // clear out any connection-related information so that it's not stale from previous use of this thread.
    RequestInfo.clear(url, entry);

    entry.setRequest(new HarRequest(method.getMethod(), url, method.getProtocolVersion().getProtocol()));
    entry.setResponse(new HarResponse(-999, "NO RESPONSE", method.getProtocolVersion().getProtocol()));
    if (this.har != null && harPageRef != null) {
        har.getLog().addEntry(entry);
    }

    String query = method.getURI().getRawQuery();
    if (query != null) {
        MultiMap<String> params = new MultiMap<String>();
        UrlEncoded.decodeTo(query, params, "UTF-8");
        for (String k : params.keySet()) {
            for (Object v : params.getValues(k)) {
                entry.getRequest().getQueryString().add(new HarNameValuePair(k, (String) v));
            }
        }
    }

    String errorMessage = null;
    HttpResponse response = null;

    BasicHttpContext ctx = new BasicHttpContext();

    ActiveRequest activeRequest = new ActiveRequest(method, ctx, entry.getStartedDateTime());
    synchronized (activeRequests) {
        activeRequests.add(activeRequest);
    }

    // for dealing with automatic authentication
    if (authType == AuthType.NTLM) {
        // todo: not supported yet
        //ctx.setAttribute("preemptive-auth", new NTLMScheme(new JCIFSEngine()));
    } else if (authType == AuthType.BASIC) {
        ctx.setAttribute("preemptive-auth", new BasicScheme());
    }

    StatusLine statusLine = null;
    try {
        // set the User-Agent if it's not already set
        if (method.getHeaders("User-Agent").length == 0) {
            method.addHeader("User-Agent", "BrowserMob VU/1.0");
        }

        // was the request mocked out?
        if (mockResponseCode != -1) {
            statusCode = mockResponseCode;

            // TODO: HACKY!!
            callback.handleHeaders(new Header[] { new Header() {
                @Override
                public String getName() {
                    return "Content-Type";
                }

                @Override
                public String getValue() {
                    return "text/plain";
                }

                @Override
                public HeaderElement[] getElements() throws ParseException {
                    return new HeaderElement[0];
                }
            } });
            // Make sure we set the status line here too.
            // Use the version number from the request
            ProtocolVersion version = null;
            int reqDotVersion = req.getProxyRequest().getDotVersion();
            if (reqDotVersion == -1) {
                version = new HttpVersion(0, 9);
            } else if (reqDotVersion == 0) {
                version = new HttpVersion(1, 0);
            } else if (reqDotVersion == 1) {
                version = new HttpVersion(1, 1);
            }
            // and if not any of these, trust that a Null version will
            // cause an appropriate error
            callback.handleStatusLine(
                    new BasicStatusLine(version, statusCode, "Status set by browsermob-proxy"));
            // No mechanism to look up the response text by status code,
            // so include a notification that this is a synthetic error code.
        } else {
            response = httpClient.execute(method, ctx);
            statusLine = response.getStatusLine();
            statusCode = statusLine.getStatusCode();

            if (callback != null) {
                callback.handleStatusLine(statusLine);
                callback.handleHeaders(response.getAllHeaders());
            }

            if (response.getEntity() != null) {
                is = response.getEntity().getContent();
            }

            // check for null (resp 204 can cause HttpClient to return null, which is what Google does with http://clients1.google.com/generate_204)
            if (is != null) {
                Header contentEncodingHeader = response.getFirstHeader("Content-Encoding");
                if (contentEncodingHeader != null
                        && "gzip".equalsIgnoreCase(contentEncodingHeader.getValue())) {
                    gzipping = true;
                }

                // deal with GZIP content!
                if (decompress && gzipping) {
                    is = new GZIPInputStream(is);
                }

                if (captureContent) {
                    // todo - something here?
                    os = new ClonedOutputStream(os);
                }

                bytes = copyWithStats(is, os);
            }
        }
    } catch (Exception e) {
        errorMessage = e.toString();

        if (callback != null) {
            callback.reportError(e);
        }

        // only log it if we're not shutdown (otherwise, errors that happen during a shutdown can likely be ignored)
        if (!shutdown) {
            LOG.info(String.format("%s when requesting %s", errorMessage, url));
        }
    } finally {
        // the request is done, get it out of here
        synchronized (activeRequests) {
            activeRequests.remove(activeRequest);
        }

        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                // this is OK to ignore
            }
        }
    }

    // record the response as ended
    RequestInfo.get().finish();

    // set the start time and other timings
    entry.setStartedDateTime(RequestInfo.get().getStart());
    entry.setTimings(RequestInfo.get().getTimings());
    entry.setServerIPAddress(RequestInfo.get().getResolvedAddress());
    entry.setTime(RequestInfo.get().getTotalTime());

    // todo: where you store this in HAR?
    // obj.setErrorMessage(errorMessage);
    entry.getResponse().setBodySize(bytes);
    entry.getResponse().getContent().setSize(bytes);
    entry.getResponse().setStatus(statusCode);
    if (statusLine != null) {
        entry.getResponse().setStatusText(statusLine.getReasonPhrase());
    }

    boolean urlEncoded = false;
    if (captureHeaders || captureContent) {
        for (Header header : method.getAllHeaders()) {
            if (header.getValue() != null && header.getValue().startsWith(URLEncodedUtils.CONTENT_TYPE)) {
                urlEncoded = true;
            }

            entry.getRequest().getHeaders().add(new HarNameValuePair(header.getName(), header.getValue()));
        }

        if (response != null) {
            for (Header header : response.getAllHeaders()) {
                entry.getResponse().getHeaders().add(new HarNameValuePair(header.getName(), header.getValue()));
            }
        }
    }

    if (captureContent) {
        // can we understand the POST data at all?
        if (method instanceof HttpEntityEnclosingRequestBase && req.getCopy() != null) {
            HttpEntityEnclosingRequestBase enclosingReq = (HttpEntityEnclosingRequestBase) method;
            HttpEntity entity = enclosingReq.getEntity();

            HarPostData data = new HarPostData();
            data.setMimeType(req.getMethod().getFirstHeader("Content-Type").getValue());
            entry.getRequest().setPostData(data);

            if (urlEncoded || URLEncodedUtils.isEncoded(entity)) {
                try {
                    final String content = new String(req.getCopy().toByteArray(), "UTF-8");
                    if (content != null && content.length() > 0) {
                        List<NameValuePair> result = new ArrayList<NameValuePair>();
                        URLEncodedUtils.parse(result, new Scanner(content), null);

                        ArrayList<HarPostDataParam> params = new ArrayList<HarPostDataParam>();
                        data.setParams(params);

                        for (NameValuePair pair : result) {
                            params.add(new HarPostDataParam(pair.getName(), pair.getValue()));
                        }
                    }
                } catch (Exception e) {
                    LOG.info("Unexpected problem when parsing input copy", e);
                }
            } else {
                // not URL encoded, so let's grab the body of the POST and capture that
                data.setText(new String(req.getCopy().toByteArray()));
            }
        }
    }

    //capture request cookies
    javax.servlet.http.Cookie[] cookies = req.getProxyRequest().getCookies();
    for (javax.servlet.http.Cookie cookie : cookies) {
        HarCookie hc = new HarCookie();
        hc.setName(cookie.getName());
        hc.setValue(cookie.getValue());
        entry.getRequest().getCookies().add(hc);
    }

    String contentType = null;

    if (response != null) {
        try {
            Header contentTypeHdr = response.getFirstHeader("Content-Type");
            if (contentTypeHdr != null) {
                contentType = contentTypeHdr.getValue();
                entry.getResponse().getContent().setMimeType(contentType);

                if (captureContent && os != null && os instanceof ClonedOutputStream) {
                    ByteArrayOutputStream copy = ((ClonedOutputStream) os).getOutput();

                    if (gzipping) {
                        // ok, we need to decompress it before we can put it in the har file
                        try {
                            InputStream temp = new GZIPInputStream(
                                    new ByteArrayInputStream(copy.toByteArray()));
                            copy = new ByteArrayOutputStream();
                            IOUtils.copy(temp, copy);
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }

                    if (hasTextualContent(contentType)) {
                        setTextOfEntry(entry, copy, contentType);
                    } else if (captureBinaryContent) {
                        setBinaryContentOfEntry(entry, copy);
                    }
                }

                NameValuePair nvp = contentTypeHdr.getElements()[0].getParameterByName("charset");

                if (nvp != null) {
                    charSet = nvp.getValue();
                }
            }

            if (os instanceof ByteArrayOutputStream) {
                responseBody = ((ByteArrayOutputStream) os).toString(charSet);

                if (verificationText != null) {
                    contentMatched = responseBody.contains(verificationText);
                }
            }
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    if (contentType != null) {
        entry.getResponse().getContent().setMimeType(contentType);
    }

    // checking to see if the client is being redirected
    boolean isRedirect = false;

    String location = null;
    if (response != null && statusCode >= 300 && statusCode < 400 && statusCode != 304) {
        isRedirect = true;

        // pulling the header for the redirect
        Header locationHeader = response.getLastHeader("location");
        if (locationHeader != null) {
            location = locationHeader.getValue();
        } else if (this.followRedirects) {
            throw new RuntimeException("Invalid redirect - missing location header");
        }
    }

    //
    // Response validation - they only work if we're not following redirects
    //

    int expectedStatusCode = req.getExpectedStatusCode();

    // if we didn't mock out the actual response code and the expected code isn't what we saw, we have a problem
    if (mockResponseCode == -1 && expectedStatusCode > -1) {
        if (this.followRedirects) {
            throw new RuntimeException("Response validation cannot be used while following redirects");
        }
        if (expectedStatusCode != statusCode) {
            if (isRedirect) {
                throw new RuntimeException("Expected status code of " + expectedStatusCode + " but saw "
                        + statusCode + " redirecting to: " + location);
            } else {
                throw new RuntimeException(
                        "Expected status code of " + expectedStatusCode + " but saw " + statusCode);
            }
        }
    }

    // Location header check:
    if (isRedirect && (req.getExpectedLocation() != null)) {
        if (this.followRedirects) {
            throw new RuntimeException("Response validation cannot be used while following redirects");
        }

        if (location.compareTo(req.getExpectedLocation()) != 0) {
            throw new RuntimeException(
                    "Expected a redirect to  " + req.getExpectedLocation() + " but saw " + location);
        }
    }

    // end of validation logic

    // basic tail recursion for redirect handling
    if (isRedirect && this.followRedirects) {
        // updating location:
        try {
            URI redirectUri = new URI(location);
            URI newUri = method.getURI().resolve(redirectUri);
            method.setURI(newUri);

            return execute(req, ++depth);
        } catch (URISyntaxException e) {
            LOG.warn("Could not parse URL", e);
        }
    }

    return new BrowserMobHttpResponse(entry, method, response, contentMatched, verificationText, errorMessage,
            responseBody, contentType, charSet);
}

From source file:info.ajaxplorer.client.http.RestRequest.java

private HttpResponse issueRequest(URI uri, Map<String, String> postParameters, File file, String fileName,
        AjxpFileBody fileBody) throws Exception {
    URI originalUri = new URI(uri.toString());
    if (RestStateHolder.getInstance().getSECURE_TOKEN() != null) {
        uri = new URI(
                uri.toString().concat("&secure_token=" + RestStateHolder.getInstance().getSECURE_TOKEN()));
    }/*from  w w w.  ja  va  2 s  . c  o  m*/
    //Log.d("RestRequest", "Issuing request : " + uri.toString());
    HttpResponse response = null;
    try {
        HttpRequestBase request;

        if (postParameters != null || file != null) {
            request = new HttpPost();
            if (file != null) {

                if (fileBody == null) {
                    if (fileName == null)
                        fileName = file.getName();
                    fileBody = new AjxpFileBody(file, fileName);
                    ProgressListener origPL = this.uploadListener;
                    Map<String, String> caps = RestStateHolder.getInstance().getServer()
                            .getRemoteCapacities(this);
                    this.uploadListener = origPL;
                    int maxUpload = 0;
                    if (caps != null && caps.containsKey(Server.capacity_UPLOAD_LIMIT))
                        maxUpload = new Integer(caps.get(Server.capacity_UPLOAD_LIMIT));
                    maxUpload = Math.min(maxUpload, 60000000);
                    if (maxUpload > 0 && maxUpload < file.length()) {
                        fileBody.chunkIntoPieces(maxUpload);
                        if (uploadListener != null) {
                            uploadListener.partTransferred(fileBody.getCurrentIndex(),
                                    fileBody.getTotalChunks());
                        }
                    }
                } else {
                    if (uploadListener != null) {
                        uploadListener.partTransferred(fileBody.getCurrentIndex(), fileBody.getTotalChunks());
                    }
                }
                MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                reqEntity.addPart("userfile_0", fileBody);

                if (fileName != null && !EncodingUtils
                        .getAsciiString(EncodingUtils.getBytes(fileName, "US-ASCII")).equals(fileName)) {
                    reqEntity.addPart("urlencoded_filename",
                            new StringBody(java.net.URLEncoder.encode(fileName, "UTF-8")));
                }
                if (fileBody != null && !fileBody.getFilename().equals(fileBody.getRootFilename())) {
                    reqEntity.addPart("appendto_urlencoded_part",
                            new StringBody(java.net.URLEncoder.encode(fileBody.getRootFilename(), "UTF-8")));
                }
                if (postParameters != null) {
                    Iterator<Map.Entry<String, String>> it = postParameters.entrySet().iterator();
                    while (it.hasNext()) {
                        Map.Entry<String, String> entry = it.next();
                        reqEntity.addPart(entry.getKey(), new StringBody(entry.getValue()));
                    }
                }
                if (uploadListener != null) {
                    CountingMultipartRequestEntity countingEntity = new CountingMultipartRequestEntity(
                            reqEntity, uploadListener);
                    ((HttpPost) request).setEntity(countingEntity);
                } else {
                    ((HttpPost) request).setEntity(reqEntity);
                }
            } else {
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(postParameters.size());
                Iterator<Map.Entry<String, String>> it = postParameters.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, String> entry = it.next();
                    nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                ((HttpPost) request).setEntity(new UrlEncodedFormEntity(nameValuePairs));
            }
        } else {
            request = new HttpGet();
        }

        request.setURI(uri);
        if (this.httpUser.length() > 0 && this.httpPassword.length() > 0) {
            request.addHeader("Ajxp-Force-Login", "true");
        }
        response = httpClient.executeInContext(request);
        if (isAuthenticationRequested(response)) {
            sendMessageToHandler(MessageListener.MESSAGE_WHAT_STATE, STATUS_REFRESHING_AUTH);
            this.discardResponse(response);
            this.authenticate();
            if (loginStateChanged) {
                // RELOAD
                loginStateChanged = false;
                sendMessageToHandler(MessageListener.MESSAGE_WHAT_STATE, STATUS_LOADING_DATA);
                if (fileBody != null)
                    fileBody.resetChunkIndex();
                return this.issueRequest(originalUri, postParameters, file, fileName, fileBody);
            }
        } else if (fileBody != null && fileBody.isChunked() && !fileBody.allChunksUploaded()) {
            this.discardResponse(response);
            this.issueRequest(originalUri, postParameters, file, fileName, fileBody);
        }
    } catch (ClientProtocolException e) {
        sendMessageToHandler(MessageListener.MESSAGE_WHAT_ERROR, e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        sendMessageToHandler(MessageListener.MESSAGE_WHAT_ERROR, e.getMessage());
        e.printStackTrace();
    } catch (AuthenticationException e) {
        sendMessageToHandler(MessageListener.MESSAGE_WHAT_ERROR, e.getMessage());
        throw e;
    } catch (Exception e) {
        sendMessageToHandler(MessageListener.MESSAGE_WHAT_ERROR, e.getMessage());
        e.printStackTrace();
    } finally {
        uploadListener = null;
    }
    return response;
}

From source file:com.lonepulse.zombielink.request.QueryParamProcessor.java

/**
 * <p>Accepts the {@link InvocationContext} along with an {@link HttpRequestBase} and creates a 
 * <a href="http://en.wikipedia.org/wiki/Query_string">query string</a> using arguments annotated 
 * with @{@link QueryParam} and @{@link QueryParams}; which is subsequently appended to the URI.</p>
 * //from www . j  av a 2s .c om
 * <p>See {@link AbstractRequestProcessor#process(InvocationContext, HttpRequestBase)}.</p>
 * 
 * @param context
 *          the {@link InvocationContext} which is used to discover annotated query parameters
 * <br><br>
 * @param request
 *          prefers an instance of {@link HttpGet} so as to conform with HTTP 1.1; however, other 
 *          request types will be entertained to allow compliance with unusual endpoint definitions 
 * <br><br>
  * @return the same instance of {@link HttpRequestBase} which was given for processing query parameters
 * <br><br>
 * @throws RequestProcessorException
 *          if the creation of a query string failed due to an unrecoverable errorS
 * <br><br>
 * @since 1.3.0
 */
@Override
protected HttpRequestBase process(InvocationContext context, HttpRequestBase request) {

    try {

        URIBuilder uriBuilder = new URIBuilder(request.getURI());

        //add static name and value pairs
        List<Param> constantQueryParams = RequestUtils.findStaticQueryParams(context);

        for (Param param : constantQueryParams) {

            uriBuilder.setParameter(param.name(), param.value());
        }

        //add individual name and value pairs
        List<Entry<QueryParam, Object>> queryParams = Metadata.onParams(QueryParam.class, context);

        for (Entry<QueryParam, Object> entry : queryParams) {

            String name = entry.getKey().value();
            Object value = entry.getValue();

            if (!(value instanceof CharSequence)) {

                StringBuilder errorContext = new StringBuilder().append("Query parameters can only be of type ")
                        .append(CharSequence.class.getName())
                        .append(". Please consider implementing CharSequence ")
                        .append("and providing a meaningful toString() representation for the ")
                        .append("<name> of the query parameter. ");

                throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString()));
            }

            uriBuilder.setParameter(name, ((CharSequence) value).toString());
        }

        //add batch name and value pairs (along with any static params)
        List<Entry<QueryParams, Object>> queryParamMaps = Metadata.onParams(QueryParams.class, context);

        for (Entry<QueryParams, Object> entry : queryParamMaps) {

            Param[] constantParams = entry.getKey().value();

            if (constantParams != null && constantParams.length > 0) {

                for (Param param : constantParams) {

                    uriBuilder.setParameter(param.name(), param.value());
                }
            }

            Object map = entry.getValue();

            if (!(map instanceof Map)) {

                StringBuilder errorContext = new StringBuilder()
                        .append("@QueryParams can only be applied on <java.util.Map>s. ")
                        .append("Please refactor the method to provide a Map of name and value pairs. ");

                throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString()));
            }

            Map<?, ?> nameAndValues = (Map<?, ?>) map;

            for (Entry<?, ?> nameAndValue : nameAndValues.entrySet()) {

                Object name = nameAndValue.getKey();
                Object value = nameAndValue.getValue();

                if (!(name instanceof CharSequence
                        && (value instanceof CharSequence || value instanceof Collection))) {

                    StringBuilder errorContext = new StringBuilder().append(
                            "The <java.util.Map> identified by @QueryParams can only contain mappings of type ")
                            .append("<java.lang.CharSequence, java.lang.CharSequence> or ")
                            .append("<java.lang.CharSequence, java.util.Collection<? extends CharSequence>>");

                    throw new RequestProcessorException(new IllegalArgumentException(errorContext.toString()));
                }

                if (value instanceof CharSequence) {

                    uriBuilder.addParameter(((CharSequence) name).toString(),
                            ((CharSequence) value).toString());
                } else { //add multi-valued query params 

                    Collection<?> multivalues = (Collection<?>) value;

                    for (Object multivalue : multivalues) {

                        if (!(multivalue instanceof CharSequence)) {

                            StringBuilder errorContext = new StringBuilder().append(
                                    "Values for the <java.util.Map> identified by @QueryParams can only contain collections ")
                                    .append("of type java.util.Collection<? extends CharSequence>");

                            throw new RequestProcessorException(
                                    new IllegalArgumentException(errorContext.toString()));
                        }

                        uriBuilder.addParameter(((CharSequence) name).toString(),
                                ((CharSequence) multivalue).toString());
                    }
                }
            }
        }

        request.setURI(uriBuilder.build());

        return request;
    } catch (Exception e) {

        throw (e instanceof RequestProcessorException) ? (RequestProcessorException) e
                : new RequestProcessorException(context, getClass(), e);
    }
}

From source file:eionet.webq.xforms.XFormsHTTPRequestAuthHandlerImpl.java

@Override
public void addAuthToHttpRequest(HttpRequestBase httpRequestBase, Map<Object, Object> context) {

    String uri = httpRequestBase.getURI().toString();

    String instance = null;/* ww  w. j a  va  2s .  c  o m*/
    String envelope = null;
    String requestURLHost = null;
    Integer fileId = null;
    String authentication = null;
    String sessionId = null;

    if (uri == null) {
        return;
    }

    // load bf context attributes
    if (context.get("instance") != null) {
        instance = (String) context.get("instance");
    }
    if (context.get("envelope") != null) {
        envelope = (String) context.get("envelope");
    }
    if (context.get(BF_REQUEST_URL_ATTRIBUTE) != null) {
        try {
            URI requestURI = new URI((String) context.get(BF_REQUEST_URL_ATTRIBUTE));
            requestURLHost = StringUtils.substringBefore(requestURI.toString(), requestURI.getHost())
                    + requestURI.getHost();
            LOGGER.info("bF requestURLHost= " + requestURLHost);
        } catch (URISyntaxException e) {
            LOGGER.warn("requestURL is not valid URL: " + context.get(BF_REQUEST_URL_ATTRIBUTE));
        }
    }
    if (context.get("fileId") != null) {
        fileId = Integer.valueOf((String) context.get("fileId"));
    }
    // http session attribute stored in betterform context
    if (context.get(BF_HTTP_SESSION_ATTRIBUTE) != null) {
        sessionId = (String) context.get(BF_HTTP_SESSION_ATTRIBUTE);
    }

    LOGGER.info("Get resource from XForm: " + uri);

    if (uri.startsWith(requestURLHost)) {
        // check if the request on the same (webq) host is done in the same session. Fix session id if required.
        if (sessionId != null) {
            validateSessionIdInRequestHeader(context, sessionId);
            LOGGER.info("Get resource from: " + uri);
        }
    } else {
        // add auth info only for URIs that are not on the same host.
        if (fileId != null && sessionId != null) {
            LOGGER.debug("Check if user is logged in to get resource for fileId=" + fileId);
            if (!context.containsKey(WEBQ_AUTH_ATTRIBUTE)) {
                // check if user is logged in - ask auth info from user_xml file table
                UserFile userFile = userFileService.getById(fileId);
                if (userFile.isAuthorized()) {
                    String authorizationInfo = userFile.getAuthorization();
                    String cookiesInfo = userFile.getCookies();
                    if (StringUtils.isNotEmpty(authorizationInfo)) {
                        authentication = "Authorization=" + authorizationInfo;
                    } else if (StringUtils.isNotEmpty(cookiesInfo)) {
                        authentication = "Cookie=" + cookiesInfo;
                    }
                }
                context.put(WEBQ_AUTH_ATTRIBUTE, authentication);
                LOGGER.debug("Store basic auth info in context for fileId=" + fileId);
            } else {
                // auth info stored in context
                authentication = context.get(WEBQ_AUTH_ATTRIBUTE) != null
                        ? (String) context.get(WEBQ_AUTH_ATTRIBUTE)
                        : null;
            }
            // add auth info only if user is logged in
            if (StringUtils.isNotEmpty(authentication)) {
                LOGGER.debug("User is logged in to get resource for fileId=" + fileId);

                String authAttribute = StringUtils.substringBefore(authentication, "=");

                // if the URI starts with instance or envelope URI, then we can use the basic auth retrieved from CDR.
                if (!"Cookie".equals(authAttribute)
                        && ((StringUtils.isNotBlank(instance) && uri.startsWith(instance))
                                || (StringUtils.isNotBlank(envelope) && uri.startsWith(envelope)))) {

                    String authAttributeValues = StringUtils.substringAfter(authentication, "=");
                    // prevent betterForm to overwrite cookies
                    /* Fall back to KnownHosts authorisation (qaaccount) if cookie auth mode is used.
                    // cookie mode does not work on test server.
                    if ("Cookie".equals(authAttribute)) {
                    if (context.containsKey(AbstractHTTPConnector.REQUEST_COOKIE)) {
                        context.remove(AbstractHTTPConnector.REQUEST_COOKIE);
                    }
                    }
                    */
                    httpRequestBase.addHeader(authAttribute, authAttributeValues);
                    LOGGER.info("Add " + authAttribute + " from session to URL: " + uri);
                } else {
                    // check if we have known host in db
                    KnownHost knownHost = knownHostsService.getKnownHost(uri);
                    if (knownHost != null) {
                        // add ticket parameter to request URI if needed
                        if (knownHost
                                .getAuthenticationMethod() == KnownHostAuthenticationMethod.REQUEST_PARAMETER) {
                            LOGGER.info("Add ticket parameter from known hosts to URL: " + uri);
                            uri = getUrlWithAuthParam(uri, knownHost);
                            if (!uri.equals(httpRequestBase.getURI().toString())) {
                                try {
                                    httpRequestBase.setURI(new URI(uri));
                                } catch (URISyntaxException e) {
                                    LOGGER.error("Unable to add known host ticket parameter for URI:" + uri);
                                    e.printStackTrace();
                                }
                            }
                        } else if (knownHost.getAuthenticationMethod() == KnownHostAuthenticationMethod.BASIC) {
                            // Add basic authorisation if needed
                            try {
                                LOGGER.info("Add basic auth from known hosts to URL: " + uri);
                                httpRequestBase.addHeader("Authorization", "Basic " + Base64.encodeBase64String(
                                        (knownHost.getKey() + ":" + knownHost.getTicket()).getBytes("utf-8"))
                                        .replaceAll("\n", ""));
                            } catch (UnsupportedEncodingException e) {
                                LOGGER.warn("UnsupportedEncodingException: utf-8");
                            }
                        }
                    }
                }
            }
        }
    }
}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.HttpRequestFilter.java

@SuppressWarnings("deprecation")
@Override/*w  ww .java  2  s  .  co  m*/
public void filterHttpRequest(SubmitContext context, HttpRequestInterface<?> request) {
    HttpRequestBase httpMethod = (HttpRequestBase) context.getProperty(BaseHttpRequestTransport.HTTP_METHOD);

    String path = PropertyExpander.expandProperties(context, request.getPath());
    StringBuffer query = new StringBuffer();
    String encoding = System.getProperty("soapui.request.encoding", StringUtils.unquote(request.getEncoding()));

    StringToStringMap responseProperties = (StringToStringMap) context
            .getProperty(BaseHttpRequestTransport.RESPONSE_PROPERTIES);

    MimeMultipart formMp = "multipart/form-data".equals(request.getMediaType())
            && httpMethod instanceof HttpEntityEnclosingRequestBase ? new MimeMultipart() : null;

    RestParamsPropertyHolder params = request.getParams();

    for (int c = 0; c < params.getPropertyCount(); c++) {
        RestParamProperty param = params.getPropertyAt(c);

        String value = PropertyExpander.expandProperties(context, param.getValue());
        responseProperties.put(param.getName(), value);

        List<String> valueParts = sendEmptyParameters(request)
                || (!StringUtils.hasContent(value) && param.getRequired())
                        ? RestUtils.splitMultipleParametersEmptyIncluded(value,
                                request.getMultiValueDelimiter())
                        : RestUtils.splitMultipleParameters(value, request.getMultiValueDelimiter());

        // skip HEADER and TEMPLATE parameter encoding (TEMPLATE is encoded by
        // the URI handling further down)
        if (value != null && param.getStyle() != ParameterStyle.HEADER
                && param.getStyle() != ParameterStyle.TEMPLATE && !param.isDisableUrlEncoding()) {
            try {
                if (StringUtils.hasContent(encoding)) {
                    value = URLEncoder.encode(value, encoding);
                    for (int i = 0; i < valueParts.size(); i++)
                        valueParts.set(i, URLEncoder.encode(valueParts.get(i), encoding));
                } else {
                    value = URLEncoder.encode(value);
                    for (int i = 0; i < valueParts.size(); i++)
                        valueParts.set(i, URLEncoder.encode(valueParts.get(i)));
                }
            } catch (UnsupportedEncodingException e1) {
                SoapUI.logError(e1);
                value = URLEncoder.encode(value);
                for (int i = 0; i < valueParts.size(); i++)
                    valueParts.set(i, URLEncoder.encode(valueParts.get(i)));
            }
            // URLEncoder replaces space with "+", but we want "%20".
            value = value.replaceAll("\\+", "%20");
            for (int i = 0; i < valueParts.size(); i++)
                valueParts.set(i, valueParts.get(i).replaceAll("\\+", "%20"));
        }

        if (param.getStyle() == ParameterStyle.QUERY && !sendEmptyParameters(request)) {
            if (!StringUtils.hasContent(value) && !param.getRequired())
                continue;
        }

        switch (param.getStyle()) {
        case HEADER:
            for (String valuePart : valueParts)
                httpMethod.addHeader(param.getName(), valuePart);
            break;
        case QUERY:
            if (formMp == null || !request.isPostQueryString()) {
                for (String valuePart : valueParts) {
                    if (query.length() > 0)
                        query.append('&');

                    query.append(URLEncoder.encode(param.getName()));
                    query.append('=');
                    if (StringUtils.hasContent(valuePart))
                        query.append(valuePart);
                }
            } else {
                try {
                    addFormMultipart(request, formMp, param.getName(), responseProperties.get(param.getName()));
                } catch (MessagingException e) {
                    SoapUI.logError(e);
                }
            }

            break;
        case TEMPLATE:
            try {
                value = getEncodedValue(value, encoding, param.isDisableUrlEncoding(),
                        request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
                path = path.replaceAll("\\{" + param.getName() + "\\}", value == null ? "" : value);
            } catch (UnsupportedEncodingException e) {
                SoapUI.logError(e);
            }
            break;
        case MATRIX:
            try {
                value = getEncodedValue(value, encoding, param.isDisableUrlEncoding(),
                        request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
            } catch (UnsupportedEncodingException e) {
                SoapUI.logError(e);
            }

            if (param.getType().equals(XmlBoolean.type.getName())) {
                if (value.toUpperCase().equals("TRUE") || value.equals("1")) {
                    path += ";" + param.getName();
                }
            } else {
                path += ";" + param.getName();
                if (StringUtils.hasContent(value)) {
                    path += "=" + value;
                }
            }
        case PLAIN:
            break;
        }
    }

    if (request.getSettings().getBoolean(HttpSettings.FORWARD_SLASHES))
        path = PathUtils.fixForwardSlashesInPath(path);

    if (PathUtils.isHttpPath(path)) {
        try {
            // URI(String) automatically URLencodes the input, so we need to
            // decode it first...
            URI uri = new URI(path, request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
            context.setProperty(BaseHttpRequestTransport.REQUEST_URI, uri);
            java.net.URI oldUri = httpMethod.getURI();
            httpMethod.setURI(new java.net.URI(oldUri.getScheme(), oldUri.getUserInfo(), oldUri.getHost(),
                    oldUri.getPort(), (uri.getPath()) == null ? "/" : uri.getPath(), oldUri.getQuery(),
                    oldUri.getFragment()));
        } catch (Exception e) {
            SoapUI.logError(e);
        }
    } else if (StringUtils.hasContent(path)) {
        try {
            java.net.URI oldUri = httpMethod.getURI();
            String pathToSet = StringUtils.hasContent(oldUri.getRawPath()) && !"/".equals(oldUri.getRawPath())
                    ? oldUri.getRawPath() + path
                    : path;
            java.net.URI newUri = URIUtils.createURI(oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(),
                    pathToSet, oldUri.getQuery(), oldUri.getFragment());
            httpMethod.setURI(newUri);
            context.setProperty(BaseHttpRequestTransport.REQUEST_URI,
                    new URI(newUri.toString(), request.getSettings().getBoolean(HttpSettings.ENCODED_URLS)));
        } catch (Exception e) {
            SoapUI.logError(e);
        }
    }

    if (query.length() > 0 && !request.isPostQueryString()) {
        try {
            java.net.URI oldUri = httpMethod.getURI();
            httpMethod.setURI(URIUtils.createURI(oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(),
                    oldUri.getRawPath(), query.toString(), oldUri.getFragment()));
        } catch (Exception e) {
            SoapUI.logError(e);
        }
    }

    if (request instanceof RestRequest) {
        String acceptEncoding = ((RestRequest) request).getAccept();
        if (StringUtils.hasContent(acceptEncoding)) {
            httpMethod.setHeader("Accept", acceptEncoding);
        }
    }

    if (formMp != null) {
        // create request message
        try {
            if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) {
                String requestContent = PropertyExpander.expandProperties(context, request.getRequestContent(),
                        request.isEntitizeProperties());
                if (StringUtils.hasContent(requestContent)) {
                    initRootPart(request, requestContent, formMp);
                }
            }

            for (Attachment attachment : request.getAttachments()) {
                MimeBodyPart part = new PreencodedMimeBodyPart("binary");

                if (attachment instanceof FileAttachment<?>) {
                    String name = attachment.getName();
                    if (StringUtils.hasContent(attachment.getContentID())
                            && !name.equals(attachment.getContentID()))
                        name = attachment.getContentID();

                    part.setDisposition(
                            "form-data; name=\"" + name + "\"; filename=\"" + attachment.getName() + "\"");
                } else
                    part.setDisposition("form-data; name=\"" + attachment.getName() + "\"");

                part.setDataHandler(new DataHandler(new AttachmentDataSource(attachment)));

                formMp.addBodyPart(part);
            }

            MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
            message.setContent(formMp);
            message.saveChanges();
            RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity(
                    message, request);
            ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity);
            httpMethod.setHeader("Content-Type", mimeMessageRequestEntity.getContentType().getValue());
            httpMethod.setHeader("MIME-Version", "1.0");
        } catch (Throwable e) {
            SoapUI.logError(e);
        }
    } else if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) {
        if (StringUtils.hasContent(request.getMediaType()))
            httpMethod.setHeader("Content-Type", getContentTypeHeader(request.getMediaType(), encoding));

        if (request.isPostQueryString()) {
            try {
                ((HttpEntityEnclosingRequest) httpMethod).setEntity(new StringEntity(query.toString()));
            } catch (UnsupportedEncodingException e) {
                SoapUI.logError(e);
            }
        } else {
            String requestContent = PropertyExpander.expandProperties(context, request.getRequestContent(),
                    request.isEntitizeProperties());
            List<Attachment> attachments = new ArrayList<Attachment>();

            for (Attachment attachment : request.getAttachments()) {
                if (attachment.getContentType().equals(request.getMediaType())) {
                    attachments.add(attachment);
                }
            }

            if (StringUtils.hasContent(requestContent) && attachments.isEmpty()) {
                try {
                    byte[] content = encoding == null ? requestContent.getBytes()
                            : requestContent.getBytes(encoding);
                    ((HttpEntityEnclosingRequest) httpMethod).setEntity(new ByteArrayEntity(content));
                } catch (UnsupportedEncodingException e) {
                    ((HttpEntityEnclosingRequest) httpMethod)
                            .setEntity(new ByteArrayEntity(requestContent.getBytes()));
                }
            } else if (attachments.size() > 0) {
                try {
                    MimeMultipart mp = null;

                    if (StringUtils.hasContent(requestContent)) {
                        mp = new MimeMultipart();
                        initRootPart(request, requestContent, mp);
                    } else if (attachments.size() == 1) {
                        ((HttpEntityEnclosingRequest) httpMethod)
                                .setEntity(new InputStreamEntity(attachments.get(0).getInputStream(), -1));

                        httpMethod.setHeader("Content-Type",
                                getContentTypeHeader(request.getMediaType(), encoding));
                    }

                    if (((HttpEntityEnclosingRequest) httpMethod).getEntity() == null) {
                        if (mp == null)
                            mp = new MimeMultipart();

                        // init mimeparts
                        AttachmentUtils.addMimeParts(request, attachments, mp, new StringToStringMap());

                        // create request message
                        MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
                        message.setContent(mp);
                        message.saveChanges();
                        RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity(
                                message, request);
                        ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity);
                        httpMethod.setHeader("Content-Type", getContentTypeHeader(
                                mimeMessageRequestEntity.getContentType().getValue(), encoding));
                        httpMethod.setHeader("MIME-Version", "1.0");
                    }
                } catch (Exception e) {
                    SoapUI.logError(e);
                }
            }
        }
    }
}

From source file:org.apache.axis2.transport.http.impl.httpclient4.HTTPSenderImpl.java

/**
 * Method used to copy all the common properties
 *
 * @param msgContext       - The messageContext of the request message
 * @param url              - The target URL
 * @param httpMethod       - The http method used to send the request
 * @param httpClient       - The httpclient used to send the request
 * @param soapActionString - The soap action atring of the request message
 * @return MessageFormatter - The messageFormatter for the relavent request
 *         message/* w  w  w.ja v  a2s .co  m*/
 * @throws org.apache.axis2.AxisFault - Thrown in case an exception occurs
 */
protected MessageFormatter populateCommonProperties(MessageContext msgContext, URL url,
        HttpRequestBase httpMethod, AbstractHttpClient httpClient, String soapActionString) throws AxisFault {

    if (isAuthenticationEnabled(msgContext)) {
        httpMethod.getParams().setBooleanParameter(ClientPNames.HANDLE_AUTHENTICATION, true);
    }

    MessageFormatter messageFormatter = TransportUtils.getMessageFormatter(msgContext);

    url = messageFormatter.getTargetAddress(msgContext, format, url);

    try {
        httpMethod.setURI(url.toURI());
    } catch (URISyntaxException e) {
        log.error("Error in URI : " + url, e);
    }

    httpMethod.setHeader(HTTPConstants.HEADER_CONTENT_TYPE,
            messageFormatter.getContentType(msgContext, format, soapActionString));

    httpMethod.setHeader(HTTPConstants.HEADER_HOST, url.getHost());

    if (msgContext.getOptions() != null && msgContext.getOptions().isManageSession()) {
        // setting the cookie in the out path
        Object cookieString = msgContext.getProperty(HTTPConstants.COOKIE_STRING);

        if (cookieString != null) {
            StringBuffer buffer = new StringBuffer();
            buffer.append(cookieString);
            httpMethod.setHeader(HTTPConstants.HEADER_COOKIE, buffer.toString());
        }
    }

    if (httpVersion.equals(HTTPConstants.HEADER_PROTOCOL_10)) {
        httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_0);
    }
    return messageFormatter;
}

From source file:org.artifactory.repo.HttpRepo.java

/**
 * Adds default headers and extra headers to the HttpRequest method
 * The extra headers are unique headers that should be added to the remote server request according to special
 * requirement example : user adds extra headers through the User Plugin (BeforeRemoteDownloadAction)
 * @param method Method to execute//from ww  w  .j  a  v a 2 s . c o m
 * @param extraHeaders Extra headers to add to the remote server request
 */
@SuppressWarnings({ "deprecation" })
private void addDefaultHeadersAndQueryParams(HttpRequestBase method, Map<String, String> extraHeaders) {
    //Explicitly force keep alive
    method.setHeader(HttpHeaders.CONNECTION, "Keep-Alive");

    //Add the current requester host id
    Set<String> originatedHeaders = RepoRequests.getOriginatedHeaders();
    for (String originatedHeader : originatedHeaders) {
        method.addHeader(ARTIFACTORY_ORIGINATED, originatedHeader);
    }
    String hostId = ContextHelper.get().beanForType(AddonsManager.class).addonByType(HaCommonAddon.class)
            .getHostId();
    // Add the extra headers to the remote request
    if (extraHeaders != null) {
        for (Map.Entry<String, String> entry : extraHeaders.entrySet()) {
            boolean isReservedKey = ARTIFACTORY_ORIGINATED.equals(entry.getKey())
                    || ORIGIN_ARTIFACTORY.equals(entry.getKey()) || ACCEPT_ENCODING.equals(entry.getKey());
            if (!isReservedKey) {
                method.addHeader(entry.getKey(), entry.getValue());
            }
        }
    }
    // Add the default artifactory headers, those headers will always override the existing headers if they already exist
    method.addHeader(ARTIFACTORY_ORIGINATED, hostId);

    //For backwards compatibility
    method.setHeader(ORIGIN_ARTIFACTORY, hostId);

    //Set gzip encoding
    if (handleGzipResponse) {
        method.addHeader(ACCEPT_ENCODING, "gzip");
    }

    // Set custom query params
    String queryParams = getDescriptor().getQueryParams();
    if (StringUtils.isNotBlank(queryParams)) {
        String url = method.getURI().toString();
        if (url.contains("?")) {
            url += "&";
        } else {
            url += "?";
        }
        url += HttpUtils.encodeQuery(queryParams);
        method.setURI(URI.create(url));
    }
}