Example usage for org.apache.http.client ClientProtocolException getLocalizedMessage

List of usage examples for org.apache.http.client ClientProtocolException getLocalizedMessage

Introduction

In this page you can find the example usage for org.apache.http.client ClientProtocolException getLocalizedMessage.

Prototype

public String getLocalizedMessage() 

Source Link

Document

Creates a localized description of this throwable.

Usage

From source file:br.com.cams7.siscom.member.MemberList.java

private static String GET(String url, String errorMsg) {
    // create HttpClient
    HttpClient httpclient = new DefaultHttpClient();

    try {//from  w  w  w .  j  a v a2 s . co  m
        // make GET request to the given URL
        HttpResponse httpResponse = httpclient.execute(new HttpGet(url));
        // receive response as inputStream
        InputStream inputStream = httpResponse.getEntity().getContent();
        if (inputStream == null) {
            Log.d(RestUtil.TAG_INPUT_STREAM, "InputStream is null");
            return errorMsg;
        }

        return RestUtil.convertInputStreamToString(inputStream);
    } catch (ClientProtocolException e) {
        Log.d(RestUtil.TAG_INPUT_STREAM, e.getLocalizedMessage(), e.getCause());
    } catch (IOException e) {
        Log.d(RestUtil.TAG_INPUT_STREAM, e.getLocalizedMessage(), e.getCause());
    }

    return errorMsg;
}

From source file:com.evolveum.midpoint.report.impl.ReportNodeUtils.java

public static InputStream executeOperation(String host, String fileName, String intraClusterHttpUrlPattern,
        String operation) throws CommunicationException, SecurityViolationException, ObjectNotFoundException,
        ConfigurationException, IOException {
    fileName = fileName.replaceAll("\\s", SPACE);
    InputStream inputStream = null;
    InputStream entityContent = null;
    LOGGER.trace("About to initiate connection with {}", host);
    try {/*  w w w .  j  a v a2s .  co  m*/
        if (StringUtils.isNotEmpty(intraClusterHttpUrlPattern)) {
            LOGGER.trace("The cluster uri pattern: {} ", intraClusterHttpUrlPattern);
            URI requestUri = buildURI(intraClusterHttpUrlPattern, host, fileName);
            fileName = URLDecoder.decode(fileName, ReportTypeUtil.URLENCODING);

            LOGGER.debug("Sending request to the following uri: {} ", requestUri);
            HttpRequestBase httpRequest = buildHttpRequest(operation);
            httpRequest.setURI(requestUri);
            httpRequest.setHeader("User-Agent", ReportTypeUtil.HEADER_USERAGENT);
            HttpClient client = HttpClientBuilder.create().build();
            try (CloseableHttpResponse response = (CloseableHttpResponse) client.execute(httpRequest)) {
                HttpEntity entity = response.getEntity();
                Integer statusCode = response.getStatusLine().getStatusCode();

                if (statusCode == HttpStatus.SC_OK) {
                    LOGGER.debug("Response OK, the file successfully returned by the cluster peer. ");
                    if (entity != null) {
                        entityContent = entity.getContent();
                        ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
                        byte[] buffer = new byte[1024];
                        int len;
                        while ((len = entityContent.read(buffer)) > -1) {
                            arrayOutputStream.write(buffer, 0, len);
                        }
                        arrayOutputStream.flush();
                        inputStream = new ByteArrayInputStream(arrayOutputStream.toByteArray());
                    }
                } else if (statusCode == HttpStatus.SC_NO_CONTENT) {
                    if (HttpDelete.METHOD_NAME.equals(operation)) {
                        LOGGER.info("Deletion of the file {} was successful.", fileName);
                    }
                } else if (statusCode == HttpStatus.SC_FORBIDDEN) {
                    LOGGER.error("The access to the report with the name {} is forbidden.", fileName);
                    String error = "The access to the report " + fileName + " is forbidden.";
                    throw new SecurityViolationException(error);
                } else if (statusCode == HttpStatus.SC_NOT_FOUND) {
                    String error = "The report file " + fileName
                            + " was not found on the originating nodes filesystem.";
                    throw new ObjectNotFoundException(error);
                }
            } catch (ClientProtocolException e) {
                String error = "An exception with the communication protocol has occurred during a query to the cluster peer. "
                        + e.getLocalizedMessage();
                throw new CommunicationException(error);
            }
        } else {
            LOGGER.error(
                    "Cluster pattern parameters is empty, please refer to the documentation and set up the parameter value accordingly");
            throw new ConfigurationException(
                    "Cluster pattern parameters is empty, please refer to the documentation and set up the parameter value accordingly");
        }
    } catch (URISyntaxException e1) {
        throw new CommunicationException("Invalid uri syntax: " + e1.getLocalizedMessage());
    } catch (UnsupportedEncodingException e) {
        LOGGER.error("Unhandled exception when listing nodes");
        LoggingUtils.logUnexpectedException(LOGGER, "Unhandled exception when listing nodes", e);
    } finally {
        IOUtils.closeQuietly(entityContent);
    }

    return inputStream;
}

