Example usage for java.io UnsupportedEncodingException toString

List of usage examples for java.io UnsupportedEncodingException toString

Introduction

In this page you can find the example usage for java.io UnsupportedEncodingException toString.

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:de.rub.nds.burp.espresso.gui.UIOptions.java

/**
 * Creates new form UIOptions//  ww  w .ja  va  2 s .c  o  m
 */
public UIOptions() {
    initComponents();
    hideAllUnsedComponents();

    String path = System.getProperty("user.home") + "/EsPReSSO";
    String decoded_path = null;
    try {
        if (path != null) {
            decoded_path = URLDecoder.decode(path, "UTF-8");
            if (decoded_path != null) {
                File file = new File(decoded_path);
                if (!file.exists()) {
                    file.mkdir();
                }
                path = decoded_path + "/config.json";
                file = new File(path);
                if (!file.exists()) {
                    // First start no config created
                    file.createNewFile();
                    configText1.setText(path);
                    saveConfig(path);
                } else {
                    // load previous config
                    configText1.setText(path);
                    loadConfig(path);
                }
            }
        }
    } catch (UnsupportedEncodingException ex) {
        JOptionPane.showMessageDialog(this, ex.toString(), "ERROR 2", JOptionPane.ERROR_MESSAGE);
    } catch (IOException ex) {
        JOptionPane.showMessageDialog(this, ex.toString(), "ERROR 2", JOptionPane.ERROR_MESSAGE);
    }
}

From source file:com.piusvelte.sonet.core.SonetCreatePost.java

