List of usage examples for org.apache.commons.httpclient NameValuePair NameValuePair
public NameValuePair(String name, String value)
From source file:com.clarkparsia.sbol.editor.sparql.StardogEndpoint.java
@Override public void removeData(RDFInput input, String namedGraph) throws Exception { String txId = startTransaction(); RequestEntity entity = createEntity(input); PostMethod post = new PostMethod(url + "/" + txId + "/remove"); if (namedGraph != null) { post.setQueryString(new NameValuePair[] { new NameValuePair("graph-uri", namedGraph) }); }/*from w w w.jav a 2 s . c o m*/ post.setRequestEntity(entity); execute(post); commitTransaction(txId); }
From source file:com.cloudmade.api.CMClient.java
/** * Find objects that match given query/*from w ww . j a v a 2 s.com*/ * <p> * Query should be in format <code>[POI],[House Number],[Street],[City],[County],[Country]</code> (comma separated names of geo objects from small to big) like * <code>Potsdamer Platz, Berlin, Germany</code>. Also supports "near" in queries, e.g. <code>hotel near Potsdamer Platz, Berlin, Germany</code> * </p> * * @param query Query by which objects should be searched. * @param results How many results should be returned. * @param skip Number of results to skip from beginning. * @param bbox Bounding box in which objects should be searched. * @param bboxOnly If set to <code>false</code>, results will be searched in the * whole world if there are no results for a given bbox. * @param returnGeometry If set to <code>true</code>, adds geometry in returned * results. Otherwise only centroid returned. * @param returnLocation If set to <code>true</code>, adds location information in returned * results. This might have some negative impact on performance of query, please use it wisely. * @return {@link GeoResults} object with found results. */ public GeoResults find(String query, int results, int skip, BBox bbox, boolean bboxOnly, boolean returnGeometry, boolean returnLocation) { byte[] response = {}; try { String uri = String.format("/geocoding/find/%s.js", URLEncoder.encode(query, "UTF-8")); List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new NameValuePair("results", String.valueOf(results))); params.add(new NameValuePair("skip", String.valueOf(skip))); params.add(new NameValuePair("bbox_only", String.valueOf(bboxOnly))); params.add(new NameValuePair("return_geometry", String.valueOf(returnGeometry))); params.add(new NameValuePair("return_location", String.valueOf(returnLocation))); if (bbox != null) { params.add(new NameValuePair("bbox", bbox.toString())); } response = callService(uri, "geocoding", params.toArray(new NameValuePair[0])); JSONObject obj = new JSONObject(new String(response, "UTF-8")); GeoResults result = new GeoResults(Utils.geoResultsFromJson(obj.optJSONArray("features")), obj.optInt("found", 0), Utils.bboxFromJson(obj.optJSONArray("bounds"))); return result; } catch (org.json.JSONException jse) { throw new RuntimeException("Error building a JSON object from the " + "geocoding service response:\n" + new String(response, 0, 500), jse); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
From source file:jeeves.utils.XmlRequest.java
public void addParam(String name, Object value) { if (value != null) alSimpleParams.add(new NameValuePair(name, value.toString())); method = Method.GET;/* w w w. ja va 2 s . com*/ }
From source file:net.datapipe.CloudStack.CloudStackAPI.java
public Document createCondition(String counterId, String relationalOperator, int threshold, HashMap<String, String> optional) throws Exception { LinkedList<NameValuePair> arguments = newQueryValues("createCondition", optional); arguments.add(new NameValuePair("counterid", counterId)); arguments.add(new NameValuePair("relationaloperator", relationalOperator)); arguments.add(new NameValuePair("threshold", Integer.toString(threshold))); return Request(arguments); }
From source file:net.neurowork.cenatic.centraldir.workers.XMLRestWorker.java
private String getXmlToken() { String token = null;//w ww . j av a 2 s . c o m HttpClient httpclient = getHttpClient(); GetMethod get = new GetMethod(restUrl.getTokenUrl()); get.addRequestHeader("Accept", "application/xml"); NameValuePair userParam = new NameValuePair(USERNAME_PARAM, satelite.getUser()); NameValuePair passwordParam = new NameValuePair(PASSWORD_PARAM, satelite.getPassword()); NameValuePair[] params = new NameValuePair[] { userParam, passwordParam }; get.setQueryString(params); try { int statusCode = httpclient.executeMethod(get); if (statusCode != HttpStatus.SC_OK) { logger.error("Method failed: " + get.getStatusLine()); } token = parseToken(get.getResponseBodyAsString()); } catch (HttpException e) { logger.error(e.getMessage()); } catch (IOException e) { logger.error(e.getMessage()); } catch (ParserConfigurationException e) { logger.error(e.getMessage()); } catch (SAXException e) { logger.error(e.getMessage()); } finally { get.releaseConnection(); } return token; }
From source file:com.mirth.connect.client.core.UpdateClient.java
private List<UpdateInfo> getUpdatesFromUri(ServerInfo serverInfo) throws Exception { HttpClientParams httpClientParams = new HttpClientParams(); HttpConnectionManager httpConnectionManager = new SimpleHttpConnectionManager(); httpClientParams.setSoTimeout(10 * 1000); httpConnectionManager.getParams().setConnectionTimeout(10 * 1000); httpConnectionManager.getParams().setSoTimeout(10 * 1000); HttpClient httpClient = new HttpClient(httpClientParams, httpConnectionManager); PostMethod post = new PostMethod(client.getUpdateSettings().getUpdateUrl() + URL_UPDATES); NameValuePair[] params = { new NameValuePair("serverInfo", serializer.toXML(serverInfo)) }; post.setRequestBody(params);// w w w. ja va2 s. com try { int statusCode = httpClient.executeMethod(post); if ((statusCode != HttpStatus.SC_OK) && (statusCode != HttpStatus.SC_MOVED_TEMPORARILY)) { throw new Exception("Failed to connect to update server: " + post.getStatusLine()); } BufferedReader reader = new BufferedReader( new InputStreamReader(post.getResponseBodyAsStream(), post.getResponseCharSet())); StringBuilder result = new StringBuilder(); String input = new String(); while ((input = reader.readLine()) != null) { result.append(input); result.append('\n'); } return (List<UpdateInfo>) serializer.fromXML(result.toString()); } catch (Exception e) { throw e; } finally { post.releaseConnection(); } }
From source file:dk.itst.oiosaml.sp.IntegrationTests.java
protected WebRequestSettings buildResponse(String status, int assuranceLevel) throws Exception { Document document = TestHelper .parseBase64Encoded(TestHelper.getParameter("SAMLRequest", handler.url.toString())); AuthnRequest ar = (AuthnRequest) Configuration.getUnmarshallerFactory() .getUnmarshaller(document.getDocumentElement()).unmarshall(document.getDocumentElement()); Assertion assertion = TestHelper.buildAssertion( spMetadata.getDefaultAssertionConsumerService().getLocation(), spMetadata.getEntityID()); assertion.getAttributeStatements().get(0).getAttributes().clear(); assertion.getAttributeStatements().get(0).getAttributes() .add(AttributeUtil.createAssuranceLevel(assuranceLevel)); Response r = TestHelper.buildResponse(assertion); r.setStatus(SAMLUtil.createStatus(status)); r.setInResponseTo(ar.getID());//from ww w . java2s.c om OIOResponse response = new OIOResponse(r); response.sign(credential); WebRequestSettings req = new WebRequestSettings(new URL(BASE + "/saml/SAMLAssertionConsumer"), SubmitMethod.POST); req.setRequestParameters(Arrays.asList(new NameValuePair("SAMLResponse", response.toBase64()), new NameValuePair("RelayState", TestHelper.getParameter("RelayState", handler.url.toString())))); return req; }
From source file:com.benfante.jslideshare.SlideShareConnectorImpl.java
public InputStream sendGetMessage(String url, Map<String, String> parameters) throws IOException, SlideShareErrorException { HttpClient client = createHttpClient(); GetMethod method = new GetMethod(url); NameValuePair[] params = new NameValuePair[parameters.size() + 3]; int i = 0;/*from ww w . jav a2s .co m*/ params[i++] = new NameValuePair("api_key", this.apiKey); Iterator<Map.Entry<String, String>> entryIt = parameters.entrySet().iterator(); while (entryIt.hasNext()) { Map.Entry<String, String> entry = entryIt.next(); params[i++] = new NameValuePair(entry.getKey(), entry.getValue()); } Date now = new Date(); String ts = Long.toString(now.getTime() / 1000); String hash = DigestUtils.shaHex(this.sharedSecret + ts).toLowerCase(); params[i++] = new NameValuePair("ts", ts); params[i++] = new NameValuePair("hash", hash); method.setQueryString(params); logger.debug("Sending GET message to " + method.getURI().getURI() + " with parameters " + Arrays.toString(params)); int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { logger.debug("Server replied with a " + statusCode + " HTTP status code (" + HttpStatus.getStatusText(statusCode) + ")"); throw new SlideShareErrorException(statusCode, HttpStatus.getStatusText(statusCode)); } if (logger.isDebugEnabled()) { logger.debug(method.getResponseBodyAsString()); } InputStream result = new ByteArrayInputStream(method.getResponseBody()); method.releaseConnection(); return result; }
From source file:com.sapienter.jbilling.server.process.AgeingBL.java
public void setUserStatus(Integer executorId, Integer userId, Integer statusId, Date today) { // find out if this user is not already in the required status UserBL user = new UserBL(userId); Integer originalStatusId = user.getEntity().getStatus().getId(); if (originalStatusId.equals(statusId)) { return;// w w w . j ava2s. c o m } LOG.debug("Setting user " + userId + " status to " + statusId); // see if this guy could login in her present status boolean couldLogin = user.getEntity().getStatus().getCanLogin() == 1; // log an event if (executorId != null) { // this came from the gui eLogger.audit(executorId, userId, Constants.TABLE_BASE_USER, user.getEntity().getUserId(), EventLogger.MODULE_USER_MAINTENANCE, EventLogger.STATUS_CHANGE, user.getEntity().getStatus().getId(), null, null); } else { // this is from a process, no executor involved eLogger.auditBySystem(user.getEntity().getEntity().getId(), userId, Constants.TABLE_BASE_USER, user.getEntity().getUserId(), EventLogger.MODULE_USER_MAINTENANCE, EventLogger.STATUS_CHANGE, user.getEntity().getStatus().getId(), null, null); } // make the notification NotificationBL notification = new NotificationBL(); try { MessageDTO message = notification.getAgeingMessage(user.getEntity().getEntity().getId(), user.getEntity().getLanguageIdField(), statusId, userId); INotificationSessionBean notificationSess = (INotificationSessionBean) Context .getBean(Context.Name.NOTIFICATION_SESSION); notificationSess.notify(user.getEntity(), message); } catch (NotificationNotFoundException e) { LOG.warn("Changeing the satus of a user. An ageing notification " + "should be " + "sent to the user, but the entity doesn't have it. " + "entity " + user.getEntity().getEntity().getId()); } // make the change UserStatusDTO status = new UserStatusDAS().find(statusId); user.getEntity().setUserStatus(status); user.getEntity().setLastStatusChange(today); if (status.getId() == UserDTOEx.STATUS_DELETED) { // yikes, it's out user.delete(executorId); return; // her orders were deleted, no need for any change in status } // see if this new status is suspended if (couldLogin && status.getCanLogin() == 0) { // all the current orders have to be suspended OrderDAS orderDas = new OrderDAS(); OrderBL order = new OrderBL(); for (Iterator it = orderDas.findByUser_Status(userId, Constants.ORDER_STATUS_ACTIVE).iterator(); it .hasNext();) { OrderDTO orderRow = (OrderDTO) it.next(); order.set(orderRow); order.setStatus(executorId, Constants.ORDER_STATUS_SUSPENDED_AGEING); } } else if (!couldLogin && status.getCanLogin() == 1) { // the oposite, it is getting out of the ageing process // all the suspended orders have to be reactivated OrderDAS orderDas = new OrderDAS(); OrderBL order = new OrderBL(); for (Iterator it = orderDas.findByUser_Status(userId, Constants.ORDER_STATUS_SUSPENDED_AGEING) .iterator(); it.hasNext();) { OrderDTO orderRow = (OrderDTO) it.next(); order.set(orderRow); order.setStatus(executorId, Constants.ORDER_STATUS_ACTIVE); } } // make the http call back String url = null; try { PreferenceBL pref = new PreferenceBL(); pref.set(user.getEntity().getEntity().getId(), Constants.PREFERENCE_URL_CALLBACK); url = pref.getString(); } catch (EmptyResultDataAccessException e2) { // no call then } if (url != null && url.length() > 0) { // get the url connection try { LOG.debug("Making callback to " + url); // cook the parameters to be sent NameValuePair[] data = new NameValuePair[6]; data[0] = new NameValuePair("cmd", "ageing_update"); data[1] = new NameValuePair("user_id", userId.toString()); data[2] = new NameValuePair("login_name", user.getEntity().getUserName()); data[3] = new NameValuePair("from_status", originalStatusId.toString()); data[4] = new NameValuePair("to_status", statusId.toString()); data[5] = new NameValuePair("can_login", String.valueOf(status.getCanLogin())); // make the call HttpClient client = new HttpClient(); client.setConnectionTimeout(30000); PostMethod post = new PostMethod(url); post.setRequestBody(data); client.executeMethod(post); } catch (Exception e1) { LOG.info("Could not make call back. url = " + url + " Message:" + e1.getMessage()); } } // trigger NewUserStatusEvent EventManager.process( new NewUserStatusEvent(user.getDto().getCompany().getId(), userId, originalStatusId, statusId)); }
From source file:edu.ucsb.eucalyptus.admin.server.extensions.store.ImageStoreServiceImpl.java
private NameValuePair[] getNameValuePairs(Parameter[] params) { NameValuePair[] pairs = new NameValuePair[params.length]; for (int i = 0; i != params.length; i++) { pairs[i] = new NameValuePair(params[i].getName(), params[i].getValue()); }//from w ww .j a v a 2 s. c om return pairs; }