List of usage examples for org.apache.http.impl.client BasicResponseHandler BasicResponseHandler
BasicResponseHandler
From source file:org.nema.medical.mint.dcm2mint.ProcessImportDir.java
/** * @throws IOException/*www .j av a2 s .co m*/ */ public void handleResponses() throws IOException { final ResponseHandler<String> responseHandler = new BasicResponseHandler(); final Iterator<Entry<String, JobInfo>> studyIter = jobIDInfo.entrySet().iterator(); while (studyIter.hasNext()) { final Entry<String, JobInfo> studyEntry = studyIter.next(); final String jobID = studyEntry.getKey(); final HttpGet httpGet = new HttpGet(jobStatusURI + "/" + jobID); final String response = httpClient.execute(httpGet, responseHandler); LOG.debug("Server job status response:\n" + response); final String statusStr; try { final Document responseDoc = documentBuilder.parse(new ByteArrayInputStream(response.getBytes())); statusStr = xPath.evaluate("/jobStatus/@jobStatus", responseDoc); } catch (final Exception ex) { LOG.error("Querying job " + jobID + ": unknown server response:\n" + response); studyIter.remove(); continue; } final JobInfo jobInfo = studyEntry.getValue(); final Collection<File> studyFiles = jobInfo.getFiles(); if (statusStr.equals("IN_PROGRESS")) { continue; } else if (statusStr.equals("FAILED")) { LOG.error("Querying job " + jobID + ": server processing failed:\n" + response); //Do not delete the study's files in case of failure removeStudyFiles(studyFiles, false); } else if (statusStr.equals("SUCCESS")) { final long approxJobEndTime = System.currentTimeMillis(); //Always round down the job processing time, as it's usually too high anyway LOG.info("Querying job " + jobID + ": server processing completed in approximately " + ((approxJobEndTime - jobInfo.getJobStartTime()) / 1000) + " seconds for " + studyFiles.size() + " instance files, Study ID " + jobInfo.getStudyID() + "."); removeStudyFiles(studyFiles, true); } else { LOG.error("Querying job " + jobID + ": unknown server response:\n" + response); //Do not delete the study's files in case of failure removeStudyFiles(studyFiles, false); } studyIter.remove(); } }
From source file:org.bungeni.ext.integration.bungeniportal.BungeniAppConnector.java
/** * Negotiate the Oauth access URL , this will forward to a login page * @return//from ww w .j av a 2 s .c om * @throws IOException */ private String oauthNegotiate() throws IOException { final HttpGet hget = new HttpGet(this.oauthLoginUrl); HttpContext context = new BasicHttpContext(); HttpResponse oauthResponse = getClient().execute(hget, context); // if the OAuth page retrieval failed throw an exception if (oauthResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new IOException(oauthResponse.getStatusLine().toString()); } // if the OAuth page retrieval succeeded we get the redirected page, // which in this case is the login page String currentUrl = getRequestEndContextURL(context); // consume the response ResponseHandler<String> responseHandler = new BasicResponseHandler(); responseHandler.handleResponse(oauthResponse); consumeContent(oauthResponse.getEntity()); return currentUrl; }
From source file:dataServer.StorageRESTClientManager.java
public String getAllProducts() { // Default HTTP client and common properties for requests requestUrl = null;/* w w w. j av a 2 s .c om*/ // Default HTTP response and common properties for responses HttpResponse response = null; ResponseHandler<String> handler = null; int status = 0; String body = null; // Query for product list requestUrl = new StringBuilder("http://" + storageLocation + ":" + storagePortRegistryC + storageRegistryContext + "/query/product/list"); try { HttpGet query = new HttpGet(requestUrl.toString()); query.setHeader("Content-type", "application/json"); response = client.execute(query); // Check status code status = response.getStatusLine().getStatusCode(); if (status != 200) { throw new RuntimeException("Failed! HTTP error code: " + status); } // Get body handler = new BasicResponseHandler(); body = handler.handleResponse(response); //System.out.println("PRODUCT LIST: " + body); return body; } catch (Exception e) { System.out.println(e.getClass().getName() + ": " + e.getMessage()); return null; } }
From source file:com.portfolio.data.attachment.XSLService.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { /**/*from www .j a v a2s. c o m*/ * Format demand: * <convert> * <portfolioid>{uuid}</portfolioid> * <portfolioid>{uuid}</portfolioid> * <nodeid>{uuid}</nodeid> * <nodeid>{uuid}</nodeid> * <documentid>{uuid}</documentid> * <xsl>{rpertoire}{fichier}</xsl> * <format>[pdf rtf xml ...]</format> * <parameters> * <maVar1>lala</maVar1> * ... * </parameters> * </convert> */ try { //On initialise le dataProvider Connection c = null; //On initialise le dataProvider if (ds == null) // Case where we can't deploy context.xml { c = getConnection(); } else { c = ds.getConnection(); } dataProvider.setConnection(c); credential = new Credential(c); } catch (Exception e) { e.printStackTrace(); } String origin = request.getRequestURL().toString(); /// Variable stuff int userId = 0; int groupId = 0; String user = ""; HttpSession session = request.getSession(true); if (session != null) { Integer val = (Integer) session.getAttribute("uid"); if (val != null) userId = val; val = (Integer) session.getAttribute("gid"); if (val != null) groupId = val; user = (String) session.getAttribute("user"); } /// TODO: A voire si un form get ne ferait pas l'affaire aussi /// On lis le xml /* BufferedReader rd = new BufferedReader(new InputStreamReader(request.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while( (line = rd.readLine()) != null ) sb.append(line); DocumentBuilderFactory documentBuilderFactory =DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = null; Document doc=null; try { documentBuilder = documentBuilderFactory.newDocumentBuilder(); doc = documentBuilder.parse(new ByteArrayInputStream(sb.toString().getBytes("UTF-8"))); } catch( Exception e ) { e.printStackTrace(); } /// On lit les paramtres NodeList portfolioNode = doc.getElementsByTagName("portfolioid"); NodeList nodeNode = doc.getElementsByTagName("nodeid"); NodeList documentNode = doc.getElementsByTagName("documentid"); NodeList xslNode = doc.getElementsByTagName("xsl"); NodeList formatNode = doc.getElementsByTagName("format"); NodeList parametersNode = doc.getElementsByTagName("parameters"); //*/ // String xslfile = xslNode.item(0).getTextContent(); String xslfile = request.getParameter("xsl"); String format = request.getParameter("format"); // String format = formatNode.item(0).getTextContent(); String parameters = request.getParameter("parameters"); String documentid = request.getParameter("documentid"); String portfolios = request.getParameter("portfolioids"); String[] portfolioid = null; if (portfolios != null) portfolioid = portfolios.split(";"); String nodes = request.getParameter("nodeids"); String[] nodeid = null; if (nodes != null) nodeid = nodes.split(";"); System.out.println("PARAMETERS: "); System.out.println("xsl: " + xslfile); System.out.println("format: " + format); System.out.println("user: " + userId); System.out.println("portfolioids: " + portfolios); System.out.println("nodeids: " + nodes); System.out.println("parameters: " + parameters); boolean redirectDoc = false; if (documentid != null) { redirectDoc = true; System.out.println("documentid @ " + documentid); } boolean usefop = false; String ext = ""; if (MimeConstants.MIME_PDF.equals(format)) { usefop = true; ext = ".pdf"; } else if (MimeConstants.MIME_RTF.equals(format)) { usefop = true; ext = ".rtf"; } //// Paramtre portfolio-uuid et file-xsl // String uuid = request.getParameter("uuid"); // String xslfile = request.getParameter("xsl"); StringBuilder aggregate = new StringBuilder(); try { int portcount = 0; int nodecount = 0; // On aggrge les donnes if (portfolioid != null) { portcount = portfolioid.length; for (int i = 0; i < portfolioid.length; ++i) { String p = portfolioid[i]; String portfolioxml = dataProvider .getPortfolio(new MimeType("text/xml"), p, userId, groupId, "", null, null, 0) .toString(); aggregate.append(portfolioxml); } } if (nodeid != null) { nodecount = nodeid.length; for (int i = 0; i < nodeid.length; ++i) { String n = nodeid[i]; String nodexml = dataProvider.getNode(new MimeType("text/xml"), n, true, userId, groupId, "") .toString(); aggregate.append(nodexml); } } // Est-ce qu'on a eu besoin d'aggrger les donnes? String input = aggregate.toString(); String pattern = "<\\?xml[^>]*>"; // Purge previous xml declaration input = input.replaceAll(pattern, ""); input = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<!DOCTYPE xsl:stylesheet [" + "<!ENTITY % lat1 PUBLIC \"-//W3C//ENTITIES Latin 1 for XHTML//EN\" \"" + servletDir + "xhtml-lat1.ent\">" + "<!ENTITY % symbol PUBLIC \"-//W3C//ENTITIES Symbols for XHTML//EN\" \"" + servletDir + "xhtml-symbol.ent\">" + "<!ENTITY % special PUBLIC \"-//W3C//ENTITIES Special for XHTML//EN\" \"" + servletDir + "xhtml-special.ent\">" + "%lat1;" + "%symbol;" + "%special;" + "]>" + // For the pesky special characters "<root>" + input + "</root>"; // System.out.println("INPUT WITH PROXY:"+ input); /// Rsolution des proxys DocumentBuilder documentBuilder; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilder = documentBuilderFactory.newDocumentBuilder(); InputSource is = new InputSource(new StringReader(input)); Document doc = documentBuilder.parse(is); /// Proxy stuff XPath xPath = XPathFactory.newInstance().newXPath(); String filterRes = "//asmResource[@xsi_type='Proxy']"; String filterCode = "./code/text()"; NodeList nodelist = (NodeList) xPath.compile(filterRes).evaluate(doc, XPathConstants.NODESET); XPathExpression codeFilter = xPath.compile(filterCode); for (int i = 0; i < nodelist.getLength(); ++i) { Node res = nodelist.item(i); Node gp = res.getParentNode(); // resource -> context -> container Node ggp = gp.getParentNode(); Node uuid = (Node) codeFilter.evaluate(res, XPathConstants.NODE); /// Fetch node we want to replace String returnValue = dataProvider .getNode(new MimeType("text/xml"), uuid.getTextContent(), true, userId, groupId, "") .toString(); Document rep = documentBuilder.parse(new InputSource(new StringReader(returnValue))); Element repNode = rep.getDocumentElement(); Node proxyNode = repNode.getFirstChild(); proxyNode = doc.importNode(proxyNode, true); // adoptNode have some weird side effect. To be banned // doc.replaceChild(proxyNode, gp); ggp.insertBefore(proxyNode, gp); // replaceChild doesn't work. ggp.removeChild(gp); } try // Convert XML document to string { DOMSource domSource = new DOMSource(doc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.transform(domSource, result); writer.flush(); input = writer.toString(); } catch (TransformerException ex) { ex.printStackTrace(); } // System.out.println("INPUT DATA:"+ input); // Setup a buffer to obtain the content length ByteArrayOutputStream stageout = new ByteArrayOutputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); //// Setup Transformer (1st stage) /// Base path String basepath = xslfile.substring(0, xslfile.indexOf(File.separator)); String firstStage = baseDir + File.separator + basepath + File.separator + "karuta" + File.separator + "xsl" + File.separator + "html2xml.xsl"; System.out.println("FIRST: " + firstStage); Source xsltSrc1 = new StreamSource(new File(firstStage)); Transformer transformer1 = transFactory.newTransformer(xsltSrc1); StreamSource stageSource = new StreamSource(new ByteArrayInputStream(input.getBytes())); Result stageRes = new StreamResult(stageout); transformer1.transform(stageSource, stageRes); // Setup Transformer (2nd stage) String secondStage = baseDir + File.separator + xslfile; Source xsltSrc2 = new StreamSource(new File(secondStage)); Transformer transformer2 = transFactory.newTransformer(xsltSrc2); // Configure parameter from xml String[] table = parameters.split(";"); for (int i = 0; i < table.length; ++i) { String line = table[i]; int var = line.indexOf(":"); String par = line.substring(0, var); String val = line.substring(var + 1); transformer2.setParameter(par, val); } // Setup input StreamSource xmlSource = new StreamSource(new ByteArrayInputStream(stageout.toString().getBytes())); // StreamSource xmlSource = new StreamSource(new File(baseDir+origin, "projectteam.xml") ); Result res = null; if (usefop) { /// FIXME: Might need to include the entity for html stuff? //Setup FOP //Make sure the XSL transformation's result is piped through to FOP Fop fop = fopFactory.newFop(format, out); res = new SAXResult(fop.getDefaultHandler()); //Start the transformation and rendering process transformer2.transform(xmlSource, res); } else { res = new StreamResult(out); //Start the transformation and rendering process transformer2.transform(xmlSource, res); } if (redirectDoc) { // /resources/resource/file/{uuid}[?size=[S|L]&lang=[fr|en]] String urlTarget = "http://" + server + "/resources/resource/file/" + documentid; System.out.println("Redirect @ " + urlTarget); HttpClientBuilder clientbuilder = HttpClientBuilder.create(); CloseableHttpClient client = clientbuilder.build(); HttpPost post = new HttpPost(urlTarget); post.addHeader("referer", origin); String sessionid = request.getSession().getId(); System.out.println("Session: " + sessionid); post.addHeader("Cookie", "JSESSIONID=" + sessionid); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE); ByteArrayBody body = new ByteArrayBody(out.toByteArray(), "generated" + ext); builder.addPart("uploadfile", body); HttpEntity entity = builder.build(); post.setEntity(entity); HttpResponse ret = client.execute(post); String stringret = new BasicResponseHandler().handleResponse(ret); int code = ret.getStatusLine().getStatusCode(); response.setStatus(code); ServletOutputStream output = response.getOutputStream(); output.write(stringret.getBytes(), 0, stringret.length()); output.close(); client.close(); /* HttpURLConnection connection = CreateConnection( urlTarget, request ); /// Helping construct Json connection.setRequestProperty("referer", origin); /// Send post data ServletInputStream inputData = request.getInputStream(); DataOutputStream writer = new DataOutputStream(connection.getOutputStream()); byte[] buffer = new byte[1024]; int dataSize; while( (dataSize = inputData.read(buffer,0,buffer.length)) != -1 ) { writer.write(buffer, 0, dataSize); } inputData.close(); writer.close(); RetrieveAnswer(connection, response, origin); //*/ } else { response.reset(); response.setHeader("Content-Disposition", "attachment; filename=generated" + ext); response.setContentType(format); response.setContentLength(out.size()); response.getOutputStream().write(out.toByteArray()); response.getOutputStream().flush(); } } catch (Exception e) { String message = e.getMessage(); response.setStatus(500); response.getOutputStream().write(message.getBytes()); response.getOutputStream().close(); e.printStackTrace(); } finally { dataProvider.disconnect(); } }
From source file:com.ibuildapp.romanblack.FanWallPlugin.data.Statics.java
public static FanWallMessage postMessage(String msg, String imagePath, int parentId, int replyId, boolean withGps) { HttpParams params = new BasicHttpParams(); params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1); HttpClient httpClient = new DefaultHttpClient(params); try {//from w ww .j a v a 2 s. c om HttpPost httpPost = new HttpPost(Statics.BASE_URL + "/"); MultipartEntity multipartEntity = new MultipartEntity(); multipartEntity.addPart("app_id", new StringBody(com.appbuilder.sdk.android.Statics.appId, Charset.forName("UTF-8"))); multipartEntity.addPart("token", new StringBody(com.appbuilder.sdk.android.Statics.appToken, Charset.forName("UTF-8"))); multipartEntity.addPart("module_id", new StringBody(Statics.MODULE_ID, Charset.forName("UTF-8"))); // ? ? multipartEntity.addPart("parent_id", new StringBody(Integer.toString(parentId), Charset.forName("UTF-8"))); multipartEntity.addPart("reply_id", new StringBody(Integer.toString(replyId), Charset.forName("UTF-8"))); if (Authorization.getAuthorizedUser().getAccountType() == User.ACCOUNT_TYPES.FACEBOOK) { multipartEntity.addPart("account_type", new StringBody("facebook", Charset.forName("UTF-8"))); } else if (Authorization.getAuthorizedUser().getAccountType() == User.ACCOUNT_TYPES.TWITTER) { multipartEntity.addPart("account_type", new StringBody("twitter", Charset.forName("UTF-8"))); } else { multipartEntity.addPart("account_type", new StringBody("ibuildapp", Charset.forName("UTF-8"))); } multipartEntity.addPart("account_id", new StringBody(Authorization.getAuthorizedUser().getAccountId(), Charset.forName("UTF-8"))); multipartEntity.addPart("user_name", new StringBody(Authorization.getAuthorizedUser().getUserName(), Charset.forName("UTF-8"))); multipartEntity.addPart("user_avatar", new StringBody(Authorization.getAuthorizedUser().getAvatarUrl(), Charset.forName("UTF-8"))); if (withGps) { if (Statics.currentLocation != null) { multipartEntity.addPart("latitude", new StringBody(Statics.currentLocation.getLatitude() + "", Charset.forName("UTF-8"))); multipartEntity.addPart("longitude", new StringBody(Statics.currentLocation.getLongitude() + "", Charset.forName("UTF-8"))); } } multipartEntity.addPart("text", new StringBody(msg, Charset.forName("UTF-8"))); if (!TextUtils.isEmpty(imagePath)) { multipartEntity.addPart("images", new FileBody(new File(imagePath))); } httpPost.setEntity(multipartEntity); String resp = httpClient.execute(httpPost, new BasicResponseHandler()); return JSONParser.parseMessagesString(resp).get(0); } catch (Exception e) { return null; } }
From source file:gov.sfmta.sfpark.MainScreenActivity.java
public static String getStringContent(String uri) throws Exception { try {//ww w .ja v a 2 s. co m HttpGet request = new HttpGet(); request.setURI(new URI(uri)); request.addHeader("Accept-Encoding", "gzip"); final HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 30 * SECOND_IN_MILLIS); HttpConnectionParams.setSoTimeout(params, 30 * SECOND_IN_MILLIS); HttpConnectionParams.setSocketBufferSize(params, 8192); final DefaultHttpClient client = new DefaultHttpClient(params); client.addResponseInterceptor(new HttpResponseInterceptor() { public void process(HttpResponse response, HttpContext context) { final HttpEntity entity = response.getEntity(); final Header encoding = entity.getContentEncoding(); if (encoding != null) { for (HeaderElement element : encoding.getElements()) { if (element.getName().equalsIgnoreCase("gzip")) { response.setEntity(new InflatingEntity(response.getEntity())); break; } } } } }); return client.execute(request, new BasicResponseHandler()); } finally { // any cleanup code... } }
From source file:com.comcast.dawg.pound.DawgPoundIT.java
/** * Calls the @link{DawgPound#isReserved()} API and returns the response string. * * @param deviceId//from w w w. j a v a2s . c om * * @return the response string * * @throws ClientProtocolException * @throws IOException */ private String isReserved(String deviceId) throws ClientProtocolException, IOException { String url = BASE_URL + "reserved/id/" + deviceId; HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String responseBody = httpclient.execute(httpget, responseHandler); logger.info(String.format("Reservation rest call(%s) response body is : %s.", url, responseBody)); return responseBody; }
From source file:org.cloudifysource.azure.CliAzureDeploymentTest.java
/** * This methods extracts the number of machines running gs-agents using the rest admin api * //from w ww . j a v a 2 s . co m * @param machinesRestAdminUrl * @return number of machines running gs-agents * @throws IOException * @throws URISyntaxException */ private static int getNumberOfMachines(URL machinesRestAdminUrl) throws IOException, URISyntaxException { HttpClient client = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(machinesRestAdminUrl.toURI()); try { String json = client.execute(httpGet, new BasicResponseHandler()); Matcher matcher = Pattern.compile("\"Size\":\"([0-9]+)\"").matcher(json); if (matcher.find()) { String rawSize = matcher.group(1); int size = Integer.parseInt(rawSize); return size; } else { return 0; } } catch (Exception e) { return 0; } finally { client.getConnectionManager().shutdown(); } }
From source file:com.ibuildapp.romanblack.TableReservationPlugin.utils.TableReservationHTTP.java
/** * Logins user via email./*w w w . j a v a 2 s. co m*/ * * @param login user login * @param pass user password * @return result code */ public static String loginPost(String login, String pass) { HttpParams params = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(params, 15000); HttpConnectionParams.setSoTimeout(params, 15000); HttpClient httpClient = new DefaultHttpClient(params); List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); try { HttpPost httpPost = new HttpPost(LOGIN_URL); //HttpPost httpPost = new HttpPost("http://ibuildapp.com/modules/user/login"); // order details nameValuePairs.add(new BasicNameValuePair("login", login)); nameValuePairs.add(new BasicNameValuePair("password", pass)); // add security part nameValuePairs.add(new BasicNameValuePair("app_id", Statics.appId)); nameValuePairs.add(new BasicNameValuePair("token", Statics.appToken)); httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); String resp = httpClient.execute(httpPost, new BasicResponseHandler()); Log.d("", ""); return resp; } catch (Exception e) { Log.e("REGISTRATION ERROR", e.getMessage(), e); return null; } }
From source file:csic.ceab.movelab.beepath.Util.java
public static boolean uploadJSONArray(Context context, JSONArray jsonArray, String uploadurl) { String response = ""; try {/*from ww w. j a v a 2 s . c o m*/ // Create a new HttpClient and Post Header HttpPatch httppatch = new HttpPatch(uploadurl); HttpParams myParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(myParams, 10000); HttpConnectionParams.setSoTimeout(myParams, 60000); HttpConnectionParams.setTcpNoDelay(myParams, true); httppatch.setHeader("Content-type", "application/json"); String auth = "-u john:1234"; httppatch.setHeader("Authorization", auth); HttpClient httpclient = new DefaultHttpClient(); ByteArrayEntity bae = new ByteArrayEntity(jsonArray.toString().getBytes("UTF8")); // StringEntity se = new StringEntity(jsonArray.toString(), // HTTP.UTF_8); // se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, // "application/json")); bae.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); httppatch.setEntity(bae); // Execute HTTP Post Request ResponseHandler<String> responseHandler = new BasicResponseHandler(); response = httpclient.execute(httppatch, responseHandler); } catch (ClientProtocolException e) { } catch (IOException e) { } if (response.contains("SUCCESS")) { Log.i("SERVER RESPONSE", response); return true; } else { Log.i("SERVER RESPONSE", response); return false; } }