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

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

Introduction

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

Prototype

public URI(URI base, URI relative) throws URIException 

Source Link

Document

Construct a general URI with the given relative URI.

Usage

From source file:com.cerema.cloud2.lib.common.OwnCloudClient.java

public RedirectionPath followRedirection(HttpMethod method) throws IOException {
    int redirectionsCount = 0;
    int status = method.getStatusCode();
    RedirectionPath result = new RedirectionPath(status, MAX_REDIRECTIONS_COUNT);
    while (redirectionsCount < MAX_REDIRECTIONS_COUNT && (status == HttpStatus.SC_MOVED_PERMANENTLY
            || status == HttpStatus.SC_MOVED_TEMPORARILY || status == HttpStatus.SC_TEMPORARY_REDIRECT)) {

        Header location = method.getResponseHeader("Location");
        if (location == null) {
            location = method.getResponseHeader("location");
        }//from w  w  w .ja v a  2s . c  o m
        if (location != null) {
            Log_OC.d(TAG + " #" + mInstanceNumber, "Location to redirect: " + location.getValue());

            String locationStr = location.getValue();
            result.addLocation(locationStr);

            // Release the connection to avoid reach the max number of connections per host
            // due to it will be set a different url
            exhaustResponse(method.getResponseBodyAsStream());
            method.releaseConnection();

            method.setURI(new URI(locationStr, true));
            Header destination = method.getRequestHeader("Destination");
            if (destination == null) {
                destination = method.getRequestHeader("destination");
            }
            if (destination != null) {
                int suffixIndex = locationStr.lastIndexOf(
                        (mCredentials instanceof OwnCloudBearerCredentials) ? AccountUtils.ODAV_PATH
                                : AccountUtils.WEBDAV_PATH_4_0);
                String redirectionBase = locationStr.substring(0, suffixIndex);

                String destinationStr = destination.getValue();
                String destinationPath = destinationStr.substring(mBaseUri.toString().length());
                String redirectedDestination = redirectionBase + destinationPath;

                destination.setValue(redirectedDestination);
                method.setRequestHeader(destination);
            }
            status = super.executeMethod(method);
            result.addStatus(status);
            redirectionsCount++;

        } else {
            Log_OC.d(TAG + " #" + mInstanceNumber, "No location to redirect!");
            status = HttpStatus.SC_NOT_FOUND;
        }
    }
    return result;
}

From source file:com.xerox.amazonws.common.AWSQueryConnection.java

/**
 * Make a http request and process the response. This method also performs automatic retries.
*
 * @param method The HTTP method to use (GET, POST, DELETE, etc)
 * @param action the name of the action for this query request
 * @param params map of request params/*from  w w  w.  j av a  2s  .  c om*/
 * @param respType the class that represents the desired/expected return type
 */
