List of usage examples for org.apache.commons.httpclient HttpException getMessage
public String getMessage()
From source file:com.tribune.uiautomation.testscripts.Photo.java
public boolean create() throws JSONException { checkValidStateForCreate();// w ww. ja v a 2s . com PostMethod post = new PostMethod(constructCreateUrl()); try { setRequestHeaders(post); setParameters(post); HttpClient client = new HttpClient(); int status = client.executeMethod(post); log.debug("Photo Service create return status: " + post.getStatusLine()); if (status == HttpStatus.SC_CREATED) { processResponse(this, post.getResponseBodyAsStream()); persisted = true; return true; } } catch (HttpException e) { log.fatal("Fatal protocol violation: " + e.getMessage(), e); } catch (IOException e) { log.fatal("Fatal transport error: " + e.getMessage(), e); } finally { // Release the connection. post.releaseConnection(); } return false; }
From source file:com.tribune.uiautomation.testscripts.Photo.java
public Photo clonePhoto(String newNamespace, String newSlug) throws JSONException { checkValidStateForDelete();//from ww w .j a v a2 s .c om Photo photo = null; PostMethod post = new PostMethod(constructCloneUrl(namespace, slug)); try { setRequestHeaders(post); setParameters(post, newNamespace, newSlug); HttpClient client = new HttpClient(); int status = client.executeMethod(post); log.debug("Photo Service create return status: " + post.getStatusLine()); if (status == HttpStatus.SC_OK) { photo = new Photo(); processResponse(photo, post.getResponseBodyAsStream()); photo.setPersisted(true); } } catch (HttpException e) { log.fatal("Fatal protocol violation: " + e.getMessage(), e); } catch (IOException e) { log.fatal("Fatal transport error: " + e.getMessage(), e); } finally { // Release the connection. post.releaseConnection(); } return photo; }
From source file:de.ingrid.portal.scheduler.jobs.UpgradeClientJob.java
private InputStream getFeed(String url) { try {//ww w . ja va2s . c om HttpClientParams httpClientParams = new HttpClientParams(); HttpConnectionManager httpConnectionManager = new SimpleHttpConnectionManager(); httpClientParams.setSoTimeout(30 * 1000); httpConnectionManager.getParams().setConnectionTimeout(30 * 1000); httpConnectionManager.getParams().setSoTimeout(30 * 1000); HttpClient client = new HttpClient(httpClientParams, httpConnectionManager); HttpMethod method = new GetMethod(url); setCredentialsIfAny(client); int status = client.executeMethod(method); if (status == 200) { log.debug("Successfully received: " + url); return method.getResponseBodyAsStream(); } else { log.error("Response code for '" + url + "' was: " + status); return null; } } catch (HttpException e) { log.error("An HTTP-Exception occured when calling: " + url + " -> " + e.getMessage()); } catch (IOException e) { log.error("An IO-Exception occured when calling: " + url + " -> " + e.getMessage()); } return null; }
From source file:com.twinsoft.convertigo.eclipse.wizards.setup.SetupWizard.java
public void checkConnected(final CheckConnectedCallback callback) { Thread th = new Thread(new Runnable() { public void run() { synchronized (SetupWizard.this) { boolean isConnected = false; String message;/* w w w .j a va 2s . c o m*/ try { String[] urlSource = { "https://c8o.convertigo.net/cems/index.html" }; HttpClient client = prepareHttpClient(urlSource); GetMethod method = new GetMethod(urlSource[0]); int statusCode = client.executeMethod(method); if (statusCode == HttpStatus.SC_OK) { isConnected = true; message = "You are currently online"; } else { message = "Bad response: HTTP status " + statusCode; } } catch (HttpException e) { message = "HTTP failure: " + e.getMessage(); } catch (IOException e) { message = "IO failure: " + e.getMessage(); } catch (Exception e) { message = "Generic failure: " + e.getClass().getSimpleName() + ", " + e.getMessage(); } callback.onCheckConnected(isConnected, message); } } }); th.setDaemon(true); th.setName("SetupWizard.checkConnected"); th.start(); }
From source file:hydrograph.ui.dataviewer.filemanager.DataViewerFileManager.java
/** * //w w w. jav a 2s . co m * Download debug file in data viewer workspace * @param filterApplied * @param filterConditions * * @return error code */ public StatusMessage downloadDataViewerFiles(boolean filterApplied, FilterConditions filterConditions, boolean isOverWritten) { // Get csv debug file name and location String csvDebugFileAbsolutePath = null; String csvDebugFileName = null; try { if (filterConditions != null) { if (!filterConditions.getRetainRemote()) { if (!filterApplied) { csvDebugFileAbsolutePath = getDebugFileAbsolutePath(); } else { csvDebugFileAbsolutePath = getDebugFileAbsolutePath(); csvDebugFileName = getFileName(csvDebugFileAbsolutePath); csvDebugFileAbsolutePath = getFilterFileAbsolutePath(filterConditions, csvDebugFileName); } } else { csvDebugFileAbsolutePath = getDebugFileAbsolutePath(); csvDebugFileName = getFileName(csvDebugFileAbsolutePath); csvDebugFileAbsolutePath = getFilterFileAbsolutePath(filterConditions, csvDebugFileName); } } else { csvDebugFileAbsolutePath = getDebugFileAbsolutePath(); } } catch (MalformedURLException malformedURLException) { Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, malformedURLException.getMessage(), malformedURLException); StatusMessage statusMessage = new StatusMessage.Builder(StatusConstants.ERROR, Messages.UNABLE_TO_FETCH_DEBUG_FILE + ": either no legal protocol could be found in a specification string or the path could not be parsed.") .errorStatus(status).build(); logger.error("Unable to fetch viewData file", malformedURLException); return statusMessage; } catch (HttpException httpException) { Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, httpException.getMessage(), httpException); StatusMessage statusMessage = new StatusMessage.Builder(StatusConstants.ERROR, Messages.UNABLE_TO_FETCH_DEBUG_FILE + ": error from Http client").errorStatus(status).build(); logger.error("Unable to fetch viewData file", httpException); return statusMessage; } catch (NumberFormatException numberFormateException) { Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, numberFormateException.getMessage(), numberFormateException); StatusMessage statusMessage = new StatusMessage.Builder(StatusConstants.ERROR, Messages.UNABLE_TO_FETCH_DEBUG_FILE + ": please check if port number is defined correctly") .errorStatus(status).build(); logger.error("Unable to fetch viewData file", numberFormateException); return statusMessage; } catch (IOException ioException) { Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID, ioException.getMessage(), ioException); StatusMessage statusMessage = new StatusMessage.Builder(StatusConstants.ERROR, Messages.UNABLE_TO_FETCH_DEBUG_FILE + ": please check if service is running") .errorStatus(status).build(); logger.error("Unable to fetch viewData file", ioException); return statusMessage; } if (csvDebugFileAbsolutePath != null) { csvDebugFileName = csvDebugFileAbsolutePath .substring(csvDebugFileAbsolutePath.lastIndexOf("/") + 1, csvDebugFileAbsolutePath.length()) .replace(DEBUG_DATA_FILE_EXTENTION, "").trim(); } //Copy csv debug file to Data viewers temporary file location if (StringUtils.isNotBlank(csvDebugFileName)) { String dataViewerDebugFile = getDataViewerDebugFile(csvDebugFileName); try { if (!filterApplied) { copyCSVDebugFileToDataViewerStagingArea(jobDetails, csvDebugFileAbsolutePath, dataViewerDebugFile, isOverWritten); } else { copyFilteredFileToDataViewerStagingArea(jobDetails, csvDebugFileAbsolutePath, dataViewerDebugFile); } } catch (IOException | JSchException e1) { logger.error("Unable to fetch viewData file", e1); return new StatusMessage(StatusConstants.ERROR, Messages.UNABLE_TO_FETCH_DEBUG_FILE + ": unable to copy the files from temporary location"); } File debugFile = new File(dataViewerDebugFile); double debugFileSizeInByte = (double) debugFile.length(); double debugFileSizeKB = (debugFileSizeInByte / 1024); debugFileSizeInKB = new BigDecimal(debugFileSizeKB).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); // Delete csv debug file after copy deleteFileOnRemote(jobDetails, csvDebugFileName); // Check for empty csv debug file if (isEmptyDebugCSVFile(dataViewerFilePath, dataViewerFileName)) { logger.error("Empty viewData file"); return new StatusMessage(StatusConstants.ERROR, Messages.EMPTY_DEBUG_FILE); } } return new StatusMessage(StatusConstants.SUCCESS); }
From source file:cn.vlabs.duckling.aone.client.impl.EmailAttachmentSenderImpl.java
/** * ?DDL/*w w w.j a va 2s.c om*/ * @param email * @param attachment * @return */ private AttachmentPushResult validateExsit(String email, int teamId, AttachmentInfo attachment) { if (attachment.getCoverFlag()) { return null; } PostMethod method = new PostMethod(getDDLValidateIp()); method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8"); method.addParameter(FILENAME, attachment.getFileName()); method.addParameter(EMAIL, email); method.addParameter(FILESIZE, attachment.getFileSize() + ""); method.addParameter(FILEID, attachment.getFileId()); method.addParameter(TEAMID, teamId + ""); AttachmentPushResult result = new AttachmentPushResult(); result.setFileName(attachment.getFileName()); try { int status = ddlClient.executeMethod(method); if (status >= 200 && status < 300) { String responseString = method.getResponseBodyAsString(); return dealValidateResult(responseString); } else { result.setStatusCode(AttachmentPushResult.NETWORK_ERROR); result.setMessage("DDL?" + status + ""); return result; } } catch (HttpException e) { result.setStatusCode(AttachmentPushResult.NETWORK_ERROR); result.setMessage("DDL?" + e.getMessage() + ""); return result; } catch (IOException e) { result.setStatusCode(AttachmentPushResult.IO_ERROR); result.setMessage("ddlIo"); e.printStackTrace(); return result; } finally { method.releaseConnection(); } }
From source file:cn.vlabs.duckling.aone.client.impl.EmailAttachmentSenderImpl.java
/** * docIdemail/*from ww w . ja va 2s. c om*/ * * @param fileName * @param email * @param teamId * @param docId * @param fileSize * @return */ private AttachmentPushResult createFileResouceInDDL(String email, int teamId, int docId, AttachmentInfo attachment) { AttachmentPushResult result = new AttachmentPushResult(); setAttachResult(result, attachment); PostMethod method = new PostMethod(getDDLIp()); method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8"); method.addParameter(CLBID, docId + ""); method.addParameter(EMAIL, email); method.addParameter(TEAMID, teamId + ""); method.addParameter(FILESIZE, attachment.getFileSize() + ""); method.addParameter(FILEID, attachment.getFileId()); try { method.addParameter(FILENAME, URLEncoder.encode(attachment.getFileName(), "UTF-8")); int status = ddlClient.executeMethod(method); if (status >= 200 && status < 300) { String responseString = method.getResponseBodyAsString(); AttachmentPushResult r = dealHttpResponse(responseString); setAttachResult(r, attachment); return r; } else { result.setStatusCode(AttachmentPushResult.NETWORK_ERROR); result.setMessage("DDL?" + status + ""); return result; } } catch (HttpException e) { result.setStatusCode(AttachmentPushResult.NETWORK_ERROR); result.setMessage("DDL?" + e.getMessage() + ""); return result; } catch (IOException e) { result.setStatusCode(AttachmentPushResult.IO_ERROR); result.setMessage("ddlIo"); return result; } catch (Exception e) { result.setStatusCode(AttachmentPushResult.IO_ERROR); result.setMessage("ddl" + e.getStackTrace()); return result; } finally { method.releaseConnection(); } }
From source file:com.baidu.qa.service.test.client.HttpReqImpl.java
/** * use httpclient/* w w w. ja v a 2 s .c o m*/ * @param file * @param config * @param vargen * @return */ public Object requestHttpByHttpClient(File file, Config config, VariableGenerator vargen) { FileCharsetDetector det = new FileCharsetDetector(); try { String oldcharset = det.guestFileEncoding(file); if (oldcharset.equalsIgnoreCase("UTF-8") == false) FileUtil.transferFile(file, oldcharset, "UTF-8"); } catch (Exception ex) { log.error("[change expect file charset error]:" + ex); } Map<String, String> datalist = FileUtil.getMapFromFile(file, "="); if (datalist.size() <= 1) { return true; } if (!datalist.containsKey(Constant.KW_ITEST_HOST) && !datalist.containsKey(Constant.KW_ITEST_URL)) { log.error("[wrong file]:" + file.getName() + " hasn't Url"); return null; } if (datalist.containsKey(Constant.KW_ITEST_HOST)) { this.url = datalist.get(Constant.KW_ITEST_HOST); this.hashost = true; datalist.remove(Constant.KW_ITEST_HOST); } else { String action = datalist.get(Constant.KW_ITEST_URL); if (config.getHost().lastIndexOf("/") == config.getHost().length() - 1 && action.indexOf("/") == 0) { action = action.substring(1); } this.url = config.getHost() + action; datalist.remove("itest_url"); } if (datalist.containsKey(Constant.KW_ITEST_EXPECT)) { this.itest_expect = datalist.get(Constant.KW_ITEST_EXPECT); datalist.remove(Constant.KW_ITEST_EXPECT); } if (datalist.containsKey(Constant.KW_ITEST_JSON)) { this.itest_expect_json = datalist.get(Constant.KW_ITEST_JSON); datalist.remove(Constant.KW_ITEST_JSON); } parammap = datalist; this.config = config; //HttpClient HttpClient httpClient = new HttpClient(); // httpClient.setConnectionTimeout(30000); httpClient.setTimeout(30000); httpClient.getParams().setParameter("http.protocol.content-charset", "UTF-8"); PostMethod postMethod = new PostMethod(url); if (hashost == false) { //cookie copy if (config.getVariable() != null && config.getVariable().containsKey(Constant.V_CONFIG_VARIABLE_COOKIE)) { postMethod.addRequestHeader(Constant.V_CONFIG_VARIABLE_COOKIE, (String) config.getVariable().get(Constant.V_CONFIG_VARIABLE_COOKIE)); log.info("[HTTP Request Cookie]" + (String) config.getVariable().get(Constant.V_CONFIG_VARIABLE_COOKIE)); } } //??keysparams??body??key=value? if (parammap.size() == 1 && (parammap.containsKey("params") || parammap.containsKey("Params"))) { String key = ""; if (parammap.containsKey("params")) { key = "params"; } else if (parammap.containsKey("Params")) { key = "Params"; } postMethod.setRequestHeader("Content-Type", "text/json;charset=utf-8"); postMethod.setRequestBody(parammap.get(key).toString()); } else { NameValuePair[] data = new NameValuePair[parammap.size()]; int i = 0; for (Map.Entry<String, String> entry : parammap.entrySet()) { log.info("[HTTP post params]" + (String) entry.getKey() + ":" + (String) entry.getValue() + ";"); if (entry.getValue().toString().contains("###")) { } else { data[i] = new NameValuePair((String) entry.getKey(), (String) entry.getValue()); } i++; } // ?postMethod postMethod.setRequestBody(data); } Assert.assertNotNull("get request error,check the input file", postMethod); String response = ""; // postMethod try { int statusCode = httpClient.executeMethod(postMethod); // HttpClient????POSTPUT??? // 301302 if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { // ??? Header locationHeader = postMethod.getResponseHeader("location"); String location = null; if (locationHeader != null) { location = locationHeader.getValue(); log.info("The page was redirected to:" + location); } else { log.info("Location field value is null."); } } //? byte[] responseBody = postMethod.getResponseBody(); if (responseBody == null) { log.error("[HTTP response is null]:please check login or servlet"); return ""; } //?utf-8 response = new String(responseBody, "UTF-8"); //? log.info("[The Post Request's Response][" + url + "]" + response); // responseoutput File resfile = FileUtil.rewriteFile(file.getParentFile().getParent() + Constant.FILENAME_OUTPUT, file.getName().substring(0, file.getName().indexOf(".")) + ".response", response); // vargen.processProps(resfile); //?? if (this.itest_expect != null && this.itest_expect.trim().length() != 0) { Assert.assertTrue( "response different with expect:[expect]:" + this.itest_expect + "[actual]:" + response, response.contains(this.itest_expect)); } // if(this.itest_expect_json!=null&&this.itest_expect_json.trim().length()!=0){ // VerifyJsonTypeResponseImpl.verifyResponseWithJson(this.itest_expect_json,response); // // } } catch (HttpException e) { //????? log.error("Please check your provided http address!" + e.getMessage()); } catch (IOException e) { //? log.error(e.getMessage()); } catch (Exception e) { log.error("[HTTP REQUEST ERROR]:", e); //case fail throw new RuntimeException("HTTP REQUEST ERROR:" + e.getMessage()); } finally { // postMethod.releaseConnection(); } return response; }
From source file:net.neurowork.cenatic.centraldir.workers.xml.OrganizacionXmlImporter.java
public void buscarOrganizacion(String token) { Organizacion organizacion = null;/*from w w w .j ava 2 s. c o m*/ if (logger.isDebugEnabled()) logger.debug("Buscando Organizaciones para Satelite: " + satelite); HttpClient httpclient = XMLRestWorker.getHttpClient(); GetMethod get = new GetMethod(restUrl.getOrganizacionUrl()); get.addRequestHeader("Accept", "application/xml"); NameValuePair tokenParam = new NameValuePair("token", token); int id = 0; // if(satelite.getLastOrgId() != null) // id = satelite.getLastOrgId(); int leap = idLeap; while (true) { id = id + 1; if (logger.isTraceEnabled()) { logger.trace("Buscando Organizacion con id: " + id + " en el Satelite: " + satelite); } NameValuePair passwordParam = new NameValuePair("id", String.valueOf(id)); NameValuePair[] params = new NameValuePair[] { tokenParam, passwordParam }; get.setQueryString(params); String queryString = get.getQueryString(); int statusCode; try { if (logger.isTraceEnabled()) { logger.trace("Query String: " + queryString); } statusCode = httpclient.executeMethod(get); if (statusCode != HttpStatus.SC_OK) { logger.error("Method failed: " + get.getStatusLine()); } else { String xmlString = get.getResponseBodyAsString(); if (logger.isInfoEnabled()) { logger.info("Xml Received."); } String xmlHash = XMLRestWorker.constructXmlHash(xmlString); organizacion = organizacionService.findByHash(xmlHash); if (organizacion == null) { organizacion = parseOrganizacion(xmlString); if (organizacion == null) { leap--; if (leap <= 0) { logger.info("Se lleg al fin de las Organizaciones. Saliendo del Satelite: " + satelite); break; } else { logger.info("Leap: " + leap); } } else { if (organizacion.getSatelites() == null) { organizacion.setSatelites(new HashSet<OrganizacionSatelite>()); } boolean sateliteFound = false; for (OrganizacionSatelite sat : organizacion.getSatelites()) { if (sat.getSatelite().getName().equals(satelite.getName())) { sateliteFound = true; break; } } if (!sateliteFound) { OrganizacionSatelite newSat = new OrganizacionSatelite(); newSat.setSatelite(satelite); newSat.setOrganizacion(organizacion); organizacion.getSatelites().add(newSat); } organizacion.setXmlHash(xmlHash); organizacionService.saveOrganization(organizacion); int numEmpresas = 0; if (satelite.getNumEmpresas() != null) { numEmpresas = satelite.getNumEmpresas(); } numEmpresas++; Date now = new Date(); satelite.setNumEmpresas(numEmpresas); satelite.setLastRetrieval(new Timestamp(now.getTime())); satelite.setLastOrgId(id); sateliteService.saveSatelite(satelite); } } else { if (logger.isInfoEnabled()) { logger.info("Organizacion with id: " + id + " already in centraldir"); } } } } 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()); } catch (ServiceException e) { logger.error(e.getMessage()); } catch (NoSuchAlgorithmException e) { logger.error(e.getMessage()); } finally { get.releaseConnection(); } } }
From source file:com.testmax.uri.HttpRestWithXmlBody.java
public String handleHTTPPostPerformance() throws Exception { String resp = null;/* w w w . j a v a 2s . co m*/ int startcount = 5; boolean isItemIdReplaced = false; String replacedParam = ""; // Create a method instance. PostMethod method = new PostMethod(this.url); System.out.println(this.url); List<NameValuePair> nvps = new ArrayList<NameValuePair>(); URLConfig urlConf = this.page.getPageURL().getUrlConfig(this.action); List<Element> globalItemList = urlConf.getItemListElement(); if (globalItemList.size() > 0) { urlConf.setItemList(); isItemIdReplaced = true; } Set<String> s = urlConf.getUrlParamset(); for (String param : s) { if (!isItemIdReplaced) { //nvps.add(new BasicNameValuePair(param,urlConf.getUrlParamValue(param))); method.addParameter(param, urlConf.getUrlParamValue(param)); } else { replacedParam = urlConf.getUrlReplacedItemIdParamValue(param); method.addParameter(param, replacedParam); //System.out.println(replacedParam); //nvps.add(new BasicNameValuePair(param,replacedParam)); } } org.apache.commons.httpclient.HttpClient client = new org.apache.commons.httpclient.HttpClient(); this.startRecording(); long starttime = this.getCurrentTime(); int statusCode = 0; try { // Execute the method. statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { WmLog.printMessage("Auth Server response received, but there was a ParserConfigurationException: "); } // Read the response body. byte[] responseBody = method.getResponseBody(); resp = new String(responseBody, "UTF-8"); // log the response WmLog.printMessage("MDE Request : " + resp); } catch (HttpException e) { WmLog.printMessage("Unable to retrieve response from MDE webservice : " + e.getMessage()); return null; } catch (IOException e) { WmLog.printMessage("Unable to retrieve response from MDE webservice : " + e.getMessage()); return null; } finally { // Release the connection. method.releaseConnection(); } // Measure the time passed between response long elaspedTime = this.getElaspedTime(starttime); this.stopMethodRecording(statusCode, elaspedTime, startcount); //System.out.println(resp); System.out.println("ElaspedTime: " + elaspedTime); WmLog.printMessage("Response XML: " + resp); WmLog.printMessage("ElaspedTime: " + elaspedTime); this.printMethodRecording(statusCode, this.url); this.printMethodLog(statusCode, this.url); if (statusCode == 200 || statusCode == 400) { this.addThreadActionMonitor(this.action, true, elaspedTime); } else { this.addThreadActionMonitor(this.action, false, elaspedTime); WmLog.printMessage("Input XML: " + replacedParam); WmLog.printMessage("Response XML: " + resp); } return (resp); }