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

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

Introduction

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

Prototype

public abstract String getPath();

Source Link

Usage

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

/**
 * Execute the given method, authenticated as the given user using ticket-based authentication.
 * @param method method to execute/*w w  w. java 2  s . c  o m*/
 * @param userName name of user to authenticate
 * @return status-code resulting from the request
 */
private <T extends Object> T executeWithTicketAuthentication(HttpMethod method, String userName,
        String password, HttpRequestCallback<T> callback) {
    String ticket = authDetailProvider.getTicketForUser(userName);
    if (ticket == null) {
        ticket = fetchLoginTicket(userName, password);
        authDetailProvider.updateTicketForUser(userName, ticket);
    }

    try {
        HttpState state = applyTicketToMethod(method, ticket);

        // Try executing the method
        int result = httpProvider.getHttpClient().executeMethod(null, method, state);

        if (result == HttpStatus.SC_UNAUTHORIZED || result == HttpStatus.SC_FORBIDDEN) {
            method.releaseConnection();
            if (!method.validate()) {
                throw new RuntimeException(
                        "Ticket re-authentication failed for user " + userName + " (HTTPMethod not reusable)");
            }
            // Fetch new ticket, store and apply to HttpMethod
            ticket = fetchLoginTicket(userName, userName);
            authDetailProvider.updateTicketForUser(userName, ticket);

            state = applyTicketToMethod(method, ticket);

            // Run method agian with new ticket
            result = httpProvider.getHttpClient().executeMethod(null, method, state);
        }

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

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

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

    } finally {
        method.releaseConnection();
    }

}

From source file:org.alfresco.wcm.client.impl.WebScriptCallerImpl.java

private void executeRequest(WebscriptResponseHandler handler, HttpMethod httpMethod,
        boolean ignoreUnauthorized) {
    long startTime = 0L;
    if (log.isDebugEnabled()) {
        startTime = System.currentTimeMillis();
    }//from  w ww  .  j  a  va2s. c  om
    try {
        httpClient.executeMethod(httpMethod);

        if ((httpMethod.getStatusCode() == 401 || httpMethod.getStatusCode() == 403) && !ignoreUnauthorized) {
            discardResponse(httpMethod);

            this.getTicket(username, password);
            httpClient.executeMethod(httpMethod);
        }

        if (httpMethod.getStatusCode() == 200) {
            handler.handleResponse(httpMethod.getResponseBodyAsStream());
        } else {
            // Must read the response, even though we don't use it
            discardResponse(httpMethod);
        }
    } catch (RuntimeException ex) {
        log.error("Rethrowing runtime exception.", ex);
        throw ex;
    } catch (Exception ex) {
        log.error("Failed to make request to Alfresco web script", ex);
    } finally {
        if (log.isDebugEnabled()) {
            log.debug(httpMethod.getName() + " request to " + httpMethod.getPath() + "?"
                    + httpMethod.getQueryString() + " completed in " + (System.currentTimeMillis() - startTime)
                    + "ms");
        }
        httpMethod.releaseConnection();
    }
}

From source file:org.alfresco.wcm.client.impl.WebScriptCallerImpl.java

void discardResponse(HttpMethod httpMethod) throws IOException {
    if (log.isDebugEnabled()) {
        log.debug("Received non-OK response when invoking method on path " + httpMethod.getPath()
                + ". Response was:\n" + httpMethod.getResponseBodyAsString());
    } else {//from w  ww.j  a  v a  2 s .  co  m
        byte[] buf = localBuffer.get();
        InputStream responseStream = httpMethod.getResponseBodyAsStream();
        while (responseStream.read(buf) != -1)
            ;
    }
}

From source file:org.apache.sling.discovery.impl.topology.connector.TopologyRequestValidator.java

/**
 * Decode a response from the server.//from   ww w .j a v a2 s  .co m
 *
 * @param method the method that received the response.
 * @return the message in clear text.
 * @throws IOException if there was a problem decoding the message.
 */
public String decodeMessage(HttpMethod method) throws IOException {
    checkActive();
    return decodeMessage("response:", method.getPath(), getResponseBody(method),
            getResponseHeader(method, HASH_HEADER));
}

From source file:org.apache.sling.discovery.impl.topology.connector.TopologyRequestValidator.java

/**
 * Trust a message on the client before sending, only if trust is enabled.
 *
 * @param method the method which will have headers set after the call.
 * @param body the body.//from   ww  w  .  j ava  2  s  . c o  m
 */
public void trustMessage(HttpMethod method, String body) {
    checkActive();
    if (trustEnabled) {
        String bodyHash = hash("request:" + method.getPath() + ":" + body);
        method.setRequestHeader(HASH_HEADER, bodyHash);
        method.setRequestHeader(SIG_HEADER, createTrustHeader(bodyHash));
    }
}

From source file:org.apache.webdav.lib.WebdavResource.java

/**
 * Generate and add the If header to the specified HTTP method.
 *///from  ww w .j  a v  a  2  s.c o m
