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:com.ixora.common.ui.ShowExceptionDialog.java

/**
 * Sends the current internal application error.
 *///from   w  w w .j av a 2  s  . c  o  m
private void handleSendError(final URL url) {
    try {
        // don't penalize the user
        // run it on a separate thread
        final Throwable copy = this.exception;
        new Thread(new Runnable() {
            public void run() {
                try {
                    Module[] mods = UpdateMgr.getRegisteredModules();
                    StringBuffer buff = new StringBuffer();
                    if (!Utils.isEmptyArray(mods)) {
                        for (Module mod : mods) {
                            buff.append(mod.toString()).append(Utils.getNewLine());
                        }
                    }
                    License lic = LicenseMgr.getLicense();
                    NetUtils.postHttpForm(url,
                            new NameValuePair[] { new NameValuePair("license", lic.toString(true)),
                                    new NameValuePair("error", Utils.getTrace(copy).toString()),
                                    new NameValuePair("appversion", buff.toString()) },
                            null);
                } catch (Exception e) {
                    logger.error(e);
                }
            }
        }).start();
        StringBuffer buff = new StringBuffer();
        buff.append("<html>");
        buff.append(MessageRepository.get(Msg.COMMON_UI_TEXT_THANK_YOU));
        buff.append("<p>");
        String msg = this.exception.getLocalizedMessage();
        if (msg == null) {
            msg = this.exception.getMessage();
        }
        buff.append(msg);
        buff.append("</p></html>");
        msg = buff.toString();
        textExceptionLong.setText(msg);
        textExceptionLong.setCaretPosition(0);
    } catch (Exception e) {
        logger.error(e);
    }
}

From source file:edu.cmu.cs.diamond.pathfind.DjangoAnnotationStore.java

@Override
public void saveAnnotations(String qh1, SelectionListModel ssModel) throws IOException {
    // convert to jaxb
    RegionList rl = new RegionList();
    List<Region> regions = rl.getRegion();
    for (Annotation a : ssModel) {
        System.out.println("saving annotation: " + a);

        Region r = new Region();
        regions.add(r);/*from   w  w  w. j  a va  2  s  .  c  o m*/

        r.setPath(SlideAnnotation.shapeToString(a.getShape()));

        if (a instanceof SlideAnnotation) {
            SlideAnnotation sa = (SlideAnnotation) a;

            r.setId(sa.getId());

            NoteList nl = new NoteList();
            r.setNotes(nl);
            List<Note> notes = nl.getNote();

            for (SlideAnnotationNote n : sa.getNotes()) {
                Note nn = new Note();
                nn.setId(n.getId());
                nn.setText(n.getText());

                notes.add(nn);
            }
        }
    }

    // marshal it to a string to post
    StringWriter sw = new StringWriter();
    JAXB.marshal(new ObjectFactory().createRegions(rl), sw);

    try {
        String u = new URI(uriPrefix + qh1 + "/").toString();
        System.out.println(u);

        PostMethod post = new PostMethod(u);
        try {
            post.addRequestHeader("Referer", u);
            NameValuePair params[] = { new NameValuePair("xml", sw.toString()),
                    new NameValuePair("csrfmiddlewaretoken", csrftoken) };
            System.out.println(Arrays.toString(params));
            post.setRequestBody(params);

            int code = httpClient.executeMethod(post);
            code = maybeAuthenticate(post, code);

            System.out.println("post code: " + code);
            System.out.println(post.getResponseBodyAsString());
        } finally {
            post.releaseConnection();
        }
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
}

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

public String obtainAccessTokenByRefreshTokenResponse(String grantType, String refreshToken, String clientId,
        String clientSecret, String scope) {
    PostMethod post = new PostMethod(baseOAuth20Uri + TOKEN_ENDPOINT);
    String response = null;/* ww w  . j av  a2  s  .  c  om*/
    try {

        post.setRequestHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
        //post.setRequestHeader(HttpHeaders.AUTHORIZATION, createBasicAuthorization(clientId, clientSecret));
        if (scope != null) {
            NameValuePair[] requestBody = { new NameValuePair(GRANT_TYPE_PARAM, grantType),
                    new NameValuePair(REFRESH_TOKEN_PARAM, refreshToken), new NameValuePair(SCOPE_PARAM, scope),
                    new NameValuePair(CLIENT_ID_PARAM, clientId),
                    new NameValuePair(CLIENT_SECRET_PARAM, clientSecret) };
            post.setRequestBody(requestBody);
        } else {
            NameValuePair[] requestBody = { new NameValuePair(GRANT_TYPE_PARAM, grantType),
                    new NameValuePair(REFRESH_TOKEN_PARAM, refreshToken),
                    new NameValuePair(CLIENT_ID_PARAM, clientId),
                    new NameValuePair(CLIENT_SECRET_PARAM, clientSecret) };
            post.setRequestBody(requestBody);
        }
        response = readResponse(post);
        log.info(response);
    } catch (IOException e) {
        log.error("cannot obtain access token by refresh token response", e);
    }
    return response;
}

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

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

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

    InputStream feedbacksStream = null;
    try {//from  www. j a va  2  s .  co  m
        httpClient.executeMethod(getMethod);
        feedbacksStream = getMethod.getResponseBodyAsStream();
    } catch (IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e);
    }

    Recommendations recommendations = null;

    try {
        JAXBContext jc = JAXBContext.newInstance(Recommendations.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        recommendations = (Recommendations) unmarshaller.unmarshal(feedbacksStream);
    } catch (JAXBException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e);
    }
    return recommendations;
}

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

