List of usage examples for org.apache.http.client ClientProtocolException getLocalizedMessage
public String getLocalizedMessage()
From source file:com.ibm.commerce.worklight.android.search.SearchSuggestionsProvider.java
/** * Retrieves the search suggestion JSON array and constructs the search suggestions list * For example, the JSON array would follow a similar structure, using a search on the * term 'dress':/*from w ww.j a va2s . c om*/ * * {'terms': * [ * {'dress':'766'}, * {'dress empire':'62'}, * {'dress empire waist':'62'}, * {'dress layered':'57'}, * ... * ] * } * * @param string The query term input into the search dialog * @return The list of search term suggestions */ private List<String> getSearchTermSuggestions(String query) { final String METHOD_NAME = CLASS_NAME + ".getSearchTermSuggestions"; boolean loggingEnabled = Log.isLoggable(LOG_TAG, Log.DEBUG); if (loggingEnabled) { Log.d(METHOD_NAME, "ENTRY"); } List<String> suggestionList = null; if (query == null || query.equals("")) { return suggestionList; } WCHybridApplication wcHybridApp = WCHybridApplication.getInstance(); String requestUrl = wcHybridApp.getSearchSuggestionUrl(query).toString(); String suggestionJsonString = null; HttpParams httpParams = new BasicHttpParams(); HttpConnectionParams.setConnectionTimeout(httpParams, HTTP_TIME_OUT); HttpClient httpClient = new DefaultHttpClient(httpParams); try { suggestionJsonString = httpClient.execute(new HttpGet(requestUrl), new BasicResponseHandler()); } catch (ClientProtocolException e) { Log.d(METHOD_NAME, "Error getting search suggestion JSON: " + e.getLocalizedMessage()); } catch (IOException e) { Log.d(METHOD_NAME, "Error getting search suggestion JSON: " + e.getLocalizedMessage()); } finally { httpClient.getConnectionManager().shutdown(); } if (suggestionJsonString != null && !suggestionJsonString.equals("")) { try { if (loggingEnabled) { Log.d(METHOD_NAME, "Suggestion JSON string: " + suggestionJsonString); } JSONObject json = new JSONObject(suggestionJsonString); JSONArray suggestions = json.getJSONArray("terms"); if (suggestions != null) { suggestionList = new ArrayList<String>(suggestions.length()); for (int i = 0; i < suggestions.length(); i++) { suggestionList.add(suggestions.getJSONObject(i).names().getString(0)); } } } catch (JSONException e) { Log.d(METHOD_NAME, "Error parsing search suggestion JSON: " + e.getLocalizedMessage()); } } if (loggingEnabled) { Log.d(METHOD_NAME, "EXIT"); } return suggestionList; }
From source file:de.lemo.apps.restws.client.InitialisationImpl.java
public Date getStartTime() throws RestServiceCommunicationException { try {/*from www .j a v a 2s . co m*/ // TODO we could use a proxy object here, just as everywhere else final ClientRequest request = new ClientRequest(InitialisationImpl.SERVICE_STARTTIME_URL); ClientResponse<ServiceStartTime> response = request.get(ServiceStartTime.class); if (response.getStatus() != HttpStatus.SC_OK) { throw new RuntimeException("Failed : HTTP error code : " + response.getStatus()); } // / XXX this seems like a duplication of the request above! final ServiceStartTime serviceProxy = ProxyFactory.create(ServiceStartTime.class, InitialisationImpl.SERVICE_STARTTIME_URL); response.releaseConnection(); if (serviceProxy != null) { return new Date(serviceProxy.startTimeJson().getTime()); } return null; } catch (final ClientProtocolException e) { throw new RestServiceCommunicationException(this.toString() + " " + e.getLocalizedMessage()); } catch (final IOException e) { throw new RestServiceCommunicationException(this.toString() + " " + e.getLocalizedMessage()); } catch (final Exception e) { throw new RestServiceCommunicationException(this.toString() + " " + e.getLocalizedMessage()); } }
From source file:com.team08storyapp.ESHelper.java
private HttpResponse getHttpResponse(HttpPost httpPost) { HttpResponse response = null;//from w w w .j av a2 s.c om try { response = httpclient.execute(httpPost); } catch (ClientProtocolException e) { Log.d(TAG, e.getLocalizedMessage()); } catch (IOException e) { Log.d(TAG, e.getLocalizedMessage()); } return response; }
From source file:com.team08storyapp.ESHelper.java
/** * Returns a Story object for a specific onlineStoryId contained on the * webservice. This Story object can be used to display a * "Chose Your Own Adventure story".//from ww w . j ava2 s .com * <p> * The method uses ElisticSearch (@link http://www.elasticsearch.org/guide/) * to retrieve the story from the webservice. * * @param storyId * The onlineStoryId of the Story to retrieve from the * webservice. * @return The Story object for a specified onlineStoryId. * @see Story */ public Story getOnlineStory(int storyId) { /* * set policy to allow for internet activity to happen within the * android application */ StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); Story story; try { /* * Create a HttpGet object with the onlineStoryId of the Story to * retrieve from the webservice */ HttpGet getRequest = new HttpGet( "http://cmput301.softwareprocess.es:8080/cmput301f13t08/stories/" + storyId + "?pretty=1"); /* * Set the HttpGet so that it knows it is retrieving a JSON * formatted object */ getRequest.addHeader("Accept", "application/json"); /* Execute the httpclient to get the object from the webservice */ HttpResponse response = httpclient.execute(getRequest); /* Retrieve and print to the log cat the status result of the post */ String status = response.getStatusLine().toString(); Log.d(TAG, status); /* * Retrieve the Story object in the form of a string to be converted * from JSON */ String json = getEntityContent(response); /* We have to tell GSON what type we expect */ Type elasticSearchResponseType = new TypeToken<ElasticSearchResponse<Story>>() { }.getType(); /* Now we expect to get a Story response */ ElasticSearchResponse<Story> esResponse = gson.fromJson(json, elasticSearchResponseType); /* We get the Story from it! */ story = esResponse.getSource(); } catch (ClientProtocolException e) { Log.d(TAG, e.getLocalizedMessage()); return null; } catch (IOException e) { Log.d(TAG, e.getLocalizedMessage()); return null; } return story; }
From source file:com.team08storyapp.ESHelper.java
/** * Returns a list of all Story objects contained on the webservice. These * stories can be used to display a list of all possible stories to view * online.//from w w w. j ava 2 s . c o m * * @return The List of Stories from the webservice. * @see Story */ public ArrayList<Story> getOnlineStories() { /* * set policy to allow for internet activity to happen within the * android application */ StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); ArrayList<Story> stories = new ArrayList<Story>(); try { /* * Create a HttpPost object to retrieve the Stories from the * webservice */ HttpPost postRequest = new HttpPost( "http://cmput301.softwareprocess.es:8080/cmput301f13t08/stories/_search?pretty=1&fields=onlineStoryId,title,author"); /* * Set the httppost so that it knows it is retrieving a JSON * formatted object */ postRequest.addHeader("Accept", "application/json"); /* Execute the httpclient to get the object from the webservice */ HttpResponse response = httpclient.execute(postRequest); /* Retrieve and print to the log cat the status result of the post */ String status = response.getStatusLine().toString(); Log.d(TAG, status); /* * Retrieve the Story object in the form of a string to be converted * from JSON */ String json = getEntityContent(response); /* We have to tell GSON what type we expect */ Type elasticSearchSearchResponseType = new TypeToken<ElasticSearchSearchResponse<Story>>() { }.getType(); /* Now we expect to get a story response */ ElasticSearchSearchResponse<Story> esResponse = gson.fromJson(json, elasticSearchSearchResponseType); /* We get the story from it! */ Log.d(TAG, esResponse.toString()); for (ElasticSearchResponse<Story> s : esResponse.getHits()) { Story story = s.getFields(); stories.add(story); } } catch (ClientProtocolException e) { Log.d(TAG, e.getLocalizedMessage()); return null; } catch (IOException e) { Log.d(TAG, e.getLocalizedMessage()); return null; } return stories; }
From source file:com.team08storyapp.ESHelper.java
/** * Returns a list of stories from the webservice that contain the searched * text in either their Author or Title fields. * <p>/*w ww . j a v a 2 s . c om*/ * The method uses ElisticSearch (@link http://www.elasticsearch.org/guide/) * to retrieve the story from the webservice. * * @param searchString * A text string containing the key set of words to use in * searching the webservices Stories. * @return A list of stories that contain the text used in the search in * either their Author or Title fields. */ public ArrayList<Story> searchOnlineStories(String searchString) { searchString = searchString.toLowerCase(Locale.US); StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); ArrayList<Story> stories = new ArrayList<Story>(); if (!searchString.matches(".*\\w.*") || searchString.contains("\n")) { return getOnlineStories(); } try { /* * Create a HttpPost object to retrieve the Stories from the * webservice */ HttpPost searchRequest = new HttpPost( "http://cmput301.softwareprocess.es:8080/cmput301f13t08/_search?pretty=1"); /* * Create the ElasticSearch query string to search the webservice * for the search text */ String query = "{\"fields\": [\"onlineStoryId\",\"title\",\"author\"], \"query\": {\"query_string\" :{ \"fields\":[\"title\",\"author\"], \"query\":\"" + searchString + "\"}}}"; StringEntity stringentity = new StringEntity(query); /* * Set the httppost so that it knows it is retrieving a JSON * formatted object */ searchRequest.setHeader("Accept", "application/json"); searchRequest.setEntity(stringentity); /* Execute the httpclient to get the object from the webservice */ HttpResponse response = httpclient.execute(searchRequest); /* Retrieve and print to the log cat the status result of the post */ String status = response.getStatusLine().toString(); Log.d(TAG, status); /* * Retrieve the Story object in the form of a string to be converted * from JSON */ String json = getEntityContent(response); /* We have to tell GSON what type we expect */ Type elasticSearchSearchResponseType = new TypeToken<ElasticSearchSearchResponse<Story>>() { }.getType(); /* Now we expect to get a story response */ ElasticSearchSearchResponse<Story> esResponse = gson.fromJson(json, elasticSearchSearchResponseType); Log.d(TAG, esResponse.toString()); /* We get the story from it! */ for (ElasticSearchResponse<Story> s : esResponse.getHits()) { Story story = s.getFields(); stories.add(story); } } catch (ClientProtocolException e) { Log.d(TAG, e.getLocalizedMessage()); return null; } catch (IOException e) { Log.d(TAG, e.getLocalizedMessage()); return null; } return stories; }
From source file:com.evolveum.polygon.scim.SalesforceHandlingStrategy.java
@Override public Uid groupUpdateProcedure(Integer statusCode, JSONObject jsonObject, String uri, Header authHeader, ScimConnectorConfiguration conf) { Uid id = null;//from w w w . j a v a 2 s .co m HttpClient httpClient = initHttpClient(conf); LOGGER.info( "Status code from first update query: {0}. Processing trough Salesforce \"group/member update\" workaround. ", statusCode); HttpGet httpGet = buildHttpGet(uri, authHeader); try (CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(httpGet);) { statusCode = response.getStatusLine().getStatusCode(); LOGGER.info("status code: {0}", statusCode); if (statusCode == 200) { String responseString = EntityUtils.toString(response.getEntity()); if (!responseString.isEmpty()) { JSONObject json = new JSONObject(responseString); LOGGER.info("Json object returned from service provider: {0}", json); for (String attributeName : jsonObject.keySet()) { json.put(attributeName, jsonObject.get(attributeName)); } StringEntity bodyContent = new StringEntity(json.toString(1)); bodyContent.setContentType(CONTENTTYPE); HttpPatch httpPatch = new HttpPatch(uri); httpPatch.addHeader(authHeader); httpPatch.addHeader(PRETTYPRINTHEADER); httpPatch.setEntity(bodyContent); try (CloseableHttpResponse secondaryResponse = (CloseableHttpResponse) httpClient .execute(httpPatch)) { responseString = EntityUtils.toString(secondaryResponse.getEntity()); statusCode = secondaryResponse.getStatusLine().getStatusCode(); LOGGER.info("status code: {0}", statusCode); if (statusCode == 200 || statusCode == 201) { LOGGER.info("Update of resource was successful"); json = new JSONObject(responseString); id = new Uid(json.getString(ID)); LOGGER.ok("Json response: {0}", json.toString(1)); return id; } else { ErrorHandler.onNoSuccess(responseString, statusCode, "updating object"); } } } } } catch (ClientProtocolException e) { LOGGER.error( "An protocol exception has occurred while in the process of updating a resource object. Possible mismatch in the interpretation of the HTTP specification: {0}", e.getLocalizedMessage()); LOGGER.info( "An protocol exception has occurred while in the process of updating a resource object. Possible mismatch in the interpretation of the HTTP specification: {0}", e); throw new ConnectionFailedException( "An protocol exception has occurred while in the process of updating a resource object, Possible mismatch in the interpretation of the HTTP specification.", e); } catch (IOException e) { StringBuilder errorBuilder = new StringBuilder( "Occurrence in the process of creating a resource object"); if ((e instanceof SocketTimeoutException || e instanceof NoRouteToHostException)) { errorBuilder.insert(0, "The connection timed out. "); throw new OperationTimeoutException(errorBuilder.toString(), e); } else { LOGGER.error( "An error has occurred while processing the http response. Occurrence in the process of updating a resource object: {0}", e.getLocalizedMessage()); LOGGER.info( "An error has occurred while processing the http response. Occurrence in the process of creating a resource object: {0}", e); throw new ConnectorIOException(errorBuilder.toString(), e); } } return id; }
From source file:org.modelio.vbasic.net.ApacheUriConnection.java
@objid("f8e1a3e4-45b3-4065-8838-90de7fe64eaa") private void openConnection() throws IOException, IllegalStateException { this.context = HttpClientContext.create(); CredentialsProvider credsProvider = new SystemDefaultCredentialsProvider(); this.context.setCredentialsProvider(credsProvider); if (this.auth != null) { switch (this.auth.getSchemeId()) { case UserPasswordAuthData.USERPASS_SCHEME_ID: UserPasswordAuthData authData = (UserPasswordAuthData) this.auth; if (authData.getUser() == null) throw new ClientProtocolException(this.uri + ": User name may not be null."); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(authData.getUser(), authData.getPassword()); AuthScope authscope = new AuthScope(this.uri.getHost(), AuthScope.ANY_PORT); credsProvider.setCredentials(authscope, credentials); break; case NoneAuthData.AUTH_NONE_SCHEME_ID: break; default:/*from www. j a v a 2s. c o m*/ throw new UnknownServiceException(this.auth + " not supported for " + this.uri); } } /** support different proxy */ configProxy(credsProvider); getRequest().setConfig(this.configBuilder.build()); try { this.res = httpclient.execute(getRequest(), this.context); int statusCode = this.res.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300) { // Try to get content now to get an exception on failure immediately this.res.getEntity().getContent(); } else { handleConnectionFailure(); } } catch (ClientProtocolException e) { throw new IOException(e.getLocalizedMessage(), e); } }
From source file:com.searchbox.collection.oppfin.TopicCollection.java
/** * Load content from a URL using a valid User agent. * * @param url The Url to load data from//from w w w. j ava2 s . c o m * @return The content of the page as string. */ private String loadFromUrl(String url) { try { HttpClient client = HttpClientBuilder.create().build(); HttpGet request = new HttpGet(url); // add request header request.addHeader("User-Agent", env.getProperty(CRAWLER_USER_AGENT, CRAWLER_USER_AGENT_DEFAULT)); HttpResponse response = client.execute(request); LOGGER.debug("Recieved the response code " + response.getStatusLine().getStatusCode() + " from " + url); String result = EntityUtils.toString(response.getEntity(), "utf-8"); return result; } catch (ClientProtocolException e) { LOGGER.error("Error loading url " + e.getLocalizedMessage()); } catch (IOException e) { LOGGER.error("Error loading url " + e.getLocalizedMessage()); } return null; }