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

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

Introduction

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

Prototype

public abstract URI getURI() throws URIException;

Source Link

Usage

From source file:net.sf.sail.webapp.domain.webservice.http.impl.HttpRestTransportImpl.java

private void logRequest(HttpMethod method, String bodyData) throws URIException {
    if (logger.isInfoEnabled()) {
        logger.info(method.getName() + ": " + method.getURI());
        if (bodyData != "")
            logger.info(method.getName() + ": " + bodyData);
    }/*from  ww  w .  j a  va2  s .  c o  m*/
}

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

/**
 * Adds the cas ticket from tgt.//from  w  w w . j  a v  a2s .co m
 *
 * @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.gisgraphy.rest.RestClient.java

private InputStream executeMethod(HttpMethod httpMethod) throws RestClientException {
    int statusCode = -1;
    try {//from w ww .j a  v a2 s. c  o m
        statusCode = executeAndCheckStatusCode(httpMethod);
        logger.info("URL " + httpMethod.getURI() + " returns http status :" + statusCode);
        return httpMethod.getResponseBodyAsStream();
    } catch (HttpException e) {
        throw new RestClientException(statusCode, e.getMessage());
    } catch (IOException e) {
        throw new RestClientException(statusCode, e.getMessage());
    }
}

From source file:com.baidu.oped.apm.profiler.modifier.connector.httpclient3.interceptor.ExecuteInterceptor.java

@Override
public void after(Object target, Object[] args, Object result, Throwable throwable) {
    if (isDebug) {
        logger.afterInterceptor(target, args);
    }/*from w w  w. jav a2s.  c  om*/

    final Trace trace = traceContext.currentTraceObject();

    if (trace == null) {
        return;
    }

    try {
        HttpMethod httpMethod = getHttpMethod(args);

        if (httpMethod != null) {
            try {
                final URI uri = httpMethod.getURI();
                String uriString = uri.getURI();
                trace.recordAttribute(AnnotationKey.HTTP_URL, uriString);
                trace.recordDestinationId(getEndpoint(uri.getHost(), uri.getPort()));
            } catch (URIException e) {
                logger.error("Fail get URI", e);
            }

            recordRequest(trace, httpMethod, throwable);
        }

        if (result != null) {
            trace.recordAttribute(AnnotationKey.HTTP_STATUS_CODE, result);
        }

        trace.recordApi(descriptor);
        trace.recordException(throwable);
        trace.markAfterTime();
    } finally {
        trace.traceBlockEnd();
    }
}

From source file:com.navercorp.pinpoint.plugin.httpclient3.interceptor.ExecuteInterceptor.java

@Override
public void after(Object target, Object[] args, Object result, Throwable throwable) {
    if (isDebug) {
        logger.afterInterceptor(target, args);
    }/*from  w  ww  .  ja  v a2s.co m*/

    final Trace trace = traceContext.currentTraceObject();
    if (trace == null) {
        return;
    }

    try {
        HttpMethod httpMethod = getHttpMethod(args);
        if (httpMethod != null) {
            try {
                final URI uri = httpMethod.getURI();
                String uriString = uri.getURI();
                trace.recordAttribute(AnnotationKey.HTTP_URL, uriString);
                trace.recordDestinationId(getEndpoint(uri.getHost(), uri.getPort()));
            } catch (URIException e) {
                logger.error("Fail get URI", e);
            }

            recordRequest(trace, httpMethod, throwable);
        }

        if (result != null) {
            trace.recordAttribute(AnnotationKey.HTTP_STATUS_CODE, result);
        }

        trace.recordApi(descriptor);
        trace.recordException(throwable);
        trace.markAfterTime();
    } finally {
        trace.traceBlockEnd();
    }
}

From source file:com.mrfeinberg.translation.AbstractTranslationService.java

