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:edu.stanford.epad.epadws.processing.pipeline.task.PluginStartTask.java

@Override
public void run() {
    String username = EPADSessionOperations.getSessionUser(jsessionID);
    EpadProjectOperations projectOperations = DefaultEpadProjectOperations.getInstance();
    projectOperations.createEventLog(username, projectID, null, null, null, null, annotationID, "Start PlugIn",
            pluginName);/*from  w  ww  .j  av  a2s. co m*/
    HttpClient client = new HttpClient(); // TODO Get rid of localhost
    String url = EPADConfig.getParamValue("serverProxy", "http://localhost:8080")
            + EPADConfig.getParamValue("webserviceBase", "/epad") + "/plugin/" + pluginName + "/?" //aimFile=" + annotationID 
            + "&frameNumber=" + frameNumber + "&projectID=" + projectID;
    if (annotationID != null)
        url += "&aimFile=" + annotationID;
    //        else
    //           url+="&aimFile=" + getAnnotationIDs();
    log.info("Triggering ePAD plugin at " + url + " is annotation null " + (annotationID != null));
    projectOperations.updateUserTaskStatus(username, TaskStatus.TASK_PLUGIN,
            pluginName.toLowerCase() + ":" + annotationID, "Started Plugin", new Date(), null);
    GetMethod method = new GetMethod(url);
    log.info("pluginurl " + url);

    if (annotationID == null && annotationIDs.length > 0) {
        NameValuePair[] params = new NameValuePair[annotationIDs.length + 2];
        int i = 0;
        for (String aimId : annotationIDs) {
            params[i++] = new NameValuePair("aims", aimId);
        }
        params[i++] = new NameValuePair("frameNumber", String.valueOf(frameNumber));
        params[i] = new NameValuePair("projectID", projectID);
        method.setQueryString(params);
    }
    method.setRequestHeader("Cookie", "JSESSIONID=" + jsessionID);
    try {
        int statusCode = client.executeMethod(method);
        log.info("Status code returned from plugin " + statusCode);
    } catch (Exception e) {
        log.warning("Error calling plugin " + pluginName, e);
        try {
            PluginOperations pluginOperations = PluginOperations.getInstance();
            Plugin plugin = pluginOperations.getPluginByName(pluginName);
            plugin.setStatus("Error calling plugin :" + e.getMessage());
            plugin.save();
        } catch (Exception e1) {
        }

    } finally {
        method.releaseConnection();
    }

}

From source file:eu.learnpad.core.impl.cw.XwikiCoreFacadeRestResource.java

@Override
public String getDashboardKpiDefaultViewer(String modelSetId, String userId) throws LpRestException {
    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/cw/corefacade/dashboardkpi/viewer", DefaultRestResource.REST_URI);
    GetMethod getMethod = new GetMethod(uri);
    getMethod.addRequestHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML);

    NameValuePair[] queryString = new NameValuePair[2];
    queryString[0] = new NameValuePair("modelsetid", modelSetId);
    queryString[1] = new NameValuePair("userid", userId);
    getMethod.setQueryString(queryString);

    try {// w ww .ja va2 s  . c  om
        httpClient.executeMethod(getMethod);
        String url = getMethod.getResponseBodyAsString();
        return url;
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e);
    }
}

From source file:com.wordpress.metaphorm.authProxy.httpClient.impl.OAuthProxyConnectionApacheHttpCommonsClientImpl.java

/**
 * Sets up the given {@link PostMethod} to send the same standard POST
 * data as was sent in the given {@link HttpServletRequest}
 * @param postMethodProxyRequest The {@link PostMethod} that we are
 *                                configuring to send a standard POST request
 * @param httpServletRequest The {@link HttpServletRequest} that contains
 *                            the POST data to be sent via the {@link PostMethod}
 *//*from  w ww.  ja  v a  2s.c  om*/