From source file:com.nononsenseapps.notepad.sync.googleapi.GoogleTaskSync.java

/**
 * Returns true if sync was successful, false otherwise
 *///w  w  w. jav a  2 s  . co  m
public static boolean fullSync(final Context context, final Account account, final Bundle extras,
        final String authority, final ContentProviderClient provider, final SyncResult syncResult) {

    Log.d(TAG, "fullSync");
    // Is saved at a successful sync
    final long startTime = Calendar.getInstance().getTimeInMillis();

    boolean success = false;
    // Initialize necessary stuff
    final AccountManager accountManager = AccountManager.get(context);
    final GoogleAPITalker apiTalker = new GoogleAPITalker(context);

    try {
        boolean connected = apiTalker.initialize(accountManager, account, AUTH_TOKEN_TYPE, NOTIFY_AUTH_FAILURE);

        if (connected) {

            Log.d(TAG, "AuthToken acquired, we are connected...");

            try {
                // IF full sync, download since start of all time
                // Temporary fix for delete all bug
                //               if (PreferenceManager.getDefaultSharedPreferences(context)
                //                     .getBoolean(SyncPrefs.KEY_FULLSYNC, false)) {
                PreferenceManager.getDefaultSharedPreferences(context).edit()
                        .putBoolean(SyncPrefs.KEY_FULLSYNC, false).putLong(PREFS_GTASK_LAST_SYNC_TIME, 0)
                        .commit();
                //               }

                // Download lists from server
                Log.d(TAG, "download lists");
                final List<GoogleTaskList> remoteLists = downloadLists(apiTalker);

                // merge with local complement
                Log.d(TAG, "merge lists");
                mergeListsWithLocalDB(context, account.name, remoteLists);

                // Synchronize lists locally
                Log.d(TAG, "sync lists locally");
                final List<Pair<TaskList, GoogleTaskList>> listPairs = synchronizeListsLocally(context,
                        remoteLists);

                // Synchronize lists remotely
                Log.d(TAG, "sync lists remotely");
                final List<Pair<TaskList, GoogleTaskList>> syncedPairs = synchronizeListsRemotely(context,
                        listPairs, apiTalker);

                // For each list
                for (Pair<TaskList, GoogleTaskList> syncedPair : syncedPairs) {
                    // Download tasks from server
                    Log.d(TAG, "download tasks");
                    final List<GoogleTask> remoteTasks = downloadChangedTasks(context, apiTalker,
                            syncedPair.second);

                    // merge with local complement
                    Log.d(TAG, "merge tasks");
                    mergeTasksWithLocalDB(context, account.name, remoteTasks, syncedPair.first._id);

                    // Synchronize tasks locally
                    Log.d(TAG, "sync tasks locally");
                    final List<Pair<Task, GoogleTask>> taskPairs = synchronizeTasksLocally(context, remoteTasks,
                            syncedPair);
                    // Synchronize tasks remotely
                    Log.d(TAG, "sync tasks remotely");
                    synchronizeTasksRemotely(context, taskPairs, syncedPair.second, apiTalker);
                }

                Log.d(TAG, "Sync Complete!");
                success = true;
                PreferenceManager.getDefaultSharedPreferences(context).edit()
                        .putLong(PREFS_GTASK_LAST_SYNC_TIME, startTime).commit();

                /*
                 * Tasks Step 1: Download changes from the server Step 2:
                 * Iterate and compare with local content Step 2a: If both
                 * versions changed, choose the latest Step 2b: If remote is
                 * newer, put info in local task, save Step 2c: If local is
                 * newer, upload it (in background) Step 3: For remote items
                 * that do not exist locally, save Step 4: For local items
                 * that do not exist remotely, upload
                 */

            } catch (ClientProtocolException e) {

                Log.e(TAG, "ClientProtocolException: " + e.getLocalizedMessage());
                syncResult.stats.numAuthExceptions++;
            } catch (IOException e) {
                syncResult.stats.numIoExceptions++;

                Log.e(TAG, "IOException: " + e.getLocalizedMessage());
            } catch (ClassCastException e) {
                // GetListofLists will cast this if it returns a string.
                // It should not return a string but it did...
                syncResult.stats.numAuthExceptions++;
                Log.e(TAG, "ClassCastException: " + e.getLocalizedMessage());
            }

        } else {
            // return real failure

            Log.d(TAG, "Could not get authToken. Reporting authException");
            syncResult.stats.numAuthExceptions++;
            // doneIntent.putExtra(SYNC_RESULT, LOGIN_FAIL);
        }

    } catch (Exception e) {
        // Something went wrong, don't punish the user
        syncResult.stats.numAuthExceptions++;
        Log.e(TAG, "bobs your uncle: " + e.getLocalizedMessage());
    } finally {
        // This must always be called or we will leak resources
        if (apiTalker != null) {
            apiTalker.closeClient();
        }

        Log.d(TAG, "SyncResult: " + syncResult.toDebugString());
    }

    return success;
}

