List of usage examples for java.io UnsupportedEncodingException getMessage
public String getMessage()
From source file:org.dasein.cloud.qingcloud.util.requester.QingCloudRequestBuilder.java
private String doMac(byte[] accessKeySecret, String stringToSign) throws InternalException { String signature;// w ww .j a v a2s .c om try { Mac mac = Mac.getInstance(SIGNATURE_ALGORITHM); mac.init(new SecretKeySpec(accessKeySecret, SIGNATURE_ALGORITHM)); byte[] signedData = mac.doFinal(stringToSign.getBytes(ENCODING)); signature = new String(Base64.encodeBase64(signedData)); } catch (NoSuchAlgorithmException noSuchAlgorithmException) { logger.error("AliyunRequestBuilderStrategy.sign() failed due to algorithm not supported: " + noSuchAlgorithmException.getMessage()); throw new InternalException(noSuchAlgorithmException); } catch (InvalidKeyException invalidKeyException) { logger.error("AliyunRequestBuilderStrategy.sign() failed due to key invalid: " + invalidKeyException.getMessage()); throw new InternalException(invalidKeyException); } catch (UnsupportedEncodingException unsupportedEncodingException) { logger.error("AliyunMethod.sign() failed due to encoding not supported: " + unsupportedEncodingException.getMessage()); throw new InternalException(unsupportedEncodingException); } return signature; }
From source file:fedroot.dacs.http.DacsPostRequest.java
/** * the following, which includes parameters in the multipart entity is not grokked * by DACS multipart parsing//from w w w.j a v a 2 s . c o m * @param webServiceRequest * @return */ private HttpPost multipartBrokenPost(WebServiceRequest webServiceRequest) { try { HttpPost multipartPost = new HttpPost(webServiceRequest.getBaseURI()); // multipartPost.setHeader("Content-Type", webServiceRequest.getEnclosureType()); multipartPost.setHeader("Content-Transfer-Encoding", "7bit"); MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, "----HttpClientBoundarynSbUMwsZpJVNlFYK", Charset.forName("US-ASCII")); for (NameValuePair nameValuePair : webServiceRequest.getNameValuePairs()) { multipartEntity.addPart(nameValuePair.getName(), new StringBody(new String(nameValuePair.getValue().getBytes(), Charset.forName("US-ASCII")), Charset.forName("US-ASCII"))); } for (NameFilePair nameFilePair : webServiceRequest.getNameFilePairs()) { multipartEntity.addPart(nameFilePair.getName(), nameFilePair.getFileBody()); } multipartPost.setEntity(multipartEntity); return multipartPost; } catch (UnsupportedEncodingException ex) { Logger.getLogger(DacsPostRequest.class.getName()).log(Level.SEVERE, null, ex); throw new RuntimeException("Invalid DacsWebServiceRequest parameters " + ex.getMessage()); } }
From source file:ch.sbb.releasetrain.action.jenkins.JenkinsJobThread.java
/** * Constructor for jenkins builds with parameters */// w w w .j a va 2 s.c om public JenkinsJobThread(final String job, final String cause, String jenkinsUrl, String jenkinsBuildtoken, HttpUtil http, final Map<String, String> params) { this.http = http; this.jenkinsUrl = jenkinsUrl; this.jenkinsBuildtoken = jenkinsBuildtoken; this.jenkinsQueueUrl = jenkinsUrl + "/queue/api/json"; apiLatestBuildURL = jenkinsUrl + "/job/" + job + "/lastBuild/api/xml"; jobUrl = jenkinsUrl + "/job/" + job + "/build?token=" + jenkinsBuildtoken; jobId = job; startBuildnumber = this.getBuildnumber(); String par = ""; if (params != null) { for (final String key : params.keySet()) { if (key == null || params.get(key) == null) { continue; } final String poormanUrlEncoded = key.replace(" ", "+") + "=" + params.get(key).replace(" ", "+"); par = par + "&" + poormanUrlEncoded; } jobUrl = jobUrl + par; jobUrl = jobUrl.replace("/build?", "/buildWithParameters?"); } if (cause != null && !cause.isEmpty()) { try { jobUrl = jobUrl + "&cause=" + URLEncoder.encode(cause, "UTF-8"); } catch (final UnsupportedEncodingException e) { log.error(e.getMessage(), e); } } }
From source file:com.jevontech.wabl.security.TokenUtils.java
private String generateToken(Map<String, Object> claims) { try {/*from w w w . ja va2 s . c o m*/ return Jwts.builder().setClaims(claims).setExpiration(this.generateExpirationDate()) .signWith(SignatureAlgorithm.HS512, configurationService.getSecret().getBytes("UTF-8")) .compact(); } catch (UnsupportedEncodingException ex) { //didn't want to have this method throw the exception, would rather log it and sign the token like it was before logger.warn(ex.getMessage()); return Jwts.builder().setClaims(claims).setExpiration(this.generateExpirationDate()) .signWith(SignatureAlgorithm.HS512, configurationService.getSecret()).compact(); } }
From source file:com.osafe.services.sagepay.SagePayTokenServices.java
public static Map<String, Object> paymentRegistration(DispatchContext ctx, Map<String, Object> context) { Debug.logInfo("SagePay Token - Entered paymentRegistration", module); // Debug.logInfo("SagePay Token - paymentRegistration context : " + context, module); Delegator delegator = ctx.getDelegator(); Map<String, Object> resultMap = new HashMap<String, Object>(); Map<String, String> props = buildSagePayProperties(context, delegator); String vendorTxCode = (String) context.get("vendorTxCode"); String currency = (String) context.get("currency"); String cardHolder = (String) context.get("cardHolder"); String cardNumber = (String) context.get("cardNumber"); String expiryDate = (String) context.get("expiryDate"); String cv2 = (String) context.get("cv2"); String cardType = (String) context.get("cardType"); String paymentMethodId = (String) context.get("paymentMethodId"); String contactMechId = (String) context.get("contactMechId"); String startDate = (String) context.get("startDate"); String issueNumber = (String) context.get("issueNumber"); String clientIPAddress = (String) context.get("clientIPAddress"); HttpClient httpClient = SagePayUtil.getHttpClient(); HttpHost host = SagePayUtil.getHost(props); //start - authentication parameters Map<String, String> parameters = new HashMap<String, String>(); String vpsProtocol = props.get("protocolVersion"); String vendor = props.get("vendor"); String txType = props.get("registrationTransType"); //start - required parameters parameters.put("VPSProtocol", vpsProtocol); parameters.put("TxType", txType); parameters.put("Vendor", vendor); if (currency != null) { parameters.put("Currency", currency); } //GBP/USD// ww w .ja va 2s .c o m if (cardHolder != null) { parameters.put("CardHolder", cardHolder); } if (cardNumber != null) { parameters.put("CardNumber", cardNumber); } if (expiryDate != null) { parameters.put("ExpiryDate", expiryDate); } if (cardType != null) { parameters.put("CardType", cardType.toUpperCase()); } //start - optional parameters if (cv2 != null) { parameters.put("CV2", cv2); } if (startDate != null) { parameters.put("StartDate", startDate); } if (issueNumber != null) { parameters.put("IssueNumber", issueNumber); } if (clientIPAddress != null) { parameters.put("ClientIPAddress", clientIPAddress); } //end - optional parameters //end - authentication parameters try { String successMessage = null; HttpPost httpPost = SagePayUtil.getHttpPost(props.get("registrationUrl"), parameters); HttpResponse response = httpClient.execute(host, httpPost); Map<String, String> responseData = SagePayUtil.getResponseData(response); String status = responseData.get("Status"); String statusDetail = responseData.get("StatusDetail"); resultMap.put("status", status); resultMap.put("statusDetail", statusDetail); //returning the below details back to the calling code, as it not returned back by the payment gateway resultMap.put("vendorTxCode", vendorTxCode); resultMap.put("transactionType", txType); resultMap.put("token", null); //start - transaction registered if ("OK".equals(status)) { resultMap.put("token", responseData.get("Token")); successMessage = "Payment Token registered"; } //end - transaction authorized if ("MALFORMED".equals(status)) { //request not formed properly or parameters missing } if ("INVALID".equals(status)) { //invalid information in request } resultMap.put(ModelService.RESPONSE_MESSAGE, ModelService.RESPOND_SUCCESS); resultMap.put(ModelService.SUCCESS_MESSAGE, successMessage); } catch (UnsupportedEncodingException uee) { //exception in encoding parameters in httpPost String errorMsg = "Error occured in encoding parameters for HttpPost (" + uee.getMessage() + ")"; Debug.logError(uee, errorMsg, module); resultMap = ServiceUtil.returnError(errorMsg); } catch (ClientProtocolException cpe) { //from httpClient execute String errorMsg = "Error occured in HttpClient execute(" + cpe.getMessage() + ")"; Debug.logError(cpe, errorMsg, module); resultMap = ServiceUtil.returnError(errorMsg); } catch (IOException ioe) { //from httpClient execute or getResponsedata String errorMsg = "Error occured in HttpClient execute or getting response (" + ioe.getMessage() + ")"; Debug.logError(ioe, errorMsg, module); resultMap = ServiceUtil.returnError(errorMsg); } finally { httpClient.getConnectionManager().shutdown(); } return resultMap; }
From source file:tr.edu.gsu.nerwip.recognition.internal.modelless.opencalais.OpenCalais.java
@Override protected List<String> detectEntities(Article article) throws RecognizerException { logger.increaseOffset();//from www.j av a 2 s . com List<String> result = new ArrayList<String>(); String text = article.getRawText(); // check if the key was set String key = KeyHandler.KEYS.get(KEY_NAME); if (key == null) throw new NullPointerException( "In order to use OpenCalais, you first need to set up your user key in file res/misc/keys.xml using the exact name \"OpenCalais\"."); // we need to break text : OpenCalais can't handle more than 100000 chars at once List<String> chunks = new ArrayList<String>(); while (text.length() > 95000) { int index = text.indexOf("\n", 90000) + 1; String chunk = text.substring(0, index); chunks.add(chunk); text = text.substring(index); } chunks.add(text); for (int i = 0; i < chunks.size(); i++) { logger.log("Processing OpenCalais chunk #" + (i + 1) + "/" + chunks.size()); logger.increaseOffset(); String chunk = chunks.get(i); try { // define HTTP message logger.log("Build OpenCalais http message"); HttpPost method = new HttpPost("http://api.opencalais.com/tag/rs/enrich"); method.setHeader("x-calais-licenseID", key); method.setHeader("Content-Type", "text/raw; charset=UTF-8"); method.setHeader("Accept", "xml/rdf"); method.setEntity(new StringEntity(chunk, "UTF-8")); // send to open calais logger.log("Send message to OpenCalais"); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(method); InputStream stream = response.getEntity().getContent(); InputStreamReader streamReader = new InputStreamReader(stream, "UTF-8"); BufferedReader bufferedReader = new BufferedReader(streamReader); // read answer logger.log("Read OpenCalais answer"); StringBuilder builder = new StringBuilder(); String line; int nbr = 0; while ((line = bufferedReader.readLine()) != null) { builder.append(line + "\n"); nbr++; } logger.log("Lines read: " + nbr); String answer = builder.toString(); result.add(chunk); result.add(answer); } catch (UnsupportedEncodingException e) { e.printStackTrace(); throw new RecognizerException(e.getMessage()); } catch (ClientProtocolException e) { e.printStackTrace(); throw new RecognizerException(e.getMessage()); } catch (IOException e) { e.printStackTrace(); throw new RecognizerException(e.getMessage()); } logger.decreaseOffset(); } logger.decreaseOffset(); return result; }
From source file:org.cerberus.servlet.publi.ExecuteNextInQueue.java
/** * Executes the next test case represented by the given * {@link TestCaseExecutionInQueue}/*w w w. j a v a 2 s . co m*/ * * @param lastInQueue * @param req * @param resp * @throws IOException */ private void executeNext(TestCaseExecutionInQueue lastInQueue, HttpServletRequest req, HttpServletResponse resp) throws IOException { String charset = resp.getCharacterEncoding(); String query = ""; try { ParamRequestMaker paramRequestMaker = makeParamRequestfromLastInQueue(lastInQueue); // TODO : Prefer use mkString(charset) instead of mkString(). // However the RunTestCase servlet does not decode parameters, // then we have to mkString() without using charset query = paramRequestMaker.mkString(); } catch (UnsupportedEncodingException uee) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, uee.getMessage()); return; } catch (IllegalArgumentException iae) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, iae.getMessage()); return; } catch (IllegalStateException ise) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, ise.getMessage()); return; } CloseableHttpClient httpclient = null; HttpGet httpget = null; try { httpclient = HttpClients.createDefault(); URI uri = new URIBuilder().setScheme(req.getScheme()).setHost(req.getServerName()) .setPort(req.getServerPort()).setPath(req.getContextPath() + RunTestCase.SERVLET_URL) .setCustomQuery(query).build(); httpget = new HttpGet(uri); } catch (URISyntaxException use) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, use.getMessage()); return; } CloseableHttpResponse response = null; try { response = httpclient.execute(httpget); if (response.getStatusLine().getStatusCode() != HttpServletResponse.SC_OK) { resp.sendError(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()); } } catch (ClientProtocolException cpe) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, cpe.getMessage()); } finally { if (response != null) { response.close(); } } }
From source file:com.orig.gls.security.Encode.java
public Encode(String keyString, String ivString) { try {//from w ww .j a va 2 s .co m final MessageDigest md = MessageDigest.getInstance("md5"); final byte[] digestOfPassword = md.digest(Base64.decodeBase64(keyString.getBytes("utf-8"))); final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24); for (int j = 0, k = 16; j < 8;) { keyBytes[k++] = keyBytes[j++]; } keySpec = new DESedeKeySpec(keyBytes); key = SecretKeyFactory.getInstance("DESede").generateSecret(keySpec); iv = new IvParameterSpec(ivString.getBytes()); } catch (UnsupportedEncodingException asd) { System.out.println(asd.getMessage()); } catch (InvalidKeyException asd) { System.out.println(asd.getMessage()); } catch (NoSuchAlgorithmException asd) { System.out.println(asd.getMessage()); } catch (InvalidKeySpecException asd) { System.out.println(asd.getMessage()); } }
From source file:org.dasein.cloud.qingcloud.util.requester.QingCloudRequestBuilder.java
private String urlEncode(String value) throws InternalException { if (value == null) { return null; }// www.j a v a 2s . com try { return URLEncoder.encode(value, ENCODING).replace("+", "%20").replace("*", "%2A").replace("%7E", "~"); } catch (UnsupportedEncodingException unsupportedEncodingException) { logger.error("AliyunRequestBuilderStrategy.urlEncode() failed due to encoding not supported: " + unsupportedEncodingException.getMessage()); throw new InternalException(unsupportedEncodingException); } }
From source file:ph.com.globe.connect.HttpRequest.java
/** * Send post request to the specified url. * /*w ww . j av a2 s . c o m*/ * @return CloseableHttpResponse * @throws HttpRequestException http request exception */ public CloseableHttpResponse sendPost() throws HttpRequestException { // try building up try { // initialize ssl context builder SSLContextBuilder builder = new SSLContextBuilder(); // set trust self signed strategy builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); // initialize ssl socket connection factory SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(builder.build()); // default http client CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(sslSocketFactory).build(); // create request method HttpPost post = new HttpPost(this.url); // set default user agent post.setHeader("User-Agent", this.USER_AGENT); // set default content type post.setHeader("Content-Type", this.CONTENT_TYPE); // convert data to json string JSONObject data = new JSONObject(this.data); try { // set the string entity StringEntity entity = new StringEntity(data.toString()); // set post data post.setEntity(entity); } catch (UnsupportedEncodingException e) { // throw exception throw new HttpRequestException(e.getMessage()); } // try request try { // execute request and get the response CloseableHttpResponse response = client.execute(post); return response; } catch (IOException e) { // throw an exception throw new HttpRequestException(e.getMessage()); } } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { // throw an exception throw new HttpRequestException(e.getMessage()); } }