Example usage for org.apache.commons.httpclient.methods PostMethod addParameter

List of usage examples for org.apache.commons.httpclient.methods PostMethod addParameter

Introduction

In this page you can find the example usage for org.apache.commons.httpclient.methods PostMethod addParameter.

Prototype

public void addParameter(String paramString1, String paramString2) throws IllegalArgumentException 

Source Link

Usage

From source file:org.phenotips.integration.lims247.internal.RemoteSynchronizationEventListener.java

/**
 * Notify a remote PhenoTips instance of a deleted document.
 *
 * @param doc the name of the deleted document
 * @param serverConfiguration the XObject holding the remote server configuration
 *//*from  w  w  w  .  jav  a  2  s  .  co  m*/
private void deleteData(String doc, BaseObject serverConfiguration) {
    // FIXME This should be asynchronous; reimplement!
    PostMethod method = null;
    try {
        String deleteURL = getDeleteURL(serverConfiguration);
        if (StringUtils.isNotBlank(deleteURL)) {
            this.logger.debug("Pushing deleted document to [{}]", deleteURL);
            method = new PostMethod(deleteURL);
            method.addParameter("document", doc);
            this.client.executeMethod(method);
        }
    } catch (Exception ex) {
        this.logger.warn("Failed to notify remote server of patient removal: {}", ex.getMessage(), ex);
    } finally {
        if (method != null) {
            method.releaseConnection();
        }
    }
}

From source file:org.redpill.alfresco.pdfapilot.client.PdfaPilotClientImpl.java

@Override
public void auditCreationResult(String id, boolean verified) {
    HttpClient client = getHttpClient();

    PostMethod method = new PostMethod(_serverUrl + "/bapi/v1/create/audit");

    method.getParams().setSoTimeout(_aliveCheckTimeout * 1000);
    method.getHostAuthState().setPreemptive();
    method.getParams().setContentCharset("UTF-8");

    method.addRequestHeader("Accept-Charset", "UTF-8");
    method.addRequestHeader("Accept-Language", "en-ca,en;q=0.8");
    method.addRequestHeader("Accept-Content", "application/text");

    try {//from  w  ww  .  j  a v  a 2 s.  c  o  m
        method.addParameter("id", id);
        method.addParameter("verified", verified ? "true" : "false");

        int status = client.executeMethod(method);

        if (status != 200) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Audit Create PDF failed: " + method.getStatusLine() + "\n"
                        + method.getResponseBodyAsString().trim());
            }

            throw new RuntimeException("Audit Create PDF failed: " + method.getStatusLine() + "\n"
                    + method.getResponseBodyAsString().trim());
        }
    } catch (Exception ex) {
        throw new RuntimeException("Audit Create PDF failed\n", ex);
    } finally {
        method.releaseConnection();
    }
}

From source file:org.sakaiproject.entitybroker.util.http.HttpRESTUtils.java