From source file:mobi.designmyapp.template.sample.ods.task.DataPickerTask.java

/**
 * Retrieves the ODS call result and processes JSON parsing
 * @param params/*from  w ww.j  a v a2 s  . c  o  m*/
 * @throws java.lang.IllegalStateException if an error occurs during HTTP call or during JSON parsing
 * @return
 */
@Override
protected List<ODSResult> doInBackground(Object... params) {

    InputStream resultStream = null;

    // Processing Http request
    try {
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(callURI);
        HttpResponse response = client.execute(request);

        resultStream = response.getEntity().getContent();

    } catch (ClientProtocolException e) {
        Log.e("Error with the used protocol: ", e.getLocalizedMessage());
        throw new IllegalStateException(e);
    } catch (IOException e) {
        Log.e("Error while getting stream: ", e.getLocalizedMessage());
        throw new IllegalStateException(e);
    }

    // Converting response to string
    String result = StreamUtils.inputStreamToString(resultStream);

    // Parsing string to JSON and mapping to result List
    List<ODSResult> results = new ArrayList<ODSResult>();
    try {
        JSONObject json = new JSONObject(result);

        JSONArray entries = json.getJSONArray(TAG_ENTRY);

        for (int i = 0; i < entries.length(); i++) {
            JSONObject s = entries.getJSONObject(i);

            ODSResult entry = new ODSResult().builder().id(s.getString(TAG_ID))
                    .title(s.getJSONObject(TAG_DATA).getString(TAG_NAME))
                    .description(s.getJSONObject(TAG_DATA).getString(TAG_AREA))
                    .latitude(Double.parseDouble(s.getJSONObject(TAG_DATA).getString(TAG_LAT)))
                    .longitude(Double.parseDouble(s.getJSONObject(TAG_DATA).getString(TAG_LONG))).build();

            results.add(entry);

        }
    } catch (JSONException e) {
        Log.e("Error while parsing JSON: ", e.getLocalizedMessage());
        throw new IllegalStateException(e);
    }
    return results;
}

From source file:org.mobiletrial.license.connect.RestClient.java