@Override
public void onClick(View v) {
    if (v == mSend) {
        if (!mAccountsService.isEmpty()) {
            final ProgressDialog loadingDialog = new ProgressDialog(this);
            final AsyncTask<Void, String, Void> asyncTask = new AsyncTask<Void, String, Void>() {
                @Override//from w ww .  ja  va 2 s . c o  m
                protected Void doInBackground(Void... arg0) {
                    Iterator<Map.Entry<Long, Integer>> entrySet = mAccountsService.entrySet().iterator();
                    while (entrySet.hasNext()) {
                        Map.Entry<Long, Integer> entry = entrySet.next();
                        final long accountId = entry.getKey();
                        final int service = entry.getValue();
                        final String placeId = mAccountsLocation.get(accountId);
                        // post or comment!
                        Cursor account = getContentResolver().query(
                                Accounts.getContentUri(SonetCreatePost.this),
                                new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET },
                                Accounts._ID + "=?", new String[] { Long.toString(accountId) }, null);
                        if (account.moveToFirst()) {
                            final String serviceName = Sonet.getServiceName(getResources(), service);
                            publishProgress(serviceName);
                            String message;
                            SonetOAuth sonetOAuth;
                            HttpPost httpPost;
                            String response = null;
                            switch (service) {
                            case TWITTER:
                                sonetOAuth = new SonetOAuth(TWITTER_KEY, TWITTER_SECRET,
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))),
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.SECRET))));
                                // limit tweets to 140, breaking up the message if necessary
                                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);
                                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                                    params.add(new BasicNameValuePair(Sstatus, send));
                                    if (placeId != null) {
                                        params.add(new BasicNameValuePair("place_id", placeId));
                                        params.add(new BasicNameValuePair("lat", mLat));
                                        params.add(new BasicNameValuePair("long", mLong));
                                    }
                                    try {
                                        httpPost.setEntity(new UrlEncodedFormEntity(params));
                                        response = SonetHttpClient.httpResponse(mHttpClient,
                                                sonetOAuth.getSignedRequest(httpPost));
                                    } catch (UnsupportedEncodingException e) {
                                        Log.e(TAG, e.toString());
                                    }
                                    publishProgress(serviceName,
                                            getString(response != null ? R.string.success : R.string.failure));
                                }
                                break;
                            case FACEBOOK:
                                // handle tags
                                StringBuilder tags = null;
                                if (mAccountsTags.containsKey(accountId)) {
                                    String[] accountTags = mAccountsTags.get(accountId);
                                    if ((accountTags != null) && (accountTags.length > 0)) {
                                        tags = new StringBuilder();
                                        tags.append("[");
                                        String tag_format;
                                        if (mPhotoPath != null)
                                            tag_format = "{\"tag_uid\":\"%s\",\"x\":0,\"y\":0}";
                                        else
                                            tag_format = "%s";
                                        for (int i = 0, l = accountTags.length; i < l; i++) {
                                            if (i > 0)
                                                tags.append(",");
                                            tags.append(String.format(tag_format, accountTags[i]));
                                        }
                                        tags.append("]");
                                    }
                                }
                                if (mPhotoPath != null) {
                                    // upload photo
                                    // uploading a photo takes a long time, have the service handle it
                                    Intent i = Sonet.getPackageIntent(
                                            SonetCreatePost.this.getApplicationContext(),
                                            PhotoUploadService.class);
                                    i.setAction(Sonet.ACTION_UPLOAD);
                                    i.putExtra(Accounts.TOKEN,
                                            account.getString(account.getColumnIndex(Accounts.TOKEN)));
                                    i.putExtra(Widgets.INSTANT_UPLOAD, mPhotoPath);
                                    i.putExtra(Statuses.MESSAGE, mMessage.getText().toString());
                                    i.putExtra(Splace, placeId);
                                    if (tags != null)
                                        i.putExtra(Stags, tags.toString());
                                    startService(i);
                                    publishProgress(serviceName + " photo");
                                } else {
                                    // regular post
                                    httpPost = new HttpPost(String.format(FACEBOOK_POST, FACEBOOK_BASE_URL,
                                            Saccess_token, mSonetCrypto.Decrypt(account
                                                    .getString(account.getColumnIndex(Accounts.TOKEN)))));
                                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                                    params.add(new BasicNameValuePair(Smessage, mMessage.getText().toString()));
                                    if (placeId != null)
                                        params.add(new BasicNameValuePair(Splace, placeId));
                                    if (tags != null)
                                        params.add(new BasicNameValuePair(Stags, tags.toString()));
                                    try {
                                        httpPost.setEntity(new UrlEncodedFormEntity(params));
                                        response = SonetHttpClient.httpResponse(mHttpClient, httpPost);
                                    } catch (UnsupportedEncodingException e) {
                                        Log.e(TAG, e.toString());
                                    }
                                    publishProgress(serviceName,
                                            getString(response != null ? R.string.success : R.string.failure));
                                }
                                break;
                            case MYSPACE:
                                sonetOAuth = new SonetOAuth(MYSPACE_KEY, MYSPACE_SECRET,
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))),
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.SECRET))));
                                try {
                                    HttpPut httpPut = new HttpPut(
                                            String.format(MYSPACE_URL_STATUSMOOD, MYSPACE_BASE_URL));
                                    httpPut.setEntity(new StringEntity(String.format(MYSPACE_STATUSMOOD_BODY,
                                            mMessage.getText().toString())));
                                    response = SonetHttpClient.httpResponse(mHttpClient,
                                            sonetOAuth.getSignedRequest(httpPut));
                                } catch (IOException e) {
                                    Log.e(TAG, e.toString());
                                }
                                // warn users about myspace permissions
                                if (response != null) {
                                    publishProgress(serviceName, getString(R.string.success));
                                } else {
                                    publishProgress(serviceName, getString(R.string.failure) + " "
                                            + getString(R.string.myspace_permissions_message));
                                }
                                break;
                            case FOURSQUARE:
                                try {
                                    message = URLEncoder.encode(mMessage.getText().toString(), "UTF-8");
                                    if (placeId != null) {
                                        if (message != null) {
                                            httpPost = new HttpPost(String.format(FOURSQUARE_CHECKIN,
                                                    FOURSQUARE_BASE_URL, placeId, message, mLat, mLong,
                                                    mSonetCrypto.Decrypt(account.getString(
                                                            account.getColumnIndex(Accounts.TOKEN)))));
                                        } else {
                                            httpPost = new HttpPost(String.format(FOURSQUARE_CHECKIN_NO_SHOUT,
                                                    FOURSQUARE_BASE_URL, placeId, mLat, mLong,
                                                    mSonetCrypto.Decrypt(account.getString(
                                                            account.getColumnIndex(Accounts.TOKEN)))));
                                        }
                                    } else {
                                        httpPost = new HttpPost(String.format(FOURSQUARE_CHECKIN_NO_VENUE,
                                                FOURSQUARE_BASE_URL, message, mSonetCrypto.Decrypt(account
                                                        .getString(account.getColumnIndex(Accounts.TOKEN)))));
                                    }
                                    response = SonetHttpClient.httpResponse(mHttpClient, httpPost);
                                } catch (UnsupportedEncodingException e) {
                                    Log.e(TAG, e.toString());
                                }
                                publishProgress(serviceName,
                                        getString(response != null ? R.string.success : R.string.failure));
                                break;
                            case LINKEDIN:
                                sonetOAuth = new SonetOAuth(LINKEDIN_KEY, LINKEDIN_SECRET,
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))),
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.SECRET))));
                                try {
                                    httpPost = new HttpPost(String.format(LINKEDIN_POST, LINKEDIN_BASE_URL));
                                    httpPost.setEntity(new StringEntity(String.format(LINKEDIN_POST_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());
                                }
                                publishProgress(serviceName,
                                        getString(response != null ? R.string.success : R.string.failure));
                                break;
                            case IDENTICA:
                                sonetOAuth = new SonetOAuth(IDENTICA_KEY, IDENTICA_SECRET,
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))),
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.SECRET))));
                                // limit tweets to 140, breaking up the message if necessary
                                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);
                                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                                    params.add(new BasicNameValuePair(Sstatus, send));
                                    if (placeId != null) {
                                        params.add(new BasicNameValuePair("place_id", placeId));
                                        params.add(new BasicNameValuePair("lat", mLat));
                                        params.add(new BasicNameValuePair("long", mLong));
                                    }
                                    try {
                                        httpPost.setEntity(new UrlEncodedFormEntity(params));
                                        response = SonetHttpClient.httpResponse(mHttpClient,
                                                sonetOAuth.getSignedRequest(httpPost));
                                    } catch (UnsupportedEncodingException e) {
                                        Log.e(TAG, e.toString());
                                    }
                                    publishProgress(serviceName,
                                            getString(response != null ? R.string.success : R.string.failure));
                                }
                                break;
                            case CHATTER:
                                // need to get an updated access_token
                                response = SonetHttpClient.httpResponse(mHttpClient, new HttpPost(
                                        String.format(CHATTER_URL_ACCESS, CHATTER_KEY, mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))))));
                                if (response != null) {
                                    try {
                                        JSONObject jobj = new JSONObject(response);
                                        if (jobj.has("instance_url") && jobj.has(Saccess_token)) {
                                            httpPost = new HttpPost(String.format(CHATTER_URL_POST,
                                                    jobj.getString("instance_url"),
                                                    Uri.encode(mMessage.getText().toString())));
                                            httpPost.setHeader("Authorization",
                                                    "OAuth " + jobj.getString(Saccess_token));
                                            response = SonetHttpClient.httpResponse(mHttpClient, httpPost);
                                        }
                                    } catch (JSONException e) {
                                        Log.e(TAG, serviceName + ":" + e.toString());
                                        Log.e(TAG, response);
                                    }
                                }
                                publishProgress(serviceName,
                                        getString(response != null ? R.string.success : R.string.failure));
                                break;
                            }
                        }
                        account.close();
                    }
                    return null;
                }

                @Override
                protected void onProgressUpdate(String... params) {
                    if (params.length == 1) {
                        loadingDialog.setMessage(String.format(getString(R.string.sending), params[0]));
                    } else {
                        (Toast.makeText(SonetCreatePost.this, params[0] + " " + params[1], Toast.LENGTH_LONG))
                                .show();
                    }
                }

                @Override
                protected void onPostExecute(Void result) {
                    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(SonetCreatePost.this, "no accounts selected", Toast.LENGTH_LONG)).show();
    }
}