/**
 * Fire off a request to a URL using the specified method but reuse the client for efficiency,
 * include optional params and data in the request,
 * the response data will be returned in the object if the request can be carried out
 * /*from ww w.j  a v  a  2 s .  com*/
 * @param httpClientWrapper (optional) allows the http client to be reused for efficiency,
 * if null a new one will be created each time, use {@link #makeReusableHttpClient(boolean, int)} to
 * create a reusable instance
 * @param URL the url to send the request to (absolute or relative, can include query params)
 * @param method the method to use (e.g. GET, POST, etc.)
 * @param params (optional) params to send along with the request, will be encoded in the query string or in the body depending on the method
 * @param params (optional) headers to send along with the request, will be encoded in the headers
 * @param data (optional) data to send along in the body of the request, this only works for POST and PUT requests, ignored for the other types
 * @param guaranteeSSL if this is true then the request is sent in a mode which will allow self signed certs to work,
 * otherwise https requests will fail if the certs cannot be centrally verified
 * @return an object representing the response, includes data about the response
 * @throws HttpRequestException if the request cannot be processed for some reason (this is unrecoverable)
 */
@SuppressWarnings("deprecation")
public static HttpResponse fireRequest(HttpClientWrapper httpClientWrapper, String URL, Method method,
        Map<String, String> params, Map<String, String> headers, Object data, boolean guaranteeSSL) {
    if (guaranteeSSL) {
        // added this to attempt to force the SSL self signed certs to work
        Protocol myhttps = new Protocol("https", new EasySSLProtocolSocketFactory(), 443);
        Protocol.registerProtocol("https", myhttps);
    }

    if (httpClientWrapper == null || httpClientWrapper.getHttpClient() == null) {
        httpClientWrapper = makeReusableHttpClient(false, 0, null);
    }

    HttpMethod httpMethod = null;
    if (method.equals(Method.GET)) {
        GetMethod gm = new GetMethod(URL);
        // put params into query string
        gm.setQueryString(mergeQueryStringWithParams(gm.getQueryString(), params));
        // warn about data being set
        if (data != null) {
            System.out.println(
                    "WARN: data cannot be passed in GET requests, data will be ignored (org.sakaiproject.entitybroker.util.http.HttpUtils#fireRequest)");
        }
        gm.setFollowRedirects(true);
        httpMethod = gm;
    } else if (method.equals(Method.POST)) {
        PostMethod pm = new PostMethod(URL);
        // special handling for post params
        if (params != null) {
            for (Entry<String, String> entry : params.entrySet()) {
                if (entry.getKey() == null || entry.getValue() == null) {
                    System.out.println("WARN: null value supplied for param name (" + entry.getKey()
                            + ") or value (" + entry.getValue()
                            + ") (org.sakaiproject.entitybroker.util.http.HttpUtils#fireRequest)");
                }
                pm.addParameter(entry.getKey(), entry.getValue());
            }
        }
        // handle data
        handleRequestData(pm, data);
        httpMethod = pm;
    } else if (method.equals(Method.PUT)) {
        PutMethod pm = new PutMethod(URL);
        // put params into query string
        pm.setQueryString(mergeQueryStringWithParams(pm.getQueryString(), params));
        // handle data
        handleRequestData(pm, data);
        httpMethod = pm;
    } else if (method.equals(Method.DELETE)) {
        DeleteMethod dm = new DeleteMethod(URL);
        // put params into query string
        dm.setQueryString(mergeQueryStringWithParams(dm.getQueryString(), params));
        // warn about data being set
        if (data != null) {
            System.out.println(
                    "WARN: data cannot be passed in DELETE requests, data will be ignored (org.sakaiproject.entitybroker.util.http.HttpUtils#fireRequest)");
        }
        httpMethod = dm;
    } else {
        throw new IllegalArgumentException("Cannot handle method: " + method);
    }
    // set the headers for the request
    if (headers != null) {
        for (Entry<String, String> entry : headers.entrySet()) {
            httpMethod.addRequestHeader(entry.getKey(), entry.getValue());
        }
    }

    HttpResponse response = null;
    try {
        int responseCode = httpClientWrapper.getHttpClient().executeMethod(httpMethod);
        response = new HttpResponse(responseCode);

        // Avoid DOS because of large responses using up all memory in the system - https://jira.sakaiproject.org/browse/SAK-20405
        InputStream is = httpMethod.getResponseBodyAsStream();
        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = is.read(b)) != -1;) {
            out.append(new String(b, 0, n));
            if (out.length() > MAX_RESPONSE_SIZE_CHARS) {
                // die if the response exceeds the maximum chars allowed
                throw new HttpRequestException("Response size (" + out.length() + " chars) from url (" + URL
                        + ") exceeded the maximum allowed batch response size (" + MAX_RESPONSE_SIZE_CHARS
                        + " chars) while processing the response");
            }
        }
        String body = out.toString();

        //String body = httpMethod.getResponseBodyAsString();
        //         byte[] responseBody = httpMethod.getResponseBody();
        //         if (responseBody != null) {
        //            body = new String(responseBody, "UTF-8");
        //         }
        response.setResponseBody(body);
        response.setResponseMessage(httpMethod.getStatusText());
        // now get the headers
        HashMap<String, String[]> responseHeaders = new HashMap<String, String[]>();
        Header[] respHeaders = httpMethod.getResponseHeaders();
        for (int i = 0; i < respHeaders.length; i++) {
            Header header = respHeaders[i];
            // now we convert the headers from these odd pairs into something more like servlets expect
            HeaderElement[] elements = header.getElements();
            if (elements == null || elements.length == 0) {
                continue;
            } else if (elements.length >= 1) {
                String[] values = new String[elements.length];
                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < elements.length; j++) {
                    sb.setLength(0); // clear the StringBuilder
                    sb.append(elements[j].getName());
                    if (elements[j].getValue() != null) {
                        sb.append("=");
                        sb.append(elements[j].getValue());
                    }
                    values[j] = sb.toString();
                }
                responseHeaders.put(header.getName(), values);
            }
        }
        response.setResponseHeaders(responseHeaders);
    } catch (HttpException he) {
        // error contained in he.getMessage()
        throw new HttpRequestException(
                "Fatal HTTP Request Error: " + "Could not sucessfully fire request to url (" + URL
                        + ") using method (" + method + ")  :: " + he.getMessage(),
                he);
    } catch (IOException ioe) {
        // other exception
        throw new HttpIOException(
                "IOException (transport/connection) Error: " + "Could not sucessfully fire request to url ("
                        + URL + ") using method (" + method + ")  :: " + ioe.getMessage(),
                ioe);
    } finally {
        httpMethod.releaseConnection();
    }
    return response;
}

