List of usage examples for java.io UnsupportedEncodingException toString
public String toString()
From source file:com.webwoz.wizard.server.components.MToutMicrosoft.java
public String translate(String inputText, String srcLang, String trgLang) { // initialize connection // adapt proxy and settings to fit your server environments initializeConnection("www-proxy.cs.tcd.ie", 8080); String translation = null;/*from w w w. j a v a2 s . c o m*/ String query = inputText; String MICROSOFT_TRANSLATION_BASE_URL = "http://api.microsofttranslator.com/V2/Http.svc/Translate?"; String appID = "226846CE16BC2542B7916B05CE9284CF4075B843"; try { // encode text query = URLEncoder.encode(query, "UTF-8"); // exchange + for space query = query.replace("+", "%20"); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); System.out.println(ex); } String requestURL = MICROSOFT_TRANSLATION_BASE_URL + "appid=" + appID + "&from=" + srcLang + "&to=" + trgLang + "&text=" + query; HttpGet getRequest = new HttpGet(requestURL); try { HttpResponse response = httpClient.execute(getRequest); HttpEntity responseEntity = response.getEntity(); InputStream inputStream = responseEntity.getContent(); Document myDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream); XPathFactory factory = XPathFactory.newInstance(); XPath xPath = factory.newXPath(); translation = (String) xPath.evaluate("/string", myDocument, XPathConstants.STRING); inputStream.close(); translation = translation.trim(); // if the original string did not have a dot at the end, then // remove the dot that Microsoft Translator sometimes places at the // end!! (not so sure it still happens anyway!) if (!inputText.endsWith(".") && (translation.endsWith("."))) { translation = translation.substring(0, translation.length() - 1); } setUttText(translation); } catch (Exception ex) { ex.printStackTrace(); translation = ex.toString(); setUttText(translation); System.out.println(translation); } shutDownConnection(); return translation; }
From source file:com.webwoz.wizard.server.components.MToutGoogle.java
/** * Submits text to Google AJAX Language API for translation. * //from w ww . ja v a 2 s.c om * @param sourceText * @param sourceLanguage * @param targetLanguage * @param sourceTextFormat * The format of the source Text (either "text" or "html", as * specified by Google Language AJAX API). * @param apiKey * API Key, obtained after registering with Google. * @param userIP * IP address of end user (i.e. currently temporarily set to my * IP or IP address of the PMIR framework's server machine) * @param referer * URL of the referrer (e.g. URL of the PMIR framework's main * page). * @return An object of <code>TransaltedText</code> object. * @throws MalformedLanguageAcronymException * if the length of a language acronym (source or target) does * not match the standard acronym length used throughout the * framework. * @throws UnsupportedLanguageException * if a language (source or target) is not supported in the * framework. */ public String translate(String inputText, String srcLang, String trgLang) { // initialize connection // adapt proxy and settings to fit your server environment initializeConnection("www-proxy.cs.tcd.ie", 8080); String translation = null; String query = inputText; String sourceTextFormat = "html"; String userIP = "134.226.35.174"; String referer = "http://kdeg-vm14.cs.tcd.ie"; String GOOGLE_TRANSLATION_BASE_URL = "https://ajax.googleapis.com/ajax/services/language/translate?v=1.0"; try { // encode text query = URLEncoder.encode(query, "UTF-8"); // exchange + for space query = query.replace("+", "%20"); } catch (UnsupportedEncodingException ex) { ex.printStackTrace(); } String requestURL = GOOGLE_TRANSLATION_BASE_URL + "&q=" + query + "&langpair=" + srcLang + "%7C" + trgLang + // %7C "&format=" + sourceTextFormat + "&userip=" + userIP; HttpGet getRequest = new HttpGet(requestURL); getRequest.addHeader("Referer", referer); try { HttpResponse response = httpClient.execute(getRequest); HttpEntity responseEntity = response.getEntity(); StringBuilder jsonStringBuilder = new StringBuilder(); if (responseEntity != null) { InputStream inputStream = responseEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line = null; while ((line = reader.readLine()) != null) { jsonStringBuilder.append(line); } inputStream.close(); reader.close(); } String jsonString = jsonStringBuilder.toString(); JSONObject wholeJSONObject = new JSONObject(jsonString); JSONObject responseDataObject = wholeJSONObject.getJSONObject("responseData"); translation = responseDataObject.getString("translatedText"); } catch (Exception ex) { ex.printStackTrace(); translation = ex.toString(); } shutDownConnection(); return translation; }
From source file:de.cellular.lib.lightlib.backend.LLRequest.java
@Override protected Exception doInBackground(Object... _params) { Exception ret = null;//from ww w.j av a2s.c om if (_params == null) { LL.e(":( Request must have a URL."); } else { DefaultHttpClient client = (DefaultHttpClient) _params[0]; if (client != null) { String urlstr = (String) _params[1]; if (!TextUtils.isEmpty(urlstr)) { LL.i(":| Request: " + urlstr); mHttpRequestBase = createHttpRequest(urlstr); // ---------------------------------------- // Set header // ---------------------------------------- onAppendHeaders(mHttpRequestBase); // ---------------------------------------- // Set cookies // ---------------------------------------- StringBuilder cookies = new StringBuilder(); String onCookies = onWriteCookies(); String someCookies = (String) _params[2]; if (!TextUtils.isEmpty(onCookies)) { cookies.append(onCookies); } if (!TextUtils.isEmpty(someCookies)) { cookies.append(someCookies); } String cookiesStr = cookies.toString(); if (!TextUtils.isEmpty(cookiesStr)) { mHttpRequestBase.setHeader("Cookie", cookiesStr); } else { LL.d(":| Empty Cookies on the request."); } // ---------------------------------------- // Set body // ---------------------------------------- if (mHttpRequestBase instanceof HttpPost) { String keyValues = onWritePostBody(); if (keyValues != null) { try { ((HttpPost) mHttpRequestBase).setEntity( new StringEntity(keyValues) /*new UrlEncodedFormEntity( keyValues )*/ ); } catch (UnsupportedEncodingException _e) { LL.d(":| Ignore setting data on HTTP-POST"); } } else { LL.d(":| Empty body on HTTP-POST"); } } // ---------------------------------------- // Do request // ---------------------------------------- try { HttpResponse response = client.execute(mHttpRequestBase); if ((mHttpRequestBase != null && mHttpRequestBase.isAborted()) || mHttpRequestBase == null) { onEmptyResponse(new LLHttpClientBaseResponse(urlstr, client, response)); } else { onResponse(LLHttpClientResponse.createInstance(urlstr, client, response)); } } catch (Exception _e) { // Abort request. Aborted request could also fire an exception. abort(); LL.e(":) The exception has been caught: " + _e.toString()); ret = new LLRequestException(_e, urlstr); } } else { LL.e(":( Unknown URL String for " + getClass().getSimpleName() + "."); } } else { LL.e(":( An HttpClient is required."); } } return ret; }
From source file:com.piusvelte.sonet.core.SonetComments.java
@Override public void onClick(View v) { if (v == mSend) { if ((mMessage.getText().toString() != null) && (mMessage.getText().toString().length() > 0) && (mSid != null) && (mEsid != null)) { mMessage.setEnabled(false);//from w ww. j av a2s . c o m mSend.setEnabled(false); // post or comment! final ProgressDialog loadingDialog = new ProgressDialog(this); final AsyncTask<Void, String, String> asyncTask = new AsyncTask<Void, String, String>() { @Override protected String doInBackground(Void... arg0) { List<NameValuePair> params; String message; String response = null; HttpPost httpPost; SonetOAuth sonetOAuth; String serviceName = Sonet.getServiceName(getResources(), mService); publishProgress(serviceName); switch (mService) { case TWITTER: // limit tweets to 140, breaking up the message if necessary sonetOAuth = new SonetOAuth(TWITTER_KEY, TWITTER_SECRET, mToken, mSecret); message = mMessage.getText().toString(); while (message.length() > 0) { final String send; if (message.length() > 140) { // need to break on a word int end = 0; int nextSpace = 0; for (int i = 0, i2 = message.length(); i < i2; i++) { end = nextSpace; if (message.substring(i, i + 1).equals(" ")) { nextSpace = i; } } // in case there are no spaces, just break on 140 if (end == 0) { end = 140; } send = message.substring(0, end); message = message.substring(end + 1); } else { send = message; message = ""; } httpPost = new HttpPost(String.format(TWITTER_UPDATE, TWITTER_BASE_URL)); // resolve Error 417 Expectation by Twitter httpPost.getParams().setBooleanParameter("http.protocol.expect-continue", false); params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(Sstatus, send)); params.add(new BasicNameValuePair(Sin_reply_to_status_id, mSid)); try { httpPost.setEntity(new UrlEncodedFormEntity(params)); response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(httpPost)); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } } break; case FACEBOOK: httpPost = new HttpPost(String.format(FACEBOOK_COMMENTS, FACEBOOK_BASE_URL, mSid, Saccess_token, mToken)); params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(Smessage, mMessage.getText().toString())); try { httpPost.setEntity(new UrlEncodedFormEntity(params)); response = SonetHttpClient.httpResponse(mHttpClient, httpPost); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } break; case MYSPACE: sonetOAuth = new SonetOAuth(MYSPACE_KEY, MYSPACE_SECRET, mToken, mSecret); try { httpPost = new HttpPost(String.format(MYSPACE_URL_STATUSMOODCOMMENTS, MYSPACE_BASE_URL, mEsid, mSid)); httpPost.setEntity(new StringEntity(String.format(MYSPACE_STATUSMOODCOMMENTS_BODY, mMessage.getText().toString()))); response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(httpPost)); } catch (IOException e) { Log.e(TAG, e.toString()); } break; case FOURSQUARE: try { message = URLEncoder.encode(mMessage.getText().toString(), "UTF-8"); httpPost = new HttpPost(String.format(FOURSQUARE_ADDCOMMENT, FOURSQUARE_BASE_URL, mSid, message, mToken)); response = SonetHttpClient.httpResponse(mHttpClient, httpPost); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } break; case LINKEDIN: sonetOAuth = new SonetOAuth(LINKEDIN_KEY, LINKEDIN_SECRET, mToken, mSecret); try { httpPost = new HttpPost( String.format(LINKEDIN_UPDATE_COMMENTS, LINKEDIN_BASE_URL, mSid)); httpPost.setEntity(new StringEntity( String.format(LINKEDIN_COMMENT_BODY, mMessage.getText().toString()))); httpPost.addHeader(new BasicHeader("Content-Type", "application/xml")); response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(httpPost)); } catch (IOException e) { Log.e(TAG, e.toString()); } break; case IDENTICA: // limit tweets to 140, breaking up the message if necessary sonetOAuth = new SonetOAuth(IDENTICA_KEY, IDENTICA_SECRET, mToken, mSecret); message = mMessage.getText().toString(); while (message.length() > 0) { final String send; if (message.length() > 140) { // need to break on a word int end = 0; int nextSpace = 0; for (int i = 0, i2 = message.length(); i < i2; i++) { end = nextSpace; if (message.substring(i, i + 1).equals(" ")) { nextSpace = i; } } // in case there are no spaces, just break on 140 if (end == 0) { end = 140; } send = message.substring(0, end); message = message.substring(end + 1); } else { send = message; message = ""; } httpPost = new HttpPost(String.format(IDENTICA_UPDATE, IDENTICA_BASE_URL)); // resolve Error 417 Expectation by Twitter httpPost.getParams().setBooleanParameter("http.protocol.expect-continue", false); params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(Sstatus, send)); params.add(new BasicNameValuePair(Sin_reply_to_status_id, mSid)); try { httpPost.setEntity(new UrlEncodedFormEntity(params)); response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(httpPost)); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } } break; case GOOGLEPLUS: break; case CHATTER: httpPost = new HttpPost(String.format(CHATTER_URL_COMMENT, mChatterInstance, mSid, Uri.encode(mMessage.getText().toString()))); httpPost.setHeader("Authorization", "OAuth " + mChatterToken); response = SonetHttpClient.httpResponse(mHttpClient, httpPost); break; } return ((response == null) && (mService == MYSPACE)) ? null : serviceName + " " + getString(response != null ? R.string.success : R.string.failure); } @Override protected void onProgressUpdate(String... params) { loadingDialog.setMessage(String.format(getString(R.string.sending), params[0])); } @Override protected void onPostExecute(String result) { if (result != null) { (Toast.makeText(SonetComments.this, result, Toast.LENGTH_LONG)).show(); } else if (mService == MYSPACE) { // myspace permissions (Toast.makeText(SonetComments.this, SonetComments.this.getResources() .getStringArray(R.array.service_entries)[MYSPACE] + getString(R.string.failure) + " " + getString(R.string.myspace_permissions_message), Toast.LENGTH_LONG)).show(); } if (loadingDialog.isShowing()) loadingDialog.dismiss(); finish(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); loadingDialog.show(); asyncTask.execute(); } else { (Toast.makeText(SonetComments.this, "error parsing message body", Toast.LENGTH_LONG)).show(); mMessage.setEnabled(true); mSend.setEnabled(true); } } }
From source file:com.piusvelte.sonet.SonetComments.java
@Override public void onClick(View v) { if (v == mSend) { if ((mMessage.getText().toString() != null) && (mMessage.getText().toString().length() > 0) && (mSid != null) && (mEsid != null)) { mMessage.setEnabled(false);/*from w w w.j a v a 2 s. c o m*/ mSend.setEnabled(false); // post or comment! final ProgressDialog loadingDialog = new ProgressDialog(this); final AsyncTask<Void, String, String> asyncTask = new AsyncTask<Void, String, String>() { @Override protected String doInBackground(Void... arg0) { List<NameValuePair> params; String message; String response = null; HttpPost httpPost; SonetOAuth sonetOAuth; String serviceName = Sonet.getServiceName(getResources(), mService); publishProgress(serviceName); switch (mService) { case TWITTER: // limit tweets to 140, breaking up the message if necessary sonetOAuth = new SonetOAuth(BuildConfig.TWITTER_KEY, BuildConfig.TWITTER_SECRET, mToken, mSecret); message = mMessage.getText().toString(); while (message.length() > 0) { final String send; if (message.length() > 140) { // need to break on a word int end = 0; int nextSpace = 0; for (int i = 0, i2 = message.length(); i < i2; i++) { end = nextSpace; if (message.substring(i, i + 1).equals(" ")) { nextSpace = i; } } // in case there are no spaces, just break on 140 if (end == 0) { end = 140; } send = message.substring(0, end); message = message.substring(end + 1); } else { send = message; message = ""; } httpPost = new HttpPost(String.format(TWITTER_UPDATE, TWITTER_BASE_URL)); // resolve Error 417 Expectation by Twitter httpPost.getParams().setBooleanParameter("http.protocol.expect-continue", false); params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(Sstatus, send)); params.add(new BasicNameValuePair(Sin_reply_to_status_id, mSid)); try { httpPost.setEntity(new UrlEncodedFormEntity(params)); response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(httpPost)); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } } break; case FACEBOOK: httpPost = new HttpPost(String.format(FACEBOOK_COMMENTS, FACEBOOK_BASE_URL, mSid, Saccess_token, mToken)); params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(Smessage, mMessage.getText().toString())); try { httpPost.setEntity(new UrlEncodedFormEntity(params)); response = SonetHttpClient.httpResponse(mHttpClient, httpPost); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } break; case MYSPACE: sonetOAuth = new SonetOAuth(BuildConfig.MYSPACE_KEY, BuildConfig.MYSPACE_SECRET, mToken, mSecret); try { httpPost = new HttpPost(String.format(MYSPACE_URL_STATUSMOODCOMMENTS, MYSPACE_BASE_URL, mEsid, mSid)); httpPost.setEntity(new StringEntity(String.format(MYSPACE_STATUSMOODCOMMENTS_BODY, mMessage.getText().toString()))); response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(httpPost)); } catch (IOException e) { Log.e(TAG, e.toString()); } break; case FOURSQUARE: try { message = URLEncoder.encode(mMessage.getText().toString(), "UTF-8"); httpPost = new HttpPost(String.format(FOURSQUARE_ADDCOMMENT, FOURSQUARE_BASE_URL, mSid, message, mToken)); response = SonetHttpClient.httpResponse(mHttpClient, httpPost); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } break; case LINKEDIN: sonetOAuth = new SonetOAuth(BuildConfig.LINKEDIN_KEY, BuildConfig.LINKEDIN_SECRET, mToken, mSecret); try { httpPost = new HttpPost( String.format(LINKEDIN_UPDATE_COMMENTS, LINKEDIN_BASE_URL, mSid)); httpPost.setEntity(new StringEntity( String.format(LINKEDIN_COMMENT_BODY, mMessage.getText().toString()))); httpPost.addHeader(new BasicHeader("Content-Type", "application/xml")); response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(httpPost)); } catch (IOException e) { Log.e(TAG, e.toString()); } break; case IDENTICA: // limit tweets to 140, breaking up the message if necessary sonetOAuth = new SonetOAuth(BuildConfig.IDENTICA_KEY, BuildConfig.IDENTICA_SECRET, mToken, mSecret); message = mMessage.getText().toString(); while (message.length() > 0) { final String send; if (message.length() > 140) { // need to break on a word int end = 0; int nextSpace = 0; for (int i = 0, i2 = message.length(); i < i2; i++) { end = nextSpace; if (message.substring(i, i + 1).equals(" ")) { nextSpace = i; } } // in case there are no spaces, just break on 140 if (end == 0) { end = 140; } send = message.substring(0, end); message = message.substring(end + 1); } else { send = message; message = ""; } httpPost = new HttpPost(String.format(IDENTICA_UPDATE, IDENTICA_BASE_URL)); // resolve Error 417 Expectation by Twitter httpPost.getParams().setBooleanParameter("http.protocol.expect-continue", false); params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(Sstatus, send)); params.add(new BasicNameValuePair(Sin_reply_to_status_id, mSid)); try { httpPost.setEntity(new UrlEncodedFormEntity(params)); response = SonetHttpClient.httpResponse(mHttpClient, sonetOAuth.getSignedRequest(httpPost)); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } } break; case GOOGLEPLUS: break; case CHATTER: httpPost = new HttpPost(String.format(CHATTER_URL_COMMENT, mChatterInstance, mSid, Uri.encode(mMessage.getText().toString()))); httpPost.setHeader("Authorization", "OAuth " + mChatterToken); response = SonetHttpClient.httpResponse(mHttpClient, httpPost); break; } return ((response == null) && (mService == MYSPACE)) ? null : serviceName + " " + getString(response != null ? R.string.success : R.string.failure); } @Override protected void onProgressUpdate(String... params) { loadingDialog.setMessage(String.format(getString(R.string.sending), params[0])); } @Override protected void onPostExecute(String result) { if (result != null) { (Toast.makeText(SonetComments.this, result, Toast.LENGTH_LONG)).show(); } else if (mService == MYSPACE) { // myspace permissions (Toast.makeText(SonetComments.this, SonetComments.this.getResources() .getStringArray(R.array.service_entries)[MYSPACE] + getString(R.string.failure) + " " + getString(R.string.myspace_permissions_message), Toast.LENGTH_LONG)).show(); } if (loadingDialog.isShowing()) loadingDialog.dismiss(); finish(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); loadingDialog.show(); asyncTask.execute(); } else { (Toast.makeText(SonetComments.this, "error parsing message body", Toast.LENGTH_LONG)).show(); mMessage.setEnabled(true); mSend.setEnabled(true); } } }
From source file:de.andreas_rueckert.trade.site.btc_e.client.BtcEClient.java
/** * Execute a authenticated query on btc-e. * * @param method The method to execute.//from ww w . j a va2 s .co m * @param arguments The arguments to pass to the server. * @param userAccount The user account on the exchange, or null if the default account should be used. * * @return The returned data as JSON or null, if the request failed. * * @see http://pastebin.com/K25Nk2Sv */ private final JSONObject authenticatedHTTPRequest(String method, Map<String, String> arguments, TradeSiteUserAccount userAccount) { HashMap<String, String> headerLines = new HashMap<String, String>(); // Create a new map for the header lines. Mac mac; SecretKeySpec key = null; String accountKey; // The used key of the account. String accountSecret; // The used secret of the account. // Try to get an account key and secret for the request. if (userAccount != null) { accountKey = userAccount.getAPIkey(); accountSecret = userAccount.getSecret(); } else { // Use the default values from the API implementation. accountKey = _key; accountSecret = _secret; } // Check, if account key and account secret are available for the request. if (accountKey == null) { throw new MissingAccountDataException("Key not available for authenticated request to btc-e"); } if (accountSecret == null) { throw new MissingAccountDataException("Secret not available for authenticated request to btc-e"); } if (arguments == null) { // If the user provided no arguments, just create an empty argument array. arguments = new HashMap<String, String>(); } arguments.put("method", method); // Add the method to the post data. arguments.put("nonce", "" + ++_nonce); // Add the dummy nonce. // Convert the arguments into a string to post them. String postData = ""; for (Iterator argumentIterator = arguments.entrySet().iterator(); argumentIterator.hasNext();) { Map.Entry argument = (Map.Entry) argumentIterator.next(); if (postData.length() > 0) { postData += "&"; } postData += argument.getKey() + "=" + argument.getValue(); } // Create a new secret key try { key = new SecretKeySpec(accountSecret.getBytes("UTF-8"), "HmacSHA512"); } catch (UnsupportedEncodingException uee) { System.err.println("Unsupported encoding exception: " + uee.toString()); return null; } // Create a new mac try { mac = Mac.getInstance("HmacSHA512"); } catch (NoSuchAlgorithmException nsae) { System.err.println("No such algorithm exception: " + nsae.toString()); return null; } // Init mac with key. try { mac.init(key); } catch (InvalidKeyException ike) { System.err.println("Invalid key exception: " + ike.toString()); return null; } // Add the key to the header lines. headerLines.put("Key", accountKey); // Encode the post data by the secret and encode the result as base64. try { headerLines.put("Sign", Hex.encodeHexString(mac.doFinal(postData.getBytes("UTF-8")))); } catch (UnsupportedEncodingException uee) { System.err.println("Unsupported encoding exception: " + uee.toString()); return null; } // Now do the actual request String requestResult = HttpUtils.httpPost("https://" + DOMAIN + "/tapi", headerLines, postData); if (requestResult != null) { // The request worked try { // Convert the HTTP request return value to JSON to parse further. JSONObject jsonResult = JSONObject.fromObject(requestResult); // Check, if the request was successful int success = jsonResult.getInt("success"); if (success == 0) { // The request failed. String errorMessage = jsonResult.getString("error"); LogUtils.getInstance().getLogger().error("btc-e.com trade API request failed: " + errorMessage); return null; } else { // Request succeeded! return jsonResult.getJSONObject("return"); } } catch (JSONException je) { System.err.println("Cannot parse json request result: " + je.toString()); return null; // An error occured... } } return null; // The request failed. }
From source file:org.josso.auth.scheme.UsernamePasswordAuthScheme.java
/** * This method allows password hashing.// w ww .j av a 2s. c om * In order to work, you need to specify hashAlgorithm and hashEncoding properties. * You can optionally set hashCharset property. * * @return the hashed password. */ protected String createPasswordHash(String password) throws SSOAuthenticationException { // If none of this properties are set, do nothing ... if (getHashAlgorithm() == null && getHashEncoding() == null) { // Nothing to do ... return password; } if (logger.isDebugEnabled()) logger.debug("Creating password hash for [" + password + "] with algorithm/encoding [" + getHashAlgorithm() + "/" + getHashEncoding() + "]"); // Check for spetial encryption mechanisms, not supported by the JDK if ("CRYPT".equalsIgnoreCase(getHashAlgorithm())) { // Get known password String knownPassword = getPassword(getKnownCredentials()); String salt = knownPassword != null && knownPassword.length() > 1 ? knownPassword.substring(0, _saltLenght) : ""; return Crypt.crypt(salt, password); } byte[] passBytes; String passwordHash = null; // convert password to byte data try { if (_hashCharset == null) passBytes = password.getBytes(); else passBytes = password.getBytes(_hashCharset); } catch (UnsupportedEncodingException e) { logger.error("charset " + _hashCharset + " not found. Using platform default."); passBytes = password.getBytes(); } // calculate the hash and apply the encoding. try { byte[] hash; // Hash algorithm is optional if (_hashAlgorithm != null) hash = getDigest().digest(passBytes); else hash = passBytes; // At this point, hashEncoding is required. if ("BASE64".equalsIgnoreCase(_hashEncoding)) { passwordHash = CipherUtil.encodeBase64(hash); } else if ("HEX".equalsIgnoreCase(_hashEncoding)) { passwordHash = CipherUtil.encodeBase16(hash); } else if (_hashEncoding == null) { logger.error("You must specify a hashEncoding when using hashAlgorithm"); } else { logger.error("Unsupported hash encoding format " + _hashEncoding); } } catch (Exception e) { logger.error("Password hash calculation failed : \n" + e.getMessage() != null ? e.getMessage() : e.toString(), e); } return passwordHash; }
From source file:org.apache.hadoop.yarn.client.cli.TestYarnCLI.java
private String createContainerCLIHelpMessage() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintWriter pw = new PrintWriter(baos); pw.println("usage: container"); pw.println(" -help Displays help for all commands."); pw.println(" -list <Application Attempt ID> List containers for application attempt."); pw.println(" -signal <container ID [signal command]> Signal the container."); pw.println("The available signal commands are "); pw.println(java.util.Arrays.asList(SignalContainerCommand.values())); pw.println(" Default command is OUTPUT_THREAD_DUMP."); pw.println(" -status <Container ID> Prints the status of the container."); pw.close();//w w w .j av a 2 s.com try { return normalize(baos.toString("UTF-8")); } catch (UnsupportedEncodingException infeasible) { return infeasible.toString(); } }
From source file:org.atricore.idbus.kernel.main.authn.scheme.UsernamePasswordAuthScheme.java
/** * This method allows password hashing.//from w w w . j a v a2 s . c o m * In order to work, you need to specify hashAlgorithm and hashEncoding properties. * You can optionally set hashCharset property. * * @return the hashed password. */ protected String createPasswordHash(String password, Credential[] knowCredentials) throws SSOAuthenticationException { // If none of this properties are set, do nothing ... if (getHashAlgorithm() == null && getHashEncoding() == null) { // Nothing to do ... return password; } if (logger.isDebugEnabled()) logger.debug("Creating password hash for [" + password + "] with algorithm/encoding [" + getHashAlgorithm() + "/" + getHashEncoding() + "]"); // Check for special encryption mechanisms, not supported by the JDK if ("CRYPT".equalsIgnoreCase(getHashAlgorithm())) { // Get known password String knownPassword = getPassword(knowCredentials); String salt = knownPassword != null && knownPassword.length() > 1 ? knownPassword.substring(0, _saltLength) : ""; return Crypt.crypt(salt, password); } // If SALT is available, use it String salt = getSalt(knowCredentials); if (salt != null) password = salt + password; // TODO : Support other LDAP prefixes !!!! byte[] passBytes; String passwordHash = null; // convert password to byte data try { if (_hashCharset == null) passBytes = password.getBytes(); else passBytes = password.getBytes(_hashCharset); } catch (UnsupportedEncodingException e) { logger.error("charset " + _hashCharset + " not found. Using platform default."); passBytes = password.getBytes(); } // calculate the hash and apply the encoding. try { byte[] hash; // Hash algorithm is optional if (_hashAlgorithm != null) hash = getDigest().digest(passBytes); else hash = passBytes; // At this point, hashEncoding is required. if ("BASE64".equalsIgnoreCase(_hashEncoding)) { passwordHash = CipherUtil.encodeBase64(hash); } else if ("HEX".equalsIgnoreCase(_hashEncoding)) { passwordHash = CipherUtil.encodeBase16(hash); } else if (_hashEncoding == null) { logger.error("You must specify a hashEncoding when using hashAlgorithm"); } else { logger.error("Unsupported hash encoding format " + _hashEncoding); } } catch (Exception e) { logger.error("Password hash calculation failed : \n" + e.getMessage() != null ? e.getMessage() : e.toString(), e); } return passwordHash; }
From source file:com.shafiq.myfeedle.core.MyfeedleComments.java
@Override public void onClick(View v) { if (v == mSend) { if ((mMessage.getText().toString() != null) && (mMessage.getText().toString().length() > 0) && (mSid != null) && (mEsid != null)) { mMessage.setEnabled(false);//from ww w . j a v a2 s . co m mSend.setEnabled(false); // post or comment! final ProgressDialog loadingDialog = new ProgressDialog(this); final AsyncTask<Void, String, String> asyncTask = new AsyncTask<Void, String, String>() { @Override protected String doInBackground(Void... arg0) { List<NameValuePair> params; String message; String response = null; HttpPost httpPost; MyfeedleOAuth myfeedleOAuth; String serviceName = Myfeedle.getServiceName(getResources(), mService); publishProgress(serviceName); switch (mService) { case TWITTER: // limit tweets to 140, breaking up the message if necessary myfeedleOAuth = new MyfeedleOAuth(TWITTER_KEY, TWITTER_SECRET, mToken, mSecret); message = mMessage.getText().toString(); while (message.length() > 0) { final String send; if (message.length() > 140) { // need to break on a word int end = 0; int nextSpace = 0; for (int i = 0, i2 = message.length(); i < i2; i++) { end = nextSpace; if (message.substring(i, i + 1).equals(" ")) { nextSpace = i; } } // in case there are no spaces, just break on 140 if (end == 0) { end = 140; } send = message.substring(0, end); message = message.substring(end + 1); } else { send = message; message = ""; } httpPost = new HttpPost(String.format(TWITTER_UPDATE, TWITTER_BASE_URL)); // resolve Error 417 Expectation by Twitter httpPost.getParams().setBooleanParameter("http.protocol.expect-continue", false); params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(Sstatus, send)); params.add(new BasicNameValuePair(Sin_reply_to_status_id, mSid)); try { httpPost.setEntity(new UrlEncodedFormEntity(params)); response = MyfeedleHttpClient.httpResponse(mHttpClient, myfeedleOAuth.getSignedRequest(httpPost)); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } } break; case FACEBOOK: httpPost = new HttpPost(String.format(FACEBOOK_COMMENTS, FACEBOOK_BASE_URL, mSid, Saccess_token, mToken)); params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(Smessage, mMessage.getText().toString())); try { httpPost.setEntity(new UrlEncodedFormEntity(params)); response = MyfeedleHttpClient.httpResponse(mHttpClient, httpPost); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } break; case MYSPACE: myfeedleOAuth = new MyfeedleOAuth(MYSPACE_KEY, MYSPACE_SECRET, mToken, mSecret); try { httpPost = new HttpPost(String.format(MYSPACE_URL_STATUSMOODCOMMENTS, MYSPACE_BASE_URL, mEsid, mSid)); httpPost.setEntity(new StringEntity(String.format(MYSPACE_STATUSMOODCOMMENTS_BODY, mMessage.getText().toString()))); response = MyfeedleHttpClient.httpResponse(mHttpClient, myfeedleOAuth.getSignedRequest(httpPost)); } catch (IOException e) { Log.e(TAG, e.toString()); } break; case FOURSQUARE: try { message = URLEncoder.encode(mMessage.getText().toString(), "UTF-8"); httpPost = new HttpPost(String.format(FOURSQUARE_ADDCOMMENT, FOURSQUARE_BASE_URL, mSid, message, mToken)); response = MyfeedleHttpClient.httpResponse(mHttpClient, httpPost); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } break; case LINKEDIN: myfeedleOAuth = new MyfeedleOAuth(LINKEDIN_KEY, LINKEDIN_SECRET, mToken, mSecret); try { httpPost = new HttpPost( String.format(LINKEDIN_UPDATE_COMMENTS, LINKEDIN_BASE_URL, mSid)); httpPost.setEntity(new StringEntity( String.format(LINKEDIN_COMMENT_BODY, mMessage.getText().toString()))); httpPost.addHeader(new BasicHeader("Content-Type", "application/xml")); response = MyfeedleHttpClient.httpResponse(mHttpClient, myfeedleOAuth.getSignedRequest(httpPost)); } catch (IOException e) { Log.e(TAG, e.toString()); } break; case IDENTICA: // limit tweets to 140, breaking up the message if necessary myfeedleOAuth = new MyfeedleOAuth(IDENTICA_KEY, IDENTICA_SECRET, mToken, mSecret); message = mMessage.getText().toString(); while (message.length() > 0) { final String send; if (message.length() > 140) { // need to break on a word int end = 0; int nextSpace = 0; for (int i = 0, i2 = message.length(); i < i2; i++) { end = nextSpace; if (message.substring(i, i + 1).equals(" ")) { nextSpace = i; } } // in case there are no spaces, just break on 140 if (end == 0) { end = 140; } send = message.substring(0, end); message = message.substring(end + 1); } else { send = message; message = ""; } httpPost = new HttpPost(String.format(IDENTICA_UPDATE, IDENTICA_BASE_URL)); // resolve Error 417 Expectation by Twitter httpPost.getParams().setBooleanParameter("http.protocol.expect-continue", false); params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair(Sstatus, send)); params.add(new BasicNameValuePair(Sin_reply_to_status_id, mSid)); try { httpPost.setEntity(new UrlEncodedFormEntity(params)); response = MyfeedleHttpClient.httpResponse(mHttpClient, myfeedleOAuth.getSignedRequest(httpPost)); } catch (UnsupportedEncodingException e) { Log.e(TAG, e.toString()); } } break; case GOOGLEPLUS: break; case CHATTER: httpPost = new HttpPost(String.format(CHATTER_URL_COMMENT, mChatterInstance, mSid, Uri.encode(mMessage.getText().toString()))); httpPost.setHeader("Authorization", "OAuth " + mChatterToken); response = MyfeedleHttpClient.httpResponse(mHttpClient, httpPost); break; } return ((response == null) && (mService == MYSPACE)) ? null : serviceName + " " + getString(response != null ? R.string.success : R.string.failure); } @Override protected void onProgressUpdate(String... params) { loadingDialog.setMessage(String.format(getString(R.string.sending), params[0])); } @Override protected void onPostExecute(String result) { if (result != null) { (Toast.makeText(MyfeedleComments.this, result, Toast.LENGTH_LONG)).show(); } else if (mService == MYSPACE) { // myspace permissions (Toast.makeText(MyfeedleComments.this, MyfeedleComments.this.getResources() .getStringArray(R.array.service_entries)[MYSPACE] + getString(R.string.failure) + " " + getString(R.string.myspace_permissions_message), Toast.LENGTH_LONG)).show(); } if (loadingDialog.isShowing()) loadingDialog.dismiss(); finish(); } }; loadingDialog.setMessage(getString(R.string.loading)); loadingDialog.setCancelable(true); loadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { if (!asyncTask.isCancelled()) asyncTask.cancel(true); } }); loadingDialog.setButton(ProgressDialog.BUTTON_NEGATIVE, getString(android.R.string.cancel), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); loadingDialog.show(); asyncTask.execute(); } else { (Toast.makeText(MyfeedleComments.this, "error parsing message body", Toast.LENGTH_LONG)).show(); mMessage.setEnabled(true); mSend.setEnabled(true); } } }