protected <T> T makeRequest(HttpMethodBase method, String action, Map<String, String> params, Class<T> respType)
        throws HttpException, IOException, JAXBException {

    // add auth params, and protocol specific headers
    Map<String, String> qParams = new HashMap<String, String>(params);
    qParams.put("Action", action);
    qParams.put("AWSAccessKeyId", getAwsAccessKeyId());
    qParams.put("SignatureVersion", "" + sigVersion);
    qParams.put("Timestamp", httpDate());
    if (headers != null) {
        for (Iterator<String> i = headers.keySet().iterator(); i.hasNext();) {
            String key = i.next();
            for (Iterator<String> j = headers.get(key).iterator(); j.hasNext();) {
                qParams.put(key, j.next());
            }
        }
    }
    // sort params by key
    ArrayList<String> keys = new ArrayList<String>(qParams.keySet());
    Collator stringCollator = Collator.getInstance();
    stringCollator.setStrength(Collator.PRIMARY);
    Collections.sort(keys, stringCollator);

    // build param string
    StringBuilder resource = new StringBuilder();
    if (sigVersion == 0) { // ensure Action, Timestamp come first!
        resource.append(qParams.get("Action"));
        resource.append(qParams.get("Timestamp"));
    } else {
        for (String key : keys) {
            resource.append(key);
            resource.append(qParams.get(key));
        }
    }

    // calculate signature
    String encoded = urlencode(encode(getSecretAccessKey(), resource.toString(), false));

    // build param string, encoding values and adding request signature
    resource = new StringBuilder();
    for (String key : keys) {
        resource.append("&");
        resource.append(key);
        resource.append("=");
        resource.append(urlencode(qParams.get(key)));
    }
    resource.setCharAt(0, '?'); // set first param delimeter
    resource.append("&Signature=");
    resource.append(encoded);

    // finally, build request object
    URL url = makeURL(resource.toString());
    method.setURI(new URI(url.toString(), true));
    method.setRequestHeader(new Header("User-Agent", userAgent));
    if (sigVersion == 0) {
        method.setRequestHeader(new Header("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"));
    }
    Object response = null;
    boolean done = false;
    int retries = 0;
    boolean doRetry = false;
    String errorMsg = "";
    do {
        int responseCode = 600; // default to high value, so we don't think it is valid
        try {
            responseCode = getHttpClient().executeMethod(method);
        } catch (SocketException ex) {
            // these can generally be retried. Treat it like a 500 error
            doRetry = true;
            errorMsg = ex.getMessage();
        }
        // 100's are these are handled by httpclient
        if (responseCode < 300) {
            // 200's : parse normal response into requested object
            if (respType != null) {
                InputStream iStr = method.getResponseBodyAsStream();
                response = JAXBuddy.deserializeXMLStream(respType, iStr);
            }
            done = true;
        } else if (responseCode < 400) {
            // 300's : what to do?
            throw new HttpException("redirect error : " + responseCode);
        } else if (responseCode < 500) {
            // 400's : parse client error message
            String body = getStringFromStream(method.getResponseBodyAsStream());
            throw new HttpException("Client error : " + getErrorDetails(body));
        } else if (responseCode < 600) {
            // 500's : retry...
            doRetry = true;
            String body = getStringFromStream(method.getResponseBodyAsStream());
            errorMsg = getErrorDetails(body);
        }
        if (doRetry) {
            retries++;
            if (retries > maxRetries) {
                throw new HttpException("Number of retries exceeded : " + action + ", " + errorMsg);
            }
            doRetry = false;
            try {
                Thread.sleep((int) Math.pow(2.0, retries) * 1000);
            } catch (InterruptedException ex) {
            }
        }
    } while (!done);
    return (T) response;
}

From source file:fr.cls.atoll.motu.library.cas.HttpClientCAS.java

/**
 * Adds the cas ticket.//  w  w w.  j  a v a  2 s .  c om
 * 
 * @param method
 *            the method
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws MotuCasException
 */
public static void addCASTicket(HttpMethod method) throws IOException, MotuCasException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("addCASTicket(HttpMethod) - entering : debugHttpMethod BEFORE  "
                + HttpClientCAS.debugHttpMethod(method));
    }

    if (HttpClientCAS.addCASTicketFromTGT(method)) {
        return;
    }

    if (!AuthenticationHolder.isCASAuthentication()) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("addCASTicket(HttpMethod) - exiting - NO CAS AUTHENTICATION : debugHttpMethod AFTER  "
                    + HttpClientCAS.debugHttpMethod(method));
        }
        return;
    }

    String newURIAsString = AssertionUtils.addCASTicket(method.getURI().getEscapedURI());
    if (!AssertionUtils.hasCASTicket(newURIAsString)) {
        newURIAsString = AssertionUtils.addCASTicket(method.getURI().getEscapedURI(),
                AuthenticationHolder.getUser());

        if (!AssertionUtils.hasCASTicket(newURIAsString)) {

            String login = AuthenticationHolder.getUserLogin();
            throw new MotuCasException(String.format(
                    "Unable to access resource '%s'. This resource has been declared as CASified, but the Motu application/API can't retrieve any ticket from CAS via REST. \nFor information, current user login is:'%s'",
                    method.getURI().getEscapedURI(), login));

        }
    }

    URI newURI = new URI(newURIAsString, true);

    // method.setURI(newURI);
    method.setPath(newURI.getPath());
    method.setQueryString(newURI.getQuery());
    // System.out.println(newURI.getPathQuery());
    if (LOG.isDebugEnabled()) {
        LOG.debug("addCASTicket(HttpMethod) - exiting : debugHttpMethod AFTER  "
                + HttpClientCAS.debugHttpMethod(method));
    }

}