public void post(final String path, final JSONObject requestJson, final OnRequestFinishedListener listener) {
    Thread t = new Thread() {
        public void run() {
            Looper.prepare(); //For Preparing Message Pool for the child Thread

            // Register Schemes for http and https
            final SchemeRegistry schemeRegistry = new SchemeRegistry();
            schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            schemeRegistry.register(new Scheme("https", createAdditionalCertsSSLSocketFactory(), 443));

            final HttpParams params = new BasicHttpParams();
            final ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry);
            HttpClient client = new DefaultHttpClient(cm, params);

            HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit

            HttpResponse response;/*ww w  .  j  a v  a2s .co  m*/
            try {
                String urlStr = mServiceUrl.toExternalForm();
                if (urlStr.charAt(urlStr.length() - 1) != '/')
                    urlStr += "/";
                urlStr += path;
                URI actionURI = new URI(urlStr);

                HttpPost post = new HttpPost(actionURI);
                StringEntity se = new StringEntity(requestJson.toString());
                se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                post.setEntity(se);
                response = client.execute(post);

                /* Checking response */
                if (response == null) {
                    listener.gotError(ERROR_CONTACTING_SERVER);
                    Log.w(TAG, "Error contacting licensing server.");
                    return;
                }
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode != HttpStatus.SC_OK) {
                    Log.w(TAG, "An error has occurred on the licensing server.");
                    listener.gotError(ERROR_SERVER_FAILURE);
                    return;
                }

                /* Convert response to JSON */
                InputStream in = response.getEntity().getContent(); //Get the data in the entity
                String responseStr = inputstreamToString(in);
                listener.gotResponse(responseStr);

            } catch (ClientProtocolException e) {
                Log.w(TAG, "ClientProtocolExeption:  " + e.getLocalizedMessage());
                e.printStackTrace();
            } catch (IOException e) {
                Log.w(TAG, "Error on contacting server: " + e.getLocalizedMessage());
                listener.gotError(ERROR_CONTACTING_SERVER);
            } catch (URISyntaxException e) {
                //This shouldn't happen   
                Log.w(TAG, "Could not build URI.. Your service Url is propably not a valid Url:  "
                        + e.getLocalizedMessage());
                e.printStackTrace();
            }
            Looper.loop(); //Loop in the message queue
        }
    };
    t.start();
}

From source file:com.couchbase.lite.performance.Test7_PullReplication.java

