Example usage for java.net SocketTimeoutException printStackTrace

List of usage examples for java.net SocketTimeoutException printStackTrace

Introduction

In this page you can find the example usage for java.net SocketTimeoutException printStackTrace.

Prototype

public void printStackTrace() 

Source Link

Document

Prints this throwable and its backtrace to the standard error stream.

Usage

From source file:net.xisberto.phonetodesktop.GoogleTasksActivity.java

/**
 * Gets a auth token from Google services for Google Tasks service. May
 * launch a new Activity to ask the user for permission. Stores the account
 * name and the auth token in preferences and executes callback.run().
 * /*ww  w . jav  a  2s .  c o m*/
 * @param account
 *            the Account to ask the auth token.
 * @param callback
 *            {@link GoogleTasksCallback} object whose run method will be
 *            executed when the new auth token is obtained.
 */
private void getAuthToken(final Account account, final GoogleTasksCallback callback) {
    AccountManagerCallback<Bundle> ac_callback = new AccountManagerCallback<Bundle>() {
        public void run(AccountManagerFuture<Bundle> future) {
            try {
                Bundle bundle = future.getResult();
                // Here we got the auth token! Saving accountname and
                // authtoken
                String new_auth_token = bundle.getString(AccountManager.KEY_AUTHTOKEN);
                //saveAccountName(bundle.getString(AccountManager.KEY_ACCOUNT_NAME));
                saveAuthToken(new_auth_token);
                credential.setAccessToken(new_auth_token);
                log("Token obtained: " + new_auth_token);
                // And executing the callback function
                callback.run();
            } catch (OperationCanceledException canceledException) {
                // User has canceled operation
                broadcastUpdatingStatus(ACTION_AUTHENTICATE, false);
            } catch (SocketTimeoutException e) {
                broadcastUpdatingStatus(ACTION_AUTHENTICATE, false);
                log("Timeout");
                dismissNotification(NOTIFICATION_SENDING);
                showNotification(NOTIFICATION_TIMEOUT);
            } catch (IOException e) {
                if (e instanceof GoogleJsonResponseException) {
                    log("Got an GoogleJson exception");
                    if (handleGoogleException(e)) {
                        getAuthToken(account, callback);
                    }
                } else {
                    e.printStackTrace();
                }
            } catch (AuthenticatorException e) {
                e.printStackTrace();
            } catch (Exception e) {
                broadcastUpdatingStatus(ACTION_AUTHENTICATE, false);
                dismissNotification(NOTIFICATION_SENDING);
                e.printStackTrace();
            }
        }
    };
    accountManager.getAccountManager().getAuthToken(account, "Manage your tasks", null,
            GoogleTasksActivity.this, ac_callback, handler);
}

From source file:scal.io.liger.LigerDownloadManager.java

