List of usage examples for org.apache.commons.httpclient HttpStatus SC_OK
int SC_OK
To view the source code for org.apache.commons.httpclient HttpStatus SC_OK.
Click Source Link
From source file:com.criticalsoftware.mobics.presentation.util.GeolocationUtil.java
public static List<PlaceDTO> getAddressFromText(String address) throws UnsupportedEncodingException { List<PlaceDTO> results = new ArrayList<PlaceDTO>(); address = URLEncoder.encode(address, Configuration.INSTANCE.getUriEnconding()); String url = MessageFormat.format(SEARCH_URL, Configuration.INSTANCE.getGeolocationServer(), address, Configuration.INSTANCE.getGeolocationServerAllowedCountries(), Configuration.INSTANCE.getMaxResults()); HttpMethod method = new GetMethod(url); try {/* w ww .j a v a 2 s .co m*/ if (LOGGER.isTraceEnabled()) { LOGGER.trace("Making search location call to: {}", url); } int statusCode = new HttpClient().executeMethod(method); if (statusCode == HttpStatus.SC_OK) { byte[] responseBody = readResponse(method); JSONArray jsonArray = (JSONArray) new JSONParser().parse(new String(responseBody)); if (LOGGER.isTraceEnabled()) { LOGGER.trace(jsonArray.toJSONString()); } @SuppressWarnings("unchecked") Iterator<JSONObject> it = jsonArray.iterator(); while (it.hasNext()) { JSONObject place = it.next(); results.add(new PlaceDTO((String) place.get(DISPLAY_NAME), (String) place.get(LATITUDE_NAME), (String) place.get(LONGITUDE_NAME))); } } else { LOGGER.warn("Recived a HTTP status {}. Response was not good from {}", statusCode, url); } } catch (HttpException e) { LOGGER.error("Error while making call.", e); } catch (IOException e) { LOGGER.error("Error while reading the response.", e); } catch (ParseException e) { LOGGER.error("Error while parsing json response.", e); } return results; }
From source file:com.eng.dotcms.polls.quartz.job.SyncCSVHandler.java
public void sync() { //Get staging endpoints List<PublishingEndPoint> endpoints = null; try {//from ww w. j a v a 2s. com endpoints = endpointAPI.getEnabledReceivingEndPoints(); //Compress files File csvRoot = new File( pAPI.loadProperty(PollsConstants.PLUGIN_ID, PollsConstants.PROP_PUT_CSV_JOB_DEST_PATH)); ArrayList<File> list = new ArrayList<File>(1); list.add(csvRoot); File csvZip = new File(csvRoot + File.separator + ".." + File.separator + "csvZip.tar.gz"); PushUtils.compressFiles(list, csvZip, csvRoot.getAbsolutePath()); //Send files ClientConfig cc = new DefaultClientConfig(); if (Config.getStringProperty("TRUSTSTORE_PATH") != null && !Config.getStringProperty("TRUSTSTORE_PATH").trim().equals("")) cc.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(tFactory.getHostnameVerifier(), tFactory.getSSLContext())); Client client = Client.create(cc); for (PublishingEndPoint endpoint : endpoints) { FormDataMultiPart form = new FormDataMultiPart(); form.bodyPart(new FileDataBodyPart("csvZip", csvZip, MediaType.MULTIPART_FORM_DATA_TYPE)); //Sending csvZip to endpoint WebResource resource = client.resource(endpoint.toURL() + "/api/syncPolls/sync"); ClientResponse response = resource.type(MediaType.MULTIPART_FORM_DATA).post(ClientResponse.class, form); if (response.getClientResponseStatus().getStatusCode() != HttpStatus.SC_OK) { throw new DotDataException("Failed to send csv to endpoint " + endpoint.toURL()); } } //Finish job } catch (DotDataException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:cn.newtouch.util.HttpClientUtil.java
/** * /*from ww w . j a v a 2s . c o m*/ * List ? * * @since 2011-11-25 * @param url * @param params * ? * @return */ public static String post(String url, List<LabelValue> params) { HttpClient client = new HttpClient(); PostMethod postMethod = new PostMethod(url); try { client.getParams().setContentCharset(ENCODING_UTF);// ? for (LabelValue temp : params) { postMethod.addParameter(new NameValuePair(temp.getValue(), temp.getValue()));// username?values } int tmpStatusCode = client.executeMethod(postMethod); // ? if (tmpStatusCode == HttpStatus.SC_OK) { return postMethod.getResponseBodyAsString(); } else { return null; } } catch (Exception e) { System.err.println(e); } finally { postMethod.releaseConnection(); } return null; }
From source file:net.mumie.cocoon.msg.AbstractPostMessage.java
/** * Sends this message./*from w ww. ja v a2s . co m*/ */ public boolean send() { final String METHOD_NAME = "send"; this.logDebug(METHOD_NAME + " 1/3: Started"); boolean success = true; MessageDestinationTable destinationTable = null; SimpleHttpClient httpClient = null; try { // Init services: destinationTable = (MessageDestinationTable) this.serviceManager.lookup(MessageDestinationTable.ROLE); httpClient = (SimpleHttpClient) this.serviceManager.lookup(SimpleHttpClient.ROLE); // Get destination: MessageDestination destination = destinationTable.getDestination(this.destinationName); // Create and setup a Http Post method object: PostMethod method = new PostMethod(destination.getURL()); DefaultMethodRetryHandler retryHandler = new DefaultMethodRetryHandler(); retryHandler.setRequestSentRetryEnabled(false); retryHandler.setRetryCount(3); method.setMethodRetryHandler(retryHandler); // Set login name and password: method.addParameter("name", destination.getLoginName()); method.addParameter("password", destination.getPassword()); // Specific setup: this.init(method, destination); // Execute method: try { if (httpClient.executeMethod(method) != HttpStatus.SC_OK) { this.logError(METHOD_NAME + ": Failed to send message: " + method.getStatusLine()); success = false; } String response = new String(method.getResponseBody()); if (response.trim().startsWith("ERROR")) { this.logError(METHOD_NAME + ": Failed to send message: " + response); success = false; } this.logDebug(METHOD_NAME + " 2/3: response = " + response); } finally { method.releaseConnection(); } } catch (Exception exception) { this.logError(METHOD_NAME, exception); success = false; } finally { if (httpClient != null) this.serviceManager.release(httpClient); if (destinationTable != null) this.serviceManager.release(destinationTable); } this.logDebug(METHOD_NAME + " 3/3: Done. success = " + success); return success; }
From source file:com.sun.faban.harness.agent.Download.java
private void downloadDir(URL url, File dir) throws IOException { String dirName = dir.getName(); logger.finer("Creating directory " + dirName + " from " + url.toString()); dir.mkdir();//from w w w .ja v a2s .c om GetMethod get = new GetMethod(url.toString()); HttpClient client = new HttpClient(); client.getHttpConnectionManager().getParams().setConnectionTimeout(2000); int status = client.executeMethod(get); if (status != HttpStatus.SC_OK) throw new IOException( "Download request for " + url + " returned " + HttpStatus.getStatusText(status) + '.'); InputStream stream = get.getResponseBodyAsStream(); DirectoryParser parser = new DirectoryParser(); int length = 0; int bufEnd = 0; while (length != -1) { length = stream.read(buffer, bufEnd, buffer.length - bufEnd); if (length != -1) bufEnd += length; if (bufEnd > buffer.length / 4 * 3 || length == -1) { if (!parser.parse(buffer, bufEnd)) { String msg = "URL " + url.toString() + " is not a directory!"; logger.severe(msg); throw new IOException(msg); } bufEnd = 0; } } stream.close(); String[] entries = parser.getEntries(); for (int i = 0; i < entries.length; i++) { String entry = entries[i]; if ("META-INF/".equals(entry)) continue; String name = entry.substring(0, entry.length() - 1); if (entry.endsWith("/")) { // Directory downloadDir(new URL(url, entry), new File(dir, name)); } else { downloadFile(new URL(url, name), new File(dir, name)); } } }
From source file:datasoul.util.OnlineUsageStats.java
@Override public void run() { // Check if enabled if (!ConfigObj.getActiveInstance().getOnlineUsageStatsBool()) { return;// w w w .ja va 2 s . c o m } // Check time from last update long last = 0; try { last = Long.parseLong(UsageStatsConfig.getInstance().getLastSent()); } catch (Exception e) { // ignore } if (System.currentTimeMillis() < last + UPD_INTERVAL) { return; } StringBuffer sb = new StringBuffer(); sb.append(OnlineUpdateCheck.ONLINE_BASE_URL + "datasoulweb?"); sb.append("sysid="); sb.append(UsageStatsConfig.getInstance().getID()); sb.append("&"); sb.append("osname="); try { sb.append(URLEncoder.encode(System.getProperty("os.name"), "UTF-8")); } catch (UnsupportedEncodingException ex) { sb.append("unknown"); } sb.append("&"); sb.append("osversion="); try { sb.append(URLEncoder.encode(System.getProperty("os.version"), "UTF-8")); } catch (UnsupportedEncodingException ex) { sb.append("unknown"); } sb.append("&"); sb.append("javaversion="); try { sb.append(URLEncoder.encode(System.getProperty("java.version"), "UTF-8")); } catch (UnsupportedEncodingException ex) { sb.append("unknown"); } sb.append("&"); sb.append("dsversion="); sb.append(DatasoulMainForm.getVersion()); sb.append("&"); sb.append("templates="); sb.append(TemplateManager.getInstance().getRowCount()); sb.append("&"); sb.append("songall="); sb.append(AllSongsListTable.getInstance().getSongCount()); sb.append("&"); sb.append("songchords="); sb.append(AllSongsListTable.getInstance().getSongsWithChords()); sb.append("&"); sb.append("numdisplays="); sb.append(OutputDevice.getNumDisplays()); sb.append("&"); sb.append("geometry1="); sb.append(ConfigObj.getActiveInstance().getMainOutputDeviceObj().getDiplayGeometry()); sb.append("&"); sb.append("geometry2="); if (ConfigObj.getActiveInstance().getMonitorOutputDeviceObj() != null) { sb.append(ConfigObj.getActiveInstance().getMonitorOutputDeviceObj().getDiplayGeometry()); } else { sb.append("disabled"); } HttpClient client = new HttpClient(); HttpMethod method = new GetMethod(sb.toString()); try { // Execute the method. int statusCode = client.executeMethod(method); if (statusCode == HttpStatus.SC_OK) { UsageStatsConfig.getInstance().setLastSent(Long.toString(System.currentTimeMillis())); } } catch (Exception e) { e.printStackTrace(); } finally { // Release the connection. method.releaseConnection(); } }
From source file:net.sf.sail.webapp.dao.sds.impl.SdsOfferingListCommandHttpRestImpl.java
/** * @see net.sf.sail.webapp.dao.sds.SdsCommand#generateRequest() *///from w w w . j av a2s. c o m public HttpGetRequest generateRequest() { final String url = "/offering"; return new HttpGetRequest(REQUEST_HEADERS_ACCEPT, EMPTY_STRING_MAP, url, HttpStatus.SC_OK); }
From source file:net.sf.jaceko.mock.resource.BasicSetupResource.java
@PUT @Path("/{operationId}/responses/{requestInOrder}") @Consumes({ MediaType.TEXT_XML, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON }) public Response setResponse(@Context HttpHeaders headers, @PathParam("serviceName") String serviceName, @PathParam("operationId") String operationId, @PathParam("requestInOrder") int requestInOrder, @QueryParam("code") int customResponseCode, @QueryParam("delay") int delaySec, @QueryParam("headers") String headersToPrime, String customResponseBody) { Map<String, String> headersMap = parseHeadersToPrime(headersToPrime); mockSetupExecutor.setCustomResponse(serviceName, operationId, requestInOrder, MockResponse.body(customResponseBody).code(customResponseCode).delaySec(delaySec) .contentType(headers.getMediaType()).headers(parseHeadersToPrime(headersToPrime)).build()); return Response.status(HttpStatus.SC_OK).build(); }
From source file:com.zimbra.qa.unittest.TestWsdlServlet.java
public void testWsdlServletXsd() throws Exception { String body = doWsdlServletRequest(wsdlUrlBase + "zimbraAccount.xsd", false, HttpStatus.SC_OK); assertTrue("Body contains expected string", body.contains(":schema>")); }
From source file:net.sf.sail.webapp.dao.sds.impl.HttpRestSdsWorkgroupDaoTest.java
/** * Test method for/* ww w. j av a 2 s. c o m*/ * {@link net.sf.sail.webapp.dao.sds.impl.HttpRestSdsWorkgroupDao#save(net.sf.sail.webapp.domain.sds.SdsWorkgroup)}. */ @SuppressWarnings("unchecked") public void testSave_NewSdsWorkgroup() throws Exception { // create offering in SDS Long sdsOfferingId = this.createWholeOffering().getSdsObjectId(); this.sdsOffering.setSdsObjectId(sdsOfferingId); this.sdsWorkgroup.setName(DEFAULT_NAME); this.sdsWorkgroup.setSdsOffering(this.sdsOffering); this.sdsWorkgroup.addMember(this.sdsUser); // create user in SDS Long sdsUserId = createUserInSds(); this.sdsUser.setSdsObjectId(sdsUserId); assertNull(this.sdsWorkgroup.getSdsObjectId()); this.sdsWorkgroupDao.save(this.sdsWorkgroup); assertNotNull(this.sdsWorkgroup.getSdsObjectId()); // retrieve newly created workgroup using httpunit and compare with // sdsWorkgroup saved via DAO WebResponse webResponse = makeHttpRestGetRequest("/workgroup/" + this.sdsWorkgroup.getSdsObjectId()); assertEquals(HttpStatus.SC_OK, webResponse.getResponseCode()); Document doc = createDocumentFromResponse(webResponse); Element rootElement = doc.getRootElement(); assertEquals(this.sdsWorkgroup.getSdsObjectId(), new Long(rootElement.getChild("id").getValue())); assertEquals(this.sdsWorkgroup.getName(), rootElement.getChild("name").getValue()); assertEquals(this.sdsWorkgroup.getSdsOffering().getSdsObjectId(), new Long(rootElement.getChild("offering-id").getValue())); // compare the members in the workgroup webResponse = makeHttpRestGetRequest("/workgroup/" + this.sdsWorkgroup.getSdsObjectId() + "/membership"); assertEquals(HttpStatus.SC_OK, webResponse.getResponseCode()); doc = createDocumentFromResponse(webResponse); List<Element> nodeList; nodeList = XPath.newInstance("/workgroup-memberships/workgroup-membership").selectNodes(doc); assertEquals(1, nodeList.size()); assertEquals(this.sdsUser.getSdsObjectId(), new Long(nodeList.get(0).getChild("sail-user-id").getValue())); }