List of usage examples for java.io UnsupportedEncodingException getMessage
public String getMessage()
From source file:com.mobilyzer.Checkin.java
public String serviceRequest(String url, String jsonString) throws IOException { if (this.accountSelector == null) { accountSelector = new AccountSelector(context); }//from w ww. j a v a 2 s . c om if (!accountSelector.isAnonymous()) { synchronized (this) { if (authCookie == null) { if (!checkGetCookie()) { throw new IOException("No authCookie yet"); } } } } HttpClient client = getNewHttpClient(); String fullurl = (accountSelector.isAnonymous() ? phoneUtils.getAnonymousServerUrl() : phoneUtils.getServerUrl()) + "/" + url; Logger.i("Checking in to " + fullurl); HttpPost postMethod = new HttpPost(fullurl); StringEntity se; try { se = new StringEntity(jsonString); } catch (UnsupportedEncodingException e) { throw new IOException(e.getMessage()); } postMethod.setEntity(se); postMethod.setHeader("Accept", "application/json"); postMethod.setHeader("Content-type", "application/json"); if (!accountSelector.isAnonymous()) { // TODO(mdw): This should not be needed postMethod.setHeader("Cookie", authCookie.getName() + "=" + authCookie.getValue()); } ResponseHandler<String> responseHandler = new BasicResponseHandler(); Logger.i("Sending request: " + fullurl); String result = client.execute(postMethod, responseHandler); return result; }
From source file:com.impetus.kundera.rest.resources.MongoQueryTest.java
@Test public void testCompositeUserCRUD() throws JsonParseException, JsonMappingException, IOException { WebResource webResource = resource(); restClient = new RESTClientImpl(); restClient.initialize(webResource, mediaType); // Get Application Token applicationToken = restClient.getApplicationToken(_PU, null); Assert.assertNotNull(applicationToken); applicationToken = applicationToken.replaceAll("^\"|\"$", ""); Assert.assertTrue(applicationToken.startsWith("AT_")); // Get Session Token sessionToken = restClient.getSessionToken(applicationToken); Assert.assertNotNull(sessionToken);/*from w ww . j a v a 2 s. c o m*/ sessionToken = sessionToken.replaceAll("^\"|\"$", ""); Assert.assertTrue(sessionToken.startsWith("ST_")); UUID timeLineId = UUID.randomUUID(); Date currentDate = new Date(); MongoCompoundKey key = new MongoCompoundKey("mevivs", 1, timeLineId); MongoPrimeUser timeLine = new MongoPrimeUser(key); timeLine.setKey(key); timeLine.setTweetBody("my first tweet"); timeLine.setTweetDate(currentDate); MongoCompoundKey key1 = new MongoCompoundKey("john", 2, timeLineId); MongoPrimeUser timeLine2 = new MongoPrimeUser(key1); timeLine2.setKey(key1); timeLine2.setTweetBody("my second tweet"); timeLine2.setTweetDate(currentDate); String mongoUser = JAXBUtils.toString(timeLine, MediaType.APPLICATION_JSON); Assert.assertNotNull(mongoUser); String mongoUser1 = JAXBUtils.toString(timeLine2, MediaType.APPLICATION_JSON); Assert.assertNotNull(mongoUser1); // Insert Record String insertResponse1 = restClient.insertEntity(sessionToken, mongoUser, "MongoPrimeUser"); String insertResponse2 = restClient.insertEntity(sessionToken, mongoUser1, "MongoPrimeUser"); Assert.assertNotNull(insertResponse1); Assert.assertNotNull(insertResponse2); Assert.assertTrue(insertResponse1.indexOf("200") > 0); Assert.assertTrue(insertResponse2.indexOf("200") > 0); String encodepk1 = null; pk1 = JAXBUtils.toString(key, MediaType.APPLICATION_JSON); pk2 = JAXBUtils.toString(key1, MediaType.APPLICATION_JSON); try { encodepk1 = java.net.URLEncoder.encode(pk1, "UTF-8"); } catch (UnsupportedEncodingException e) { log.error(e.getMessage()); } // Find Record String foundUser = restClient.findEntity(sessionToken, encodepk1, "MongoPrimeUser"); Assert.assertNotNull(foundUser); Assert.assertNotNull(foundUser); Assert.assertTrue(foundUser.indexOf("mevivs") > 0); foundUser = foundUser.substring(1, foundUser.length() - 1); Map<String, Object> userDetails = new HashMap<String, Object>(); ObjectMapper mapper = new ObjectMapper(); userDetails = mapper.readValue(foundUser, userDetails.getClass()); foundUser = mapper.writeValueAsString(userDetails.get("mongoprimeuser")); // Update Record foundUser = foundUser.replaceAll("first", "hundreth"); String updatedUser = restClient.updateEntity(sessionToken, foundUser, MongoPrimeUser.class.getSimpleName()); Assert.assertNotNull(updatedUser); Assert.assertTrue(updatedUser.indexOf("hundreth") > 0); /** JPA Query - Select */ // Get All users String jpaQuery = "select p from " + MongoPrimeUser.class.getSimpleName() + " p"; String queryResult = restClient.runJPAQuery(sessionToken, jpaQuery, new HashMap<String, Object>()); log.debug("Query Result:" + queryResult); Assert.assertNotNull(queryResult); Assert.assertFalse(StringUtils.isEmpty(queryResult)); Assert.assertTrue(queryResult.indexOf("mongoprimeuser") > 0); Assert.assertTrue(queryResult.indexOf(pk1) > 0); Assert.assertTrue(queryResult.indexOf(pk2) > 0); Assert.assertTrue(queryResult.indexOf("Motif") < 0); jpaQuery = "select p from " + MongoPrimeUser.class.getSimpleName() + " p WHERE p.key = :key"; Map<String, Object> params = new HashMap<String, Object>(); params.put("key", pk1); queryResult = restClient.runObjectJPAQuery(sessionToken, jpaQuery, params); log.debug("Query Result:" + queryResult); Assert.assertNotNull(queryResult); Assert.assertFalse(StringUtils.isEmpty(queryResult)); Assert.assertTrue(queryResult.indexOf("mongoprimeuser") > 0); Assert.assertTrue(queryResult.indexOf(timeLineId.toString()) > 0); Assert.assertTrue(queryResult.indexOf(pk2) < 0); Assert.assertTrue(queryResult.indexOf("Motif") < 0); jpaQuery = "select p from " + MongoPrimeUser.class.getSimpleName() + " p"; params = new HashMap<String, Object>(); params.put("firstResult", 0); params.put("maxResult", 1); queryResult = restClient.runObjectJPAQuery(sessionToken, jpaQuery, params); log.debug("Query Result:" + queryResult); String userList = queryResult.substring(1, queryResult.length() - 1); mapper = new ObjectMapper(); userDetails = new HashMap<String, Object>(); userDetails = mapper.readValue(userList, userDetails.getClass()); userList = mapper.writeValueAsString(userDetails.get("mongoprimeuser")); List<MongoPrimeUser> navigation = mapper.readValue(userList, mapper.getTypeFactory().constructCollectionType(List.class, MongoPrimeUser.class)); Assert.assertNotNull(queryResult); Assert.assertFalse(StringUtils.isEmpty(queryResult)); Assert.assertTrue(queryResult.indexOf("mongoprimeuser") > 0); Assert.assertTrue(queryResult.indexOf(timeLineId.toString()) > 0); Assert.assertEquals(1, navigation.size()); /** JPA Query - Select All */ // Get All Users String allUsers = restClient.getAllEntities(sessionToken, MongoPrimeUser.class.getSimpleName()); log.debug(allUsers); Assert.assertNotNull(allUsers); // Close Session restClient.closeSession(sessionToken); // Close Application restClient.closeApplication(applicationToken); }
From source file:hudson.plugins.jira.JiraRestService.java
public JiraRestService(URI uri, JiraRestClient jiraRestClient, String username, String password, int timeout) { this.uri = uri; this.objectMapper = new ObjectMapper(); this.timeout = timeout; final String login = username + ":" + password; try {/* w w w .j ava 2 s .c o m*/ byte[] encodeBase64 = Base64.encodeBase64(login.getBytes("UTF-8")); this.authHeader = "Basic " + new String(encodeBase64, "UTF-8"); } catch (UnsupportedEncodingException e) { LOGGER.warning("jira rest encode username:password error. cause: " + e.getMessage()); throw new RuntimeException("failed to encode username:password using Base64"); } this.jiraRestClient = jiraRestClient; final StringBuilder builder = new StringBuilder(); if (uri.getPath() != null) { builder.append(uri.getPath()); if (!uri.getPath().endsWith("/")) { builder.append('/'); } } else { builder.append('/'); } builder.append(BASE_API_PATH); baseApiPath = builder.toString(); }
From source file:com.google.wireless.speed.speedometer.Checkin.java
private String speedometerServiceRequest(String url, String jsonString) throws IOException { synchronized (this) { if (authCookie == null) { if (!checkGetCookie()) { throw new IOException("No authCookie yet"); }/*from ww w . j a va 2 s . c o m*/ } } HttpClient client = getNewHttpClient(); String fullurl = serverUrl + "/" + url; HttpPost postMethod = new HttpPost(fullurl); StringEntity se; try { se = new StringEntity(jsonString); } catch (UnsupportedEncodingException e) { throw new IOException(e.getMessage()); } postMethod.setEntity(se); postMethod.setHeader("Accept", "application/json"); postMethod.setHeader("Content-type", "application/json"); // TODO(mdw): This should not be needed postMethod.setHeader("Cookie", authCookie.getName() + "=" + authCookie.getValue()); ResponseHandler<String> responseHandler = new BasicResponseHandler(); Log.i(SpeedometerApp.TAG, "Sending request: " + fullurl); String result = client.execute(postMethod, responseHandler); return result; }
From source file:com.windigo.http.client.ApacheHttpClient.java
/** * Create {@link HttpPost} request with given {@link String} url and * {@link NameValuePair} request parameters * //from w ww . jav a2 s . co m * @param url * @param nameValuePairs * @throws IllegalArgumentException * @return {@link HttpPost} */ public HttpPost createHttpPostRequest(String url, List<NameValuePair> nameValuePairs) { HttpPost httpPost = new HttpPost(url); try { httpPost.setEntity(new UrlEncodedFormEntity(sanitizeParameters(nameValuePairs), HTTP.UTF_8)); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException("Problem while encoding url parameters " + e.getMessage()); } return httpPost; }
From source file:edu.hawaii.soest.hioos.storx.StorXFrame.java
public String getSerialNumber() { try {//from ww w . ja va 2s. c om return new String(this.serialNumber.array(), "US-ASCII"); } catch (UnsupportedEncodingException uee) { logger.debug("The string encoding was not recognized: " + uee.getMessage()); return null; } }
From source file:com.dbay.apns4j.impl.ApnsConnectionImpl.java
@Override public void sendNotification(PushNotification notification) { byte[] plBytes = null; String payload = notification.getPayload().toString(); try {// w w w. j a va 2s. co m plBytes = payload.getBytes(CHARSET_ENCODING); if (plBytes.length > PAY_LOAD_MAX_LENGTH) { logger.error("Payload execeed limit, the maximum size allowed is 256 bytes. " + payload); return; } } catch (UnsupportedEncodingException e) { logger.error(e.getMessage(), e); return; } /** * EN: If error happened before, just wait until the resending work * finishes by another thread and close the current socket CN: * ??error-response????????? */ synchronized (lock) { if (errorHappendedLastConn) { closeSocket(socket); socket = null; } byte[] data = notification.generateData(plBytes); boolean isSuccessful = false; int retries = 0; while (retries < maxRetries) { try { boolean exceedIntervalTime = lastSuccessfulTime > 0 && (System.currentTimeMillis() - lastSuccessfulTime) > intervalTime; if (exceedIntervalTime) { closeSocket(socket); socket = null; } if (socket == null || socket.isClosed()) { socket = createNewSocket(); } OutputStream socketOs = socket.getOutputStream(); socketOs.write(data); socketOs.flush(); isSuccessful = true; break; } catch (Exception e) { logger.error(serviceName + "," + connName + " " + e.getMessage(), e); closeSocket(socket); socket = null; } retries++; } if (!isSuccessful) { logger.error( String.format("%s, %s Notification send failed. %s", serviceName, connName, notification)); return; } else { logger.info(String.format("%s, %s Send success. count: %s, notificaion: %s", serviceName, connName, notificaionSentCount.incrementAndGet(), notification)); notificationCachedQueue.add(notification); lastSuccessfulTime = System.currentTimeMillis(); /** * TODO there is a bug, maybe, theoretically. CN: * ?????? maxCacheLength ?APNS? * ??error-response?? * ??100?????APNS?? */ if (notificationCachedQueue.size() > maxCacheLength) { notificationCachedQueue.poll(); } } } if (isFirstWrite) { isFirstWrite = false; /** * EN: When we create a socket, just a TCP/IP connection created. * After we wrote data to the stream, the SSL connection had been * created. Now, it's time to read data from InputStream CN: * createSocket?TCPSSL??????? * ?InputStream */ startErrorWorker(); } }
From source file:edu.hawaii.soest.hioos.storx.StorXFrame.java
public String getHeader() { this.header.flip(); try {//from ww w . j a v a 2 s .c om return new String(this.header.array(), "US-ASCII"); } catch (UnsupportedEncodingException uee) { logger.debug("The string encoding was not recognized: " + uee.getMessage()); return null; } }
From source file:edu.hawaii.soest.hioos.storx.StorXFrame.java
/** * Get the frame terminator field as a String * @return terminator - the terminator as a String */// ww w .jav a2 s .c o m public String getTerminator() { this.terminator.flip(); try { return new String(this.terminator.array(), "US-ASCII"); } catch (UnsupportedEncodingException uee) { logger.debug("The string encoding was not recognized: " + uee.getMessage()); return null; } }
From source file:org.meerkat.services.WebServiceApp.java
/** * checkWebAppStatus/*from w ww . j a va 2 s . com*/ */ public final WebAppResponse checkWebAppStatus() { // Set the response at this point to empty in case of no response at all setCurrentResponse(""); int statusCode = 0; // Create a HttpClient MeerkatHttpClient meerkatClient = new MeerkatHttpClient(); DefaultHttpClient httpClient = meerkatClient.getHttpClient(); HttpResponse httpresponse = null; WebAppResponse response = new WebAppResponse(); XMLComparator xmlCompare; response.setResponseWebService(); String responseFromPostXMLRequest; // Get target URL String strURL = this.getUrl(); // Prepare HTTP post HttpPost httpPost = new HttpPost(strURL); StringEntity strEntity = null; try { strEntity = new StringEntity(postXML, "UTF-8"); } catch (UnsupportedEncodingException e3) { log.error("UnsupportedEncodingException: " + e3.getMessage()); } httpPost.setEntity(strEntity); // Set Headers httpPost.setHeader("Content-type", "text/xml; charset=ISO-8859-1"); // Set the SOAP Action if specified if (!soapAction.equalsIgnoreCase("")) { httpPost.setHeader("SOAPAction", this.soapAction); } // Measure the request time Counter c = new Counter(); c.startCounter(); // Get headers // Header[] headers = httpPost.getAllHeaders(); // int total = headers.length; // log.info("\nHeaders"); // for(int i=0;i<total;i++){ // log.info(headers[i]); // } // Execute the request try { httpresponse = httpClient.execute(httpPost); // Set status code statusCode = httpresponse.getStatusLine().getStatusCode(); } catch (Exception e) { log.error("WebService Exception: " + e.getMessage() + " [URL: " + this.getUrl() + "]"); httpClient.getConnectionManager().shutdown(); c.stopCounter(); response.setPageLoadTime(c.getDurationSeconds()); setCurrentResponse(e.getMessage()); return response; } response.setHttpStatus(statusCode); // Get the response BufferedReader br = null; try { // Read in UTF-8 br = new BufferedReader(new InputStreamReader(httpresponse.getEntity().getContent(), "UTF-8")); } catch (IllegalStateException e1) { log.error("IllegalStateException in http buffer: " + e1.getMessage()); } catch (IOException e1) { log.error("IOException in http buffer: " + e1.getMessage()); } String readLine; String responseBody = ""; try { while (((readLine = br.readLine()) != null)) { responseBody += "\n" + readLine; } } catch (IOException e) { log.error("IOException in http response: " + e.getMessage()); } try { br.close(); } catch (IOException e1) { log.error("Closing BufferedReader: " + e1.getMessage()); } response.setHttpTextResponse(responseBody); setCurrentResponse(responseBody); // When HttpClient instance is no longer needed, // shut down the connection manager to ensure // immediate deallocation of all system resources httpClient.getConnectionManager().shutdown(); // Stop the counter c.stopCounter(); response.setPageLoadTime(c.getDurationSeconds()); if (statusCode != HttpStatus.SC_OK) { log.warn("Httpstatus code: " + statusCode + " | Method failed: " + httpresponse.getStatusLine()); // Set the response to the error if none present if (this.getCurrentResponse().equals("")) { setCurrentResponse(httpresponse.getStatusLine().toString()); } } // Prepare to compare with expected response responseFromPostXMLRequest = responseBody; // Format both request response and response file XML String responseFromPostXMLRequestFormatted = ""; String xmlResponseExpected = ""; XmlFormatter formatter = new XmlFormatter(); try { responseFromPostXMLRequestFormatted = formatter.format(responseFromPostXMLRequest.trim()); xmlResponseExpected = formatter.format(responseXML); } catch (Exception e) { log.error("Error parsing XML: " + e.getMessage()); } try { // Compare the XML response file with the response XML xmlCompare = new XMLComparator(xmlResponseExpected, responseFromPostXMLRequestFormatted); if (xmlCompare.areXMLsEqual()) { response.setContainsWebServiceExpectedResponse(true); } } catch (Exception e) { log.error("Error parsing XML for comparison: " + e.getMessage()); } return response; }