public Runnable translate(final String phrase, final LanguagePair lp, final TranslationListener listener) {
    final Language b = lp.b();

    final HttpClient httpClient = new HttpClient();
    if (proxyPrefs.getUseProxy()) {
        httpClient.getHostConfiguration().setProxy(proxyPrefs.getProxyHost(), proxyPrefs.getProxyPort());
    }//ww  w .j a  v  a 2s.c o m

    final HttpMethod httpMethod = getHttpMethod(phrase, lp);
    final Callable<String> callable = new Callable<String>() {
        public String call() throws Exception {
            int result = httpClient.executeMethod(httpMethod);
            if (result != 200) {
                throw new Exception("Got " + result + " status for " + httpMethod.getURI());
            }
            final BufferedReader in = new BufferedReader(
                    new InputStreamReader(httpMethod.getResponseBodyAsStream(), "utf8"));
            try {
                final StringBuilder sb = new StringBuilder();
                String line;
                while ((line = in.readLine()) != null)
                    sb.append(line);
                return sb.toString();
            } finally {
                in.close();
                httpMethod.releaseConnection();
            }
        }
    };
    final FutureTask<String> tc = new FutureTask<String>(callable);
    return new Runnable() {
        public void run() {
            try {
                executor.execute(tc);
                final String result = tc.get(timeout, TimeUnit.MILLISECONDS);
                String found = findTranslatedText(result);
                if (found == null) {
                    listener.error("Cannot find translated text in result.");
                } else {
                    found = found.replaceAll("\\s+", " ");
                    listener.result(found, b);
                }
            } catch (final TimeoutException e) {
                listener.timedOut();
            } catch (final InterruptedException e) {
                listener.cancelled();
            } catch (final Exception e) {
                e.printStackTrace();
                listener.error(e.toString());
            }
        }
    };
}

From source file:davmail.http.SpNegoScheme.java

/**
 * Produces Negotiate authorization string for the given set of
 * {@link Credentials}./*w  w  w  . j a  v  a 2s. c om*/
 *
 * @param credentials The set of credentials to be used for authentication
 * @param httpMethod  The method being authenticated
 * @return an Negotiate authorization string
 * @throws org.apache.commons.httpclient.auth.InvalidCredentialsException
 *                                 if authentication credentials
 *                                 are not valid or not applicable for this authentication scheme
 * @throws AuthenticationException if authorization string cannot
 *                                 be generated due to an authentication failure
 */
public String authenticate(Credentials credentials, HttpMethod httpMethod) throws AuthenticationException {
    if (this.state == UNINITIATED) {
        throw new IllegalStateException("Negotiate authentication process has not been initiated");
    }
    String host = null;
    try {
        host = httpMethod.getURI().getHost();
    } catch (URIException e) {
        // ignore
    }
    if (host == null) {
        Header header = httpMethod.getRequestHeader("Host");
        if (header != null) {
            host = header.getValue();
            if (host.indexOf(':') >= 0) {
                host = host.substring(0, host.indexOf(':'));
            }
        }
    }
    if (host == null) {
        throw new IllegalStateException("Negotiate authentication failed: empty host");
    }

    // no credentials needed
    String response;
    try {
        if (this.state == INITIATED || this.state == FAILED) {
            // send initial token to server
            response = EncodingUtil.getAsciiString(
                    Base64.encodeBase64(KerberosHelper.initSecurityContext("HTTP", host, new byte[0])));
            this.state = TYPE1_MSG_GENERATED;
        } else {
            // send challenge response
            response = EncodingUtil.getAsciiString(
                    Base64.encodeBase64(KerberosHelper.initSecurityContext("HTTP", host, serverToken)));
            this.state = TYPE3_MSG_GENERATED;
        }
    } catch (GSSException gsse) {
        state = FAILED;
        if (gsse.getMajor() == GSSException.DEFECTIVE_CREDENTIAL
                || gsse.getMajor() == GSSException.CREDENTIALS_EXPIRED)
            throw new InvalidCredentialsException(gsse.getMessage(), gsse);
        if (gsse.getMajor() == GSSException.NO_CRED)
            throw new CredentialsNotAvailableException(gsse.getMessage(), gsse);
        if (gsse.getMajor() == GSSException.DEFECTIVE_TOKEN || gsse.getMajor() == GSSException.DUPLICATE_TOKEN
                || gsse.getMajor() == GSSException.OLD_TOKEN)
            throw new AuthChallengeException(gsse.getMessage(), gsse);
        // other error
        throw new AuthenticationException(gsse.getMessage(), gsse);
    } catch (LoginException e) {
        state = FAILED;
        throw new InvalidCredentialsException(e.getMessage(), e);
    }
    return "Negotiate " + response;
}

