List of usage examples for org.apache.http.client ClientProtocolException getMessage
public String getMessage()
From source file:com.brienwheeler.svc.authorize_net.impl.CIMClientService.java
@Override @MonitoredWork/* w ww . j a v a 2 s . co m*/ @GracefulShutdown @Transactional //(readOnly=true, propagation=Propagation.SUPPORTS) public String getHostedProfilePageToken(DbId<User> userId, String returnUrl) { // More than two years later this still isn't in their Java SDK. Oh well, let's just do it // the stupid way... String customerProfileId = userAttributeService.getAttribute(userId, ATTR_PROFILE_ID); if (customerProfileId == null) customerProfileId = createCustomerProfile(userId); StringBuffer buffer = new StringBuffer(4096); buffer.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); buffer.append("<getHostedProfilePageRequest xmlns=\"AnetApi/xml/v1/schema/AnetApiSchema.xsd\">\n"); buffer.append(" <merchantAuthentication>\n"); buffer.append(" <name>" + apiLoginID + "</name>"); buffer.append(" <transactionKey>" + transactionKey + "</transactionKey>\n"); buffer.append(" </merchantAuthentication>\n"); buffer.append(" <customerProfileId>" + customerProfileId + "</customerProfileId> \n"); buffer.append(" <hostedProfileSettings>\n"); buffer.append(" <setting>\n"); buffer.append(" <settingName>hostedProfileReturnUrl</settingName>\n"); buffer.append(" <settingValue>" + returnUrl + "</settingValue>\n"); buffer.append(" </setting>\n"); buffer.append(" </hostedProfileSettings>\n"); buffer.append("</getHostedProfilePageRequest>\n"); CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(merchant.isSandboxEnvironment() ? TEST_URL : PRODUCTION_URL); EntityBuilder entityBuilder = EntityBuilder.create(); entityBuilder.setContentType(ContentType.TEXT_XML); entityBuilder.setContentEncoding("utf-8"); entityBuilder.setText(buffer.toString()); httpPost.setEntity(entityBuilder.build()); try { CloseableHttpResponse httpResponse = httpClient.execute(httpPost); String response = EntityUtils.toString(httpResponse.getEntity()); int start = response.indexOf(ELEMENT_TOKEN_OPEN); if (start == -1) throw new AuthorizeNetException( "error fetching hosted profile page token for " + userId + ", response: " + response); int end = response.indexOf(ELEMENT_TOKEN_CLOSE); if (end == -1) throw new AuthorizeNetException( "error fetching hosted profile page token for " + userId + ", response: " + response); return response.substring(start + ELEMENT_TOKEN_OPEN.length(), end); } catch (ClientProtocolException e) { throw new AuthorizeNetException(e.getMessage(), e); } catch (IOException e) { throw new AuthorizeNetException(e.getMessage(), e); } }
From source file:com.mnxfst.testing.client.TSClientPlanResultCollectCallable.java
/** * TODO TEST!!!/*from www . j a v a 2 s.c o m*/ * @see java.util.concurrent.Callable#call() */ public TSClientPlanExecutionResult call() throws Exception { InputStream ptestServerInputStream = null; try { HttpResponse response = httpClient.execute(httpHost, getMethod); ptestServerInputStream = response.getEntity().getContent(); XPath xpath = XPathFactory.newInstance().newXPath(); Document responseDoc = DocumentBuilderFactory.newInstance().newDocumentBuilder() .parse(ptestServerInputStream); if (response == null) throw new TSClientExecutionException( "No response document received from " + httpHost.getHostName()); // fetch root node Node rootNode = responseDoc.getFirstChild(); if (rootNode == null) throw new TSClientExecutionException( "No valid root node found in document received from " + httpHost.getHostName()); if (rootNode.getNodeName() == null || !rootNode.getNodeName().equalsIgnoreCase(TEST_EXEC_RESPONSE_ROOT)) throw new TSClientExecutionException( "No valid root node found in document received from " + httpHost.getHostName()); int responseCode = parseIntValue(rootNode, TEST_EXEC_RESPONSE_CODE, xpath); String resultIdentifier = parseStringValue(rootNode, TEST_EXEC_RESULT_IDENTIFIER, xpath); switch (responseCode) { case RESPONSE_CODE_EXECUTION_RESULTS_PENDING: { TSClientPlanExecutionResult planExecutionResult = new TSClientPlanExecutionResult(); planExecutionResult.setResponseCode(RESPONSE_CODE_EXECUTION_RESULTS_PENDING); planExecutionResult.setResultIdentifier(resultIdentifier); planExecutionResult.setHostName(httpHost.getHostName()); planExecutionResult.setPort(httpHost.getPort()); return planExecutionResult; } case RESPONSE_CODE_EXECUTION_RESULTS_CONTAINED: { long averageDuration = parseLongValue(rootNode, TEST_EXEC_AVERAGE_DURATION, xpath); double averageDurationMedian = parseDoubleValue(rootNode, TEST_EXEC_AVERAGE_MEDIAN, xpath); long endTimestamp = parseLongValue(rootNode, TEST_EXEC_END, xpath); long startTimestamp = parseLongValue(rootNode, TEST_EXEC_START, xpath); int errors = parseIntValue(rootNode, TEST_EXEC_ERRORS, xpath); String executionEnvironmentId = parseStringValue(rootNode, TEST_EXEC_ENVIRONMENT, xpath); long singleAverageDuration = parseLongValue(rootNode, TEST_EXEC_SINGLE_AVERAGE_DURATION, xpath); long singleMaxDuration = parseLongValue(rootNode, TEST_EXEC_SINGLE_MAX_DURATION, xpath); long singleMinDuration = parseLongValue(rootNode, TEST_EXEC_SINGLE_MIN_DURATION, xpath); String testPlan = parseStringValue(rootNode, TEST_EXEC_TEST_PLAN, xpath); TSClientPlanExecutionResult planExecutionResult = new TSClientPlanExecutionResult(); planExecutionResult.setResponseCode(RESPONSE_CODE_EXECUTION_RESULTS_PENDING); planExecutionResult.setResultIdentifier(resultIdentifier); planExecutionResult.setHostName(httpHost.getHostName()); planExecutionResult.setPort(httpHost.getPort()); planExecutionResult.setAverageDuration(averageDuration); planExecutionResult.setAverageDurationMedian(averageDurationMedian); planExecutionResult.setEndTimestamp(endTimestamp); planExecutionResult.setErrors(errors); planExecutionResult.setExecutionEnvironmentId(executionEnvironmentId); planExecutionResult.setSingleAverageDuration(singleAverageDuration); planExecutionResult.setSingleMaxDuration(singleMaxDuration); planExecutionResult.setSingleMinDuration(singleMinDuration); planExecutionResult.setStartTimestamp(startTimestamp); planExecutionResult.setTestPlan(testPlan); return planExecutionResult; } default: { throw new TSClientExecutionException("Unexpected response code '" + responseCode + "' received from " + httpHost.getHostName() + ":" + httpHost.getPort()); } } } catch (ClientProtocolException e) { throw new TSClientExecutionException("Failed to call " + httpHost.getHostName() + ":" + httpHost.getPort() + "/" + getMethod.getURI() + ". Error: " + e.getMessage()); } catch (IOException e) { throw new TSClientExecutionException("Failed to call " + httpHost.getHostName() + ":" + httpHost.getPort() + "/" + getMethod.getURI() + ". Error: " + e.getMessage()); } finally { if (ptestServerInputStream != null) { try { ptestServerInputStream.close(); httpClient.getConnectionManager().shutdown(); } catch (Exception e) { System.out.println("Failed to close ptest-server connection"); } } } }
From source file:custom.application.login.java
public String oAuth2_github_callback() throws ApplicationException { HttpServletRequest request = (HttpServletRequest) this.context.getAttribute("HTTP_REQUEST"); HttpServletResponse response = (HttpServletResponse) this.context.getAttribute("HTTP_RESPONSE"); Reforward reforward = new Reforward(request, response); if (this.getVariable("github_client_secrets") == null) { TextFileLoader loader = new TextFileLoader(); loader.setInputStream(login.class.getResourceAsStream("/clients_secrets.json")); builder = new Builder(); builder.parse(loader.getContent().toString()); if (builder.get("github") instanceof Builder) { builder = (Builder) builder.get("github"); System.out.println(builder.get("client_secret")); System.out.println(builder.get("client_id")); this.setVariable(new ObjectVariable("github_client_secrets", builder)); }/*ww w . j a v a2 s.c om*/ } else builder = (Builder) this.getVariable("github_client_secrets").getValue(); String arguments = this.http_client("https://github.com/login/oauth/access_token?client_id=" + builder.get("client_id") + "&client_secret=" + builder.get("client_secret") + "&code=" + request.getParameter("code")); try { HttpClient httpClient = new DefaultHttpClient(); String url = "https://api.github.com/user"; HttpGet httpget = new HttpGet(url + "?" + arguments); httpClient.getParams().setParameter(HttpProtocolParams.HTTP_CONTENT_CHARSET, "UTF-8"); HttpResponse http_response = httpClient.execute(httpget); HeaderIterator iterator = http_response.headerIterator(); while (iterator.hasNext()) { Header next = iterator.nextHeader(); System.out.println(next.getName() + ":" + next.getValue()); } InputStream instream = http_response.getEntity().getContent(); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] bytes = new byte[1024]; int len; while ((len = instream.read(bytes)) != -1) { out.write(bytes, 0, len); } instream.close(); out.close(); Struct struct = new Builder(); struct.parse(new String(out.toByteArray(), "utf-8")); this.usr = new User(); this.usr.setEmail(struct.toData().getFieldInfo("email").stringValue()); if (this.usr.findOneByKey("email", this.usr.getEmail()).size() == 0) { usr.setPassword(""); usr.setUsername(usr.getEmail()); usr.setLastloginIP(request.getRemoteAddr()); usr.setLastloginTime(new Date()); usr.setRegistrationTime(new Date()); usr.append(); } new passport(request, response, "waslogined").setLoginAsUser(this.usr.getId()); reforward.setDefault(URLDecoder.decode(this.getVariable("from").getValue().toString(), "utf8")); reforward.forward(); return new String(out.toByteArray(), "utf-8"); } catch (ClientProtocolException e) { throw new ApplicationException(e.getMessage(), e); } catch (IOException e) { throw new ApplicationException(e.getMessage(), e); } catch (ParseException e) { throw new ApplicationException(e.getMessage(), e); } }
From source file:org.deviceconnect.android.profile.restful.test.RESTfulDConnectTestCase.java
/** * RESTful?dConnectManager??./* ww w . ja v a 2s .co m*/ * @param request Http * @return HttpResponse */ protected final HttpResponse requestHttpResponse(final HttpUriRequest request) { HttpClient client = new DefaultHttpClient(); try { return client.execute(request); } catch (ClientProtocolException e) { Assert.fail("ClientProtocolException: " + e.getMessage()); } catch (IOException e) { Assert.fail("IOException: " + e.getMessage()); } return null; }
From source file:org.deviceconnect.android.profile.restful.test.RESTfulDConnectTestCase.java
/** * HTTP???.//from www.j a v a 2 s .c o m * @param uri ??URI * @return */ protected final byte[] getBytesFromHttp(final String uri) { HttpUriRequest request = new HttpGet(uri); HttpClient client = new DefaultHttpClient(); try { HttpResponse response = client.execute(request); switch (response.getStatusLine().getStatusCode()) { case HttpStatus.SC_OK: InputStream in = response.getEntity().getContent(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buf = new byte[BUF_SIZE]; int len; while ((len = in.read(buf)) > 0) { baos.write(buf, 0, len); } return baos.toByteArray(); case HttpStatus.SC_NOT_FOUND: Assert.fail("Not found page. 404: " + uri); break; default: Assert.fail("Connection Error. " + response.getStatusLine().getStatusCode()); break; } } catch (ClientProtocolException e) { Assert.fail("ClientProtocolException: " + e.getMessage()); } catch (IOException e) { Assert.fail("IOException: " + e.getMessage()); } return null; }
From source file:com.sourcey.materiallogindemo.MainActivity.java
public String getJSONUrl(String url, List<NameValuePair> params) { StringBuilder str = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); try {//from w ww . jav a 2s. c o m httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8")); HttpResponse response = client.execute(httpPost); StatusLine statusLine = response.getStatusLine(); int statusCode = statusLine.getStatusCode(); if (statusCode == 200) { // Download OK HttpEntity entity = response.getEntity(); InputStream content = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(content)); String line; while ((line = reader.readLine()) != null) { str.append(line); } } else { Log.e("Log", "Failed to download file.."); } } catch (ClientProtocolException e) { e.getMessage(); e.getMessage(); } catch (IOException e) { e.getMessage(); } return str.toString(); }
From source file:com.ibm.watson.developer_cloud.professor_languo.pipeline.RnrMergerAndRanker.java
/** * Rank {@code answers} to {@code question} * /*from www .j ava2s . c o m*/ * @param question {@link Question} from which {@link answers} are formed * @param answers list of {@link CandidateAnswer}'s * @return Ranked answers */ private Observable<CandidateAnswer> apply(Question question, Observable<CandidateAnswer> answers) { try { // Create authorized HttpClient CloseableHttpClient client = RankerCreationUtil.createHttpClient(AuthScope.ANY, creds); // Build feature vector data for candidate answers in csv format String csvAnswerData = RankerCreationUtil.getCsvAnswerData(answers.toList().toBlocking().first(), null); // Send rank request String rank_request_url = ranker_url + "/" + current_ranker_id + RetrieveAndRankSearcherConstants.RANK_REQUEST_HANDLER; JSONObject responseJSON = RankerCreationUtil.rankAnswers(client, rank_request_url, csvAnswerData); JSONArray rankedAnswerArray = (JSONArray) responseJSON.get("answers"); // If there is an error with the service, wait a moment // and retry up to retry limit int retryAttempt = 1; while (rankedAnswerArray == null) { if (retryAttempt > retryLimit) { throw new PipelineException(MessageFormat .format(Messages.getString("RetrieveAndRank.QUERY_RETRY_FAILED"), retryAttempt)); //$NON-NLS-1$ } Thread.sleep(3000); logger.info(MessageFormat.format(Messages.getString("RetrieveAndRank.QUERY_RETRY"), retryAttempt)); //$NON-NLS-1$ responseJSON = RankerCreationUtil.rankAnswers(client, rank_request_url, csvAnswerData); rankedAnswerArray = (JSONArray) responseJSON.get("answers"); retryAttempt++; } // Iterate through JSONArray of ranked answers and match with the // original List<CandidateAnswer> answerList = answers.toList().toBlocking().first(); // Set confidence to the top answers chosen by the ranker, // ignore the rest List<CandidateAnswer> rankedAnswerList = new ArrayList<CandidateAnswer>(); for (int i = 0; i < answerList.size(); i++) { for (int j = 0; j < rankedAnswerArray.size(); j++) { JSONObject ans = (JSONObject) rankedAnswerArray.get(j); // Get the answer_id String answer_id = (String) ans.get(RetrieveAndRankConstants.ANSWER_ID_HEADER); double confidence = (double) ans.get(RetrieveAndRankConstants.CONFIDENCE_HEADER); if (answerList.get(i).getAnswerLabel().equals(answer_id)) { // Set the answer's confidence answerList.get(i).setConfidence(confidence); rankedAnswerList.add(answerList.get(i)); } } } return Observable.from(rankedAnswerList); } catch (ClientProtocolException e) { logger.error(e.getMessage()); } catch (IOException e) { logger.error(e.getMessage()); // Something wrong with the service. Set all confidence to 0 List<CandidateAnswer> answerList = answers.toList().toBlocking().first(); for (CandidateAnswer answer : answerList) { answer.setConfidence(0); } } catch (Exception e) { logger.error(e.getMessage()); } return answers; }
From source file:org.corfudb.sharedlog.ClientLib.java
public CorfuConfiguration pullConfig(String master) throws CorfuException { DefaultHttpClient httpclient = new DefaultHttpClient(); try {/*from ww w . jav a 2 s. c om*/ HttpGet httpget = new HttpGet(master); System.out.println("Executing request: " + httpget.getRequestLine()); HttpResponse response = httpclient.execute(httpget); System.out.println("pullConfig from master: " + response.getStatusLine()); CM = new CorfuConfiguration(response.getEntity().getContent()); } catch (ClientProtocolException e) { throw new InternalCorfuException("cannot pull configuration: " + e.getMessage()); } catch (IOException e) { throw new InternalCorfuException("cannot pull configuration: " + e.getMessage()); } return CM; }
From source file:redstone.xmlrpc.XmlRpcClient.java
private Object endCall(Context ctx, String method) throws XmlRpcException, XmlRpcFault { try {/*w w w . j a v a 2 s . c o m*/ writer.write("</params>"); writer.write("</methodCall>"); StringBuffer buffer = ((StringWriter) writer).getBuffer(); // // try { // FileUtil.saveTextToFile(FileUtil.getCacheRootPath(ctx) + method + ".xml", buffer.toString(), "UTF-8"); // } catch (Exception e) { // } // // DefaultHttpClient client = getConnection(ctx); // HttpResponse response = doPost(client, this.url.toString(), buffer.toString()); if (response == null) { String errorMessage = XmlRpcMessages.getString("XmlRpcClient.NetworkError"); throw new XmlRpcNetworkException(errorMessage); } // int retCode = response.getStatusLine().getStatusCode(); if (retCode != 200) { String errorMessage = XmlRpcMessages.getString("XmlRpcClient.NetworkErrorTimeout"); errorMessage = errorMessage.replaceAll("%1", Integer.toString(retCode)); throw new XmlRpcNetworkException(errorMessage); } // HttpEntity httpEntity = response.getEntity(); // InputStream is = httpEntity.getContent(); try { handleResponse(method, is); } finally { if (is != null) { is.close(); } } } catch (ClientProtocolException err) { err.printStackTrace(); throw new XmlRpcNetworkException(err.getMessage()); } catch (java.net.SocketTimeoutException err) { throw new XmlRpcNetworkException(XmlRpcMessages.getString("XmlRpcClient.NetworkErrorTimeout")); } catch (org.apache.http.conn.ConnectTimeoutException err) { throw new XmlRpcNetworkException(err.getMessage()); } catch (IOException err) { err.printStackTrace(); throw new XmlRpcNetworkException(err.getMessage()); } finally { } return returnValue; }
From source file:no.ntnu.idi.socialhitchhiking.Main.java
/** * Initializes GUI components./*from www . ja v a 2 s.c om*/ * Is called via {@link #onCreate(Bundle)} and {@link #setName(String)} * * @param n - A String which is used to set the users name in a TextField */ public void initMainScreen() { //If create user crashes, this might be the problem Request req2 = new UserRequest(RequestType.GET_USER, getApp().getUser()); UserResponse res2 = null; try { res2 = (UserResponse) RequestTask.sendRequest(req2, getApp()); User resUser = res2.getUser(); User tempUser = getApp().getUser(); tempUser.setCarId(resUser.getCarId()); tempUser.setAbout(resUser.getAbout()); tempUser.setRating(resUser.getRating()); //tempUser.setRating(1); getApp().setUser(tempUser); } catch (ClientProtocolException e1) { Log.e("Error", e1.getMessage()); } catch (IOException e1) { Log.e("Error", e1.getMessage()); } catch (InterruptedException e1) { Log.e("Error", e1.getMessage()); } catch (ExecutionException e1) { Log.e("Error", e1.getMessage()); } user = getApp().getUser(); if (!getApp().isKey("main")) { sendLoginRequest(); } runOnUiThread(new Runnable() { @Override public void run() { setContentView(R.layout.main_layout); sceduleDrive = (Button) findViewById(R.id.startScreenDrive); notifications = (Button) findViewById(R.id.startScreenInbox); hitchhike = (Button) findViewById(R.id.startScreenHitchhike); myAccount = (Button) findViewById(R.id.startScreenMyAccount); myTrips = (Button) findViewById(R.id.startScreenMyTrips); name = (TextView) findViewById(R.id.startScreenProfileName); picture = (ImageView) findViewById(R.id.startScreenProfilePicture); name.setText(user.getFullName()); picture.setImageBitmap(getFacebookPicture(user)); /*picture.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loginAsNewClicked(true); } }); */ sceduleDrive.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startCreateJourney(); } }); hitchhike.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startFindDriver(); } }); notifications.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { startInbox(); } }); myAccount.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub startMyAccount(); } }); pbLogin.setVisibility(View.GONE); checkSettings(); } }); if (getApp().getSettings().isPullNotifications() && !getApp().isKey("alarmService")) getApp().startService(); getApp().setKeyState("main", true); }