/**
 * adds the basic stats about the Institution ... Collection
 * @param stats the list of stats//from w w  w.ja  v a 2 s  .  c  om
 */
protected void appendBasicCollStats(final Vector<NameValuePair> stats) {
    if (collectionId == null) {
        getIds();
    }

    if (specifyUserId != null) {
        String userName = BasicSQLUtils
                .querySingleObj("SELECT Name FROM specifyuser WHERE SpecifyUSerID = " + specifyUserId);
        stats.add(new NameValuePair("specifyuser", fixParam(userName))); //$NON-NLS-1$
    }

    // Gather Collection Counts;
    if (collectionId != null) {
        Object[] row = BasicSQLUtils.getRow(
                "SELECT EstimatedSize, RegNumber, WebSiteURI, WebPortalURI, CollectionName FROM collection WHERE CollectionID = "
                        + collectionId);
        Integer estSize = (Integer) row[0];
        String estSizeStr = estSize != null ? Integer.toString(estSize) : "";

        stats.add(new NameValuePair("Collection_estsize", estSizeStr)); //$NON-NLS-1$
        stats.add(new NameValuePair("Collection_number", fixParam(row[1]))); //$NON-NLS-1$
        stats.add(new NameValuePair("Collection_website", fixParam(row[2]))); //$NON-NLS-1$
        stats.add(new NameValuePair("Collection_portal", fixParam(row[3]))); //$NON-NLS-1$
        stats.add(new NameValuePair("Collection_name", fixParam(row[4]))); //$NON-NLS-1$
    }

    String fmt = "SELECT RegNumber, Name FROM %s WHERE %s = %d";
    if (disciplineId != null) {
        Object[] row = BasicSQLUtils.getRow(String.format(fmt, "discipline", "DisciplineID", disciplineId));
        stats.add(new NameValuePair("Discipline_number", fixParam(row[0]))); //$NON-NLS-1$
        stats.add(new NameValuePair("Discipline_name", fixParam(row[1]))); //$NON-NLS-1$
    }

    if (divisionId != null) {
        Object[] row = BasicSQLUtils.getRow(String.format(fmt, "division", "DivisionID", divisionId));
        stats.add(new NameValuePair("Division_number", fixParam(row[0]))); //$NON-NLS-1$
        stats.add(new NameValuePair("Division_name", fixParam(row[1]))); //$NON-NLS-1$
    }

    if (institutionId != null) {
        Object[] row = BasicSQLUtils.getRow(String.format(fmt, "institution", "InstitutionID", institutionId));
        stats.add(new NameValuePair("Institution_number", fixParam(row[0]))); //$NON-NLS-1$
        stats.add(new NameValuePair("Institution_name", fixParam(row[1]))); //$NON-NLS-1$
    }
}

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

