List of usage examples for org.apache.commons.httpclient NameValuePair NameValuePair
public NameValuePair(String name, String value)
From source file:com.sonyericsson.hudson.plugins.multislaveconfigplugin.UIHudsonTest.java
/** * Test removing properties for a number of nodes. * The tests mocks a form containing the desired changes. * This was done since HTMLUNIT's javascript support isn't good enough. * @throws Exception on failure.//from w w w .j ava 2 s . co m */ public void testRemoveNodeProperties() throws Exception { //First make sure the nodes have some random properties: for (Node node : jenkins.getNodes()) { Entry entry = new Entry(RandomStringUtils.random(5), RandomStringUtils.random(5)); node.getNodeProperties().add(new EnvironmentVariablesNodeProperty(entry)); } //Takes the web client to "search for slaves"-page. clickLinkOnCurrentPage(CONFIGURE); searchForAndSelectAllSlaves(); // Instead of requesting the page directly we create a WebRequestSettings object WebRequestSettings requestSettings = new WebRequestSettings( webClient.createCrumbedUrl(NodeManageLink.URL + "/apply"), HttpMethod.POST); // Then we set the request parameters List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new NameValuePair("json", "{\"removeProperties\": " + "{\"stapler-class\": \"hudson.slaves.EnvironmentVariablesNodeProperty$DescriptorImpl\",\"kind\": " + "\"hudson.slaves.EnvironmentVariablesNodeProperty$DescriptorImpl\"}}")); params.add(new NameValuePair("Submit", "Save")); requestSettings.setRequestParameters(params); webClient.getPage(requestSettings); for (Node node : jenkins.getNodes()) { assertTrue("Slave should not have any node properties", node.getNodeProperties().isEmpty()); } }
From source file:com.gargoylesoftware.htmlunit.html.HtmlButtonTest.java
/** * @throws Exception if the test fails/*from w w w. j a va 2 s. c o m*/ */ @Test public void testButtonTypeSubmit() throws Exception { final String htmlContent = "<html><head><title>foo</title></head><body>\n" + "<form id='form1' method='post' onSubmit='alert(\"bar\")' onReset='alert(\"reset\")'>\n" + " <button type='submit' name='button' id='button' value='foo'" + " >Push me</button>\n" + "</form></body></html>"; final List<String> collectedAlerts = new ArrayList<String>(); final HtmlPage page = loadPage(htmlContent, collectedAlerts); final HtmlButton button = page.getHtmlElementById("button"); final HtmlPage secondPage = button.click(); final String[] expectedAlerts = { "bar" }; assertEquals(expectedAlerts, collectedAlerts); assertNotSame(page, secondPage); final List<NameValuePair> expectedParameters = Arrays .asList(new NameValuePair[] { new NameValuePair("button", "foo") }); final List<NameValuePair> collectedParameters = getMockConnection(secondPage).getLastParameters(); assertEquals(expectedParameters, collectedParameters); }
From source file:edu.ku.brc.specify.config.SpecifyExceptionTracker.java
@Override protected Vector<NameValuePair> collectionSecondaryInfo(final FeedBackSenderItem item) { AppContextMgr mgr = AppContextMgr.getInstance(); Vector<NameValuePair> stats = new Vector<NameValuePair>(); if (mgr.hasContext()) { Collection collection = mgr.getClassObject(Collection.class); Discipline discipline = mgr.getClassObject(Discipline.class); Division division = mgr.getClassObject(Division.class); Institution institution = mgr.getClassObject(Institution.class); stats.add(new NameValuePair("collection", //$NON-NLS-1$ collection != null ? collection.getCollectionName() : "No Collection")); //$NON-NLS-2$ stats.add(new NameValuePair("discipline", discipline != null ? discipline.getName() : "No Discipline")); //$NON-NLS-1$ $NON-NLS-2$ stats.add(new NameValuePair("division", division != null ? division.getName() : "No Division")); //$NON-NLS-1$ $NON-NLS-2$ stats.add(new NameValuePair("institution", //$NON-NLS-1$ institution != null ? institution.getName() : "No Institution")); //$NON-NLS-2$ stats.add(new NameValuePair("Collection_number", //$NON-NLS-1$ collection != null ? collection.getRegNumber() : "No Collection Number")); //$NON-NLS-2$ stats.add(new NameValuePair("Discipline_number", //$NON-NLS-1$ discipline != null ? discipline.getRegNumber() : "No Discipline Number")); //$NON-NLS-2$ stats.add(new NameValuePair("Division_number", //$NON-NLS-1$ division != null ? division.getRegNumber() : "No Division Number")); //$NON-NLS-2$ stats.add(new NameValuePair("Institution_number", //$NON-NLS-1$ institution != null ? institution.getRegNumber() : "No Institution Number")); //$NON-NLS-2$ if (collection != null && StringUtils.isNotEmpty(collection.getIsaNumber())) { stats.add(new NameValuePair("ISA_number", collection.getIsaNumber())); //$NON-NLS-1$ }/*from ww w . ja v a2 s. c o m*/ if (item.isIncludeEmail()) { String email = ((SpecifyAppContextMgr) mgr).getMailAddr(false); if (StringUtils.isNotEmpty(email)) { stats.add(new NameValuePair("email", email)); //$NON-NLS-1$ } } } return stats; }
From source file:com.clarkparsia.sbol.editor.sparql.StardogEndpoint.java
private NameValuePair graphParam(String namedGraph) { return (namedGraph == null) ? new NameValuePair("default", "") : new NameValuePair("graph", namedGraph); }
From source file:fr.openwide.talendalfresco.rest.client.importer.RestImportFileTest.java
public void login() { // 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 + "login"); 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("username", "admin"), new NameValuePair("password", "admin") }; method.setQueryString(params);/*from w ww. j a v a 2 s .c o m*/ 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(); System.out.println(new String(responseBody)); // TODO rm HashSet<String> defaultElementSet = new HashSet<String>( Arrays.asList(new String[] { RestConstants.TAG_COMMAND, RestConstants.TAG_CODE, RestConstants.TAG_CONTENT, RestConstants.TAG_ERROR, RestConstants.TAG_MESSAGE })); HashMap<String, String> elementValueMap = new HashMap<String, String>(6); try { XMLEventReader xmlReader = XmlHelper.getXMLInputFactory() .createXMLEventReader(new ByteArrayInputStream(responseBody)); StringBuffer singleLevelTextBuf = null; while (xmlReader.hasNext()) { XMLEvent event = xmlReader.nextEvent(); switch (event.getEventType()) { case XMLEvent.CHARACTERS: case XMLEvent.CDATA: if (singleLevelTextBuf != null) { singleLevelTextBuf.append(event.asCharacters().getData()); } // else element not meaningful break; case XMLEvent.START_ELEMENT: StartElement startElement = event.asStartElement(); String elementName = startElement.getName().getLocalPart(); if (defaultElementSet.contains(elementName) // TODO another command specific level || "ticket".equals(elementName)) { // reinit buffer at start of meaningful elements singleLevelTextBuf = new StringBuffer(); } else { singleLevelTextBuf = null; // not useful } break; case XMLEvent.END_ELEMENT: if (singleLevelTextBuf == null) { break; // element not meaningful } // TODO or merely put it in the map since the element has been tested at start EndElement endElement = event.asEndElement(); elementName = endElement.getName().getLocalPart(); if (defaultElementSet.contains(elementName)) { String value = singleLevelTextBuf.toString(); elementValueMap.put(elementName, value); // TODO test if it is code and it is not OK, break to error handling } // TODO another command specific level else if ("ticket".equals(elementName)) { ticket = singleLevelTextBuf.toString(); } // singleLevelTextBuf = new StringBuffer(); // no ! in start break; } } } catch (XMLStreamException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (Throwable t) { // TODO Auto-generated catch block t.printStackTrace(); //throw t; } String code = elementValueMap.get(RestConstants.TAG_CODE); assertTrue(RestConstants.CODE_OK.equals(code)); System.out.println("got ticket " + ticket); } catch (HttpException e) { // TODO e.printStackTrace(); } catch (IOException e) { // TODO e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); } }
From source file:com.bigcommerce.http.QueryStringBuilder.java
/** * Invokes {@link #addQueryParameter(NameValuePair)} with a <code>String</code> * converted value./*from w ww . j a v a 2s . co m*/ */ public QueryStringBuilder addQueryParameter(final String name, final boolean value) { return addQueryParameter(new NameValuePair(name, String.valueOf(value))); }
From source file:com.panet.imeta.trans.steps.httppost.HTTPPOST.java
public boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException { meta = (HTTPPOSTMeta) smi;/*from ww w . j av a 2 s. c om*/ data = (HTTPPOSTData) sdi; boolean sendToErrorRow = false; String errorMessage = null; Object[] r = getRow(); // Get row from input rowset & set row busy! if (r == null) // no more input to be expected... { setOutputDone(); return false; } if (first) { first = false; data.inputRowMeta = getInputRowMeta(); data.outputRowMeta = getInputRowMeta().clone(); meta.getFields(data.outputRowMeta, getStepname(), null, null, this); if (meta.isUrlInField()) { if (Const.isEmpty(meta.getUrlField())) { logError(Messages.getString("HTTPPOST.Log.NoField")); throw new KettleException(Messages.getString("HTTPPOST.Log.NoField")); } // cache the position of the field if (data.indexOfUrlField < 0) { String realUrlfieldName = environmentSubstitute(meta.getUrlField()); data.indexOfUrlField = data.inputRowMeta.indexOfValue((realUrlfieldName)); if (data.indexOfUrlField < 0) { // The field is unreachable ! logError(Messages.getString("HTTPPOST.Log.ErrorFindingField", realUrlfieldName)); throw new KettleException( Messages.getString("HTTPPOST.Exception.ErrorFindingField", realUrlfieldName)); } } } else { data.realUrl = environmentSubstitute(meta.getUrl()); } // set body parameters int nrargs = meta.getArgumentField().length; if (nrargs > 0) { data.useBodyParameters = true; data.body_parameters_nrs = new int[nrargs]; data.bodyParameters = new NameValuePair[nrargs]; for (int i = 0; i < nrargs; i++) { data.body_parameters_nrs[i] = data.inputRowMeta.indexOfValue(meta.getArgumentField()[i]); if (data.body_parameters_nrs[i] < 0) { logError(Messages.getString("HTTPPOST.Log.ErrorFindingField") + meta.getArgumentField()[i] //$NON-NLS-1$ + "]"); //$NON-NLS-1$ throw new KettleStepException(Messages.getString("HTTPPOST.Exception.CouldnotFindField", //$NON-NLS-1$ meta.getArgumentField()[i])); //$NON-NLS-2$ } data.bodyParameters[i] = new NameValuePair( environmentSubstitute(meta.getArgumentParameter()[i]), data.outputRowMeta.getString(r, data.body_parameters_nrs[i])); } } // set query parameters int nrQuery = meta.getQueryField().length; if (nrQuery > 0) { data.useQueryParameters = true; data.query_parameters_nrs = new int[nrQuery]; data.queryParameters = new NameValuePair[nrQuery]; for (int i = 0; i < nrQuery; i++) { data.query_parameters_nrs[i] = data.inputRowMeta.indexOfValue(meta.getQueryField()[i]); if (data.query_parameters_nrs[i] < 0) { logError(Messages.getString("HTTPPOST.Log.ErrorFindingField") + meta.getQueryField()[i] //$NON-NLS-1$ + "]"); //$NON-NLS-1$ throw new KettleStepException(Messages.getString("HTTPPOST.Exception.CouldnotFindField", //$NON-NLS-1$ meta.getQueryField()[i])); //$NON-NLS-2$ } data.queryParameters[i] = new NameValuePair(environmentSubstitute(meta.getQueryParameter()[i]), data.outputRowMeta.getString(r, data.query_parameters_nrs[i])); } } // set request entity? if (!Const.isEmpty(meta.getRequestEntity())) { data.indexOfRequestEntity = data.inputRowMeta .indexOfValue(environmentSubstitute(meta.getRequestEntity())); if (data.indexOfRequestEntity < 0) { throw new KettleStepException(Messages.getString( "HTTPPOST.Exception.CouldnotFindRequestEntityField", meta.getRequestEntity())); //$NON-NLS-1$ //$NON-NLS-2$ } } data.realEncoding = environmentSubstitute(meta.getEncoding()); } // end if first try { Object[] outputRowData = callHTTPPOST(r); putRow(data.outputRowMeta, outputRowData); // copy row to output rowset(s); if (checkFeedback(getLinesRead())) { if (log.isDetailed()) logDetailed(Messages.getString("HTTPPOST.LineNumber") + getLinesRead()); //$NON-NLS-1$ } } catch (KettleException e) { if (getStepMeta().isDoingErrorHandling()) { sendToErrorRow = true; errorMessage = e.toString(); } else { logError(Messages.getString("HTTPPOST.ErrorInStepRunning") + e.getMessage()); //$NON-NLS-1$ setErrors(1); logError(Const.getStackTracker(e)); stopAll(); setOutputDone(); // signal end to receiver(s) return false; } if (sendToErrorRow) { // Simply add this row to the error row putError(getInputRowMeta(), r, 1, errorMessage, null, "HTTPPOST001"); } } return true; }
From source file:com.thoughtworks.twist.mingle.core.MingleClient.java
public void attachComment(String taskId, String comment, String description, InputStream createInputStream, String filename, IProgressMonitor monitor) { PostMethod post = new PostMethod(commentUrl(taskId)); NameValuePair[] data = { new NameValuePair("comment", comment), }; post.setRequestBody(data);/*from w w w . ja v a2 s .co m*/ try { getClient().executeMethod(post); } catch (HttpException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } finally { post.releaseConnection(); } }
From source file:it.geosolutions.geoserver.rest.publisher.GeoserverRESTImageMosaicTest.java
@Test public void testPublishImageMosaic() throws IOException { if (!enabled()) { return;/*w w w .ja va 2s .co m*/ } deleteAll(); String storeName = "testImageMosaic"; assertTrue(reader.getWorkspaces().isEmpty()); assertTrue(publisher.createWorkspace(DEFAULT_WS)); File imageMosaicFile = new ClassPathResource("testdata/mosaic_geotiff.zip").getFile(); // test publish boolean wp = publisher.publishImageMosaic(DEFAULT_WS, storeName, imageMosaicFile, ParameterConfigure.NONE, (NameValuePair) null); assertTrue("Publish imagemosaic with no layer configured, failed.", wp); assertTrue("Unpublish() failed", publisher.removeCoverageStore(DEFAULT_WS, storeName, true)); // create default style File sldFile = new ClassPathResource("testdata/restteststyle.sld").getFile(); assertTrue(publisher.publishStyle(sldFile, "raster")); wp = publisher.publishImageMosaic(DEFAULT_WS, storeName, imageMosaicFile, ParameterConfigure.FIRST, new NameValuePair("coverageName", "imageMosaic_test")); assertTrue("Publish imagemosaic configuring layer name, failed.", wp); assertTrue("Unpublish() failed", publisher.removeCoverageStore(DEFAULT_WS, storeName, true)); wp = publisher.publishImageMosaic(DEFAULT_WS, storeName, imageMosaicFile, ParameterConfigure.ALL, (NameValuePair) null); assertTrue("Publish imagemosaic configuring all available layers, failed.", wp); assertTrue("Unpublish() failed", publisher.removeCoverageStore(DEFAULT_WS, storeName, true)); }
From source file:edu.uci.ics.asterix.test.aql.TestsUtils.java
public static InputStream executeAnyAQLAsync(String str, boolean defer, OutputFormat fmt) throws Exception { final String url = "http://localhost:19002/aql"; // Create a method instance. PostMethod method = new PostMethod(url); if (defer) {//from w w w . j av a 2 s. co m method.setQueryString(new NameValuePair[] { new NameValuePair("mode", "asynchronous-deferred") }); } else { method.setQueryString(new NameValuePair[] { new NameValuePair("mode", "asynchronous") }); } method.setRequestEntity(new StringRequestEntity(str)); method.setRequestHeader("Accept", fmt.mimeType()); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); executeHttpMethod(method); InputStream resultStream = method.getResponseBodyAsStream(); String theHandle = IOUtils.toString(resultStream, "UTF-8"); //take the handle and parse it so results can be retrieved InputStream handleResult = getHandleResult(theHandle, fmt); return handleResult; }