private void pushDocumentToSyncGateway(String docId, final String docJson) throws MalformedURLException {
    // push a document to server
    URL replicationUrlTrailingDoc1 = new URL(
            String.format("%s/%s", getReplicationURL().toExternalForm(), docId));
    final URL pathToDoc1 = new URL(replicationUrlTrailingDoc1, docId);
    Log.d(TAG, "Send http request to " + pathToDoc1);

    final CountDownLatch httpRequestDoneSignal = new CountDownLatch(1);
    BackgroundTask getDocTask = new BackgroundTask() {

        @Override/*from  w  w w  . jav  a2 s . c om*/
        public void run() {

            HttpClient httpclient = new DefaultHttpClient();

            HttpResponse response;
            String responseString = null;
            try {
                HttpPut post = new HttpPut(pathToDoc1.toExternalForm());
                StringEntity se = new StringEntity(docJson.toString());
                se.setContentType(new BasicHeader("content_type", "application/json"));
                post.setEntity(se);
                response = httpclient.execute(post);
                StatusLine statusLine = response.getStatusLine();
                Log.d(TAG, "Got response: " + statusLine);
                assertTrue(statusLine.getStatusCode() == HttpStatus.SC_CREATED);
            } catch (ClientProtocolException e) {
                assertNull("Got ClientProtocolException: " + e.getLocalizedMessage(), e);
            } catch (IOException e) {
                assertNull("Got IOException: " + e.getLocalizedMessage(), e);
            }

            httpRequestDoneSignal.countDown();
        }

    };
    getDocTask.execute();

    Log.d(TAG, "Waiting for http request to finish");
    try {
        httpRequestDoneSignal.await(300, TimeUnit.SECONDS);
        Log.d(TAG, "http request finished");
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:org.tomahawk.tomahawk_android.utils.TomahawkExceptionReporter.java

/**
 * Pull information from the given {@link CrashReportData} and send it via HTTP to
 * oops.tomahawk-player.org or sends it as a TEXT intent, if IS_SILENT is true
 *//*from   w  w w .  j  a va 2s.  c om*/
@Override
public void send(CrashReportData data) throws ReportSenderException {
    StringBuilder body = new StringBuilder();

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("Version", data.getProperty(ReportField.APP_VERSION_NAME)));

    nameValuePairs.add(new BasicNameValuePair("BuildID", data.getProperty(ReportField.BUILD)));
    nameValuePairs.add(new BasicNameValuePair("ProductName", "tomahawk-android"));
    nameValuePairs.add(new BasicNameValuePair("Vendor", "Tomahawk"));
    nameValuePairs.add(new BasicNameValuePair("timestamp", data.getProperty(ReportField.USER_CRASH_DATE)));

    for (NameValuePair pair : nameValuePairs) {
        body.append("--thkboundary\r\n");
        body.append("Content-Disposition: form-data; name=\"");
        body.append(pair.getName()).append("\"\r\n\r\n").append(pair.getValue()).append("\r\n");
    }

    body.append("--thkboundary\r\n");
    body.append("Content-Disposition: form-data; name=\"upload_file_minidump\"; filename=\"")
            .append(data.getProperty(ReportField.REPORT_ID)).append("\"\r\n");
    body.append("Content-Type: application/octet-stream\r\n\r\n");

    body.append("============== Tomahawk Exception Report ==============\r\n\r\n");
    body.append("Report ID: ").append(data.getProperty(ReportField.REPORT_ID)).append("\r\n");
    body.append("App Start Date: ").append(data.getProperty(ReportField.USER_APP_START_DATE)).append("\r\n");
    body.append("Crash Date: ").append(data.getProperty(ReportField.USER_CRASH_DATE)).append("\r\n\r\n");

    body.append("--------- Phone Details  ----------\r\n");
    body.append("Phone Model: ").append(data.getProperty(ReportField.PHONE_MODEL)).append("\r\n");
    body.append("Brand: ").append(data.getProperty(ReportField.BRAND)).append("\r\n");
    body.append("Product: ").append(data.getProperty(ReportField.PRODUCT)).append("\r\n");
    body.append("Display: ").append(data.getProperty(ReportField.DISPLAY)).append("\r\n");
    body.append("-----------------------------------\r\n\r\n");

    body.append("----------- Stack Trace -----------\r\n");
    body.append(data.getProperty(ReportField.STACK_TRACE)).append("\r\n");
    body.append("-----------------------------------\r\n\r\n");

    body.append("------- Operating System  ---------\r\n");
    body.append("App Version Name: ").append(data.getProperty(ReportField.APP_VERSION_NAME)).append("\r\n");
    body.append("Total Mem Size: ").append(data.getProperty(ReportField.TOTAL_MEM_SIZE)).append("\r\n");
    body.append("Available Mem Size: ").append(data.getProperty(ReportField.AVAILABLE_MEM_SIZE)).append("\r\n");
    body.append("Dumpsys Meminfo: ").append(data.getProperty(ReportField.DUMPSYS_MEMINFO)).append("\r\n");
    body.append("-----------------------------------\r\n\r\n");

    body.append("-------------- Misc ---------------\r\n");
    body.append("Package Name: ").append(data.getProperty(ReportField.PACKAGE_NAME)).append("\r\n");
    body.append("File Path: ").append(data.getProperty(ReportField.FILE_PATH)).append("\r\n");

    body.append("Android Version: ").append(data.getProperty(ReportField.ANDROID_VERSION)).append("\r\n");
    body.append("Build: ").append(data.getProperty(ReportField.BUILD)).append("\r\n");
    body.append("Initial Configuration:  ").append(data.getProperty(ReportField.INITIAL_CONFIGURATION))
            .append("\r\n");
    body.append("Crash Configuration: ").append(data.getProperty(ReportField.CRASH_CONFIGURATION))
            .append("\r\n");
    body.append("Settings Secure: ").append(data.getProperty(ReportField.SETTINGS_SECURE)).append("\r\n");
    body.append("User Email: ").append(data.getProperty(ReportField.USER_EMAIL)).append("\r\n");
    body.append("User Comment: ").append(data.getProperty(ReportField.USER_COMMENT)).append("\r\n");
    body.append("-----------------------------------\r\n\r\n");

    body.append("---------------- Logs -------------\r\n");
    body.append("Logcat: ").append(data.getProperty(ReportField.LOGCAT)).append("\r\n\r\n");
    body.append("Events Log: ").append(data.getProperty(ReportField.EVENTSLOG)).append("\r\n\r\n");
    body.append("Radio Log: ").append(data.getProperty(ReportField.RADIOLOG)).append("\r\n");
    body.append("-----------------------------------\r\n\r\n");

    body.append("=======================================================\r\n\r\n");
    body.append("--thkboundary\r\n");
    body.append(
            "Content-Disposition: form-data; name=\"upload_file_tomahawklog\"; filename=\"Tomahawk.log\"\r\n");
    body.append("Content-Type: text/plain\r\n\r\n");
    body.append(data.getProperty(ReportField.LOGCAT));
    body.append("\r\n--thkboundary--\r\n");

    if ("true".equals(data.getProperty(ReportField.IS_SILENT))) {
        Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        body.insert(0, "Please tell us why you're sending us this log:\n\n\n\n\n");
        intent.putExtra(Intent.EXTRA_TEXT, body.toString());
        intent.putExtra(Intent.EXTRA_EMAIL, new String[] { "support@tomahawk-player.org" });
        intent.putExtra(Intent.EXTRA_SUBJECT, "Tomahawk Android Log");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        TomahawkApp.getContext().startActivity(intent);
    } else {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://oops.tomahawk-player.org/addreport.php");
        httppost.setHeader("Content-type", "multipart/form-data; boundary=thkboundary");
        try {
            httppost.setEntity(new StringEntity(body.toString()));
            httpclient.execute(httppost);
        } catch (ClientProtocolException e) {
            Log.e(TAG, "send: " + e.getClass() + ": " + e.getLocalizedMessage());
        } catch (IOException e) {
            Log.e(TAG, "send: " + e.getClass() + ": " + e.getLocalizedMessage());
        }
    }
}

From source file:com.csipsimple.plugins.twvoip.CallHandler.java

@Override
public void onReceive(Context context, Intent intent) {
    if (ACTION_GET_PHONE_HANDLERS.equals(intent.getAction())) {

        PendingIntent pendingIntent = null;
        // Extract infos from intent received
        String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);

        // Extract infos from settings
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        String user = prefs.getString(CallHandlerConfig.KEY_12VOIP_USER, "");
        String pwd = prefs.getString(CallHandlerConfig.KEY_12VOIP_PWD, "");
        String nbr = prefs.getString(CallHandlerConfig.KEY_12VOIP_NBR, "");

        // We must handle that clean way cause when call just to
        // get the row in account list expect this to reply correctly
        if (!TextUtils.isEmpty(number) && !TextUtils.isEmpty(user) && !TextUtils.isEmpty(nbr)
                && !TextUtils.isEmpty(pwd)) {
            // Build pending intent
            Intent i = new Intent(ACTION_DO_TWVOIP_CALL);
            i.setClass(context, getClass());
            i.putExtra(Intent.EXTRA_PHONE_NUMBER, number);

            pendingIntent = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);
            // = PendingIntent.getActivity(context, 0, i, 0);
        }/*from w w  w.ja  v a 2s. c  o m*/

        // Build icon
        Bitmap bmp = null;
        Drawable icon = context.getResources().getDrawable(R.drawable.icon);
        BitmapDrawable bd = ((BitmapDrawable) icon);
        bmp = bd.getBitmap();

        // Build the result for the row (label, icon, pending intent, and
        // excluded phone number)
        Bundle results = getResultExtras(true);
        if (pendingIntent != null) {
            results.putParcelable(Intent.EXTRA_REMOTE_INTENT_TOKEN, pendingIntent);
        }
        results.putString(Intent.EXTRA_TITLE, "12voip WebCallback");
        if (bmp != null) {
            results.putParcelable(Intent.EXTRA_SHORTCUT_ICON, bmp);
        }

        // DO *NOT* exclude from next tel: intent cause we use a http method
        // results.putString(Intent.EXTRA_PHONE_NUMBER, number);

    } else if (ACTION_DO_TWVOIP_CALL.equals(intent.getAction())) {

        // Extract infos from intent received
        String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);

        // Extract infos from settings
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        String user = prefs.getString(CallHandlerConfig.KEY_12VOIP_USER, "");
        String pwd = prefs.getString(CallHandlerConfig.KEY_12VOIP_PWD, "");
        String nbr = prefs.getString(CallHandlerConfig.KEY_12VOIP_NBR, "");

        // params
        List<NameValuePair> params = new LinkedList<NameValuePair>();
        params.add(new BasicNameValuePair("username", user));
        params.add(new BasicNameValuePair("password", pwd));
        params.add(new BasicNameValuePair("from", nbr));
        params.add(new BasicNameValuePair("to", number));
        String paramString = URLEncodedUtils.format(params, "utf-8");

        String requestURL = "https://www.12voip.com//myaccount/makecall.php?" + paramString;

        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(requestURL);

        // Create a response handler
        HttpResponse httpResponse;
        try {
            httpResponse = httpClient.execute(httpGet);
            Log.d(THIS_FILE, "response code is " + httpResponse.getStatusLine().getStatusCode());
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                InputStreamReader isr = new InputStreamReader(httpResponse.getEntity().getContent());
                BufferedReader br = new BufferedReader(isr);

                String line;
                String fullReply = "";
                boolean foundSuccess = false;
                while ((line = br.readLine()) != null) {
                    if (!TextUtils.isEmpty(line) && line.toLowerCase().contains("success")) {
                        showToaster(context, "Success... wait a while you'll called back");
                        foundSuccess = true;
                        break;
                    }
                    if (!TextUtils.isEmpty(line)) {
                        fullReply = fullReply.concat(line);
                    }
                }
                if (!foundSuccess) {
                    showToaster(context, "Error : server error : " + fullReply);
                }
            } else {
                showToaster(context, "Error : invalid request " + httpResponse.getStatusLine().getStatusCode());
            }
        } catch (ClientProtocolException e) {
            showToaster(context, "Error : " + e.getLocalizedMessage());
        } catch (IOException e) {
            showToaster(context, "Error : " + e.getLocalizedMessage());
        }

    }
}