@SuppressWarnings("unchecked")
private void handleStandardPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest) {

    _log.debug("handleStandardPost()");

    // Get the client POST data as a Map
    Map<String, String[]> mapPostParameters = (Map<String, String[]>) httpServletRequest.getParameterMap();
    // Create a List to hold the NameValuePairs to be passed to the PostMethod
    List<NameValuePair> listNameValuePairs = new ArrayList<NameValuePair>();
    // Iterate the parameter names
    for (String stringParameterName : mapPostParameters.keySet()) {

        StringBuffer debugMsg = new StringBuffer();
        debugMsg.append("Post param: " + stringParameterName);

        // Iterate the values for each parameter name
        String[] stringArrayParameterValues = mapPostParameters.get(stringParameterName);
        for (String stringParamterValue : stringArrayParameterValues) {

            debugMsg.append(" \"" + stringParamterValue + "\"");

            // Create a NameValuePair and store in list
            NameValuePair nameValuePair = new NameValuePair(stringParameterName, stringParamterValue);
            listNameValuePairs.add(nameValuePair);
        }
        _log.debug(debugMsg.toString());
    }
    // Set the proxy request POST data 
    postMethodProxyRequest.setRequestBody(listNameValuePairs.toArray(new NameValuePair[] {}));
}

From source file:edu.ku.brc.specify.tasks.StatsTrackerTask.java

/**
 * @param stats//from w ww.  j  ava2s  .c om
 * @param valName
 * @param value
 */
private void addEncodedPair(final Vector<NameValuePair> stats, final String valName, final String value) {
    String val = "";
    try {
        val = URLEncoder.encode(value, "UTF-8");
    } catch (Exception ex) {
    }
    //System.out.println(String.format("[%s][%s]", valName, val));
    stats.add(new NameValuePair(valName, val));
}

From source file:fr.openwide.talendalfresco.rest.client.importer.RestImportFileTest.java

public void logout() {
    // 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);//from  ww  w .  j a  va  2s  .com

    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:de.laeubisoft.tools.ant.validation.W3CMarkupValidationTask.java

/**
 * Creates the actual request to the validation server for a given
 * {@link URL} and returns an inputstream the result can be read from
 * //from w w w.  ja  v  a  2s.co  m
 * @param uriToCheck
 *            the URL to check
 * @return the stream to read the response from
 * @throws IOException
 *             if unrecoverable communication error occurs
 * @throws BuildException
 *             if server returned unexspected results
 */
private InputStream buildConnection(final URL uriToCheck) throws IOException, BuildException {
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new NameValuePair("output", VALIDATOR_FORMAT_OUTPUT));
    if (uriToCheck != null) {
        params.add(new NameValuePair("uri", uriToCheck.toString()));
    } else {
        if (fragment != null) {
            params.add(new NameValuePair("fragment", fragment));
        }
    }
    if (debug) {
        params.add(new NameValuePair("debug", "1"));
    }
    if (charset != null) {
        params.add(new NameValuePair("charset", charset));
    }
    if (doctype != null) {
        params.add(new NameValuePair("doctype", doctype));
    }
    HttpClient httpClient = new HttpClient();
    HttpMethodBase method;
    if (uriToCheck != null) {
        //URIs must be checked wia traditonal GET...
        GetMethod getMethod = new GetMethod(validator);
        getMethod.setQueryString(params.toArray(new NameValuePair[0]));
        method = getMethod;
    } else {
        PostMethod postMethod = new PostMethod(validator);
        if (fragment != null) {
            //Fragment request can be checked via FORM Submission
            postMethod.addParameters(params.toArray(new NameValuePair[0]));
        } else {
            //Finally files must be checked with multipart-forms....
            postMethod.setRequestEntity(Tools.createFileUpload(uploaded_file, "uploaded_file", charset, params,
                    postMethod.getParams()));
        }
        method = postMethod;
    }
    int result = httpClient.executeMethod(method);
    if (result == HttpStatus.SC_OK) {
        return method.getResponseBodyAsStream();
    } else {
        throw new BuildException("Server returned " + result + " " + method.getStatusText());
    }

}

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