From source file:com.piusvelte.sonet.SonetCreatePost.java

@Override
public void onClick(View v) {
    if (v == mSend) {
        if (!mAccountsService.isEmpty()) {
            final ProgressDialog loadingDialog = new ProgressDialog(this);
            final AsyncTask<Void, String, Void> asyncTask = new AsyncTask<Void, String, Void>() {
                @Override/* w  ww .  j av  a  2s . com*/
                protected Void doInBackground(Void... arg0) {
                    Iterator<Map.Entry<Long, Integer>> entrySet = mAccountsService.entrySet().iterator();
                    while (entrySet.hasNext()) {
                        Map.Entry<Long, Integer> entry = entrySet.next();
                        final long accountId = entry.getKey();
                        final int service = entry.getValue();
                        final String placeId = mAccountsLocation.get(accountId);
                        // post or comment!
                        Cursor account = getContentResolver().query(
                                Accounts.getContentUri(SonetCreatePost.this),
                                new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET },
                                Accounts._ID + "=?", new String[] { Long.toString(accountId) }, null);
                        if (account.moveToFirst()) {
                            final String serviceName = Sonet.getServiceName(getResources(), service);
                            publishProgress(serviceName);
                            String message;
                            SonetOAuth sonetOAuth;
                            HttpPost httpPost;
                            String response = null;
                            switch (service) {
                            case TWITTER:
                                sonetOAuth = new SonetOAuth(BuildConfig.TWITTER_KEY, BuildConfig.TWITTER_SECRET,
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))),
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.SECRET))));
                                // limit tweets to 140, breaking up the message if necessary
                                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);
                                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                                    params.add(new BasicNameValuePair(Sstatus, send));
                                    if (placeId != null) {
                                        params.add(new BasicNameValuePair("place_id", placeId));
                                        params.add(new BasicNameValuePair("lat", mLat));
                                        params.add(new BasicNameValuePair("long", mLong));
                                    }
                                    try {
                                        httpPost.setEntity(new UrlEncodedFormEntity(params));
                                        response = SonetHttpClient.httpResponse(mHttpClient,
                                                sonetOAuth.getSignedRequest(httpPost));
                                    } catch (UnsupportedEncodingException e) {
                                        Log.e(TAG, e.toString());
                                    }
                                    publishProgress(serviceName,
                                            getString(response != null ? R.string.success : R.string.failure));
                                }
                                break;
                            case FACEBOOK:
                                // handle tags
                                StringBuilder tags = null;
                                if (mAccountsTags.containsKey(accountId)) {
                                    String[] accountTags = mAccountsTags.get(accountId);
                                    if ((accountTags != null) && (accountTags.length > 0)) {
                                        tags = new StringBuilder();
                                        tags.append("[");
                                        String tag_format;
                                        if (mPhotoPath != null)
                                            tag_format = "{\"tag_uid\":\"%s\",\"x\":0,\"y\":0}";
                                        else
                                            tag_format = "%s";
                                        for (int i = 0, l = accountTags.length; i < l; i++) {
                                            if (i > 0)
                                                tags.append(",");
                                            tags.append(String.format(tag_format, accountTags[i]));
                                        }
                                        tags.append("]");
                                    }
                                }
                                if (mPhotoPath != null) {
                                    // upload photo
                                    // uploading a photo takes a long time, have the service handle it
                                    Intent i = Sonet.getPackageIntent(
                                            SonetCreatePost.this.getApplicationContext(),
                                            PhotoUploadService.class);
                                    i.setAction(Sonet.ACTION_UPLOAD);
                                    i.putExtra(Accounts.TOKEN,
                                            account.getString(account.getColumnIndex(Accounts.TOKEN)));
                                    i.putExtra(Widgets.INSTANT_UPLOAD, mPhotoPath);
                                    i.putExtra(Statuses.MESSAGE, mMessage.getText().toString());
                                    i.putExtra(Splace, placeId);
                                    if (tags != null)
                                        i.putExtra(Stags, tags.toString());
                                    startService(i);
                                    publishProgress(serviceName + " photo");
                                } else {
                                    // regular post
                                    httpPost = new HttpPost(String.format(FACEBOOK_POST, FACEBOOK_BASE_URL,
                                            Saccess_token, mSonetCrypto.Decrypt(account
                                                    .getString(account.getColumnIndex(Accounts.TOKEN)))));
                                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                                    params.add(new BasicNameValuePair(Smessage, mMessage.getText().toString()));
                                    if (placeId != null)
                                        params.add(new BasicNameValuePair(Splace, placeId));
                                    if (tags != null)
                                        params.add(new BasicNameValuePair(Stags, tags.toString()));
                                    try {
                                        httpPost.setEntity(new UrlEncodedFormEntity(params));
                                        response = SonetHttpClient.httpResponse(mHttpClient, httpPost);
                                    } catch (UnsupportedEncodingException e) {
                                        Log.e(TAG, e.toString());
                                    }
                                    publishProgress(serviceName,
                                            getString(response != null ? R.string.success : R.string.failure));
                                }
                                break;
                            case MYSPACE:
                                sonetOAuth = new SonetOAuth(BuildConfig.MYSPACE_KEY, BuildConfig.MYSPACE_SECRET,
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))),
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.SECRET))));
                                try {
                                    HttpPut httpPut = new HttpPut(
                                            String.format(MYSPACE_URL_STATUSMOOD, MYSPACE_BASE_URL));
                                    httpPut.setEntity(new StringEntity(String.format(MYSPACE_STATUSMOOD_BODY,
                                            mMessage.getText().toString())));
                                    response = SonetHttpClient.httpResponse(mHttpClient,
                                            sonetOAuth.getSignedRequest(httpPut));
                                } catch (IOException e) {
                                    Log.e(TAG, e.toString());
                                }
                                // warn users about myspace permissions
                                if (response != null) {
                                    publishProgress(serviceName, getString(R.string.success));
                                } else {
                                    publishProgress(serviceName, getString(R.string.failure) + " "
                                            + getString(R.string.myspace_permissions_message));
                                }
                                break;
                            case FOURSQUARE:
                                try {
                                    message = URLEncoder.encode(mMessage.getText().toString(), "UTF-8");
                                    if (placeId != null) {
                                        if (message != null) {
                                            httpPost = new HttpPost(String.format(FOURSQUARE_CHECKIN,
                                                    FOURSQUARE_BASE_URL, placeId, message, mLat, mLong,
                                                    mSonetCrypto.Decrypt(account.getString(
                                                            account.getColumnIndex(Accounts.TOKEN)))));
                                        } else {
                                            httpPost = new HttpPost(String.format(FOURSQUARE_CHECKIN_NO_SHOUT,
                                                    FOURSQUARE_BASE_URL, placeId, mLat, mLong,
                                                    mSonetCrypto.Decrypt(account.getString(
                                                            account.getColumnIndex(Accounts.TOKEN)))));
                                        }
                                    } else {
                                        httpPost = new HttpPost(String.format(FOURSQUARE_CHECKIN_NO_VENUE,
                                                FOURSQUARE_BASE_URL, message, mSonetCrypto.Decrypt(account
                                                        .getString(account.getColumnIndex(Accounts.TOKEN)))));
                                    }
                                    response = SonetHttpClient.httpResponse(mHttpClient, httpPost);
                                } catch (UnsupportedEncodingException e) {
                                    Log.e(TAG, e.toString());
                                }
                                publishProgress(serviceName,
                                        getString(response != null ? R.string.success : R.string.failure));
                                break;
                            case LINKEDIN:
                                sonetOAuth = new SonetOAuth(BuildConfig.LINKEDIN_KEY,
                                        BuildConfig.LINKEDIN_SECRET,
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))),
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.SECRET))));
                                try {
                                    httpPost = new HttpPost(String.format(LINKEDIN_POST, LINKEDIN_BASE_URL));
                                    httpPost.setEntity(new StringEntity(String.format(LINKEDIN_POST_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());
                                }
                                publishProgress(serviceName,
                                        getString(response != null ? R.string.success : R.string.failure));
                                break;
                            case IDENTICA:
                                sonetOAuth = new SonetOAuth(BuildConfig.IDENTICA_KEY,
                                        BuildConfig.IDENTICA_SECRET,
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))),
                                        mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.SECRET))));
                                // limit tweets to 140, breaking up the message if necessary
                                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);
                                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                                    params.add(new BasicNameValuePair(Sstatus, send));
                                    if (placeId != null) {
                                        params.add(new BasicNameValuePair("place_id", placeId));
                                        params.add(new BasicNameValuePair("lat", mLat));
                                        params.add(new BasicNameValuePair("long", mLong));
                                    }
                                    try {
                                        httpPost.setEntity(new UrlEncodedFormEntity(params));
                                        response = SonetHttpClient.httpResponse(mHttpClient,
                                                sonetOAuth.getSignedRequest(httpPost));
                                    } catch (UnsupportedEncodingException e) {
                                        Log.e(TAG, e.toString());
                                    }
                                    publishProgress(serviceName,
                                            getString(response != null ? R.string.success : R.string.failure));
                                }
                                break;
                            case CHATTER:
                                // need to get an updated access_token
                                response = SonetHttpClient.httpResponse(mHttpClient, new HttpPost(String.format(
                                        CHATTER_URL_ACCESS, BuildConfig.CHATTER_KEY, mSonetCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))))));
                                if (response != null) {
                                    try {
                                        JSONObject jobj = new JSONObject(response);
                                        if (jobj.has("instance_url") && jobj.has(Saccess_token)) {
                                            httpPost = new HttpPost(String.format(CHATTER_URL_POST,
                                                    jobj.getString("instance_url"),
                                                    Uri.encode(mMessage.getText().toString())));
                                            httpPost.setHeader("Authorization",
                                                    "OAuth " + jobj.getString(Saccess_token));
                                            response = SonetHttpClient.httpResponse(mHttpClient, httpPost);
                                        }
                                    } catch (JSONException e) {
                                        Log.e(TAG, serviceName + ":" + e.toString());
                                        Log.e(TAG, response);
                                    }
                                }
                                publishProgress(serviceName,
                                        getString(response != null ? R.string.success : R.string.failure));
                                break;
                            }
                        }
                        account.close();
                    }
                    return null;
                }

                @Override
                protected void onProgressUpdate(String... params) {
                    if (params.length == 1) {
                        loadingDialog.setMessage(String.format(getString(R.string.sending), params[0]));
                    } else {
                        (Toast.makeText(SonetCreatePost.this, params[0] + " " + params[1], Toast.LENGTH_LONG))
                                .show();
                    }
                }

                @Override
                protected void onPostExecute(Void result) {
                    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(SonetCreatePost.this, "no accounts selected", Toast.LENGTH_LONG)).show();
    }
}

