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

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

Introduction

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

Prototype

public NameValuePair(String name, String value) 

Source Link

Document

Constructor.

Usage

From source file:fr.openwide.talendalfresco.rest.client.RestAuthenticationTest.java

public void testRestLogout() {
    // first login
    testRestLogin();// w ww.j a v  a2s  .com

    // create client and configure it
    HttpClient client = new HttpClient();
    client.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);

    // instantiating a new method and configuring it
    GetMethod method = new GetMethod(restCommandUrlPrefix + "logout");
    method.setFollowRedirects(true); // ?
    // Provide custom retry handler is necessary (?)
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    NameValuePair[] params = new NameValuePair[] { new NameValuePair("ticket", ticket) }; // TODO always provide ticket
    method.setQueryString(params);

    try {
        // Execute the method.
        int statusCode = client.executeMethod(method);

        if (statusCode != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + method.getStatusLine());
        }

        // Read the response body.
        byte[] responseBody = method.getResponseBody();

        // Deal with the response.
        // Use caution: ensure correct character encoding and is not binary data
        System.out.println(new String(responseBody));

    } catch (HttpException e) {
        // TODO
        e.printStackTrace();
    } catch (IOException e) {
        // TODO
        e.printStackTrace();
    } finally {
        // Release the connection.
        method.releaseConnection();
    }
}

From source file:eu.learnpad.core.impl.sim.XwikiBridgeInterfaceRestResource.java

@Override
public String addProcessInstance(String processId, Collection<UserData> potentialUsers, String currentUser)
        throws LpRestException {
    HttpClient httpClient = this.getAnonymousClient();
    String uri = String.format("%s/learnpad/sim/bridge/instances/%s", this.restPrefix, processId);

    PostMethod postMethod = new PostMethod(uri);
    postMethod.addRequestHeader("Content-Type", "application/json");

    NameValuePair[] queryString = new NameValuePair[1];
    queryString[0] = new NameValuePair("currentuser", currentUser);
    postMethod.setQueryString(queryString);

    StringRequestEntity requestEntity = null;
    String potentialUsersJson = "[]";

    try {/*from w  w  w .  ja v  a  2  s . c  o  m*/
        potentialUsersJson = this.objectWriter.writeValueAsString(potentialUsers);
        requestEntity = new StringRequestEntity(potentialUsersJson, "application/json", "UTF-8");

        postMethod.setRequestEntity(requestEntity);

        httpClient.executeMethod(postMethod);

        return IOUtils.toString(postMethod.getResponseBodyAsStream());
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause());
    }
}

From source file:net.datapipe.CloudStack.CloudStackAPI.java

public Document deleteCondition(String id) throws Exception {
    LinkedList<NameValuePair> arguments = newQueryValues("deleteCondition", null);
    arguments.add(new NameValuePair("id", id));
    return Request(arguments);
}

From source file:gov.nih.nci.cabio.portal.portlet.GlobalQueries.java

private void loadAssemblies() {

    try {//from w w  w . java 2 s . c o  m
        log.info("Loading assembly data...");

        String hql = "select assembly, count(*) " + "from gov.nih.nci.cabio.domain.PhysicalLocation "
                + "group by assembly " + "order by count(*) desc ";

        List<Object[]> results = as.query(new HQLCriteria(hql, QueryUtils.createCountQuery(hql), null));

        assemblies = new ArrayList<NameValuePair>();

        for (Object[] row : results) {
            String assembly = (String) row[0];
            Long count = (Long) row[1];
            if (count >= MIN_ASSEMBLY_COUNT) {
                NameValuePair nv = new NameValuePair(assembly + " (" + count.toString() + " locations)",
                        assembly);
                assemblies.add(nv);
            }
        }
        log.info("Done loading assembly data.");
    } catch (Exception e) {
        log.error("Error loading assembly data.", e);
    }
}

From source file:eu.learnpad.core.impl.or.XwikiBridgeInterfaceRestResource.java

@Override
public void simulationInstanceNotification(String modelSetId, String modelId, String action,
        String simulationId, SimulationData data) throws LpRestException {
    // <host>/learnpad/or/bridge/{modelsetid}/{modelid}/simulationinstancenotification?action={started|stopped},simulationid=id
    String contentType = "application/xml";

    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/or/bridge/%s/%s/simulationinstancenotification",
            DefaultRestResource.REST_URI, modelSetId, modelId);
    PostMethod postMethod = new PostMethod(uri);
    postMethod.addRequestHeader("Content-Type", contentType);

    NameValuePair[] queryString = new NameValuePair[2];
    queryString[0] = new NameValuePair("action", action);
    queryString[1] = new NameValuePair("simulationid", simulationId);
    postMethod.setQueryString(queryString);

    try {// ww  w.  j  a va 2 s. c  om
        Writer simDataWriter = new StringWriter();
        JAXBContext jc = JAXBContext.newInstance(SimulationData.class);
        jc.createMarshaller().marshal(data, simDataWriter);

        RequestEntity requestEntity = new StringRequestEntity(simDataWriter.toString(), contentType, "UTF-8");
        postMethod.setRequestEntity(requestEntity);

        httpClient.executeMethod(postMethod);

    } catch (JAXBException | IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause());
    }
}