From source file:com.liferay.portal.util.HttpImpl.java

public HostConfiguration getHostConfiguration(String location) throws IOException {

    if (_log.isDebugEnabled()) {
        _log.debug("Location is " + location);
    }/*w  w w . ja  v  a2s.  c  om*/

    HostConfiguration hostConfiguration = new HostConfiguration();

    hostConfiguration.setHost(new URI(location, false));

    if (isProxyHost(hostConfiguration.getHost())) {
        hostConfiguration.setProxy(_PROXY_HOST, _PROXY_PORT);
    }

    HttpConnectionManager httpConnectionManager = _httpClient.getHttpConnectionManager();

    HttpConnectionManagerParams httpConnectionManagerParams = httpConnectionManager.getParams();

    int defaultMaxConnectionsPerHost = httpConnectionManagerParams.getMaxConnectionsPerHost(hostConfiguration);

    int maxConnectionsPerHost = GetterUtil.getInteger(PropsUtil.get(
            HttpImpl.class.getName() + ".max.connections.per.host", new Filter(hostConfiguration.getHost())));

    if ((maxConnectionsPerHost > 0) && (maxConnectionsPerHost != defaultMaxConnectionsPerHost)) {

        httpConnectionManagerParams.setMaxConnectionsPerHost(hostConfiguration, maxConnectionsPerHost);
    }

    int timeout = GetterUtil.getInteger(
            PropsUtil.get(HttpImpl.class.getName() + ".timeout", new Filter(hostConfiguration.getHost())));

    if (timeout > 0) {
        HostParams hostParams = hostConfiguration.getParams();

        hostParams.setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, timeout);
        hostParams.setIntParameter(HttpConnectionParams.SO_TIMEOUT, timeout);
    }

    return hostConfiguration;
}

From source file:fr.cls.atoll.motu.library.cas.HttpClientCAS.java

/**
 * Adds the cas ticket from tgt./*from w  ww. j av a2s.c  om*/
 *
 * @param method the method
 * @return true, if successful
 * @throws MotuCasException the motu cas exception
 * @throws URIException the uRI exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static boolean addCASTicketFromTGT(HttpMethod method)
        throws MotuCasException, URIException, IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("addCASTicketFromTGT(HttpMethod) - entering : debugHttpMethod BEFORE  "
                + HttpClientCAS.debugHttpMethod(method));
    }

    Header headerTgt = method.getRequestHeader(HttpClientCAS.TGT_PARAM);
    Header headerCasRestUrl = method.getRequestHeader(HttpClientCAS.CAS_REST_URL_PARAM);

    if ((headerTgt == null) || (headerCasRestUrl == null)) {
        return false;
    }
    String ticketGrantingTicket = headerTgt.getValue();
    String casRestUrl = headerCasRestUrl.getValue();

    if ((RestUtil.isNullOrEmpty(ticketGrantingTicket)) || (RestUtil.isNullOrEmpty(casRestUrl))) {
        return false;
    }

    String ticket = RestUtil.loginToCASWithTGT(casRestUrl, ticketGrantingTicket,
            method.getURI().getEscapedURI());

    String newURIAsString = AssertionUtils.addCASTicket(ticket, method.getURI().getEscapedURI());

    if (!AssertionUtils.hasCASTicket(newURIAsString)) {
        throw new MotuCasException(String.format(
                "Unable to access resource '%s'. This resource has been declared as CASified, but the Motu application/API can't retrieve any ticket from CAS via REST. \nFor information, current TGT is:'%s', CAS REST url is:'%s'",
                method.getURI().getEscapedURI(), ticketGrantingTicket, casRestUrl));

    }

    URI newURI = new URI(newURIAsString, true);

    // method.setURI(newURI);
    method.setPath(newURI.getPath());
    method.setQueryString(newURI.getQuery());
    // System.out.println(newURI.getPathQuery());
    if (LOG.isDebugEnabled()) {
        LOG.debug("addCASTicketFromTGT(HttpMethod) - exiting : debugHttpMethod AFTER  "
                + HttpClientCAS.debugHttpMethod(method));
    }

    return true;

}