protected void generateIfHeader(HttpMethod method) {

    if (client == null)
        return;
    if (method == null)
        return;

    WebdavState state = (WebdavState) client.getState();
    String[] lockTokens = state.getAllLocks(method.getPath());

    if (lockTokens.length == 0)
        return;

    StringBuffer ifHeaderValue = new StringBuffer();

    for (int i = 0; i < lockTokens.length; i++) {
        ifHeaderValue.append("(<").append(lockTokens[i]).append(">) ");
    }

    method.setRequestHeader("If", ifHeaderValue.toString());

}

From source file:org.chiba.xml.xforms.connector.http.AbstractHTTPConnector.java

protected void execute(HttpMethod httpMethod) throws Exception {
    //      (new HttpClient()).executeMethod(httpMethod);
    HttpClient client = new HttpClient();

    if (submissionMap != null) {
        String sessionid = submissionMap.get(ChibaAdapter.SESSION_ID).toString();
        if (sessionid != null) {
            HttpState state = client.getState();
            state.setCookiePolicy(CookiePolicy.COMPATIBILITY);
            state.addCookie(new Cookie(httpMethod.getURI().getHost(), "JSESSIONID", sessionid,
                    httpMethod.getPath(), null, false));
            client.setState(state);/*from   w  w  w . j av  a 2 s  . c  o  m*/
        }
    }

    client.executeMethod(httpMethod);

    if (httpMethod.getStatusCode() >= 300) {
        throw new XFormsException(
                "HTTP status " + httpMethod.getStatusCode() + ": " + httpMethod.getStatusText());
    }
    this.handleHttpMethod(httpMethod);
}

From source file:org.colombbus.tangara.net.CommandExceptionFactory.java

public static BadServerCmdException createBadServerException(HttpMethod method, int code, String msg) {
    return new BadServerCmdException(method.getPath(), code, msg);
}

From source file:org.colombbus.tangara.net.CommandExceptionFactory.java

public static BadServerCmdException createBadServerException(HttpMethod method, int code, String msg,
        Throwable th) {//from   ww  w  .ja  va  2  s. c om
    return new BadServerCmdException(method.getPath(), code, msg, th);
}

From source file:org.colombbus.tangara.net.CommandExceptionFactory.java

public static CommandException createException(HttpMethod method, int code, String msg, Throwable th) {
    CommandException cmdEx = null;//from  w w w.j ava2 s  .co  m

    // MalformedCommandException
    // BadServerCmdException
    Class<?> exClass = null;
    switch (code) {
    case 1: // Could not connect to database
    case 2: // Could not select database
    case 3: // Connection count query failed
    case 4: // Old connection removing query failed
    case 7: // List user query failed
    case 10: // Insert registration query failed
        // FIXME, the remove registration has the same error code
    case 11: // Delete all objects query failed
    case 14: // List objects query failed
    case 15: // Insert object registration query failed. <sql error code>
    case 16: // Unregister object failed. <sql error code>
    case 17: // Fail to start transaction
    case 18: // Fail to commit transaction
    case 19: // Fail to analyse message
    case 20: // Fail to insert message
    case 21: // Fail to list messages
    case 22: // Fail to find a connection
    case 26: // Fail to update last connection time
    case 28: // Old connection message removing query failed
    case 29: // Fail to find previous unset messages
    case 30: // Fail to delete previous unset messages
    case 36: // QUERY_FAILURE The query execution failed [$query]
        exClass = InternalSeverCmdException.class;
        break;
    case 5: // No action defined
    case 6: // Unsupported action +$action
    case 8: // username parameter not defined
    case 9: // connectID parameter not defined
    case 12: // objectname parameter not defined
    case 13: // objectclass parameter not defined
    case 24: // ipAddress parameter not defined
        exClass = MalformedCommandException.class;
        break;
    case 23: // User $username already exists with address $ipAddress //
        // already connected
    case 25: // User already connected // already exists
    case 27: // Unknown user
    case 31: // Fail to get username from connectID $connectID
    case 32: // Fail to register avatar image of user $connectID
    case 34: // Fail to get avatar image of user $username
        exClass = BadParamCmdException.class;
        break;
    case 35: // NOT_CONNECTED The connectID $connectID does not exist
        exClass = UnknownUserCmdException.class;
        break;
    default:
        LOG.warn("unhandled error code " + code);
        exClass = CommandException.class;
    }

    try {
        Constructor<?> construct = null;
        Object[] args = null;
        if (th == null) {
            construct = exClass.getConstructor(String.class, Integer.TYPE, String.class);
            args = new Object[3];
            args[0] = method.getPath();
            args[1] = code;
            args[2] = msg;
        } else {
            construct = exClass.getConstructor(String.class, Integer.TYPE, String.class, Throwable.class);
            args = new Object[4];
            args[0] = method.getPath();
            args[1] = code;
            args[2] = msg;
            args[3] = th;
        }
        cmdEx = (CommandException) construct.newInstance(args);
    } catch (Throwable thEx) {
        LOG.error("Cannot instanciate the dedicated command exception", thEx);
        if (th == null) {
            cmdEx = new CommandException(method.getPath(), 0, msg);
        } else {
            cmdEx = new CommandException(method.getPath(), 0, msg, th);
        }
    }

    return cmdEx;
}