private void downloadWithTor(boolean useTor, Uri uri, String title, String desc, File targetFile) {

    String fileName = ZipHelper.getExpansionZipFilename(context, mainOrPatch, version);
    String filePath = ZipHelper.getExpansionZipDirectory(context, mainOrPatch, version);

    initNotificationManager();/*from  w w w  .  j a  va  2s  .co  m*/

    // generate id/tag for notification
    String nTag = mainOrPatch;
    int nId = version;

    StrongHttpsClient httpClient = getHttpClientInstance();

    // we're now using this method to support non-tor downloads as well, so settings must be checked
    if (useTor) {
        if (checkTor(context)) {

            Timber.d("DOWNLOAD WITH TOR PROXY: " + Constants.TOR_PROXY_HOST + "/" + Constants.TOR_PROXY_PORT);

            httpClient.useProxy(true, "http", Constants.TOR_PROXY_HOST, Constants.TOR_PROXY_PORT); // CLASS DOES NOT APPEAR TO REGISTER A SCHEME FOR SOCKS, ORBOT DOES NOT APPEAR TO HAVE AN HTTPS PORT
        } else {
            Timber.e("CANNOT DOWNLOAD WITH TOR, TOR IS NOT ACTIVE");

            if (context instanceof Activity) {
                Utility.toastOnUiThread((Activity) context,
                        "Check settings, can't use tor if orbot isn't running", true); // FIXME move to strings
            }

            QueueManager.checkQueueFinished(context, targetFile.getName());

            return;
        }
    }

    // disable attempts to retry (more retries ties up connection and prevents failure handling)
    HttpRequestRetryHandler retryHandler = new DefaultHttpRequestRetryHandler(1, false);
    httpClient.setHttpRequestRetryHandler(retryHandler);

    // set modest timeout (longer timeout ties up connection and prevents failure handling)
    HttpParams params = httpClient.getParams();
    HttpConnectionParams.setConnectionTimeout(params, 3000);
    HttpConnectionParams.setSoTimeout(params, 3000);

    httpClient.setParams(params);

    Timber.d("CHECKING URI: " + uri.toString());

    try {

        HttpGet request = new HttpGet(uri.toString());

        // TODO - can't support partial files until file size is known

        HttpResponse response = httpClient.execute(request);

        HttpEntity entity = response.getEntity();
        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode == 200) {

            Timber.d("DOWNLOAD SUCCEEDED, STATUS CODE: " + statusCode);

            // queue item here, "download" doesn't start until after we get a status code

            // queue item, use date to get a unique long, subtract to get a negative number (to distinguish from download manager items)
            Date startTime = new Date();
            long queueId = 0 - startTime.getTime();
            QueueManager.addToQueue(context, queueId, targetFile.getName());

            targetFile.getParentFile().mkdirs();

            Timber.d("DOWNLOAD SUCCEEDED, GETTING ENTITY...");

            BufferedInputStream responseInput = new BufferedInputStream(response.getEntity().getContent());

            try {
                FileOutputStream targetOutput = new FileOutputStream(targetFile);
                byte[] buf = new byte[1024];
                int i;

                // create status bar notification
                // TODO - can't support % complete until file size is known
                Notification nProgress = new Notification.Builder(context)
                        .setContentTitle(mAppTitle + " content download").setContentText(fileName)
                        .setSmallIcon(android.R.drawable.arrow_down_float).setWhen(startTime.getTime()).build();
                nManager.notify(nTag, nId, nProgress);

                while ((i = responseInput.read(buf)) > 0) {
                    targetOutput.write(buf, 0, i);
                }
                targetOutput.close();
                responseInput.close();

                /*
                if (!handleFile(targetFile)) {
                Timber.d("ERROR DURING FILE PROCESSING");
                return;
                }
                */

                Timber.d("SAVED DOWNLOAD TO " + targetFile);
            } catch (ConnectTimeoutException cte) {
                Timber.e("FAILED TO SAVE DOWNLOAD TO " + fileName + " (CONNECTION EXCEPTION)");
                cte.printStackTrace();
            } catch (SocketTimeoutException ste) {
                Timber.e("FAILED TO SAVE DOWNLOAD TO " + fileName + " (SOCKET EXCEPTION)");
                ste.printStackTrace();
            } catch (IOException ioe) {
                Timber.e("FAILED TO SAVE DOWNLOAD TO " + fileName + " (IO EXCEPTION)");
                ioe.printStackTrace();
            }

            // remove from queue here, regardless of success
            QueueManager.removeFromQueue(context, queueId);

            // remove notification, regardless of success
            nManager.cancel(nTag, nId);

            // handle file here, regardless of success
            // (assumes .tmp file will exist if download is interrupted)
            if (!handleFile(targetFile)) {
                Timber.e("ERROR DURING FILE PROCESSING FOR " + fileName);
            }
        } else {
            Timber.e("DOWNLOAD FAILED FOR " + fileName + ", STATUS CODE: " + statusCode);

            QueueManager.checkQueueFinished(context, targetFile.getName());
        }

        // clean up connection
        EntityUtils.consume(entity);
        request.abort();
        request.releaseConnection();

    } catch (IOException ioe) {
        Timber.e("DOWNLOAD FAILED FOR " + fileName + ", EXCEPTION THROWN");
        ioe.printStackTrace();

        QueueManager.checkQueueFinished(context, targetFile.getName());
    }
}

From source file:javax.microedition.ims.core.xdm.XDMServiceImpl.java