From source file:com.linkedin.pinot.controller.api.resources.LLCSegmentCompletionHandlers.java

@Nullable
private String uploadSegment(FormDataMultiPart multiPart, String instanceId, String segmentName,
        boolean isSplitCommit) {
    try {//from   w ww. j  a v a 2  s .  c o  m
        Map<String, List<FormDataBodyPart>> map = multiPart.getFields();
        if (!PinotSegmentUploadRestletResource.validateMultiPart(map, segmentName)) {
            return null;
        }
        String name = map.keySet().iterator().next();
        FormDataBodyPart bodyPart = map.get(name).get(0);

        FileUploadPathProvider provider = new FileUploadPathProvider(_controllerConf);
        File tmpFile = new File(provider.getFileUploadTmpDir(), name + "." + UUID.randomUUID().toString());
        tmpFile.deleteOnExit();

        try (InputStream inputStream = bodyPart.getValueAs(InputStream.class);
                OutputStream outputStream = new FileOutputStream(tmpFile)) {
            IOUtils.copyLarge(inputStream, outputStream);
        }

        LLCSegmentName llcSegmentName = new LLCSegmentName(segmentName);
        final String rawTableName = llcSegmentName.getTableName();
        final File tableDir = new File(provider.getBaseDataDir(), rawTableName);
        File segmentFile;
        if (isSplitCommit) {
            String uniqueSegmentFileName = SegmentCompletionUtils.generateSegmentFileName(segmentName);
            segmentFile = new File(tableDir, uniqueSegmentFileName);
        } else {
            segmentFile = new File(tableDir, segmentName);
        }

        if (isSplitCommit) {
            FileUtils.moveFile(tmpFile, segmentFile);
        } else {
            // Multiple threads can reach this point at the same time, if the following scenario happens
            // The server that was asked to commit did so very slowly (due to network speeds). Meanwhile the FSM in
            // SegmentCompletionManager timed out, and allowed another server to commit, which did so very quickly (somehow
            // the network speeds changed). The second server made it through the FSM and reached this point.
            // The synchronization below takes care that exactly one file gets moved in place.
            // There are still corner conditions that are not handled correctly. For example,
            // 1. What if the offset of the faster server was different?
            // 2. We know that only the faster server will get to complete the COMMIT call successfully. But it is possible
            //    that the race to this statement is won by the slower server, and so the real segment that is in there is that
            //    of the slower server.
            // In order to overcome controller restarts after the segment is renamed, but before it is committed, we DO need to
            // check for existing segment file and remove it. So, the block cannot be removed altogether.
            // For now, we live with these corner cases. Once we have split-commit enabled and working, this code will no longer
            // be used.
            synchronized (SegmentCompletionManager.getInstance()) {
                if (segmentFile.exists()) {
                    LOGGER.warn("Segment file {} exists. Replacing with upload from {}",
                            segmentFile.getAbsolutePath(), instanceId);
                    FileUtils.deleteQuietly(segmentFile);
                }
                FileUtils.moveFile(tmpFile, segmentFile);
            }
        }
        LOGGER.info("Moved file {} to {}", tmpFile.getAbsolutePath(), segmentFile.getAbsolutePath());
        return new URI(SCHEME + segmentFile.getAbsolutePath(), /* boolean escaped */ false).toString();
    } catch (InvalidControllerConfigException e) {
        LOGGER.error("Invalid controller config exception from instance {} for segment {}", instanceId,
                segmentName, e);
        return null;
    } catch (IOException e) {
        LOGGER.error("File upload exception from instance {} for segment {}", instanceId, segmentName, e);
        return null;
    } finally {
        multiPart.cleanup();
    }
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Execute webdav request.//w  ww .  ja va  2  s. c om
 *
 * @param httpClient http client instance
 * @param method     webdav method
 * @return Responses enumeration
 * @throws IOException on error
 */
public static MultiStatusResponse[] executeMethod(HttpClient httpClient, DavMethodBase method)
        throws IOException {
    MultiStatusResponse[] responses = null;
    try {
        int status = httpClient.executeMethod(method);

        // need to follow redirects (once) on public folders
        if (isRedirect(status)) {
            method.releaseConnection();
            URI targetUri = new URI(method.getResponseHeader("Location").getValue(), true);
            checkExpiredSession(targetUri.getQuery());
            method.setURI(targetUri);
            status = httpClient.executeMethod(method);
        }

        if (status != HttpStatus.SC_MULTI_STATUS) {
            throw buildHttpException(method);
        }
        responses = method.getResponseBodyAsMultiStatus().getResponses();

    } catch (DavException e) {
        throw new IOException(e.getMessage());
    } finally {
        method.releaseConnection();
    }
    return responses;
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Execute webdav request./*  w w  w.  j  a v  a 2  s.com*/
 *
 * @param httpClient http client instance
 * @param method     webdav method
 * @return Responses enumeration
 * @throws IOException on error
 */
public static MultiStatusResponse[] executeMethod(HttpClient httpClient, ExchangeDavMethod method)
        throws IOException {
    MultiStatusResponse[] responses = null;
    try {
        int status = httpClient.executeMethod(method);

        // need to follow redirects (once) on public folders
        if (isRedirect(status)) {
            method.releaseConnection();
            URI targetUri = new URI(method.getResponseHeader("Location").getValue(), true);
            checkExpiredSession(targetUri.getQuery());
            method.setURI(targetUri);
            status = httpClient.executeMethod(method);
        }

        if (status != HttpStatus.SC_MULTI_STATUS) {
            throw buildHttpException(method);
        }
        responses = method.getResponses();

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

From source file:dk.defxws.fedoragsearch.server.Config.java

private byte[] httpRetrieve(final String url) throws ConfigException {
    byte[] stylesheetBytes = null;
    try {//from   w  w w  .j  a va 2s .c  o  m
        HttpClient httpClient = new HttpClient();
        String proxyHostName = EscidocConfiguration.getInstance()
                .get(EscidocConfiguration.ESCIDOC_CORE_PROXY_HOST);
        String proxyPort = EscidocConfiguration.getInstance().get(EscidocConfiguration.ESCIDOC_CORE_PROXY_PORT);
        String nonProxyHosts = EscidocConfiguration.getInstance()
                .get(EscidocConfiguration.ESCIDOC_CORE_NON_PROXY_HOSTS);
        if (proxyHostName != null && !proxyHostName.trim().equals("")) {
            //check noProxyHosts
            boolean noProxy = false;
            if (nonProxyHosts != null && !nonProxyHosts.trim().equals("")) {
                nonProxyHosts = nonProxyHosts.replaceAll("\\.", "\\\\.");
                nonProxyHosts = nonProxyHosts.replaceAll("\\*", "");
                nonProxyHosts = nonProxyHosts.replaceAll("\\?", "\\\\?");
                Pattern nonProxyPattern = Pattern.compile(nonProxyHosts);
                Matcher nonProxyMatcher = nonProxyPattern.matcher(url);
                if (nonProxyMatcher.find()) {
                    noProxy = true;
                }
            }
            if (!noProxy) {
                ProxyHost proxyHost = null;
                if (proxyPort != null && !proxyPort.trim().equals("")) {
                    proxyHost = new ProxyHost(proxyHostName, Integer.parseInt(proxyPort));
                } else {
                    proxyHost = new ProxyHost(proxyHostName);
                }

                httpClient.getHostConfiguration().setProxyHost(proxyHost);
            }
        }
        GetMethod method = null;
        try {
            method = new GetMethod(url);
        } catch (IllegalArgumentException e) {
            method = new GetMethod(new URI(url, false).getEscapedURI());
        }
        int statusCode = httpClient.executeMethod(method);
        if (statusCode != HttpStatus.SC_OK) {
            throw new ConfigException("Retrieving stylesheet failed: " + method.getStatusLine());
        }
        stylesheetBytes = method.getResponseBody();
        method.releaseConnection();
    } catch (Exception e) {
        //MIH: added for URLDecoding
        throw new ConfigException("get stylesheet from url " + url + ":\n", e);
    }
    return stylesheetBytes;
}

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

protected Folder buildFolder(MultiStatusResponse entity) throws IOException {
    String href = URIUtil.decode(entity.getHref());
    Folder folder = new Folder();
    DavPropertySet properties = entity.getProperties(HttpStatus.SC_OK);
    folder.displayName = getPropertyIfExists(properties, "displayname");
    folder.folderClass = getPropertyIfExists(properties, "folderclass");
    folder.hasChildren = "1".equals(getPropertyIfExists(properties, "hassubs"));
    folder.noInferiors = "1".equals(getPropertyIfExists(properties, "nosubs"));
    folder.count = getIntPropertyIfExists(properties, "count");
    folder.unreadCount = getIntPropertyIfExists(properties, "unreadcount");
    // fake recent value
    folder.recent = folder.unreadCount;/*from   w  w  w .  j  ava 2s .  co  m*/
    folder.ctag = getPropertyIfExists(properties, "contenttag");
    folder.etag = getPropertyIfExists(properties, "lastmodified");

    folder.uidNext = getIntPropertyIfExists(properties, "uidNext");

    // replace well known folder names
    if (inboxUrl != null && href.startsWith(inboxUrl)) {
        folder.folderPath = href.replaceFirst(inboxUrl, INBOX);
    } else if (sentitemsUrl != null && href.startsWith(sentitemsUrl)) {
        folder.folderPath = href.replaceFirst(sentitemsUrl, SENT);
    } else if (draftsUrl != null && href.startsWith(draftsUrl)) {
        folder.folderPath = href.replaceFirst(draftsUrl, DRAFTS);
    } else if (deleteditemsUrl != null && href.startsWith(deleteditemsUrl)) {
        folder.folderPath = href.replaceFirst(deleteditemsUrl, TRASH);
    } else if (calendarUrl != null && href.startsWith(calendarUrl)) {
        folder.folderPath = href.replaceFirst(calendarUrl, CALENDAR);
    } else if (contactsUrl != null && href.startsWith(contactsUrl)) {
        folder.folderPath = href.replaceFirst(contactsUrl, CONTACTS);
    } else {
        int index = href.indexOf(mailPath.substring(0, mailPath.length() - 1));
        if (index >= 0) {
            if (index + mailPath.length() > href.length()) {
                folder.folderPath = "";
            } else {
                folder.folderPath = href.substring(index + mailPath.length());
            }
        } else {
            try {
                URI folderURI = new URI(href, false);
                folder.folderPath = folderURI.getPath();
            } catch (URIException e) {
                throw new DavMailException("EXCEPTION_INVALID_FOLDER_URL", href);
            }
        }
    }
    if (folder.folderPath.endsWith("/")) {
        folder.folderPath = folder.folderPath.substring(0, folder.folderPath.length() - 1);
    }
    return folder;
}