public String obtainPasswordCredentialsAccessTokenResponse(String currentClientId, String currentClientSecret,
        String username, String password, String scope, boolean addAuthHeader) {
    PostMethod post = new PostMethod(baseOAuth20Uri + TOKEN_ENDPOINT);
    String response = null;//  w w w .  j  av  a2s.  c om
    try {
        post.setRequestHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
        if (addAuthHeader) {
            post.setRequestHeader(HttpHeaders.AUTHORIZATION,
                    createBasicAuthorization(currentClientId, currentClientSecret));
            NameValuePair[] requestBody = { new NameValuePair(GRANT_TYPE_PARAM, GRANT_TYPE_PASSWORD),
                    new NameValuePair("username", username), new NameValuePair("password", password),
                    new NameValuePair(SCOPE_PARAM, scope) };
            post.setRequestBody(requestBody);
        } else {
            NameValuePair[] requestBody = { new NameValuePair(GRANT_TYPE_PARAM, GRANT_TYPE_PASSWORD),
                    new NameValuePair("username", username), new NameValuePair("password", password),
                    new NameValuePair(SCOPE_PARAM, scope), new NameValuePair(CLIENT_ID_PARAM, currentClientId),
                    new NameValuePair(CLIENT_SECRET_PARAM, currentClientSecret) };
            post.setRequestBody(requestBody);
        }
        response = readResponse(post);
        log.info(response);
    } catch (IOException e) {
        log.error("cannot obtain password acces token response", e);
    }
    return response;
}

From source file:com.qlkh.client.server.proxy.ProxyServlet.java

/**
 * Sets up the given {@link org.apache.commons.httpclient.methods.PostMethod} to send the same standard POST
 * data as was sent in the given {@link javax.servlet.http.HttpServletRequest}
 *
 * @param postMethodProxyRequest The {@link org.apache.commons.httpclient.methods.PostMethod} that we are
 *                               configuring to send a standard POST request
 * @param httpServletRequest     The {@link javax.servlet.http.HttpServletRequest} that contains
 *                               the POST data to be sent via the {@link org.apache.commons.httpclient.methods.PostMethod}
 *//*w  w w.ja  v a2 s  .  c o m*/
@SuppressWarnings("unchecked")
private void handleStandardPost(PostMethod postMethodProxyRequest, HttpServletRequest httpServletRequest) {
    // Get the client POST data as a Map
    Map<String, String[]> mapPostParameters = (Map<String, String[]>) httpServletRequest.getParameterMap();
    // Create a List to hold the NameValuePairs to be passed to the PostMethod
    List<NameValuePair> listNameValuePairs = new ArrayList<NameValuePair>();
    // Iterate the parameter names
    for (String stringParameterName : mapPostParameters.keySet()) {
        // Iterate the values for each parameter name
        String[] stringArrayParameterValues = mapPostParameters.get(stringParameterName);
        for (String stringParamterValue : stringArrayParameterValues) {
            // Create a NameValuePair and store in list
            NameValuePair nameValuePair = new NameValuePair(stringParameterName, stringParamterValue);
            listNameValuePairs.add(nameValuePair);
        }
    }
    // Set the proxy request POST data
    postMethodProxyRequest.setRequestBody(listNameValuePairs.toArray(new NameValuePair[] {}));
}

From source file:com.taobao.diamond.sdkapi.impl.DiamondSDKManagerImpl.java