public XDMResponse sendXCAPRequest(final XDMRequest request) throws XCAPException, SAXException {

    Logger.log("XCAP REQUEST", "------------------------------ Request Begin ------------------------------");
    Logger.log("XCAP REQUEST", "METHOD: " + request.getMethod());
    Logger.log("XCAP REQUEST", "URI: " + request.getURI());
    Logger.log("XCAP REQUEST", "HEADERS: " + request.getHeaders());
    Logger.log("XCAP REQUEST", "TYPE: " + request.getEntityType());
    Logger.log("XCAP REQUEST", "ID: " + request.getIMSEntityId());
    Logger.log("XCAP REQUEST", "BODY: " + request.getBody());
    Logger.log("XCAP REQUEST", "------------------------------ Request End ------------------------------");

    // final String content = "content goes here";
    // final String etag = "etag goes here";
    // final String mimeType = "mime type goes here";

    XDMResponse retValue = null;//from   ww w. j a  v a2  s.  c o  m

    final HttpClient httpclient = HttpClientHolder.httpClient;

    HttpResponse response = null;
    try {
        // prepare and send first request
        HttpRequestBase httpRequest = createHttpRequest(request);

        prepareUrlConnection(request, httpRequest, lastChallenge.get());
        // HttpURLConnection urlConnection = (HttpURLConnection)
        // url.openConnection();

        /*
         * System.out.println("AllowUserInteraction = " +
         * urlConnection.getAllowUserInteraction());
         * System.out.println("DoInput = " + urlConnection.getDoInput());
         * System.out.println("DoOutput = " + urlConnection.getDoOutput());
         * System.out.println("DefaultUseCaches = " +
         * urlConnection.getDefaultUseCaches());
         * System.out.println("InstanceFollowRedirects = " +
         * urlConnection.getInstanceFollowRedirects());
         * System.out.println("UseCaches = " +
         * urlConnection.getUseCaches());
         * System.out.println("DefaultAllowUserInteraction = " +
         * HttpURLConnection.getDefaultAllowUserInteraction());
         * urlConnection.setDoInput(true); urlConnection.setDoOutput(true);
         * urlConnection.setAllowUserInteraction(true);
         * URLConnection.setDefaultAllowUserInteraction(true);
         */
        printRequest(httpRequest);
        response = httpclient.execute(httpRequest);
        printResponse(response);

        // if (urlConnection.getResponseCode() == 401) {//this line causes
        // additional request to server without auth challenge
        boolean isAuthRequired = response.containsHeader("WWW-Authenticate");
        if (isAuthRequired) {
            String wwwAuthenticateHeader = response.getFirstHeader("WWW-Authenticate").getValue();
            AuthenticationChallenge challenge = (AuthenticationChallenge) ChallengeParser
                    .consume(wwwAuthenticateHeader);
            lastChallenge.set(challenge);

            response.getEntity().consumeContent();

            // prepare and send second request with auth
            HttpRequestBase httpRequestWithAuth = createHttpRequest(request);
            prepareUrlConnection(request, httpRequestWithAuth, challenge);

            printRequest(httpRequest);
            response = httpclient.execute(httpRequestWithAuth);
            printResponse(response);
        }

        int responseCode = response.getStatusLine().getStatusCode();

        if (responseCode == HttpStatus.SC_OK || responseCode == 201) {

            final Header etagHeader = response.getFirstHeader("ETag");
            Logger.log(TAG, "etagHeader: " + etagHeader);
            final Header contentTypeHeader = response.getFirstHeader("Content-Type");
            Logger.log(TAG, "contentTypeHeader: " + contentTypeHeader);

            final byte[] content = extractBody(response);
            Logger.log(TAG, "extracted");
            Logger.log(TAG, "BODY: " + (content != null ? new String(content, DEFAULT_CHARSET) : ""));

            retValue = new XDMResponseImpl(content == null ? null : db.parse(new ByteArrayInputStream(content)),
                    content, etagHeader != null ? etagHeader.getValue() : null,
                    contentTypeHeader != null ? contentTypeHeader.getValue() : null);
        } else {
            String reasonPhrase = response.getStatusLine().getReasonPhrase();
            XCAPException xcapException = new XCAPException(responseCode, reasonPhrase);
            if (responseCode == HttpStatus.SC_CONFLICT) {
                // TODO Add XCAPError
            }
            throw xcapException;
        }
    } catch (SocketTimeoutException e) {
        Logger.log(TAG, e.getMessage());
        XCAPException xcapException = new XCAPException(408, "Request Timeout");
        throw xcapException;
    } catch (IOException e) {
        Logger.log(TAG, e.getMessage());
        e.printStackTrace();
    } finally {
        if (response != null) {
            try {
                if (response.getEntity() != null)
                    response.getEntity().consumeContent();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return retValue;
}

From source file:watch.oms.omswatch.actioncenter.helpers.WatchPostAsyncTaskHelper.java

/**
 * @param//from w  w w  . j  a v a 2 s.  c om
 * @param
 * @return
 */
/*private String processPostResponse(String clientTableName, HttpEntity httpEntity){
   String       response          =   null;
   String       jsonString         =   null;
   JSONObject    responseJSONObject   =   null;
           
   try{
 jsonString = EntityUtils.toString(httpEntity);
         
 JSONObject responseWebServiceJSON =  new JSONObject(jsonString);
         
 responseJSONObject = responseWebServiceJSON
       .getJSONObject(OMSMessages.RESPONSE_STRING
             .getValue());
   }catch(JSONException jex){
 if(jex!=null && jex.getMessage().contains("No value for "+(OMSMessages.RESPONSE_STRING.getValue()))){
    Log.d(TAG, "response key is not present. Assuming json response contains data set");
    // This changes are for Oasis Project. # Start
    DataParser dataParser = new DataParser(context);
    // This changes are for Oasis Project. # End
    dataParser.parseAndUpdate(jsonString);
    response = "BLPostSuccess";
 }else{
    Log.e(TAG,
          "Exception occurred while reading the json response. Error is:"
                + jex.getMessage());
 }
 return response = OMSMessages.ACTION_CENTER_FAILURE.getValue();
   } catch (ParseException e) {
 Log.e(TAG,
       "Exception occurred while parsing the json response. Error is:"
             + e.getMessage());
   } catch (IOException e) {
 Log.e(TAG,
       "IO Exception occurred while parsing the json response. Error is:"
             + e.getMessage());
   }
            
   try{
 String code = responseJSONObject
       .getString(OMSMessages.CODE.getValue());
 if (code.equals(OMSMessages.DEFAULT_JSON_CODE.getValue())) {
    Log.i(TAG,
          "Response Message :"
                + responseJSONObject
                      .getString(OMSMessages.MESSAGE
                            .getValue()));
    double processedModifiedDate = responseJSONObject
          .getDouble(OMSMessages.PROCESSED_DATE
                .getValue());
            
    parseJSONObject(jsonPayLoad.toString(),
          OMSDatabaseConstants.STATUS_TYPE_FINISHED,
          processedModifiedDate);
    progressString = context.getResources().getString(
          R.string.post_success);
    response = "BLPostSuccess";
        
 } else {
    Log.e(TAG,
          "Response Message :"
                + responseJSONObject
                      .getString(OMSMessages.MESSAGE
                            .getValue()));
    try {
       Log.e(TAG,
             "Response Message Additional:"
                   + responseJSONObject
                         .getString(OMSMessages.ERROR_ADDITIONAL_MESSAGE
                               .getValue()));
    } catch (JSONException je) {
       // ignore if field is not available
    }
    response = OMSMessages.ACTION_CENTER_FAILURE
          .getValue();
            
            
    ContentValues contentValues = new ContentValues();
    contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_STATUS,
          OMSDatabaseConstants.ACTION_STATUS_TRIED);
    contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_SERVER_URL,
          serviceUrl);
    contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_DATA_TABLE_NAME,
          tableName);
    contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_TYPE,
          OMSDatabaseConstants.POST_TYPE_REQUEST);
    contentValues.put(OMSDatabaseConstants.BL_SCHEMA_NAME,
          schemaName);
 actionCenterHelper.insertOrUpdateTransactionFailQueue(contentValues,
          uniqueRowId,configAppId);
 }
   } catch (JSONException e) {
 Log.e(TAG,
       "Exception occurred while updating the Action Queue status."
             + e.getMessage());
 e.printStackTrace();
   } catch (IllegalFormatConversionException e) {
 Log.e(TAG,
       "Exception occurred while updating the Action Queue status."
             + e.getMessage());
 e.printStackTrace();
   }
   return response;
}*/

private String fetchPostResponse(JSONObject jsonPayLoad, String serviceURL) {
    String postResponse = "";
    InputStream inputStream = null;
    OutputStream os = null;
    HttpURLConnection conn = null;
    try {
        /* conn = (HttpURLConnection) AppSecurityAndPerformance.getInstance()
            .getAppGuardSecuredHttpsUrlConnection(serviceURL);*/
        URL urlToRequest = new URL(serviceURL);
        conn = (HttpURLConnection) urlToRequest.openConnection();
        String jsonMessage = jsonPayLoad.toString();
        conn.setReadTimeout(10000 /*milliseconds*/ );
        conn.setConnectTimeout(15000 /* milliseconds */ );
        conn.setRequestMethod("POST");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setFixedLengthStreamingMode(jsonMessage.getBytes().length);

        //make some HTTP header nicety
        conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
        conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");
        conn.setRequestProperty("Content-Encoding", "gzip");

        /*// AppMonitor
           analyzer.startNetworkConnection(serviceURL, OMSMessages.CONNECTION_PREFIX.getValue()
          + connectionID);
           if(conn!=null){
              // AppMonitor
              analyzer.updateConnectionStatus(connectionID, true);
           }
          //open*/
        conn.connect();
        //setup send
        os = new BufferedOutputStream(conn.getOutputStream());
        os.write(jsonMessage.getBytes());
        //clean up
        os.flush();
        inputStream = new BufferedInputStream(conn.getInputStream());
        String serviceResponse = convertStreamToString(inputStream);
        int statusCode = conn.getResponseCode();

        if (statusCode == OMSConstants.STATUSCODE_OK) {
            // AppMonitor
            /*analyzer.receivedConnectionResponse(connectionID,
             conn.getContentLength(),
             OMSDatabaseConstants.POST_TYPE_REQUEST);*/
            if (serviceResponse != null) {
                Log.d(TAG, "PostResponse for HTTPURLConnection:::" + serviceResponse);
                postResponse = processHttpURLConnectionPostResponse(clientTableName, serviceResponse);
                String traceType = OMSApplication.getInstance().getTraceType();
                OMSApplication.getInstance().setTraceType(OMSConstants.TRACE_TYPE_SERVER);
                /*ServerDBUpdateHelper dbhelper = new ServerDBUpdateHelper(context);
                dbhelper.insertCallTraceTypeData(ConsoleDBConstants.CALL_TRACE_TYPE_TABLE, ""+OMSApplication.getInstance().getAppId());*/
                /*Log.i(TAG, "Server Response time::"+OMSApplication.getInstance().getServerProcessDuration());
                Log.i(TAG, "DataBase Response time::"+OMSApplication.getInstance().getDatabaseProcessDuration());
                */ Log.i(TAG, serviceURL + "\n" + "ServerResponseTime::"
                        + OMSApplication.getInstance().getServerProcessDuration() + "\n"
                        + "DataBaseResponseTime::" + OMSApplication.getInstance().getDatabaseProcessDuration());
                OMSApplication.getInstance().setTraceType(traceType);
                return postResponse;
            } else {
                Log.e(TAG, "HttpEntity is NULL :" + jsonPayLoad.toString());
            }

        } else {
            postResponse = OMSMessages.ACTION_CENTER_FAILURE.getValue();
            inputStream = new BufferedInputStream(conn.getInputStream());
            // AppMonitor
            /*analyzer.receivedConnectionResponse(connectionID,
             conn.getContentLength(),
             OMSDatabaseConstants.POST_TYPE_REQUEST);*/
            String result = convertStreamToString(inputStream);
            if (result != null) {
                Log.d(TAG, "Post Service Response :" + result);
                try {
                    JSONObject resultJSON = new JSONObject(result);

                    JSONObject childResponse = resultJSON.getJSONObject("response");
                    if (!childResponse.getString("code").equals("00")) {
                        postResponse = OMSMessages.BL_FAILURE.getValue();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put(OMSMessages.ERROR.getValue(), conn.getResponseCode());
                    jsonObject.put(OMSMessages.ERROR_DESCRIPTION.getValue(), conn.getResponseMessage());
                    result = jsonObject.toString();

                } catch (JSONException e) {
                    Log.e(TAG, "JSON Exception occurred in ActionCenterFailure." + e.getMessage());
                    e.printStackTrace();
                }
            }

            parseJSONObject(jsonPayLoad.toString(), OMSDatabaseConstants.STATUS_TYPE_TRIED, 0.0);

            ContentValues contentValues = new ContentValues();
            contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_STATUS,
                    OMSDatabaseConstants.ACTION_STATUS_TRIED);
            contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_SERVER_URL, serviceUrl);
            contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_DATA_TABLE_NAME, tableName);
            contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_TYPE,
                    OMSDatabaseConstants.POST_TYPE_REQUEST);
            contentValues.put(OMSDatabaseConstants.BL_SCHEMA_NAME, schemaName);
            actionCenterHelper.insertOrUpdateTransactionFailQueue(contentValues, uniqueRowId, configAppId);

            //response = OMSMessages.FAILED.getValue();
            postResponse = OMSMessages.BL_FAILURE.getValue();
            Log.e(TAG, "Post Action Failed");
        }

    } catch (SocketTimeoutException se) {
        progressDialog.dismiss();
        Log.e(TAG, "SocketTimeoutException occurred while Posting the Actions" + se.getMessage());
        if (rListener != null) {
            rListener.receiveResult(OMSMessages.ACTION_CENTER_FAILURE.getValue());
        }
        se.printStackTrace();
    } /* catch (ClientProtocolException e) {
        progressDialog.dismiss();
        Log.e(TAG,
         "ClientProtocolException occurred while Posting the Actions"
               + e.getMessage());
        e.printStackTrace();
      }*/
    catch (ProtocolException pe) {
        progressDialog.dismiss();
        postResponse = OMSMessages.BL_FAILURE.getValue();
        Log.e(TAG, "ProtocolException");
    } catch (MalformedURLException mle) {
        progressDialog.dismiss();
        postResponse = OMSMessages.BL_FAILURE.getValue();
        Log.e(TAG, "MalformedURLException");
    }

    catch (IOException e) {
        progressDialog.dismiss();
        Log.e(TAG, "IOException occurred while Posting the Actions" + e.getMessage());
        e.printStackTrace();

        ContentValues contentValues = new ContentValues();
        contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_STATUS,
                OMSDatabaseConstants.ACTION_STATUS_TRIED);
        contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_SERVER_URL, serviceUrl);
        contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_DATA_TABLE_NAME, tableName);
        contentValues.put(OMSDatabaseConstants.TRANSACTION_QUEUE_TYPE, OMSDatabaseConstants.POST_TYPE_REQUEST);
        contentValues.put(OMSDatabaseConstants.BL_SCHEMA_NAME, schemaName);
        actionCenterHelper.insertOrUpdateTransactionFailQueue(contentValues, uniqueRowId, configAppId);
        postResponse = OMSMessages.BL_FAILURE.getValue();
        return postResponse;
    }

    finally {
        //clean up
        try {
            os.close();
        } catch (NullPointerException ex) {
            postResponse = OMSMessages.BL_FAILURE.getValue();
            Log.e(TAG, "NullPointerException");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            inputStream.close();
        } catch (NullPointerException ex) {
            postResponse = OMSMessages.BL_FAILURE.getValue();
            Log.e(TAG, "NullPointerException");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        conn.disconnect();
    }
    return postResponse;
}