From source file:com.csipsimple.plugins.betamax.CallHandlerWeb.java

@Override
public void onReceive(Context context, Intent intent) {
    if (Utils.ACTION_GET_PHONE_HANDLERS.equals(intent.getAction())) {

        PendingIntent pendingIntent = null;
        // Extract infos from intent received
        String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);

        // Extract infos from settings
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        String user = prefs.getString(CallHandlerConfig.KEY_TW_USER, "");
        String pwd = prefs.getString(CallHandlerConfig.KEY_TW_PWD, "");
        String nbr = prefs.getString(CallHandlerConfig.KEY_TW_NBR, "");
        String provider = prefs.getString(CallHandlerConfig.KEY_TW_PROVIDER, "");

        // We must handle that clean way cause when call just to
        // get the row in account list expect this to reply correctly
        if (!TextUtils.isEmpty(number) && !TextUtils.isEmpty(user) && !TextUtils.isEmpty(nbr)
                && !TextUtils.isEmpty(pwd) && !TextUtils.isEmpty(provider)) {
            // Build pending intent
            Intent i = new Intent(ACTION_DO_WEB_CALL);
            i.setClass(context, getClass());
            i.putExtra(Intent.EXTRA_PHONE_NUMBER, number);
            pendingIntent = PendingIntent.getBroadcast(context, 0, i, PendingIntent.FLAG_CANCEL_CURRENT);

        }/*  w w w  .  j av  a  2  s . com*/

        // Build icon
        Bitmap bmp = Utils.getBitmapFromResource(context, R.drawable.icon_web);

        // Build the result for the row (label, icon, pending intent, and
        // excluded phone number)
        Bundle results = getResultExtras(true);
        if (pendingIntent != null) {
            results.putParcelable(Utils.EXTRA_REMOTE_INTENT_TOKEN, pendingIntent);
        }

        // Text for the row
        String providerName = "";
        Resources r = context.getResources();
        if (!TextUtils.isEmpty(provider)) {
            String[] arr = r.getStringArray(R.array.provider_values);
            String[] arrEntries = r.getStringArray(R.array.provider_entries);
            int i = 0;
            for (String prov : arr) {
                if (prov.equalsIgnoreCase(provider)) {
                    providerName = arrEntries[i];
                    break;
                }
                i++;
            }
        }
        results.putString(Intent.EXTRA_TITLE, providerName + " " + r.getString(R.string.web_callback));
        Log.d(THIS_FILE, "icon is " + bmp);
        if (bmp != null) {
            results.putParcelable(Intent.EXTRA_SHORTCUT_ICON, bmp);
        }

        // DO *NOT* exclude from next tel: intent cause we use a http method
        // results.putString(Intent.EXTRA_PHONE_NUMBER, number);

    } else if (ACTION_DO_WEB_CALL.equals(intent.getAction())) {

        // Extract infos from intent received
        String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);

        // Extract infos from settings
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        String user = prefs.getString(CallHandlerConfig.KEY_TW_USER, "");
        String pwd = prefs.getString(CallHandlerConfig.KEY_TW_PWD, "");
        String nbr = prefs.getString(CallHandlerConfig.KEY_TW_NBR, "");
        String provider = prefs.getString(CallHandlerConfig.KEY_TW_PROVIDER, "");

        // params
        List<NameValuePair> params = new LinkedList<NameValuePair>();
        params.add(new BasicNameValuePair("username", user));
        params.add(new BasicNameValuePair("password", pwd));
        params.add(new BasicNameValuePair("from", nbr));
        params.add(new BasicNameValuePair("to", number));
        String paramString = URLEncodedUtils.format(params, "utf-8");

        String requestURL = "https://www." + provider + "/myaccount/makecall.php?" + paramString;

        HttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(requestURL);

        // Create a response handler
        HttpResponse httpResponse;
        try {
            httpResponse = httpClient.execute(httpGet);
            Log.d(THIS_FILE, "response code is " + httpResponse.getStatusLine().getStatusCode());
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                InputStreamReader isr = new InputStreamReader(httpResponse.getEntity().getContent());
                BufferedReader br = new BufferedReader(isr);

                String line;
                String fullReply = "";
                boolean foundSuccess = false;
                while ((line = br.readLine()) != null) {
                    if (!TextUtils.isEmpty(line) && line.toLowerCase().contains("success")) {
                        showToaster(context, "Success... wait a while you'll called back");
                        foundSuccess = true;
                        break;
                    }
                    if (!TextUtils.isEmpty(line)) {
                        fullReply = fullReply.concat(line);
                    }
                }
                if (!foundSuccess) {
                    showToaster(context, "Error : server error : " + fullReply);
                }
            } else {
                showToaster(context, "Error : invalid request " + httpResponse.getStatusLine().getStatusCode());
            }
        } catch (ClientProtocolException e) {
            showToaster(context, "Error : " + e.getLocalizedMessage());
        } catch (IOException e) {
            showToaster(context, "Error : " + e.getLocalizedMessage());
        }

    }
}

