Example usage for org.apache.commons.httpclient URI setPath

List of usage examples for org.apache.commons.httpclient URI setPath

Introduction

In this page you can find the example usage for org.apache.commons.httpclient URI setPath.

Prototype

public void setPath(String path) throws URIException 

Source Link

Document

Set the path.

Usage

From source file:com.thoughtworks.go.server.controller.PipelineStatusController.java

String getFullContextPath(HttpServletRequest request) throws URIException {
    String contextPath = request.getContextPath();
    StringBuffer url = request.getRequestURL();
    URI uri = new URI(url.toString());
    uri.setPath(contextPath);
    return uri.toString();
}

From source file:davmail.exchange.ExchangeSession.java

protected String getAbsoluteUri(HttpMethod method, String path) throws URIException {
    URI uri = method.getURI();
    if (path != null) {
        // reset query string
        uri.setQuery(null);/*from ww  w .j a  va 2 s .  com*/
        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.ExchangeSession.java

protected String getScriptBasedFormURL(HttpMethod initmethod, String pathQuery) throws URIException {
    URI initmethodURI = initmethod.getURI();
    int queryIndex = pathQuery.indexOf('?');
    if (queryIndex >= 0) {
        if (queryIndex > 0) {
            // update path
            String newPath = pathQuery.substring(0, queryIndex);
            if (newPath.startsWith("/")) {
                // absolute path
                initmethodURI.setPath(newPath);
            } else {
                String currentPath = initmethodURI.getPath();
                int folderIndex = currentPath.lastIndexOf('/');
                if (folderIndex >= 0) {
                    // replace relative path
                    initmethodURI.setPath(currentPath.substring(0, folderIndex + 1) + newPath);
                } else {
                    // should not happen
                    initmethodURI.setPath('/' + newPath);
                }/*from   w  ww  .java  2s.c o  m*/
            }
        }
        initmethodURI.setQuery(pathQuery.substring(queryIndex + 1));
    }
    return initmethodURI.getURI();
}

From source file:nl.nn.adapterframework.http.HttpSender.java

protected URI getURI(String url) throws URIException {
    URI uri = new URI(url);

    if (uri.getPath() == null) {
        uri.setPath("/");
    }//from  w w w  .j a  v a  2  s  .  c  o m

    log.info(getLogPrefix() + "created uri: scheme=[" + uri.getScheme() + "] host=[" + uri.getHost()
            + "] path=[" + uri.getPath() + "]");
    return uri;
}

From source file:org.infoscoop.request.filter.ProxyFilterContainer.java

public final int invoke(HttpClient client, HttpMethod method, ProxyRequest request) throws Exception {
    int preStatus = prepareInvoke(client, method, request);
    switch (preStatus) {
    case 0:/*from w ww.j  ava2s  .  c  om*/
        break;
    case EXECUTE_POST_STATUS:
        doFilterChain(request, request.getResponseBody());
    default:
        return preStatus;
    }
    // copy headers sent target server
    List ignoreHeaderNames = request.getIgnoreHeaders();
    List allowedHeaderNames = request.getAllowedHeaders();
    boolean allowAllHeader = false;

    Proxy proxy = request.getProxy();
    if (proxy != null) {
        allowAllHeader = proxy.isAllowAllHeader();
        if (!allowAllHeader)
            allowedHeaderNames.addAll(proxy.getAllowedHeaders());
    }

    AuthenticatorUtil.doAuthentication(client, method, request);

    StringBuffer headersSb = new StringBuffer();
    for (String name : request.getRequestHeaders().keySet()) {

        String value = request.getRequestHeader(name);
        String lowname = name.toLowerCase();

        if (!allowAllHeader && !allowedHeaderNames.contains(lowname))
            continue;

        if (ignoreHeaderNames.contains(lowname))
            continue;

        if ("cookie".equalsIgnoreCase(name)) {
            if (proxy.getSendingCookies() != null) {
                value = RequestUtil.removeCookieParam(value, proxy.getSendingCookies());
            }
        }

        if ("if-modified-since".equalsIgnoreCase(name) && "Thu, 01 Jun 1970 00:00:00 GMT".equals(value))
            continue;

        method.addRequestHeader(new Header(name, value));
        headersSb.append(name + "=" + value + ",  ");
    }

    int cacheStatus = getCache(client, method, request);
    if (cacheStatus != 0)
        return cacheStatus;

    if (log.isInfoEnabled())
        log.info("RequestHeader: " + headersSb);

    // execute http method and process redirect
    method.setFollowRedirects(false);

    client.executeMethod(method);

    int statusCode = method.getStatusCode();

    for (int i = 0; statusCode == HttpStatus.SC_MOVED_TEMPORARILY
            || statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_SEE_OTHER
            || statusCode == HttpStatus.SC_TEMPORARY_REDIRECT; i++) {

        // connection release
        method.releaseConnection();

        if (i == 5) {
            log.error("The circular redirect is limited by five times.");
            return 500;
        }

        Header location = method.getResponseHeader("Location");
        String redirectUrl = location.getValue();

        // According to 2,068 1.1 rfc http spec, we cannot appoint the relative URL,
        // but microsoft.com gives back the relative URL.
        if (redirectUrl.startsWith("/")) {
            URI baseURI = method.getURI();
            baseURI.setPath(redirectUrl);

            redirectUrl = baseURI.toString();
        }

        //method.setURI(new URI(redirectUrl, false));
        Header[] headers = method.getRequestHeaders();
        method = new GetMethod(redirectUrl);
        for (int j = 0; j < headers.length; j++) {
            String headerName = headers[j].getName();
            if (!headerName.equalsIgnoreCase("content-length") && !headerName.equalsIgnoreCase("authorization"))
                method.setRequestHeader(headers[j]);
        }
        AuthenticatorUtil.doAuthentication(client, method, request);
        method.setRequestHeader("authorization", request.getRequestHeader("Authorization"));
        method.setFollowRedirects(false);
        client.executeMethod(method);
        statusCode = method.getStatusCode();
        request.setRedirectURL(redirectUrl);

        if (log.isInfoEnabled())
            log.info("Redirect " + request.getTargetURL() + " to " + location + ".");
    }

    // copy response headers to proxyReqeust
    Header[] headers = method.getResponseHeaders();
    for (int i = 0; i < headers.length; i++) {
        request.putResponseHeader(headers[i].getName(), headers[i].getValue());
    }

    if (log.isInfoEnabled())
        log.info("Original Status:" + statusCode);

    // check response code
    if (statusCode == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
        log.error("Proxy Authentication Required. Confirm ajax proxy setting.");
        throw new Exception(
                "Http Status 407, Proxy Authentication Required. Please contuct System Administrator.");
    }
    if (statusCode == HttpStatus.SC_NOT_MODIFIED || statusCode == HttpStatus.SC_RESET_CONTENT) {
        return statusCode;
    } else if (statusCode < 200 || statusCode >= 300) {
        request.setResponseBody(method.getResponseBodyAsStream());
        return statusCode;
    }

    // process response body
    InputStream responseStream = null;
    if (statusCode != HttpStatus.SC_NO_CONTENT) {
        if (request.allowUserPublicCache()) {
            byte[] responseBody = method.getResponseBody();

            Map<String, List<String>> responseHeaders = request.getResponseHeaders();
            if (request.getRedirectURL() != null)
                responseHeaders.put("X-IS-REDIRECTED-FROM",
                        Arrays.asList(new String[] { request.getRedirectURL() }));
            if (method instanceof GetMethod) {
                putCache(request.getOriginalURL(), new ByteArrayInputStream(responseBody), responseHeaders);
            }

            responseStream = new ByteArrayInputStream(responseBody);
        } else {
            responseStream = method.getResponseBodyAsStream();
        }
    }
    doFilterChain(request, responseStream);

    return statusCode != HttpStatus.SC_NO_CONTENT ? method.getStatusCode() : 200;
}

From source file:org.parosproxy.paros.core.scanner.Analyser.java

/**
 * Analyse a single folder entity. Results are stored into
 * mAnalysedEntityTable./*w  w w  . j a  v  a 2 s.c  o m*/
 */
private void analyse(StructuralNode node) throws Exception {
    // if analysed already, return;
    // move to host part
    if (node.getHistoryReference() == null) {
        return;
    }

    if (!parent.nodeInScope(node.getName())) {
        return;
    }

    // ZAP: Removed unnecessary cast.
    HttpMessage baseMsg = node.getHistoryReference().getHttpMessage();
    URI baseUri = (URI) baseMsg.getRequestHeader().getURI().clone();

    baseUri.setQuery(null);
    //System.out.println("analysing: " + baseUri.toString());

    // already exist one.  no need to test
    if (mapVisited.get(baseUri.toString()) != null) {
        return;
    }

    String path = getRandomPathSuffix(node, baseUri);
    HttpMessage msg = baseMsg.cloneRequest();

    URI uri = (URI) baseUri.clone();
    uri.setPath(path);
    msg.getRequestHeader().setURI(uri);
    //System.out.println("analysing 2: " + uri);

    sendAndReceive(msg);

    // standard RFC response, no further check is needed
    if (msg.getResponseHeader().getStatusCode() == HttpStatusCode.NOT_FOUND) {
        addAnalysedHost(baseUri, msg, SampleResponse.ERROR_PAGE_RFC);
        return;
    }

    if (HttpStatusCode.isRedirection(msg.getResponseHeader().getStatusCode())) {
        addAnalysedHost(baseUri, msg, SampleResponse.ERROR_PAGE_REDIRECT);
        return;
    }

    if (msg.getResponseHeader().getStatusCode() != HttpStatusCode.OK) {
        addAnalysedHost(baseUri, msg, SampleResponse.ERROR_PAGE_NON_RFC);
        return;
    }

    HttpMessage msg2 = baseMsg.cloneRequest();
    URI uri2 = msg2.getRequestHeader().getURI();
    String path2 = getRandomPathSuffix(node, uri2);
    uri2 = (URI) baseUri.clone();
    uri2.setPath(path2);
    msg2.getRequestHeader().setURI(uri2);
    sendAndReceive(msg2);

    // remove HTML HEAD as this may contain expiry time which dynamic changes      
    String resBody1 = msg.getResponseBody().toString().replaceAll(p_REMOVE_HEADER, "");
    String resBody2 = msg2.getResponseBody().toString().replaceAll(p_REMOVE_HEADER, "");

    // check if page is static.  If so, remember this static page
    if (resBody1.equals(resBody2)) {
        msg.getResponseBody().setBody(resBody1);
        addAnalysedHost(baseUri, msg, SampleResponse.ERROR_PAGE_STATIC);
        return;
    }

    // else check if page is dynamic but deterministic
    resBody1 = resBody1.replaceAll(getPathRegex(uri), "").replaceAll("\\s[012]\\d:[0-5]\\d:[0-5]\\d\\s", "");
    resBody2 = resBody2.replaceAll(getPathRegex(uri2), "").replaceAll("\\s[012]\\d:[0-5]\\d:[0-5]\\d\\s", "");
    if (resBody1.equals(resBody2)) {
        msg.getResponseBody().setBody(resBody1);
        addAnalysedHost(baseUri, msg, SampleResponse.ERROR_PAGE_DYNAMIC_BUT_DETERMINISTIC);
        return;
    }

    // else mark app "undeterministic".
    addAnalysedHost(baseUri, msg, SampleResponse.ERROR_PAGE_UNDETERMINISTIC);

}

From source file:org.parosproxy.paros.core.scanner.Analyser.java

public boolean isFileExist(HttpMessage msg) {

    if (msg.getResponseHeader().isEmpty()) {
        return false;
    }//from  w  w  w  . j  a v a 2  s . c o m

    // RFC
    if (msg.getResponseHeader().getStatusCode() == HttpStatusCode.NOT_FOUND) {
        return false;
    }

    // ZAP: catch CloneNotSupportedException as introduced with version 3.1 of HttpClient
    URI uri = null;
    String sUri = null;
    try {
        uri = (URI) msg.getRequestHeader().getURI().clone();

        // strip off last part of path - use folder only
        uri.setQuery(null);
        String path = uri.getPath();
        path = path.replaceAll("/[^/]*$", "");
        uri.setPath(path);

    } catch (Exception e) {
    } finally {
        if (uri != null) {
            sUri = uri.toString();
        }
    }

    // get sample with same relative path position when possible.
    // if not exist, use the host only   
    // ZAP: Removed unnecessary cast.
    SampleResponse sample = mapVisited.get(sUri);
    if (sample == null) {
        try {
            uri.setPath(null);

        } catch (URIException e2) {
        }

        String sHostOnly = uri.toString();

        // ZAP: Removed unnecessary cast.
        sample = mapVisited.get(sHostOnly);
    }

    // check if any analysed result.
    if (sample == null) {
        if (msg.getResponseHeader().getStatusCode() == HttpStatusCode.OK) {
            // no anlaysed result to confirm, assume file exist and return
            return true;
        } else {
            return false;
        }
    }

    // check for redirect response.  If redirect to same location, then file does not exist
    if (HttpStatusCode.isRedirection(msg.getResponseHeader().getStatusCode())) {
        try {
            if (sample.getMessage().getResponseHeader().getStatusCode() == msg.getResponseHeader()
                    .getStatusCode()) {
                String location = msg.getResponseHeader().getHeader(HttpHeader.LOCATION);
                if (location != null && location
                        .equals(sample.getMessage().getResponseHeader().getHeader(HttpHeader.LOCATION))) {
                    return false;
                }
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return true;
    }

    // Not success code
    if (msg.getResponseHeader().getStatusCode() != HttpStatusCode.OK) {
        return false;
    }

    // remain only OK response here
    // nothing more to determine.  Check for possible not found page pattern.
    Matcher matcher = patternNotFound.matcher(msg.getResponseBody().toString());
    if (matcher.find()) {
        return false;
    }

    // static response
    String body = msg.getResponseBody().toString().replaceAll(p_REMOVE_HEADER, "");
    if (sample.getErrorPageType() == SampleResponse.ERROR_PAGE_STATIC) {
        try {
            if (sample.getMessage().getResponseBody().toString().equals(body)) {
                return false;
            }

        } catch (HttpMalformedHeaderException | DatabaseException e) {
            logger.error("Failed to read the message: " + e.getMessage(), e);
        }
        return true;
    }

    uri = msg.getRequestHeader().getURI();
    try {
        if (sample.getErrorPageType() == SampleResponse.ERROR_PAGE_DYNAMIC_BUT_DETERMINISTIC) {
            body = msg.getResponseBody().toString().replaceAll(getPathRegex(uri), "")
                    .replaceAll("\\s[012]\\d:[0-5]\\d:[0-5]\\d\\s", "");
            // ZAP: FindBugs fix - added call to HttpBody.toString() 
            if (sample.getMessage().getResponseBody().toString().equals(body)) {
                return false;
            }
            return true;
        }

    } catch (Exception e) {
        logger.error(e.getMessage(), e);

    }

    return true;
}

From source file:org.parosproxy.paros.core.scanner.plugin.TestInfoGatheringObsoleteFile.java

/**
 * Test existence of obsolete file with the suffix.
 * /* w ww.  j  a va  2  s . c  o  m*/
 * @param suffix
 *            suffix to run scan with.
 * @param replaceSuffix
 *            true = replace the suffix for checking. false = append the
 *            suffix.
 */
private void testSuffix(String suffix, boolean replaceSuffix) throws IOException {
    HttpMessage msg = getNewMsg();
    URI uri = msg.getRequestHeader().getURI();
    String path = uri.getPath();

    if (path == null || path.equals("")) {
        return;
    }

    if (replaceSuffix) {
        int pos = path.lastIndexOf(".");
        if (pos > -1) {
            path = path.substring(0, pos);
        }
    }

    path = path + suffix;

    uri.setPath(path);
    msg.getRequestHeader().setURI(uri);

    sendAndReceive(msg);

    if (!isFileExist(msg)) {
        return;
    }

    bingo(Alert.RISK_LOW, Alert.WARNING, uri.toString(), "", "", msg);

}

From source file:org.parosproxy.paros.core.scanner.plugin.TestInformationDisclosurePhpInfo.java

/**
 * Test existence of file./* w  w  w  . j a  va2  s  .c om*/
 * 
 * @param fileName
 *            to run scan with.
 */
private void testFile(String fileName) throws IOException {

    boolean suspiciousFileFound = false;
    HttpMessage msg = getNewMsg();

    try {
        URI uri = msg.getRequestHeader().getURI();
        String path = uri.getPath();

        if (path == null || path.equals("")) {
            return;
        }

        if (!path.endsWith("/")) {
            path = path + "/";
        }

        path = path + fileName;

        uri.setPath(path);
        msg.getRequestHeader().setURI(uri);

        sendAndReceive(msg);

        if (msg.getResponseHeader().getStatusCode() != HttpStatusCode.OK) {
            return;
        }

        if (matchBodyPattern(msg, patternPhpInfo, null)) {
            suspiciousFileFound = true;
        }
    } catch (IOException e) {
    }

    if (suspiciousFileFound) {
        bingo(Alert.RISK_MEDIUM, Alert.WARNING, msg.getRequestHeader().getURI().toString(), "", "", msg);
    }
}

From source file:org.parosproxy.paros.core.scanner.VariantDdnPath.java

private String setParameter(HttpMessage msg, NameValuePair originalPair, String name, String value,
        boolean escaped) {
    URI uri = msg.getRequestHeader().getURI();
    String[] paths = uri.getEscapedPath().split("/");
    if (originalPair.getPosition() < paths.length) {
        String encodedValue = (escaped) ? value : getEscapedValue(value);
        paths[originalPair.getPosition()] = encodedValue;
        String path = String.join("/", paths);
        try {// w w  w  .  ja v a2  s. c  o  m
            uri.setEscapedPath(path);
        } catch (URIException e) {
            // Looks like it wasn't escaped after all
            try {
                uri.setPath(path);
            } catch (URIException e1) {
                LOGGER.debug(e1.getMessage(), e1);
            }
            LOGGER.warn(e.getMessage(), e);
        }
    }
    return value;
}