From source file:com.akop.bach.parser.Parser.java

protected String getResponse(HttpUriRequest request, List<NameValuePair> inputs)
        throws IOException, ParserException {
    if (!request.containsHeader("Accept"))
        request.addHeader("Accept", "text/javascript, text/html, application/xml, text/xml, */*");
    if (!request.containsHeader("Accept-Charset"))
        request.addHeader("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");

    if (App.getConfig().logToConsole())
        App.logv("Parser: Fetching %s", request.getURI());

    long started = System.currentTimeMillis();

    initRequest(request);//from   ww w. ja va2 s . c om

    try {
        synchronized (mHttpClient) {
            HttpContext context = new BasicHttpContext();

            StringBuilder log = null;

            if (App.getConfig().logHttp()) {
                log = new StringBuilder();

                log.append(String.format("URL: %s\n", request.getURI()));

                log.append("Headers: \n");
                for (Header h : request.getAllHeaders())
                    log.append(String.format("  '%s': '%s'\n", h.getName(), h.getValue()));

                log.append("Cookies: \n");
                for (Cookie c : mHttpClient.getCookieStore().getCookies())
                    log.append(String.format("  '%s': '%s'\n", c.getName(), c.getValue()));

                log.append("Query Elements: \n");

                if (inputs != null) {
                    for (NameValuePair p : inputs)
                        log.append(String.format("  '%s': '%s'\n", p.getName(), p.getValue()));
                } else {
                    log.append("  [empty]\n");
                }
            }

            try {
                mLastResponse = mHttpClient.execute(request, context);
            } catch (SocketTimeoutException e) {
                throw new ParserException(mContext, R.string.error_timed_out);
            }

            try {
                if (mLastResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    HttpUriRequest currentReq = (HttpUriRequest) context
                            .getAttribute(ExecutionContext.HTTP_REQUEST);
                    HttpHost currentHost = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);

                    this.mLastUrl = currentHost.toURI() + currentReq.getURI();
                }
            } catch (Exception e) {
                if (App.getConfig().logToConsole()) {
                    App.logv("Unable to get last URL - see stack:");
                    e.printStackTrace();
                }

                this.mLastUrl = null;
            }

            HttpEntity entity = mLastResponse.getEntity();

            if (entity == null)
                return null;

            InputStream stream = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(stream), 10000);
            StringBuilder builder = new StringBuilder(10000);

            try {
                int read;
                char[] buffer = new char[1000];

                while ((read = reader.read(buffer)) >= 0)
                    builder.append(buffer, 0, read);
            } catch (OutOfMemoryError e) {
                return null;
            }

            stream.close();
            entity.consumeContent();

            String response;

            try {
                response = builder.toString();
            } catch (OutOfMemoryError e) {
                if (App.getConfig().logToConsole())
                    e.printStackTrace();

                return null;
            }

            if (App.getConfig().logHttp()) {
                log.append(String.format("\nResponse: \n%s\n", response));

                writeToFile(
                        generateDatedFilename(
                                "http-log-" + request.getURI().toString().replaceAll("[^A-Za-z0-9]", "_")),
                        log.toString());
            }

            return preparseResponse(response);
        }
    } finally {
        if (App.getConfig().logToConsole())
            displayTimeTaken("Parser: Fetch took", started);
    }
}