From source file:org.apromore.service.impl.ProcessServiceImpl.java

/**
 * @see org.apromore.service.ProcessService#readProcessSummaries(Integer, String)
 *      {@inheritDoc}//ww w.  ja v a  2  s . co m
 */
@Override
public SummariesType readProcessSummaries(final Integer folderId, final String searchExpression) {
    SummariesType processSummaries = null;

    try {
        // Firstly, do we need to use the searchExpression
        SearchExpressionBuilder seb = new SearchExpressionBuilder();
        String conditions = seb.buildSearchConditions(searchExpression);

        // Now... Build the Object tree from this list of processes.
        processSummaries = ui.buildProcessSummaryList(folderId, conditions, null);
    } catch (UnsupportedEncodingException usee) {
        LOGGER.error("Failed to get Process Summaries: " + usee.toString());
    }

    return processSummaries;
}

From source file:servlets.module.challenge.SessionManagement5ChangePassword.java

/**
 * Function used by Session Management Challenge Five to change the password of the submitted user name. The function requires a valid token which is a base64'd timestamp. If the current time is within 10 minutes of the token, the function will execute 
 * @param userName User cookie used to store the user password to be reset
 * @param newPassword the password which to use to update an accounts password
 * @param resetPasswordToken Base64'd time stamp
 */// w  w  w  .  j a v  a 2  s.c o m
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    //Setting IpAddress To Log and taking header for original IP if forwarded from proxy
    ShepherdLogManager.setRequestIp(request.getRemoteAddr(), request.getHeader("X-Forwarded-For"));
    HttpSession ses = request.getSession(true);

    //Translation Stuff
    Locale locale = new Locale(Validate.validateLanguage(request.getSession()));
    ResourceBundle errors = ResourceBundle.getBundle("i18n.servlets.errors", locale);
    ResourceBundle bundle = ResourceBundle
            .getBundle("i18n.servlets.challenges.sessionManagement.sessionManagement5", locale);

    if (Validate.validateSession(ses)) {
        ShepherdLogManager.setRequestIp(request.getRemoteAddr(), request.getHeader("X-Forwarded-For"),
                ses.getAttribute("userName").toString());
        log.debug(levelName + " servlet accessed by: " + ses.getAttribute("userName").toString());
        PrintWriter out = response.getWriter();
        out.print(getServletInfo());
        String htmlOutput = new String();
        String errorMessage = new String();
        int tokenLife = 11;
        try {
            log.debug("Getting Challenge Parameters");
            Object passNewObj = request.getParameter("newPassword");
            Object userNewObj = request.getParameter("userName");
            Object tokenObj = request.getParameter("resetPasswordToken");
            String userName = new String();
            String newPass = new String();
            String token = new String();
            if (passNewObj != null)
                newPass = (String) passNewObj;
            if (userNewObj != null)
                userName = (String) userNewObj;
            if (tokenObj != null)
                token = (String) tokenObj;
            log.debug("userName = " + userName);
            log.debug("newPass = " + newPass);
            log.debug("token = " + token);
            String tokenTime = new String();
            try {
                byte[] decodedToken = Base64.decodeBase64(token);
                tokenTime = new String(decodedToken, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                log.debug("Could not decode password token");
                errorMessage += "<p>" + bundle.getString("changePass.noDecode") + "</p>";
            }
            if (tokenTime.isEmpty()) {
                log.debug("Could not decode token. Ending Servlet.");
                out.write(errorMessage);
            } else {
                log.debug("Decoded Token = " + tokenTime);

                //Get Time from Token and see if it is inside the last 10 minutes
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss Z yyyy");
                try {
                    Date tokenDateTime = simpleDateFormat.parse(tokenTime);
                    Date currentDateTime = new Date();
                    //Get difference in minutes
                    tokenLife = (int) ((currentDateTime.getTime() / 60000) - (tokenDateTime.getTime() / 60000));
                    log.debug("Token life = " + tokenLife);
                } catch (ParseException e) {
                    log.error("Date Parsing Error: " + e.toString());
                    errorMessage += bundle.getString("changePass.badTokenData") + ": " + e.toString();
                }

                if (tokenLife < 10 && tokenLife >= 0) {
                    if (newPass.length() >= 12) {
                        log.debug("Getting ApplicationRoot");
                        String ApplicationRoot = getServletContext().getRealPath("");
                        log.debug("Servlet root = " + ApplicationRoot);

                        Connection conn = Database.getChallengeConnection(ApplicationRoot,
                                "BrokenAuthAndSessMangChalFive");
                        log.debug("Changing password for user: " + userName);
                        log.debug("Changing password to: " + newPass);
                        PreparedStatement callstmt;

                        callstmt = conn
                                .prepareStatement("UPDATE users SET userPassword = SHA(?) WHERE userName = ?");

                        callstmt.setString(1, newPass);
                        callstmt.setString(2, userName);

                        log.debug("Executing changePassword");
                        callstmt.execute();

                        log.debug("Committing changes made to database");
                        callstmt = conn.prepareStatement("COMMIT");
                        callstmt.execute();
                        log.debug("Changes committed.");

                        htmlOutput = "<p>" + bundle.getString("changePass.success") + "</p>";
                    } else {
                        log.debug("Invalid password submitted: " + newPass);
                        htmlOutput = "<p>" + bundle.getString("changePass.failure") + "</p>";
                    }
                } else {
                    if (!errorMessage.isEmpty()) {
                        htmlOutput = "<p><font colour='red'><b>" + errorMessage + "</b></font</p>";
                    } else if (tokenLife >= 10) {
                        log.debug("Token too old");
                        htmlOutput = "<p>" + bundle.getString("changePass.oldToken") + "</p>";
                    } else if (tokenLife < 0) {
                        log.debug("Token to young");
                        htmlOutput = "<p>" + bundle.getString("changePass.youngToken") + "</p>";
                    } else {
                        log.error("Token to Strange: Unexpected Error");
                        htmlOutput = "<p>" + bundle.getString("changePass.funkyToken") + "</p>";
                    }
                }
            }
            log.debug("Outputting HTML");
            out.write(htmlOutput);
        } catch (Exception e) {
            out.write(errors.getString("error.funky"));
            log.fatal(levelName + " - Change Password - " + e.toString());
        }
    } else {
        log.error(levelName + " servlet accessed with no session");
    }
}