From source file:org.sakaiproject.nakamura.captcha.ReCaptchaService.java

/**
 * /*from  w ww .  j ava 2  s.  c  o  m*/
 * {@inheritDoc}
 * 
 * @see org.sakaiproject.nakamura.api.captcha.CaptchaService#checkRequest(javax.servlet.http.HttpServletRequest)
 */
public boolean checkRequest(HttpServletRequest request) {
    // We need the following things to verify a request with reCAPTCHA
    // - Our private key (privatekey)
    // - The user his IP address (remoteip)
    // - The challenge (challenge)
    // - The response (response)

    String challenge = request.getParameter(":recaptcha-challenge");
    String response = request.getParameter(":recaptcha-response");

    // No point in doing a request when this one is false.
    if (challenge == null || response == null) {
        return false;
    }

    PostMethod method = new PostMethod(endpoint);
    method.addParameter("privatekey", keyPrivate);
    method.addParameter("remoteip", request.getRemoteAddr());
    method.addParameter("challenge", challenge);
    method.addParameter("response", response);

    try {
        int code = client.executeMethod(method);
        if (code != 200) {
            LOGGER.warn(
                    "ReCaptcha request responded with {} {} if this persists enable debug logging on this class for more info ",
                    code, method.getStatusText());
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Response was {} ", method.getResponseBodyAsString());
            }
            return false;
        }

        InputStream bodyStream = method.getResponseBodyAsStream();
        StringWriter writer = new StringWriter();
        IOUtils.copy(bodyStream, writer);
        String body = writer.toString();

        LOGGER.debug("=== start of reCAPTCHA output ===\n" + body + "\n=== end of reCAPTCHA output ==="); // allow logging statement to show more clearly that the reCAPTCHA output contains a crlf character.
        if (!body.startsWith("true")) {
            LOGGER.warn("ReCaptcha challenge [{}] responde [{}] denied, debug level has more info ", challenge,
                    response);
            return false;
        }

        return true;
    } catch (HttpException e) {
        LOGGER.error("Caught an HTTPException when trying to check a request with the reCAPTCHA service.", e);
    } catch (IOException e) {
        LOGGER.error("Caught an IOException when trying to check a request with the reCAPTCHA service.", e);
    }

    return false;
}

From source file:org.sakaiproject.nakamura.docproxy.url.UrlRepositoryProcessor.java

public Map<String, Object> updateDocument(Node node, String path, Map<String, Object> properties,
        InputStream documentStream, long streamLength) throws DocProxyException {
    PostMethod method = new PostMethod(updateUrl + path);
    for (Entry<String, Object> entry : properties.entrySet()) {
        method.addParameter(entry.getKey(), entry.getValue().toString());
    }/*from w ww  .j  a  va  2 s.c o  m*/
    method.setRequestEntity(new InputStreamRequestEntity(documentStream));
    executeMethod(method, node);
    return null;
}

From source file:org.sakaiproject.nakamura.docproxy.url.UrlRepositoryProcessor.java