From source file:com.FluksoViz.FluksoVizActivity.java

private List<Number> getserwerAPIdata(String SENSOR_KEY, String SENSOR_TOKEN, String INTERVAL)
        throws Exception, IOException {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
    HttpParams params = new BasicHttpParams();
    params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
    params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
    params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);
    HttpClient httpclient2 = new DefaultHttpClient(cm, params);
    HttpParams httpParams = httpclient2.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
    HttpConnectionParams.setSoTimeout(httpParams, 5000);

    HttpResponse response = null;/*from   w  ww .  j  a va2 s. c o m*/
    StatusLine statusLine2 = null;
    try {
        response = httpclient2.execute(new HttpGet("https://" + api_server_ip + "/sensor/" + SENSOR_KEY
                + "?version=1.0&token=" + SENSOR_TOKEN + "&interval=" + INTERVAL + "&unit=watt"));
        statusLine2 = response.getStatusLine();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        throw new IOException("failed ClientProtocolException");
    } catch (SocketTimeoutException ste) {
        ste.printStackTrace();
        throw new IOException("failed SocketTimeoutExeption");
    } catch (IOException e) {
        e.printStackTrace();
        throw new IOException("IO failed API Server down?");
    }

    if (statusLine2.getStatusCode() == HttpStatus.SC_OK) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        out.close();
        String responseString = out.toString().replace("]", "").replace("[", "").replace("nan", "0")
                .replace("\"", "");

        String[] responseArray = responseString.split(",");
        Number[] responseArrayNumber = new Number[responseArray.length];
        for (int numb = 0; numb < (responseArray.length) - 1; numb++) {
            responseArrayNumber[numb] = Integer.parseInt(responseArray[numb]);
        }

        List<Number> series = Arrays.asList(responseArrayNumber);

        return series;

    } else {
        // Closes the connection.
        response.getEntity().getContent().close();
        throw new IOException(statusLine2.getReasonPhrase());
    }

}