private void invokeSimulationTaskNotification(String restOperationName, String modelSetId, String modelId,
        String artifactId, String simulationId, SimulationData data) throws LpRestException {
    // <host>/learnpad/or/bridge/{modelsetid}/{modelid}/{restOperationName}?artifactid=aid,simulationid=id
    String contentType = "application/xml";

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

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

    try {// ww w  .j a  v  a2 s.  com
        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

private static InputStream getHandleResult(String handle, OutputFormat fmt) throws Exception {
    final String url = "http://localhost:19002/query/result";

    // Create a method instance.
    GetMethod method = new GetMethod(url);
    method.setQueryString(new NameValuePair[] { new NameValuePair("handle", handle) });
    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 w w  .  j av a2 s  . c o m*/
    return method.getResponseBodyAsStream();
}

From source file:com.cloud.network.bigswitch.BigSwitchVnsApi.java

@SuppressWarnings("unchecked")
protected <T> T executeRetrieveObject(Type returnObjectType, String uri, int port,
        Map<String, String> parameters) throws BigSwitchVnsApiException {
    if (_host == null || _host.isEmpty()) {
        throw new BigSwitchVnsApiException("Hostname is null or empty");
    }//from  w  w  w  .  j  a  v a  2s  .c  o  m

    GetMethod gm = (GetMethod) createMethod("get", uri, port);
    gm.setRequestHeader(CONTENT_TYPE, CONTENT_JSON);
    gm.setRequestHeader(ACCEPT, CONTENT_JSON);
    gm.setRequestHeader(HTTP_HEADER_INSTANCE_ID, CLOUDSTACK_INSTANCE_ID);

    if (parameters != null && !parameters.isEmpty()) {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(parameters.size());
        for (Entry<String, String> e : parameters.entrySet()) {
            nameValuePairs.add(new NameValuePair(e.getKey(), e.getValue()));
        }
        gm.setQueryString(nameValuePairs.toArray(new NameValuePair[0]));
    }

    executeMethod(gm);

    if (gm.getStatusCode() != HttpStatus.SC_OK) {
        String errorMessage = responseToErrorMessage(gm);
        gm.releaseConnection();
        s_logger.error("Failed to retrieve object : " + errorMessage);
        throw new BigSwitchVnsApiException("Failed to retrieve object : " + errorMessage);
    }

    Gson gson = new Gson();
    T returnValue;
    try {
        returnValue = (T) gson.fromJson(gm.getResponseBodyAsString(), returnObjectType);
    } catch (IOException e) {
        s_logger.error("IOException while retrieving response body", e);
        throw new BigSwitchVnsApiException(e);
    } finally {
        gm.releaseConnection();
    }
    return returnValue;
}

From source file:com.cloud.utils.rest.RESTServiceConnector.java

@SuppressWarnings("unchecked")
public <T> T executeRetrieveObject(final Type returnObjectType, final String uri,
        final Map<String, String> parameters) throws CloudstackRESTException {
    final GetMethod gm = (GetMethod) createMethod(GET_METHOD_TYPE, uri);
    gm.setRequestHeader(CONTENT_TYPE, JSON_CONTENT_TYPE);
    if (parameters != null && !parameters.isEmpty()) {
        final List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(parameters.size());
        for (final Entry<String, String> e : parameters.entrySet()) {
            nameValuePairs.add(new NameValuePair(e.getKey(), e.getValue()));
        }/*from  w  w w.  j  ava2  s  .  c  o  m*/
        gm.setQueryString(nameValuePairs.toArray(new NameValuePair[0]));
    }

    executeMethod(gm);

    if (gm.getStatusCode() != HttpStatus.SC_OK) {
        final String errorMessage = responseToErrorMessage(gm);
        gm.releaseConnection();
        s_logger.error("Failed to retrieve object : " + errorMessage);
        throw new CloudstackRESTException("Failed to retrieve object : " + errorMessage);
    }

    T returnValue;
    try {
        returnValue = (T) gson.fromJson(gm.getResponseBodyAsString(), returnObjectType);
    } catch (final IOException e) {
        s_logger.error("IOException while retrieving response body", e);
        throw new CloudstackRESTException(e);
    } finally {
        gm.releaseConnection();
    }
    return returnValue;
}

From source file:lucee.commons.net.http.httpclient3.HTTPEngine3Impl.java

private static void setParams(HttpMethod httpMethod, Map<String, String> params) {
    if (params == null || !(httpMethod instanceof PostMethod))
        return;/*  ww  w  . java 2 s  .  c  o m*/
    PostMethod post = (PostMethod) httpMethod;
    Iterator<Entry<String, String>> it = params.entrySet().iterator();
    Entry<String, String> e;
    while (it.hasNext()) {
        e = it.next();
        post.addParameter(new NameValuePair(e.getKey(), e.getValue()));
    }
}