public ExternalSearchResultSet search(Node node, Map<String, Object> searchProperties)
        throws DocProxyException {
    try {/*from  w ww .  ja v  a2  s.c  o m*/
        PostMethod method = new PostMethod(searchUrl);
        for (Entry<String, Object> entry : searchProperties.entrySet()) {
            method.addParameter(entry.getKey(), entry.getValue().toString());
        }
        executeMethod(method, node);
        List<ExternalDocumentResult> results = parseSearch(method.getResponseBodyAsStream());
        ExternalSearchResultSet resultSet = new ExternalSearchResultSetImpl(results.iterator(),
                (long) results.size());
        return resultSet;
    } catch (XMLStreamException e) {
        throw new DocProxyException(500, e.getMessage());
    } catch (IOException e) {
        throw new DocProxyException(500, e.getMessage());
    }
}

From source file:org.sakaiproject.nakamura.grouper.changelog.HttpNakamuraManagerImpl.java

public void addMembership(String nakamuraGroupId, String memberId) throws GroupModificationException {
    String parentGroupId = groupIdAdapter.getWorldId(nakamuraGroupId);
    String role = StringUtils.substringAfterLast(nakamuraGroupId, "-");
    PostMethod method = new PostMethod(url.toString() + getUpdateURI(nakamuraGroupId));
    method.addParameter(MEMBER_PARAM, memberId);
    method.addParameter(VIEWER_PARAM, memberId);
    method.addParameter(CHARSET_PARAM, UTF_8);
    try {// w  w  w  .  ja va2s  . c o  m
        if (!dryrun) {
            NakamuraHttpUtils.http(NakamuraHttpUtils.getHttpClient(url, username, password), method);
            AuditLogUtils.audit(AuditLogUtils.USER_ADDED, memberId, parentGroupId, role, AuditLogUtils.SUCCESS);
        }
        log.info("Added subjectId=" + memberId + " to group=" + nakamuraGroupId);
    } catch (GrouperException ge) {
        AuditLogUtils.audit(AuditLogUtils.USER_ADDED, memberId, parentGroupId, role, AuditLogUtils.FAILURE);
        throw ge;
    }
}

From source file:org.sakaiproject.nakamura.grouper.changelog.HttpNakamuraManagerImpl.java

public void deleteMembership(String nakamuraGroupId, String memberId) throws GroupModificationException {
    String parentGroupId = groupIdAdapter.getWorldId(nakamuraGroupId);
    String role = StringUtils.substringAfterLast(nakamuraGroupId, "-");
    PostMethod method = new PostMethod(url.toString() + getUpdateURI(nakamuraGroupId));
    method.addParameter(MEMBER_DELETE_PARAM, memberId);
    method.addParameter(VIEWER_DELETE_PARAM, memberId);
    method.addParameter(CHARSET_PARAM, UTF_8);
    try {//  w w w  .j  av  a2  s .c o m
        if (!dryrun) {
            NakamuraHttpUtils.http(NakamuraHttpUtils.getHttpClient(url, username, password), method);
            AuditLogUtils.audit(AuditLogUtils.USER_DELETED, memberId, parentGroupId, role,
                    AuditLogUtils.SUCCESS);
        }
        log.info("Deleted subjectId=" + memberId + " from group=" + nakamuraGroupId);
    } catch (GrouperException ge) {
        AuditLogUtils.audit(AuditLogUtils.USER_DELETED, memberId, parentGroupId, role, AuditLogUtils.FAILURE);
        throw ge;
    }
}

From source file:org.sakaiproject.nakamura.grouper.changelog.HttpNakamuraManagerImpl.java

/**
 * Create a user in OAE if it doesn't exist.
 * @param userId/*from   ww  w. j av  a 2 s .  c  om*/
 * @throws Exception
 */