From source file:com.FluksoViz.FluksoVizActivity.java

private List<Number> getserwerAPIdata_last2month(String SENSOR_KEY, String SENSOR_TOKEN)
        throws Exception, IOException {
    SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    schemeRegistry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
    HttpParams params = new BasicHttpParams();
    params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
    params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
    params.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, false);

    HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
    ClientConnectionManager cm = new SingleClientConnManager(params, schemeRegistry);
    HttpClient httpclient2 = new DefaultHttpClient(cm, params);
    HttpParams httpParams = httpclient2.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 5000);
    HttpConnectionParams.setSoTimeout(httpParams, 5000);

    /*/*w w w.  j  a v  a  2 s. com*/
     * Get local UTC time (now) to request data to server
     */
    //TODO verify with Bart if shall request UTC or local time (guessed UTC)
    Date d = new Date(); // already return UTC
    //long moja_data = d.getTime() - (d.getTimezoneOffset() * 60 * 1000); // calculate
    // data/time
    // (milliseconds)
    // at local timzone
    //d.setTime(moja_data);

    d.setHours(00);
    d.setSeconds(00);
    d.setMinutes(00);

    HttpResponse response = null;
    StatusLine statusLine2 = null;
    try {
        response = httpclient2.execute(new HttpGet(
                "https://" + api_server_ip + "/sensor/" + SENSOR_KEY + "?version=1.0&token=" + SENSOR_TOKEN
                        + "&start=" + ((d.getTime() / 1000) - 5184000) + "&resolution=day&unit=watt"));

        statusLine2 = response.getStatusLine();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        throw new IOException("failed ClientProtocolException");
    } catch (SocketTimeoutException ste) {
        ste.printStackTrace();
        throw new IOException("failed SocketTimeoutExeption");
    } catch (IOException e) {
        e.printStackTrace();
        throw new IOException("IO failed API Server down?");
    }

    if (statusLine2.getStatusCode() == HttpStatus.SC_OK) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        response.getEntity().writeTo(out);
        out.close();
        String responseString = out.toString().replace("]", "").replace("[", "").replace("nan", "0")
                .replace("\"", "");

        String[] responseArray = responseString.split(",");
        Number[] responseArrayNumber = new Number[responseArray.length];
        for (int numb = 0; numb < (responseArray.length) - 1; numb++) {
            responseArrayNumber[numb] = Integer.parseInt(responseArray[numb]);
        }

        List<Number> series = Arrays.asList(responseArrayNumber);

        return series;

    } else {
        // Closes the connection.
        response.getEntity().getContent().close();
        throw new IOException(statusLine2.getReasonPhrase());
    }

}

