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.owncloud.android.lib.resources.notifications.RegisterAccountDeviceForNotificationsOperation.java
private boolean isSuccess(int status) { return (status == HttpStatus.SC_OK || status == HttpStatus.SC_CREATED); }
From source file:com.sun.faban.harness.agent.Download.java
private void downloadFile(URL url, File file) throws IOException { logger.finer("Downloading file " + url.toString()); 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 in = get.getResponseBodyAsStream(); FileOutputStream out = new FileOutputStream(file); int length = in.read(buffer); while (length != -1) { out.write(buffer, 0, length);/*from w w w . j a v a2s . c om*/ length = in.read(buffer); } out.flush(); out.close(); in.close(); }
From source file:com.bluexml.side.framework.facetmap.alfrescoConnector.AlfrescoCommunicator.java
private byte[] buildGetMethodAndExecute(String url, Map<String, String> params) { byte[] responseBody = {}; GetMethod get = new GetMethod(url); get.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); logger.debug("parameters :" + params); ArrayList<NameValuePair> pairs = new ArrayList<NameValuePair>(); for (Map.Entry<String, String> entry : params.entrySet()) { pairs.add(new NameValuePair(entry.getKey(), entry.getValue())); }/*from w w w . j av a2 s . com*/ NameValuePair[] arr = new NameValuePair[pairs.size()]; arr = pairs.toArray(arr); get.setQueryString(arr); // Execute the method. int statusCode; try { statusCode = http.executeMethod(get); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + get.getStatusLine()); } // Read the response body. responseBody = get.getResponseBody(); } catch (HttpException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { // Release the connection. get.releaseConnection(); } return responseBody; }
From source file:com.hp.alm.ali.idea.services.AttachmentService.java
public void deleteAttachment(String name, EntityRef parent) { MyResultInfo result = new MyResultInfo(); if (restService.delete(result, "{0}s/{1}/attachments/{2}", parent.type, parent.id, EntityQuery.encode(name)) != HttpStatus.SC_OK) { errorService.showException(new RestException(result)); } else {// www. j a v a2 s. c o m EntityList list = EntityList.create(result.getBodyAsStream()); if (!list.isEmpty()) { entityService.fireEntityNotFound(new EntityRef(list.get(0)), true); } } }
From source file:com.taobao.ad.easyschedule.action.schedule.ScheduleAction.java
private SchedulerDTO getSchedulerInfo(String instanceName) { SchedulerDTO result = null;/*from w w w. jav a2 s .c om*/ try { HttpClient client = new HttpClient(); int connTimeout = 1000; client.getHttpConnectionManager().getParams().setConnectionTimeout(connTimeout); GetMethod getMethod = null; String url = configBO.getStringValue(ConfigDO.CONFIG_KEY_INSTANCE_CONTROL_INTERFACE); url = url.replaceAll("#instance#", instanceName); url = url + "getInstanceAjax"; getMethod = new GetMethod(url); getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler()); int statusCode = client.executeMethod(getMethod); if (statusCode == HttpStatus.SC_OK) { result = JSONObject.parseObject(getMethod.getResponseBodyAsString(), SchedulerDTO.class); } } catch (Exception e) { } return result; }
From source file:de.juwimm.cms.content.modules.ModuleFactoryStandardImpl.java
public Module loadPlugins(String classname, List<String> additionalJarFiles) { Module module = null;/*from w w w . j a va 2 s . com*/ Communication comm = ((Communication) getBean(Beans.COMMUNICATION)); SiteValue site = comm.getCurrentSite(); String urlPath = site.getDcfUrl(); final String userHome = System.getProperty("user.home"); final String fileSeparator = System.getProperty("file.separator"); StringBuffer pluginCachePath = new StringBuffer(userHome); pluginCachePath.append(fileSeparator); pluginCachePath.append(".tizzitCache"); pluginCachePath.append(fileSeparator); pluginCachePath.append("plugins"); pluginCachePath.append(fileSeparator); pluginCachePath.append(Constants.SERVER_HOST); pluginCachePath.append(fileSeparator); final String pluginPath = pluginCachePath.toString(); final int addSize = additionalJarFiles.size(); /* enthaelt alle Jar files die sich nicht auf dem lokalen Rechner befinden */ ArrayList<String> httpLoad = new ArrayList<String>(); for (int i = 0; i < addSize; i++) { String filePath = pluginPath + additionalJarFiles.get(i); File tempFile = new File(filePath); if (!tempFile.exists()) { httpLoad.add(additionalJarFiles.get(i)); } } if (httpLoad.size() > 0) { File dir = new File(pluginPath); if (!dir.exists()) { if (log.isDebugEnabled()) log.debug("Going to create plugin directory..."); boolean ret = dir.mkdirs(); if (!ret) { log.warn("Could not create plugin directory"); } } /* laedt die Jarfiles auf den lokalen Rechner herunter */ HttpClient httpclient = new HttpClient(); for (int i = 0; i < httpLoad.size(); i++) { String url = urlPath + httpLoad.get(i); if (log.isDebugEnabled()) log.debug("Plugin URL " + url); HttpMethod method = new GetMethod(url); try { int status = httpclient.executeMethod(method); if (status == HttpStatus.SC_OK) { File file = new File(pluginPath + httpLoad.get(i)); byte[] data = method.getResponseBody(); if (log.isDebugEnabled()) log.debug("Received " + data.length + " bytes of data"); FileOutputStream output = new FileOutputStream(file); output.write(data); output.close(); } else { log.warn("No OK received"); } } catch (HttpException htex) { log.warn("HTTP exception " + htex.getMessage()); } catch (IOException ioe) { log.warn("IO exception " + ioe.getMessage()); } method.releaseConnection(); } } try { if (log.isDebugEnabled()) log.debug("Creating URL"); URL[] url = new URL[addSize]; for (int i = 0; i < addSize; i++) { String jarModule = additionalJarFiles.get(i); String jarPath = "file:///" + pluginPath + jarModule; if (log.isDebugEnabled()) log.debug("Jar path " + jarPath); url[i] = new URL(jarPath); } URLClassLoader cl = this.getURLClassLoader(url); //URLClassLoader cl = new URLClassLoader(url, this.getClass().getClassLoader()); if (log.isDebugEnabled()) log.debug("Created URL classloader"); Class c = cl.loadClass(classname); if (log.isDebugEnabled()) log.debug("Created class"); module = (Module) c.newInstance(); if (log.isDebugEnabled()) log.debug("Got the module"); } catch (Exception loadex) { log.warn(loadex.getClass().toString()); log.error("Cannot load from URL " + loadex.getMessage(), loadex); } return module; }
From source file:cz.vity.freerapid.plugins.services.rapidshare_premium.RapidShareRunner.java
private void checkFile() throws Exception { Matcher matcher = PlugUtils//from ww w . j a v a2 s . c om .matcher("!download(?:%7C|\\|)(?:[^%\\|]+)(?:%7C|\\|)(\\d+)(?:%7C|\\|)([^%\\|]+)", fileURL); if (matcher.find()) { fileURL = "http://rapidshare.com/files/" + matcher.group(1) + "/" + matcher.group(2); httpFile.setNewURL(new URL(fileURL)); } else { matcher = PlugUtils.matcher("/share/([A-Z0-9]+)", fileURL); if (matcher.find()) { HttpMethod method = getMethodBuilder().setReferer(fileURL) .setAction("https://api.rapidshare.com/cgi-bin/rsapi.cgi").setParameter("rsource", "web") .setParameter("sub", "sharelinkcontent").setParameter("share", matcher.group(1)) .setParameter("cbid", "2").setParameter("cbf", "rsapi.system.jsonp.callback") .setParameter("callt", String.valueOf(System.currentTimeMillis())).toGetMethod(); if (!makeRedirectedRequest(method)) { checkFileProblems(); throw new ServiceConnectionProblemException(); } checkFileProblems(); matcher = getMatcherAgainstContent("\"file:(\\d+),([^,]+),"); if (!matcher.find()) { throw new PluginImplementationException("Error getting file ID and file name"); } fileURL = "http://rapidshare.com/files/" + matcher.group(1) + "/" + matcher.group(2); httpFile.setNewURL(new URL(fileURL)); } } matcher = PlugUtils.matcher("/files/(\\d+)/(.+)", fileURL); if (!matcher.find()) { throw new PluginImplementationException("Error parsing file URL"); } final String fileId = matcher.group(1); final String fileName = URLDecoder.decode(matcher.group(2), "UTF-8"); HttpMethod method = getMethodBuilder().setAction("http://api.rapidshare.com/cgi-bin/rsapi.cgi") .setParameter("sub", "checkfiles").setParameter("files", fileId).setParameter("filenames", fileName) .toGetMethod(); int status = 0; String responseString = ""; try { status = client.makeRequest(method, true); responseString = client.getContentAsString(); logger.log(Level.INFO, "Response check:{0}", responseString); } finally { method.abort(); method.releaseConnection(); } if (status == HttpStatus.SC_OK && responseString != null && !responseString.isEmpty()) { String[] response = responseString.split(","); int fileStatus = Integer.parseInt(response[4]); if (fileStatus == 1 || fileStatus == 2 || fileStatus == 6 || fileStatus >= 50) { //http://rs$serverid$shorthost.rapidshare.com/files/$fileid/$filename) finalUrl = String.format("http://rs%s%s.rapidshare.com/files/%s/%s?directstart=1", response[3], response[5], response[0], response[1]); logger.info(finalUrl); httpFile.setFileName(response[1]); httpFile.setFileSize(Long.parseLong(response[2])); httpFile.setFileState(FileState.CHECKED_AND_EXISTING); } if (fileStatus == 0) { throw new URLNotAvailableAnymoreException("File not found"); } if (fileStatus == 4) { throw new URLNotAvailableAnymoreException("File marked as illegal"); } if (fileStatus == 5) { throw new URLNotAvailableAnymoreException( "Anonymous file locked, because it has more than 10 downloads already"); } if (fileStatus == 3) { throw new InvalidURLOrServiceProblemException("Server down"); } } else { throw new ServiceConnectionProblemException("Server return status " + status); } }
From source file:com.epam.wilma.service.http.WilmaHttpClient.java
/** * Posting the given stream to the given URL via HTTP POST method and returns * {@code true} if the request was successful. * * @param url the given URL/*from ww w. ja v a 2s . c o m*/ * @param resource the given string that will be uploaded as resource * @return {@code true} if the request is successful, otherwise return {@code false} */ public boolean uploadString(String url, String resource) { boolean requestSuccessful = false; PostMethod method = new PostMethod(url); try { method.setRequestEntity(new StringRequestEntity(resource, null, null)); int statusCode = httpclient.executeMethod(method); if (HttpStatus.SC_OK == statusCode) { requestSuccessful = true; } } catch (HttpException e) { LOG.error("Protocol exception occurred when called: " + url, e); } catch (IOException e) { LOG.error("I/O (transport) error occurred when called: " + url, e); } finally { method.releaseConnection(); } return requestSuccessful; }
From source file:gr.upatras.ece.nam.fci.uop.UoPGWClient.java
/** * It makes a POST towards the gateway//from www . ja va2 s .co m * @author ctranoris * @param resourceInstance sets the name of the resource Instance, e.g.: uop.rubis_db-27 * @param ptmAlias sets the name of the provider URI, e.g.: uop * @param content sets the name of the content; send in utf8 */ public boolean POSTExecute(String resourceInstance, String ptmAlias, String content) { boolean status = false; log.info("content body=" + "\n" + content); HttpClient client = new HttpClient(); String tgwcontent = content; // resource instance is like uop.rubis_db-6 so we need to make it like // this /uop/uop.rubis_db-6 String ptm = ptmAlias; String url = uopGWAddress + "/" + ptm + "/" + resourceInstance; log.info("Request: " + url); // Create a method instance. PostMethod post = new PostMethod(url); post.setRequestHeader("User-Agent", userAgent); post.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // Provide custom retry handler is necessary post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(0, false)); //HttpMethodParams. RequestEntity requestEntity = null; try { requestEntity = new StringRequestEntity(tgwcontent, "application/x-www-form-urlencoded", "utf-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } post.setRequestEntity(requestEntity); try { // Execute the method. int statusCode = client.executeMethod(post); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " + post.getStatusLine()); } // Deal with the response. // Use caution: ensure correct character encoding and is not binary // data // print the status and response InputStream responseBody = post.getResponseBodyAsStream(); CopyInputStream cis = new CopyInputStream(responseBody); response_stream = cis.getCopy(); log.info("Response body=" + "\n" + convertStreamToString(response_stream)); response_stream.reset(); // log.info("for address: " + url + " the response is:\n " // + post.getResponseBodyAsString()); status = true; } catch (HttpException e) { System.err.println("Fatal protocol violation: " + e.getMessage()); e.printStackTrace(); return false; } catch (IOException e) { System.err.println("Fatal transport error: " + e.getMessage()); e.printStackTrace(); return false; } finally { // Release the connection. post.releaseConnection(); } return status; }
From source file:com.bigdata.rdf.sail.remoting.GraphRepositoryClient.java
/** * @see {@link GraphRepository#create(String)} *///from ww w . j a va 2s .c o m public void create(String rdfXml) throws Exception { // POST PostMethod post = new PostMethod(servletURL); try { // set the body if (rdfXml != null) { post.setRequestEntity(new StringRequestEntity(rdfXml, // the rdf/xml body GraphRepositoryServlet.RDF_XML, // includes the encoding null // so we don't need to say it here. )); post.setContentChunked(true); } // Execute the method. int sc = getHttpClient().executeMethod(post); if (sc != HttpStatus.SC_OK) { throw new IOException("HTTP-POST failed: " + post.getStatusLine()); } } finally { // Release the connection. post.releaseConnection(); } }