From source file:com.shafiq.myfeedle.core.MyfeedleCreatePost.java

@Override
public void onClick(View v) {
    if (v == mSend) {
        if (!mAccountsService.isEmpty()) {
            final ProgressDialog loadingDialog = new ProgressDialog(this);
            final AsyncTask<Void, String, Void> asyncTask = new AsyncTask<Void, String, Void>() {
                @Override/*ww  w.  j a  v  a  2s.  co m*/
                protected Void doInBackground(Void... arg0) {
                    Iterator<Map.Entry<Long, Integer>> entrySet = mAccountsService.entrySet().iterator();
                    while (entrySet.hasNext()) {
                        Map.Entry<Long, Integer> entry = entrySet.next();
                        final long accountId = entry.getKey();
                        final int service = entry.getValue();
                        final String placeId = mAccountsLocation.get(accountId);
                        // post or comment!
                        Cursor account = getContentResolver().query(
                                Accounts.getContentUri(MyfeedleCreatePost.this),
                                new String[] { Accounts._ID, Accounts.TOKEN, Accounts.SECRET },
                                Accounts._ID + "=?", new String[] { Long.toString(accountId) }, null);
                        if (account.moveToFirst()) {
                            final String serviceName = Myfeedle.getServiceName(getResources(), service);
                            publishProgress(serviceName);
                            String message;
                            MyfeedleOAuth myfeedleOAuth;
                            HttpPost httpPost;
                            String response = null;
                            switch (service) {
                            case TWITTER:
                                myfeedleOAuth = new MyfeedleOAuth(TWITTER_KEY, TWITTER_SECRET,
                                        mMyfeedleCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))),
                                        mMyfeedleCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.SECRET))));
                                // limit tweets to 140, breaking up the message if necessary
                                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);
                                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                                    params.add(new BasicNameValuePair(Sstatus, send));
                                    if (placeId != null) {
                                        params.add(new BasicNameValuePair("place_id", placeId));
                                        params.add(new BasicNameValuePair("lat", mLat));
                                        params.add(new BasicNameValuePair("long", mLong));
                                    }
                                    try {
                                        httpPost.setEntity(new UrlEncodedFormEntity(params));
                                        response = MyfeedleHttpClient.httpResponse(mHttpClient,
                                                myfeedleOAuth.getSignedRequest(httpPost));
                                    } catch (UnsupportedEncodingException e) {
                                        Log.e(TAG, e.toString());
                                    }
                                    publishProgress(serviceName,
                                            getString(response != null ? R.string.success : R.string.failure));
                                }
                                break;
                            case FACEBOOK:
                                // handle tags
                                StringBuilder tags = null;
                                if (mAccountsTags.containsKey(accountId)) {
                                    String[] accountTags = mAccountsTags.get(accountId);
                                    if ((accountTags != null) && (accountTags.length > 0)) {
                                        tags = new StringBuilder();
                                        tags.append("[");
                                        String tag_format;
                                        if (mPhotoPath != null)
                                            tag_format = "{\"tag_uid\":\"%s\",\"x\":0,\"y\":0}";
                                        else
                                            tag_format = "%s";
                                        for (int i = 0, l = accountTags.length; i < l; i++) {
                                            if (i > 0)
                                                tags.append(",");
                                            tags.append(String.format(tag_format, accountTags[i]));
                                        }
                                        tags.append("]");
                                    }
                                }
                                if (mPhotoPath != null) {
                                    // upload photo
                                    // uploading a photo takes a long time, have the service handle it
                                    Intent i = Myfeedle.getPackageIntent(
                                            MyfeedleCreatePost.this.getApplicationContext(),
                                            PhotoUploadService.class);
                                    i.setAction(Myfeedle.ACTION_UPLOAD);
                                    i.putExtra(Accounts.TOKEN,
                                            account.getString(account.getColumnIndex(Accounts.TOKEN)));
                                    i.putExtra(Widgets.INSTANT_UPLOAD, mPhotoPath);
                                    i.putExtra(Statuses.MESSAGE, mMessage.getText().toString());
                                    i.putExtra(Splace, placeId);
                                    if (tags != null)
                                        i.putExtra(Stags, tags.toString());
                                    startService(i);
                                    publishProgress(serviceName + " photo");
                                } else {
                                    // regular post
                                    httpPost = new HttpPost(String.format(FACEBOOK_POST, FACEBOOK_BASE_URL,
                                            Saccess_token, mMyfeedleCrypto.Decrypt(account
                                                    .getString(account.getColumnIndex(Accounts.TOKEN)))));
                                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                                    params.add(new BasicNameValuePair(Smessage, mMessage.getText().toString()));
                                    if (placeId != null)
                                        params.add(new BasicNameValuePair(Splace, placeId));
                                    if (tags != null)
                                        params.add(new BasicNameValuePair(Stags, tags.toString()));
                                    try {
                                        httpPost.setEntity(new UrlEncodedFormEntity(params));
                                        response = MyfeedleHttpClient.httpResponse(mHttpClient, httpPost);
                                    } catch (UnsupportedEncodingException e) {
                                        Log.e(TAG, e.toString());
                                    }
                                    publishProgress(serviceName,
                                            getString(response != null ? R.string.success : R.string.failure));
                                }
                                break;
                            case MYSPACE:
                                myfeedleOAuth = new MyfeedleOAuth(MYSPACE_KEY, MYSPACE_SECRET,
                                        mMyfeedleCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))),
                                        mMyfeedleCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.SECRET))));
                                try {
                                    HttpPut httpPut = new HttpPut(
                                            String.format(MYSPACE_URL_STATUSMOOD, MYSPACE_BASE_URL));
                                    httpPut.setEntity(new StringEntity(String.format(MYSPACE_STATUSMOOD_BODY,
                                            mMessage.getText().toString())));
                                    response = MyfeedleHttpClient.httpResponse(mHttpClient,
                                            myfeedleOAuth.getSignedRequest(httpPut));
                                } catch (IOException e) {
                                    Log.e(TAG, e.toString());
                                }
                                // warn users about myspace permissions
                                if (response != null) {
                                    publishProgress(serviceName, getString(R.string.success));
                                } else {
                                    publishProgress(serviceName, getString(R.string.failure) + " "
                                            + getString(R.string.myspace_permissions_message));
                                }
                                break;
                            case FOURSQUARE:
                                try {
                                    message = URLEncoder.encode(mMessage.getText().toString(), "UTF-8");
                                    if (placeId != null) {
                                        if (message != null) {
                                            httpPost = new HttpPost(String.format(FOURSQUARE_CHECKIN,
                                                    FOURSQUARE_BASE_URL, placeId, message, mLat, mLong,
                                                    mMyfeedleCrypto.Decrypt(account.getString(
                                                            account.getColumnIndex(Accounts.TOKEN)))));
                                        } else {
                                            httpPost = new HttpPost(String.format(FOURSQUARE_CHECKIN_NO_SHOUT,
                                                    FOURSQUARE_BASE_URL, placeId, mLat, mLong,
                                                    mMyfeedleCrypto.Decrypt(account.getString(
                                                            account.getColumnIndex(Accounts.TOKEN)))));
                                        }
                                    } else {
                                        httpPost = new HttpPost(String.format(FOURSQUARE_CHECKIN_NO_VENUE,
                                                FOURSQUARE_BASE_URL, message, mMyfeedleCrypto.Decrypt(account
                                                        .getString(account.getColumnIndex(Accounts.TOKEN)))));
                                    }
                                    response = MyfeedleHttpClient.httpResponse(mHttpClient, httpPost);
                                } catch (UnsupportedEncodingException e) {
                                    Log.e(TAG, e.toString());
                                }
                                publishProgress(serviceName,
                                        getString(response != null ? R.string.success : R.string.failure));
                                break;
                            case LINKEDIN:
                                myfeedleOAuth = new MyfeedleOAuth(LINKEDIN_KEY, LINKEDIN_SECRET,
                                        mMyfeedleCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))),
                                        mMyfeedleCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.SECRET))));
                                try {
                                    httpPost = new HttpPost(String.format(LINKEDIN_POST, LINKEDIN_BASE_URL));
                                    httpPost.setEntity(new StringEntity(String.format(LINKEDIN_POST_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());
                                }
                                publishProgress(serviceName,
                                        getString(response != null ? R.string.success : R.string.failure));
                                break;
                            case IDENTICA:
                                myfeedleOAuth = new MyfeedleOAuth(IDENTICA_KEY, IDENTICA_SECRET,
                                        mMyfeedleCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))),
                                        mMyfeedleCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.SECRET))));
                                // limit tweets to 140, breaking up the message if necessary
                                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);
                                    List<NameValuePair> params = new ArrayList<NameValuePair>();
                                    params.add(new BasicNameValuePair(Sstatus, send));
                                    if (placeId != null) {
                                        params.add(new BasicNameValuePair("place_id", placeId));
                                        params.add(new BasicNameValuePair("lat", mLat));
                                        params.add(new BasicNameValuePair("long", mLong));
                                    }
                                    try {
                                        httpPost.setEntity(new UrlEncodedFormEntity(params));
                                        response = MyfeedleHttpClient.httpResponse(mHttpClient,
                                                myfeedleOAuth.getSignedRequest(httpPost));
                                    } catch (UnsupportedEncodingException e) {
                                        Log.e(TAG, e.toString());
                                    }
                                    publishProgress(serviceName,
                                            getString(response != null ? R.string.success : R.string.failure));
                                }
                                break;
                            case CHATTER:
                                // need to get an updated access_token
                                response = MyfeedleHttpClient.httpResponse(mHttpClient, new HttpPost(
                                        String.format(CHATTER_URL_ACCESS, CHATTER_KEY, mMyfeedleCrypto.Decrypt(
                                                account.getString(account.getColumnIndex(Accounts.TOKEN))))));
                                if (response != null) {
                                    try {
                                        JSONObject jobj = new JSONObject(response);
                                        if (jobj.has("instance_url") && jobj.has(Saccess_token)) {
                                            httpPost = new HttpPost(String.format(CHATTER_URL_POST,
                                                    jobj.getString("instance_url"),
                                                    Uri.encode(mMessage.getText().toString())));
                                            httpPost.setHeader("Authorization",
                                                    "OAuth " + jobj.getString(Saccess_token));
                                            response = MyfeedleHttpClient.httpResponse(mHttpClient, httpPost);
                                        }
                                    } catch (JSONException e) {
                                        Log.e(TAG, serviceName + ":" + e.toString());
                                        Log.e(TAG, response);
                                    }
                                }
                                publishProgress(serviceName,
                                        getString(response != null ? R.string.success : R.string.failure));
                                break;
                            }
                        }
                        account.close();
                    }
                    return null;
                }

                @Override
                protected void onProgressUpdate(String... params) {
                    if (params.length == 1) {
                        loadingDialog.setMessage(String.format(getString(R.string.sending), params[0]));
                    } else {
                        (Toast.makeText(MyfeedleCreatePost.this, params[0] + " " + params[1],
                                Toast.LENGTH_LONG)).show();
                    }
                }

                @Override
                protected void onPostExecute(Void result) {
                    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(MyfeedleCreatePost.this, "no accounts selected", Toast.LENGTH_LONG)).show();
    }
}