From source file:com.FluksoViz.FluksoVizActivity.java

private List<Number> getAPIdata(String IPA, String SENSOR_KEY) throws Exception, IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpParams httpParams = httpclient.getParams();
    HttpConnectionParams.setConnectionTimeout(httpParams, 1000);
    HttpConnectionParams.setSoTimeout(httpParams, 1000);
    StatusLine statusLine = null;//from  www .j  av a2 s.co  m
    HttpResponse response = null;

    try {
        response = httpclient.execute(new HttpGet("http://" + IPA + ":8080/sensor/" + SENSOR_KEY
                + "?version=1.0&interval=minute&unit=watt&callback=realtime"));
        statusLine = response.getStatusLine();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        // Napis3.setText(e.toString());
    } catch (SocketTimeoutException ste) {
        // Napis3.setText(ste.toString());
        ste.printStackTrace();
    } catch (IOException e) {
        // Napis3.setText(e.toString());
        e.printStackTrace();
    }

    if (statusLine != null) {
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            String responseString = out.toString().replace("realtime(", "").replace(")", "").replace("]", "")
                    .replace("[", "").replace("nan", "0").replace("\"", "");

            String[] responseArray = responseString.split(",");
            Number[] responseArrayNumber = new Number[responseArray.length];
            for (int numb = 0; numb < (responseArray.length) - 1; numb++) {
                responseArrayNumber[numb] = Integer.parseInt(responseArray[numb]);
            }
            series = Arrays.asList(responseArrayNumber);
            return series;
        } else {
            // Closes the connection.
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    } else {
        // response.getEntity().getContent().close();
        throw new IOException();
    }

}