From source file:edu.uci.ics.asterix.test.aql.TestsUtils.java

public static InputStream executeQuery(String str, OutputFormat fmt) throws Exception {
    final String url = "http://localhost:19002/query";

    // Create a method instance.
    GetMethod method = new GetMethod(url);
    method.setQueryString(new NameValuePair[] { new NameValuePair("query", str) });
    method.setRequestHeader("Accept", fmt.mimeType());

    // Provide custom retry handler is necessary
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    executeHttpMethod(method);//from w  ww.  java 2 s  . co  m
    return method.getResponseBodyAsStream();
}

From source file:com.bigcommerce.http.QueryStringBuilder.java

/**
 * Invokes {@link #addQueryParameter(NameValuePair)} with a <code>String</code>
 * converted value./*ww  w  .  java 2  s  .  com*/
 */
public QueryStringBuilder addQueryParameter(final String name, final int value) {
    return addQueryParameter(new NameValuePair(name, String.valueOf(value)));
}

From source file:com.sfs.jbtimporter.JBTProcessor.java

/**
 * Passes the XML to Jira's Jelly runner.
 *
 * @param key the key//from   ww w . ja v a  2  s  .  com
 * @param xmldata the xmldata
 * @return the result from the jelly runner
 * @throws IOException Signals that an I/O exception has occurred.
 */
public final String importXML(final String key, final String xmldata) throws IOException {

    String result = "";

    final String runnerUrl = this.getBaseUrl() + this.jiraRunnerPath;

    PostMethod postMethod = new PostMethod(runnerUrl);
    NameValuePair[] data = { new NameValuePair("os_username", this.getUsername()),
            new NameValuePair("os_password", this.getPassword()), new NameValuePair("atl_token", key),
            new NameValuePair("file", ""), new NameValuePair("script", xmldata) };

    final String raw = postData(postMethod, data);

    if (raw.indexOf("xmlns:j='jelly:core'") > 0 || raw.indexOf("xmlns:j=\"jelly:core\"") > 0) {
        // The Jelly script has successfully run, capture outcome
        final int precount = 24;
        final int postcount = 4;
        // Value returned
        String startResult = raw.substring(raw.indexOf("xmlns:j='jelly:core'") + precount, raw.length());
        result = startResult.substring(0, startResult.indexOf("/JiraJelly") - postcount);
    }

    if (raw.indexOf("xmlns:j=&quot;jelly:core&quot;") > 0) {
        // The Jelly script has been run, capture outcome
        final int precount = 34;
        final int postcount = 4;
        // Value returned
        String startResult = raw.substring(raw.indexOf("xmlns:j=&quot;jelly:core&quot;") + precount,
                raw.length());
        result = startResult.substring(0, startResult.indexOf("/JiraJelly") - postcount);
    }

    if (raw.indexOf("id=\"scriptException\"") > 0) {
        // A script exception has been thrown. i.e. The script couldn't be run
        final int precount = 203;
        final int postcount = 1;
        // Value returned
        String startResult = raw.substring(raw.indexOf("id=\"scriptException\"") + precount, raw.length());
        result = startResult.substring(0, startResult.indexOf("/div") - postcount);
    }

    return reformatHtml(result);
}

From source file:com.dtolabs.client.utils.WebserviceHttpClientChannel.java

@Override
protected NameValuePair[] getRequestBody(final PostMethod method) {
    if (null != formData && formData.size() > 0) {
        final ArrayList<NameValuePair> list = new ArrayList<NameValuePair>();
        for (final Map.Entry<String, ? extends Object> stringStringEntry : formData.entrySet()) {
            final Object value = stringStringEntry.getValue();
            if (value instanceof String) {
                list.add(new NameValuePair(stringStringEntry.getKey(), (String) value));
            } else if (value instanceof Collection) {
                Collection values = (Collection) value;
                for (final Object o : values) {
                    list.add(new NameValuePair(stringStringEntry.getKey(), o.toString()));
                }// w w w .j  av a  2 s .  co  m
            }
        }
        return list.toArray(new NameValuePair[formData.size()]);
    } else {
        return null;
    }
}

From source file:com.apifest.oauth20.tests.OAuth20BasicTest.java

public String obtainAccessTokenResponse(String grantType, String authCode, String clientId, String clientSecret,
        String uri) {//from  w w w . jav a2s  .  c o m
    PostMethod post = new PostMethod(baseOAuth20Uri + TOKEN_ENDPOINT);
    String response = null;
    try {
        NameValuePair[] requestBody = { new NameValuePair(GRANT_TYPE_PARAM, grantType),
                new NameValuePair(CODE_PARAM, authCode), new NameValuePair(REDIRECT_URI_PARAM, uri),
                new NameValuePair(CLIENT_ID_PARAM, clientId),
                new NameValuePair(CLIENT_SECRET_PARAM, clientSecret) };
        post.setRequestHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
        post.setRequestHeader(HttpHeaders.AUTHORIZATION, createBasicAuthorization(clientId, clientSecret));
        post.setRequestBody(requestBody);
        response = readResponse(post);
        log.info(response);
    } catch (IOException e) {
        log.error("cannot obtain access token response", e);
    }
    return response;
}