public void createUser(String userId) throws UserModificationException {

    if (dryrun || userExists(userId)) {
        return;
    }
    HttpClient client = NakamuraHttpUtils.getHttpClient(url, username, password);

    String fullName = null;
    try {
        // throws exception if not found or not unique
        Subject subject = SubjectFinder.findByIdOrIdentifier(userId, true);

        String randomPassword = UUID.randomUUID().toString();
        PostMethod method = new PostMethod(url.toString() + USER_CREATE_URI);

        // Get properties from the Grouper Subject
        String firstName = subject.getAttributeValue(firstNameAttribute);
        if (firstName == null) {
            firstName = "Firstname";
        }
        String lastName = subject.getAttributeValue(lastNameAttribute);
        if (lastName == null) {
            lastName = "Lastname";
        }

        fullName = firstName + " " + lastName;

        String email = subject.getAttributeValue(emailAttribute);
        if (email == null) {
            email = userId + "@" + defaultEmailDomain;
        }
        // Fill in the template
        String profileTemplate = "{\"basic\":{\"elements\":{\"firstName\":{\"value\":\"FIRSTNAME\"},\"lastName\":{\"value\":\"LASTNAME\"},\"email\":{\"value\":\"EMAIL\"}},\"access\":\"everybody\"},\"email\":\"EMAIL\"}}";
        profileTemplate = profileTemplate.replaceAll("FIRSTNAME", firstName).replaceAll("LASTNAME", lastName)
                .replaceAll("EMAIL", email);

        method.addParameter(NAME_PARAM, userId);
        method.addParameter(PWD_PARAM, randomPassword);
        method.addParameter(PWD_CONFIRM_PARAM, randomPassword);
        method.addParameter(FIRST_NAME_PARAM, firstName);
        method.addParameter(LAST_NAME_PARAM, lastName);
        method.addParameter(EMAIL_PARAM, email);
        method.addParameter(TIMEZONE_PARAM, "America/New_York");
        method.addParameter(LOCALE_PARAM, "en_US");
        method.addParameter(PROFILE_IMPORT_PARAM, profileTemplate);

        NakamuraHttpUtils.http(client, method);
        userExistsInSakai.put(userId, Boolean.TRUE);
        log.info("Created a user in Sakai OAE for " + userId);
        AuditLogUtils.audit(AuditLogUtils.USER_CREATED, userId, null, fullName, AuditLogUtils.SUCCESS);
    } catch (Exception e) {
        log.error("Unable to create the user in Sakai OAE", e);
        AuditLogUtils.audit(AuditLogUtils.USER_CREATED, userId, null, fullName, AuditLogUtils.FAILURE);
        throw new UserModificationException(e.getMessage());
    }
}

From source file:org.sakaiproject.nakamura.grouper.changelog.HttpNakamuraManagerImpl.java

/**
 * Create a pseudoGroup in Sakai OAE./*w  w  w  .  ja v  a2  s  .c  o  m*/
 * A pseudoGroup is an Authorizable that represents a role group for a course.
 * @param nakamuraGroupId the id of the psuedoGroup in OAE
 * @param groupName the name of the Grouper group.
 * @param description a description for the group in OAE
 * @throws GroupModificationException
 */
protected void createPseudoGroup(String nakamuraGroupId, String groupName, String description)
        throws GroupModificationException {
    String role = nakamuraGroupId.substring(nakamuraGroupId.lastIndexOf('-') + 1);
    HttpClient client = NakamuraHttpUtils.getHttpClient(url, username, password);
    PostMethod method = new PostMethod(url + GROUP_CREATE_URI);
    method.addParameter(":name", nakamuraGroupId);
    method.addParameter(CHARSET_PARAM, UTF_8);
    method.addParameter("sakai:group-id", nakamuraGroupId);
    method.addParameter("sakai:excludeSearch", WorldConstants.TRUE);
    method.addParameter("sakai:group-description", description);
    method.addParameter("sakai:group-title", nakamuraGroupId + "(" + role + ")");
    method.addParameter("sakai:pseudoGroup", WorldConstants.TRUE);
    method.addParameter("sakai:pseudogroupparent", groupIdAdapter.getWorldId(nakamuraGroupId));
    method.setParameter("sakai:group-joinable", WorldConstants.NO);
    method.addParameter(GROUPER_NAME_PROP, groupName.substring(0, groupName.lastIndexOf(":") + 1)
            + nakamuraGroupId.substring(nakamuraGroupId.lastIndexOf("-") + 1));
    method.setParameter(GROUPER_PROVISIONED_PROP, WorldConstants.TRUE);

    try {
        if (!dryrun) {
            NakamuraHttpUtils.http(client, method);
        }
        log.info("Created pseudoGroup in OAE for " + nakamuraGroupId);
        AuditLogUtils.audit(AuditLogUtils.GROUP_CREATED, null, nakamuraGroupId, description,
                AuditLogUtils.SUCCESS);
    } catch (GroupModificationException e) {
        AuditLogUtils.audit(AuditLogUtils.GROUP_CREATED, null, nakamuraGroupId, description,
                AuditLogUtils.FAILURE);
        throw e;
    }
}