From source file:ing.rbi.poc.ResolveConnection.java

private Boolean Connect() {
    String txtResponse = "";
    Boolean OK = false;/* www .  j a  v a  2 s .  c o m*/
    try {

        DefaultHttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet(uri);
        //Nothing to construct here

        HttpResponse response = client.execute(request);
        HttpEntity httpEntity = response.getEntity();
        txtResponse = httpEntity.getContent().toString();
        Integer StatCode;
        StatCode = response.getStatusLine().getStatusCode();
        txtResponse = Integer.toString(StatCode);
        String ticket;
        ticket = Login();

        if (ticket != "" && ticket != "null") {
            //Now Get a list of Capture flows and open a new screen
            CaptureFlows = GetCaptureFlowList(ticket);
            //Now we need to pass this to the new UI
            OK = true;
        } else {
            txtResponse = "Unable to Login";
            OK = false;
        }
    } catch (ClientProtocolException e) {
        Log.d("HTTPCLIENT", e.getLocalizedMessage());
        txtResponse = "Unable To Reach Server";
    } catch (IOException e) {
        Log.d("HTTPCLIENT", e.getLocalizedMessage());
        txtResponse = "Unable To Reach Server";
        StrResponse = txtResponse;
    } catch (IllegalArgumentException e) {
        Log.d("HTTPCLIENT", e.getLocalizedMessage());
        txtResponse = "Unable To Reach Server";
    } finally {
        //If this works then try to login
    }
    return OK;

}