From source file:net.sourceforge.jcctray.model.HTTPCruise.java

private boolean isInvokeSuccessful(HttpMethod method, DashBoardProject project) throws InvocationException {
    try {//from   w w w  .  j ava 2  s .c o  m
        String message = getSuccessMessage(project);
        boolean invokeSuccessful = (method.getResponseBodyAsString().indexOf(message) > -1);
        if (!invokeSuccessful)
            getLog().error(
                    "Could not find the string '" + message + "' in the page located at " + method.getURI());
        return invokeSuccessful;
    } catch (IOException e) {
        getLog().error("Attempted to force the build, but the force was not successful", e);
        throw new InvocationException("Attempted to force the build, but the force was not successful", e);
    }
}

From source file:com.thoughtworks.go.agent.launcher.ServerCall.java

public static ServerResponseWrapper invoke(HttpMethod method) throws Exception {
    HashMap<String, String> headers = new HashMap<String, String>();
    HttpClient httpClient = new HttpClient();
    httpClient.setConnectionTimeout(HTTP_TIMEOUT_IN_MILLISECONDS);
    try {/*w  w w .ja v a 2  s. co  m*/
        final int status = httpClient.executeMethod(method);
        if (status == HttpStatus.SC_NOT_FOUND) {
            StringWriter sw = new StringWriter();
            PrintWriter out = new PrintWriter(sw);
            out.println("Return Code: " + status);
            out.println("Few Possible Causes: ");
            out.println("1. Your Go Server is down or not accessible.");
            out.println(
                    "2. This agent might be incompatible with your Go Server.Please fix the version mismatch between Go Server and Go Agent.");
            out.close();
            throw new Exception(sw.toString());
        }
        if (status != HttpStatus.SC_OK) {
            throw new Exception("Got status " + status + " " + method.getStatusText() + " from server");
        }
        for (Header header : method.getResponseHeaders()) {
            headers.put(header.getName(), header.getValue());
        }
        return new ServerResponseWrapper(headers, method.getResponseBodyAsStream());
    } catch (Exception e) {
        String message = "Couldn't access Go Server with base url: " + method.getURI() + ": " + e.toString();
        LOG.error(message);
        throw new Exception(message, e);
    } finally {
        method.releaseConnection();
    }
}

From source file:com.zimbra.cs.dav.client.WebDavClient.java

private void logRequestInfo(HttpMethod method, String body) throws IOException {
    if (!mDebugEnabled) {
        return;//from   ww  w  .  jav  a  2 s  . c om
    }
    StringBuilder reqLog = new StringBuilder();
    reqLog.append("WebDAV request:\n").append(method.getName()).append(" ").append(method.getURI().toString());
    reqLog.append('\n');
    Header headers[] = method.getRequestHeaders();
    if (headers != null && headers.length > 0) {
        for (Header hdr : headers) {
            String hdrName = hdr.getName();
            reqLog.append(hdrName).append('=');
            if (hdrName.contains("Auth") || (hdrName.contains(HttpHeaders.COOKIE))) {
                reqLog.append("*** REPLACED ***\n");
            } else {
                reqLog.append(hdr.getValue()).append('\n');
            }
        }
    }
    if (Strings.isNullOrEmpty(body) || !ZimbraLog.dav.isTraceEnabled()) {
        ZimbraLog.dav.debug(reqLog.toString());
    } else {
        ZimbraLog.dav.debug("%s\n%s", reqLog.toString(), body);
    }
}