From source file:apimanager.ZohoSupportAPIManager.java

private JSONObject searchTicketsbyCriteria(String authToken, String portal, String department,
        String searchField, String searchValue, String columns, String fileToWriteResponse, int index) {
    int fromIndex = ((index - 1) * 200 + 1);
    int toIndex = index * 200;

    String baseURL = "";

    try {//from  w  ww . j  a v  a2  s  .co  m
        baseURL = "https://support.zoho.com/api/json/requests/getrecordsbysearch?authtoken=" + authToken
                + "&portal=" + URLEncoder.encode(portal, ENCODETYPE) + "&department="
                + URLEncoder.encode(department, ENCODETYPE) + "&searchfield="
                + URLEncoder.encode(searchField, ENCODETYPE) + "&searchvalue="
                + URLEncoder.encode(searchValue, ENCODETYPE) + "&selectfields=requests("
                + URLEncoder.encode(columns, ENCODETYPE) + ")" + "&fromindex=" + fromIndex + "&toindex="
                + toIndex;
    } catch (UnsupportedEncodingException ex) {
        loggerObj.log(Level.SEVERE, "UnsupportedEncodingException for the url" + baseURL + "Exception is ", ex);
        return null;
    }

    loggerObj.log(Level.INFO, "Base url to connet to zoho is: " + baseURL);

    //https://support.zoho.com/api/json/requests/getrecordsbysearch?authtoken=46a5e812261b7f237b5fc440866a43fb&portal=medcsupport&department=MDM%20Plus&searchfield=Request%20Id&searchvalue=36485&selectfields=requests(Ticket%20Classification)&fromindex=1&toindex=200
    HttpsClient httpsClient = new HttpsClient();
    String result = httpsClient.OpenHTTPSConnection(baseURL);

    JSONObject json = null;
    if (!JSONOperations.isErrorJSON(result)) {
        JSONParser parser = new JSONParser();
        try {
            json = (JSONObject) parser.parse(result);
        } catch (ParseException ex) {
            loggerObj.log(Level.INFO,
                    "Problem in parsing the data from Zoho Support. Exception is " + ex.toString());
            return null;
        }
    }

    if (json != null) {
        String fileToWrite = fileToWriteResponse + index + ".json";
        loggerObj.log(Level.INFO, "File to write  is " + fileToWrite);
        boolean isFileWriteSuccess = FileOperations.writeObjectToFile(json, fileToWrite);
        if (!isFileWriteSuccess) {
            loggerObj.log(Level.INFO,
                    "Problem in writing the data from Zoho Support to the file: " + fileToWrite);
            return null;
        }
    }
    return json;

}

From source file:com.webwoz.wizard.server.components.MTinMicrosoft.java

public String translate(String inputText, String srcLang, String trgLang) {

    // initialize connection
    // adapt proxies and settings to fit your server environment
    initializeConnection("www-proxy.cs.tcd.ie", 8080);
    String translation = null;/*w  ww .  j a  v  a  2s.  c om*/
    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();
    }

    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();
    }

    shutDownConnection();
    return translation;
}

From source file:com.webwoz.wizard.server.components.MTinGoogle.java

/**
 * Submits text to Google AJAX Language API for translation.
 * //from  w  w w . jav a2s .co m
 * @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 proxies 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 = "http://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
            + "&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;
}