private ContextResult processPulishAfterModifiedByDefinedServerId(String dataId, String groupName,
        String context, String serverId) {
    ContextResult response = new ContextResult();
    // /*from ww  w  .  j  a  va 2s.  com*/
    if (!login(serverId)) {
        response.setSuccess(false);
        response.setStatusMsg(",serverId");
        return response;
    }
    if (log.isDebugEnabled())
        log.debug("processPulishAfterModifiedByDefinedServerId(" + dataId + "," + groupName + "," + context
                + "," + serverId + ")");
    // dataId,groupName
    ContextResult result = null;
    result = queryByDataIdAndGroupName(dataId, groupName, serverId);
    if (null == result || !result.isSuccess()) {
        response.setSuccess(false);
        response.setStatusMsg("!");
        log.warn("! dataId=" + dataId + ",group=" + groupName + ",serverId="
                + serverId);
        return response;
    }
    // 
    else {
        String postUrl = "/diamond-server/admin.do?method=updateConfig";
        PostMethod post = new PostMethod(postUrl);
        // 
        post.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, require_timeout);
        try {
            NameValuePair dataId_value = new NameValuePair("dataId", dataId);
            NameValuePair group_value = new NameValuePair("group", groupName);
            NameValuePair content_value = new NameValuePair("content", context);
            // 
            post.setRequestBody(new NameValuePair[] { dataId_value, group_value, content_value });
            // 
            ConfigInfo configInfo = new ConfigInfo();
            configInfo.setDataId(dataId);
            configInfo.setGroup(groupName);
            configInfo.setContent(context);
            if (log.isDebugEnabled())
                log.debug("ConfigInfo: " + configInfo);
            // 
            response.setConfigInfo(configInfo);
            // http
            int status = client.executeMethod(post);
            response.setReceiveResult(post.getResponseBodyAsString());
            response.setStatusCode(status);
            log.info("" + status + "," + post.getResponseBodyAsString());
            if (status == HttpStatus.SC_OK) {
                response.setSuccess(true);
                response.setStatusMsg("");
                log.info("");
            } else if (status == HttpStatus.SC_REQUEST_TIMEOUT) {
                response.setSuccess(false);
                response.setStatusMsg(":" + require_timeout + "");
                log.error(":" + require_timeout + ", dataId=" + dataId
                        + ",group=" + groupName + ",content=" + context + ",serverId=" + serverId);
            } else {
                response.setSuccess(false);
                response.setStatusMsg(
                        ",ContextResultgetReceiveResult()");
                log.error(":" + response.getReceiveResult() + ",dataId=" + dataId + ",group="
                        + groupName + ",content=" + context + ",serverId=" + serverId);
            }

        } catch (HttpException e) {
            response.setSuccess(false);
            response.setStatusMsg("HttpException" + e.getMessage());
            log.error(
                    "processPulishAfterModifiedByDefinedServerId(String dataId, String groupName, String context,String serverId)HttpExceptiondataId="
                            + dataId + ",group=" + groupName + ",content=" + context + ",serverId=" + serverId,
                    e);
            return response;
        } catch (IOException e) {
            response.setSuccess(false);
            response.setStatusMsg("IOException" + e.getMessage());
            log.error(
                    "processPulishAfterModifiedByDefinedServerId(String dataId, String groupName, String context,String serverId)IOExceptiondataId="
                            + dataId + ",group=" + groupName + ",content=" + context + ",serverId=" + serverId,
                    e);
            return response;
        } finally {
            // 
            post.releaseConnection();
        }

        return response;
    }
}

From source file:com.springsource.hq.plugin.tcserver.serverconfig.web.services.SettingsLoaderImpl.java

private void configureMethod(HttpMethod method, String eid, String sessionId, String csrfNonce) {
    method.setFollowRedirects(false);// ww w.  ja  v a 2s .c o m
    method.getParams().setCookiePolicy(CookiePolicy.IGNORE_COOKIES);
    method.setRequestHeader("Cookie", "JSESSIONID=" + sessionId);
    method.setQueryString(new NameValuePair[] { new NameValuePair("eid", eid),
            new NameValuePair(REQUEST_PARAMETER_CSRF_NONCE, csrfNonce) });
}