Java Examples for android.os.NetworkOnMainThreadException

The following java examples will help you to understand the usage of android.os.NetworkOnMainThreadException. These source code samples are taken from different open source projects.

Example 1
Project: TransfuseSample-master  File: MethodInterceptors.java View source code
@UIThread
public void loadUiThread() {
    try {
        URL url = new URL(LOAD_URL);
        String result = IOUtils.toString(url);
        setResult(result);
    } catch (NetworkOnMainThreadException e) {
        e.printStackTrace();
        setResult("NetworkOnMainThreadException");
    } catch (Exception e) {
        e.printStackTrace();
        setResult(e.getMessage());
    }
}
Example 2
Project: Loop-master  File: BaseFragment.java View source code
@Override
public void onDestroyView() {
    super.onDestroyView();
    Timber.d("onDestroyView()");
    String className = this.getClass().toString();
    Timber.d("onDestroyView() : className - " + className);
    if (this instanceof VideosFragment) {
        String query = ((VideosFragment) this).getQuery();
        Timber.d("onDestroyView() : query - " + query);
    }
    Timber.d("onDestroyView() : calls.size() - " + calls.size());
    for (final Call call : calls) {
        Timber.d("onDestroyView() : call.cancel() - " + call.toString());
        try {
            call.cancel();
        } catch (NetworkOnMainThreadException e) {
            Timber.d("onDestroyView() : NetworkOnMainThreadException thrown");
            e.printStackTrace();
        }
    //            new CancelTask().execute(call);
    //            OkHttpClient client = new OkHttpClient();
    //            client.getDispatcher().getExecutorService().execute(new Runnable() {
    //                @Override
    //                public void run() {
    //                    call.cancel();
    //                }
    //            });
    }
    calls.clear();
}
Example 3
Project: asmack-android-8-4.0.7-master  File: SmackAndroid.java View source code
@Override
public void onReceive(Context context, Intent intent) {
    LOGGER.fine("ConnectivityChange received, calling ResolverConfig.refresh() and Lookup.refreshDefault() in new Thread");
    // Lookup.refreshDefault may cause network I/O. So in order to prevent a NetworkOnMainThreadException,
    // we refresh dnsjava in a new thread.
    // Full stacktrace of the offending call:
    // Caused by: android.os.NetworkOnMainThreadException
    // at android.os.StrictMode.onNetwork(StrictMode.java:1128)
    // at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
    // at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
    // at java.net.InetAddress.getByName(InetAddress.java:289)
    // at org.xbill.DNS.SimpleResolver.<init>(SimpleResolver.java:56)
    // at org.xbill.DNS.SimpleResolver.<init>(SimpleResolver.java:68)
    // at org.xbill.DNS.ExtendedResolver.<init>(ExtendedResolver.java:266)
    // at org.xbill.DNS.Lookup.refreshDefault(Lookup.java:86)
    // at org.xbill.DNS.Lookup.<clinit>(Lookup.java:97)
    Thread thread = new Thread() {

        @Override
        public void run() {
            ResolverConfig.refresh();
            Lookup.refreshDefault();
        }
    };
    thread.setDaemon(true);
    thread.start();
}
Example 4
Project: AndyMark-Arduino-Examples-master  File: MainActivity.java View source code
public void onToggleClicked(View view) {
    switch(view.getId()) {
        case R.id.buttonConnect:
            ip = text.getText().toString();
            //Hint: Right-Click on yellow sign and select "disable check"
            if (ip != null && !ip.isEmpty()) {
                if (connect.isChecked()) {
                    try {
                        //Take the text from editText1 and make it the IP Address
                        roboCop = new RobotOpenRobot(ip);
                        roboCop.connect();
                    } catch (NetworkOnMainThreadException e) {
                        CharSequence text1 = "Type A Correct IP Address OR Check Your Connection";
                        int duration = Toast.LENGTH_LONG;
                        Toast.makeText(getApplicationContext(), text1, duration).show();
                        connect.setChecked(false);
                    }
                } else {
                    roboCop.disable();
                    roboCop.disconnect();
                    enable.setChecked(false);
                }
            } else {
                connect.setChecked(false);
                CharSequence text1 = "Please Type An IP Address";
                int duration = 3;
                Toast.makeText(getApplicationContext(), text1, duration).show();
            }
            break;
        case R.id.buttonEnable:
            boolean click = ((ToggleButton) view).isChecked();
            try {
                if (connect.isChecked() == false) {
                    enable.setChecked(false);
                    CharSequence text = "Please Connect First";
                    int duration = 3;
                    Toast.makeText(getApplicationContext(), text, duration).show();
                } else if (click) {
                    roboCop.connect();
                    roboCop.enable();
                    //Set the OnChangeListeners up 
                    VerticalSeekBar seekL = (VerticalSeekBar) findViewById(R.id.seekBarL);
                    seekL.setOnSeekBarChangeListener(new OnChangeVerticalSeekBarListener(txtLeft, roboCop, MainActivity.this.getApplicationContext(), connect, enable, ip));
                    VerticalSeekBar seekR = (VerticalSeekBar) findViewById(R.id.seekBarR);
                    seekR.setOnSeekBarChangeListener(new OnChangeVerticalSeekBarListener(txtRight, roboCop, MainActivity.this.getApplicationContext(), connect, enable, ip));
                } else {
                    roboCop.disable();
                }
            } catch (NullPointerException e) {
                CharSequence text = "Please Connect First";
                int duration = 3;
                Toast.makeText(getApplicationContext(), text, duration).show();
                ToggleButton enable = (ToggleButton) findViewById(R.id.buttonEnable);
                enable.setChecked(false);
            }
            break;
        default:
            break;
    }
}
Example 5
Project: Fast-Android-Networking-master  File: Utils.java View source code
public static ANError getErrorForNetworkOnMainThreadOrConnection(Exception e) {
    ANError error = new ANError(e);
    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB && e instanceof NetworkOnMainThreadException) {
        error.setErrorDetail(ANConstants.NETWORK_ON_MAIN_THREAD_ERROR);
    } else {
        error.setErrorDetail(ANConstants.CONNECTION_ERROR);
    }
    error.setErrorCode(0);
    return error;
}
Example 6
Project: PacketSender-Android-master  File: PacketListenerService.java View source code
// Do the long-running work in here
protected Void doInBackground(Packet... params) {
    Log.d("SendPacketsTask", DataStorage.FILE_LINE("length" + params.length));
    Packet fetchedPacket = params[0];
    Log.d("SendPacketsTask", DataStorage.FILE_LINE("send packet " + fetchedPacket.toString()));
    //if(1+1 == 2) return null;
    if (fetchedPacket.tcpOrUdp.equalsIgnoreCase("tcp")) {
        UpdateNotification("Send TCP: " + fetchedPacket.toIP, ":" + fetchedPacket.port);
    } else {
        UpdateNotification("Send UDP: " + fetchedPacket.toIP, ":" + fetchedPacket.port);
        //dataStore.SavePacket(storepacket);
        try {
            ByteBuffer buf = ByteBuffer.allocate(fetchedPacket.data.length);
            buf.clear();
            buf.put(fetchedPacket.data);
            buf.flip();
            udpserver.send(buf, new InetSocketAddress(fetchedPacket.toIP, fetchedPacket.port));
            fetchedPacket.fromIP = "You";
            fetchedPacket.nowMe();
            dataStore.saveTrafficPacket(fetchedPacket);
            Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    try {
        Socket clientSocket;
        InetSocketAddress translateSocket = new InetSocketAddress(fetchedPacket.toIP, fetchedPacket.port);
        clientSocket = new Socket(translateSocket.getHostName(), translateSocket.getPort());
        // 2 second timeout
        clientSocket.setSoTimeout(2000);
        DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
        DataInputStream in = new DataInputStream(clientSocket.getInputStream());
        out.write(fetchedPacket.data);
        Packet savePacket = fetchedPacket.duplicate();
        savePacket.nowMe();
        savePacket.fromIP = "You";
        fetchedPacket.nowMe();
        dataStore.saveTrafficPacket(savePacket);
        Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));
        byte[] buffer = new byte[1024];
        int received = in.read(buffer);
        if (received > 0) {
            byte[] bufferConvert = new byte[received];
            System.arraycopy(buffer, 0, bufferConvert, 0, received);
            Log.i("service", DataStorage.FILE_LINE("FROM SERVER: " + Packet.toHex(bufferConvert)));
            savePacket = fetchedPacket.duplicate();
            savePacket.nowMe();
            savePacket.data = bufferConvert;
            savePacket.fromIP = fetchedPacket.toIP;
            savePacket.fromPort = fetchedPacket.port;
            savePacket.toIP = "You";
            savePacket.port = fetchedPacket.fromPort;
            fetchedPacket.nowMe();
            dataStore.saveTrafficPacket(savePacket);
            Log.d("service", DataStorage.FILE_LINE("sendBroadcast"));
        }
        out.close();
        in.close();
        clientSocket.close();
    } catch (SocketTimeoutException e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        Log.i("service", DataStorage.FILE_LINE("SocketTimeoutException: " + sw.toString()));
    } catch (NetworkOnMainThreadException e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        Log.w("service", DataStorage.FILE_LINE("NetworkOnMainThreadException: " + sw.toString()));
    } catch (UnknownHostException e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        Log.i("service", DataStorage.FILE_LINE("UnknownHostException: " + sw.toString()));
        Log.i("service", DataStorage.FILE_LINE("Saving the error to packet."));
        fetchedPacket.errorString = "Unknown host";
        fetchedPacket.nowMe();
        dataStore.saveTrafficPacket(fetchedPacket);
    } catch (IOException e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        Log.w("service", DataStorage.FILE_LINE("IOException: " + sw.toString()));
        Log.i("service", DataStorage.FILE_LINE("Saving the error to packet."));
        fetchedPacket.errorString = "Connection error";
        fetchedPacket.nowMe();
        dataStore.saveTrafficPacket(fetchedPacket);
    } catch (Exception e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        Log.w("service", DataStorage.FILE_LINE("Exception: " + sw.toString()));
    }
    return null;
}
Example 7
Project: AppMall-master  File: Downloader.java View source code
/**
     * @Title: getFileSizeByNetwork
     * @Description: get file size from network and update listBeans
     * @param bean
     * @return
     * @return: boolean
     */
private boolean getFileSizeByNetwork(DownloadBean bean) {
    //        HttpURLConnection connection = null;
    long fileSize = bean.fileSize;
    try {
        //resolve android.os.NetworkOnMainThreadException
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        String terminalId = AppStorePreference.getTerminalID(mContext);
        JSONObject downloadJson = ApiService.getDownloadFileJson(terminalId, bean.downloadId);
        //get file size from network if file size is not initialized
        if (fileSize <= 0) {
            //            	HttpClient client = new DefaultHttpClient();
            //https request
            HttpClient client = AsyncHttpClient.getDefaultHttpClient();
            HttpPost request = new HttpPost(bean.url);
            request.setHeader("Content-Type", "application/json;charset=UTF8");
            request.setEntity(new StringEntity(downloadJson.toString()));
            HttpResponse response = client.execute(request);
            int resopnseCode = response.getStatusLine().getStatusCode();
            if (resopnseCode != 200 && resopnseCode != 206) {
                callBackError("http return code error:" + resopnseCode);
                return false;
            }
            // get file size
            fileSize = response.getEntity().getContentLength();
            mBean.fileSize = fileSize;
            if (fileSize <= 0) {
                callBackError("Can't get file size from server:" + fileSize);
                return false;
            }
            //there is no free space both in sdcard and internal
            if (!hasSpaceInSDCard()) {
                return false;
            }
            long range = fileSize / mThreadCount;
            // update listBean
            for (int i = 0; i < mThreadCount - 1; i++) {
                DownloadBean subBean = mBeans.get(i);
                subBean.fileSize = fileSize;
                subBean.startPosition = i * range;
                subBean.endPosition = (i + 1) * range - 1;
            }
            DownloadBean subBean = mBeans.get(mThreadCount - 1);
            subBean.fileSize = fileSize;
            subBean.startPosition = (mThreadCount - 1) * range;
            subBean.endPosition = fileSize - 1;
            // update database
            if (mDBOper != null) {
                mDBOper.updateTaskCompleteSize(mBeans, mBean.url);
            } else {
                callBackError("getFileSizeByNetwork error��Maybe EngineDBOperator is Null.");
                throw new DownloaderErrorException("getFileSizeByNetwork error��Maybe EngineDBOperator is Null.");
            }
            return true;
        } else {
            // exit directly when file size > 0
            return true;
        }
    } catch (Exception e) {
        callBackError("Time out when get file size from server");
        e.printStackTrace();
    }
    return false;
}
Example 8
Project: azure-storage-android-master  File: ExecutionEngine.java View source code
/**
     * Executes an operation and enforces a retrypolicy to handle any potential errors
     * 
     * @param <CLIENT_TYPE>
     *            The type of the service client
     * @param <PARENT_TYPE>
     *            The type of the parent object, i.e. CloudBlobContainer for downloadAttributes etc.
     * @param <RESULT_TYPE>
     *            The type of the expected result
     * @param client
     *            the service client associated with the request
     * @param parentObject
     *            the parent object
     * @param task
     *            the StorageRequest to execute
     * @param policyFactory
     *            the factory used to generate a new retry policy instance
     * @param opContext
     *            an object used to track the execution of the operation
     * @return the result of the operation
     * @throws StorageException
     *             an exception representing any error which occurred during the operation.
     */
public static <CLIENT_TYPE, PARENT_TYPE, RESULT_TYPE> RESULT_TYPE executeWithRetry(final CLIENT_TYPE client, final PARENT_TYPE parentObject, final StorageRequest<CLIENT_TYPE, PARENT_TYPE, RESULT_TYPE> task, final RetryPolicyFactory policyFactory, final OperationContext opContext) throws StorageException {
    RetryPolicy policy = null;
    if (policyFactory == null) {
        policy = new RetryNoRetry();
    } else {
        policy = policyFactory.createInstance(opContext);
        // if the returned policy is null, set to not retry
        if (policy == null) {
            policy = new RetryNoRetry();
        }
    }
    int currentRetryCount = 0;
    StorageException translatedException = null;
    HttpURLConnection request = null;
    final long startTime = new Date().getTime();
    while (true) {
        try {
            // 1-4: setup the request
            request = setupStorageRequest(client, parentObject, task, currentRetryCount, opContext);
            Logger.info(opContext, LogConstants.START_REQUEST, request.getURL(), request.getRequestProperty(Constants.HeaderConstants.DATE));
            // 5. Potentially upload data
            if (task.getSendStream() != null) {
                Logger.info(opContext, LogConstants.UPLOAD);
                final StreamMd5AndLength descriptor = Utility.writeToOutputStream(task.getSendStream(), request.getOutputStream(), task.getLength(), false, /* rewindStream */
                false, /* calculate MD5 */
                opContext, task.getRequestOptions());
                task.validateStreamWrite(descriptor);
                Logger.info(opContext, LogConstants.UPLOADDONE);
            }
            Utility.logHttpRequest(request, opContext);
            // 6. Process the request - Get response
            RequestResult currResult = task.getResult();
            currResult.setStartDate(new Date());
            Logger.info(opContext, LogConstants.GET_RESPONSE);
            currResult.setStatusCode(request.getResponseCode());
            currResult.setStatusMessage(request.getResponseMessage());
            currResult.setStopDate(new Date());
            currResult.setServiceRequestID(BaseResponse.getRequestId(request));
            currResult.setEtag(BaseResponse.getEtag(request));
            currResult.setRequestDate(BaseResponse.getDate(request));
            currResult.setContentMD5(BaseResponse.getContentMD5(request));
            // 7. Fire ResponseReceived Event
            ExecutionEngine.fireResponseReceivedEvent(opContext, request, task.getResult());
            Logger.info(opContext, LogConstants.RESPONSE_RECEIVED, currResult.getStatusCode(), currResult.getServiceRequestID(), currResult.getContentMD5(), currResult.getEtag(), currResult.getRequestDate());
            Utility.logHttpResponse(request, opContext);
            // 8. Pre-process response to check if there was an exception. Do Response parsing (headers etc).
            Logger.info(opContext, LogConstants.PRE_PROCESS);
            RESULT_TYPE result = task.preProcessResponse(parentObject, client, opContext);
            Logger.info(opContext, LogConstants.PRE_PROCESS_DONE);
            if (!task.isNonExceptionedRetryableFailure()) {
                // 9. Post-process response. Read stream from server.
                Logger.info(opContext, LogConstants.POST_PROCESS);
                result = task.postProcessResponse(request, parentObject, client, opContext, result);
                Logger.info(opContext, LogConstants.POST_PROCESS_DONE);
                // Success return result and drain the input stream.
                if ((task.getResult().getStatusCode() >= 200) && (task.getResult().getStatusCode() < 300)) {
                    if (request != null) {
                        InputStream inStream = request.getInputStream();
                        // This is just an optimization to improve socket reuse.
                        try {
                            Utility.writeToOutputStream(inStream, null, -1, false, false, null, task.getRequestOptions());
                        } catch (final IOException ex) {
                        } catch (StorageException e) {
                        } finally {
                            inStream.close();
                        }
                    }
                }
                Logger.info(opContext, LogConstants.COMPLETE);
                return result;
            } else {
                Logger.warn(opContext, LogConstants.UNEXPECTED_RESULT_OR_EXCEPTION);
                // The task may have already parsed an exception.
                translatedException = task.materializeException(opContext);
                task.getResult().setException(translatedException);
                // throw on non retryable status codes: 501, 505, blob type mismatch
                if (task.getResult().getStatusCode() == HttpURLConnection.HTTP_NOT_IMPLEMENTED || task.getResult().getStatusCode() == HttpURLConnection.HTTP_VERSION || translatedException.getErrorCode().equals(StorageErrorCodeStrings.INVALID_BLOB_TYPE)) {
                    throw translatedException;
                }
            }
        } catch (final NetworkOnMainThreadException e) {
            translatedException = new StorageException("NetworkOnMainThreadException", SR.NETWORK_ON_MAIN_THREAD_EXCEPTION, -1, null, e);
            task.getResult().setException(translatedException);
            Logger.error(opContext, LogConstants.UNRETRYABLE_EXCEPTION, e.getClass().getName(), e.getMessage());
            throw translatedException;
        } catch (final StorageException e) {
            task.getResult().setStatusCode(e.getHttpStatusCode());
            task.getResult().setStatusMessage(e.getMessage());
            task.getResult().setException(e);
            Logger.warn(opContext, LogConstants.RETRYABLE_EXCEPTION, e.getClass().getName(), e.getMessage());
            translatedException = e;
        } catch (final Exception e) {
            Logger.warn(opContext, LogConstants.RETRYABLE_EXCEPTION, e.getClass().getName(), e.getMessage());
            translatedException = StorageException.translateException(task, e, opContext);
            task.getResult().setException(translatedException);
        } finally {
            opContext.setClientTimeInMs(new Date().getTime() - startTime);
            // 10. Fire RequestCompleted Event
            if (task.isSent()) {
                ExecutionEngine.fireRequestCompletedEvent(opContext, request, task.getResult());
            }
        }
        // Evaluate Retry Policy
        Logger.info(opContext, LogConstants.RETRY_CHECK, currentRetryCount, task.getResult().getStatusCode(), translatedException == null ? null : translatedException.getMessage());
        task.setCurrentLocation(getNextLocation(task.getCurrentLocation(), task.getLocationMode()));
        Logger.info(opContext, LogConstants.NEXT_LOCATION, task.getCurrentLocation(), task.getLocationMode());
        RetryContext retryContext = new RetryContext(currentRetryCount++, task.getResult(), task.getCurrentLocation(), task.getLocationMode());
        RetryInfo retryInfo = policy.evaluate(retryContext, opContext);
        if (retryInfo == null) {
            // policy does not allow for retry
            Logger.error(opContext, LogConstants.DO_NOT_RETRY_POLICY, translatedException == null ? null : translatedException.getMessage());
            throw translatedException;
        } else if (Utility.validateMaxExecutionTimeout(task.getRequestOptions().getOperationExpiryTimeInMs(), retryInfo.getRetryInterval())) {
            // maximum execution time would be exceeded by current time plus retry interval delay
            TimeoutException timeoutException = new TimeoutException(SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION);
            translatedException = new StorageException(StorageErrorCodeStrings.OPERATION_TIMED_OUT, SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION, Constants.HeaderConstants.HTTP_UNUSED_306, null, timeoutException);
            task.initialize(opContext);
            task.getResult().setException(translatedException);
            Logger.error(opContext, LogConstants.DO_NOT_RETRY_TIMEOUT, translatedException == null ? null : translatedException.getMessage());
            throw translatedException;
        } else {
            // attempt to retry
            task.setCurrentLocation(retryInfo.getTargetLocation());
            task.setLocationMode(retryInfo.getUpdatedLocationMode());
            Logger.info(opContext, LogConstants.RETRY_INFO, task.getCurrentLocation(), task.getLocationMode());
            try {
                ExecutionEngine.fireRetryingEvent(opContext, task.getConnection(), task.getResult(), retryContext);
                Logger.info(opContext, LogConstants.RETRY_DELAY, retryInfo.getRetryInterval());
                Thread.sleep(retryInfo.getRetryInterval());
            } catch (final InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}
Example 9
Project: logging-log4j2-master  File: LoggerContext.java View source code
/**
     * Sets the Configuration to be used.
     *
     * @param config The new Configuration.
     * @return The previous Configuration.
     */
private Configuration setConfiguration(final Configuration config) {
    if (config == null) {
        LOGGER.error("No configuration found for context '{}'.", contextName);
        // No change, return the current configuration.
        return this.configuration;
    }
    configLock.lock();
    try {
        final Configuration prev = this.configuration;
        config.addListener(this);
        final ConcurrentMap<String, String> map = config.getComponent(Configuration.CONTEXT_PROPERTIES);
        try {
            // LOG4J2-719 network access may throw android.os.NetworkOnMainThreadException
            map.putIfAbsent("hostName", NetUtils.getLocalHostname());
        } catch (final Exception ex) {
            LOGGER.debug("Ignoring {}, setting hostName to 'unknown'", ex.toString());
            map.putIfAbsent("hostName", "unknown");
        }
        map.putIfAbsent("contextName", contextName);
        config.start();
        this.configuration = config;
        updateLoggers();
        if (prev != null) {
            prev.removeListener(this);
            prev.stop();
        }
        firePropertyChangeEvent(new PropertyChangeEvent(this, PROPERTY_CONFIG, prev, config));
        try {
            Server.reregisterMBeansAfterReconfigure();
        } catch (final LinkageErrorException |  e) {
            LOGGER.error("Could not reconfigure JMX", e);
        }
        // AsyncLoggers update their nanoClock when the configuration changes
        Log4jLogEvent.setNanoClock(configuration.getNanoClock());
        return prev;
    } finally {
        configLock.unlock();
    }
}
Example 10
Project: athere-android-master  File: ExecutionEngine.java View source code
/**
     * Executes an operation and enforces a retrypolicy to handle any potential errors
     * 
     * @param <CLIENT_TYPE>
     *            The type of the service client
     * @param <PARENT_TYPE>
     *            The type of the parent object, i.e. CloudBlobContainer for downloadAttributes etc.
     * @param <RESULT_TYPE>
     *            The type of the expected result
     * @param client
     *            the service client associated with the request
     * @param parentObject
     *            the parent object
     * @param task
     *            the StorageRequest to execute
     * @param policyFactory
     *            the factory used to generate a new retry policy instance
     * @param opContext
     *            an object used to track the execution of the operation
     * @return the result of the operation
     * @throws StorageException
     *             an exception representing any error which occurred during the operation.
     */
public static <CLIENT_TYPE, PARENT_TYPE, RESULT_TYPE> RESULT_TYPE executeWithRetry(final CLIENT_TYPE client, final PARENT_TYPE parentObject, final StorageRequest<CLIENT_TYPE, PARENT_TYPE, RESULT_TYPE> task, final RetryPolicyFactory policyFactory, final OperationContext opContext) throws StorageException {
    RetryPolicy policy = null;
    if (policyFactory == null) {
        policy = new RetryNoRetry();
    } else {
        policy = policyFactory.createInstance(opContext);
        // if the returned policy is null, set to not retry
        if (policy == null) {
            policy = new RetryNoRetry();
        }
    }
    int currentRetryCount = 0;
    StorageException translatedException = null;
    HttpURLConnection request = null;
    final long startTime = new Date().getTime();
    while (true) {
        try {
            // 1-4: setup the request
            request = setupStorageRequest(client, parentObject, task, currentRetryCount, opContext);
            Logger.info(opContext, LogConstants.START_REQUEST, request.getURL(), request.getRequestProperty(Constants.HeaderConstants.DATE));
            // 5. Potentially upload data
            if (task.getSendStream() != null) {
                Logger.info(opContext, LogConstants.UPLOAD);
                final StreamMd5AndLength descriptor = Utility.writeToOutputStream(task.getSendStream(), request.getOutputStream(), task.getLength(), false, /* rewindStream */
                false, /* calculate MD5 */
                opContext, task.getRequestOptions());
                task.validateStreamWrite(descriptor);
                Logger.info(opContext, LogConstants.UPLOADDONE);
            }
            // 6. Process the request - Get response
            RequestResult currResult = task.getResult();
            currResult.setStartDate(new Date());
            Logger.info(opContext, LogConstants.GET_RESPONSE);
            currResult.setStatusCode(request.getResponseCode());
            currResult.setStatusMessage(request.getResponseMessage());
            currResult.setStopDate(new Date());
            currResult.setServiceRequestID(BaseResponse.getRequestId(request));
            currResult.setEtag(BaseResponse.getEtag(request));
            currResult.setRequestDate(BaseResponse.getDate(request));
            currResult.setContentMD5(BaseResponse.getContentMD5(request));
            // 7. Fire ResponseReceived Event
            ExecutionEngine.fireResponseReceivedEvent(opContext, request, task.getResult());
            Logger.info(opContext, LogConstants.RESPONSE_RECEIVED, currResult.getStatusCode(), currResult.getServiceRequestID(), currResult.getContentMD5(), currResult.getEtag());
            // 8. Pre-process response to check if there was an exception. Do Response parsing (headers etc).
            Logger.info(opContext, LogConstants.PRE_PROCESS);
            RESULT_TYPE result = task.preProcessResponse(parentObject, client, opContext);
            Logger.info(opContext, LogConstants.PRE_PROCESS_DONE);
            if (!task.isNonExceptionedRetryableFailure()) {
                // 9. Post-process response. Read stream from server.
                Logger.info(opContext, LogConstants.POST_PROCESS);
                result = task.postProcessResponse(request, parentObject, client, opContext, result);
                Logger.info(opContext, LogConstants.POST_PROCESS_DONE);
                // Success return result and drain the input stream.
                if ((task.getResult().getStatusCode() >= 200) && (task.getResult().getStatusCode() < 300)) {
                    if (request != null) {
                        InputStream inStream = request.getInputStream();
                        // This is just an optimization to improve socket reuse.
                        try {
                            Utility.writeToOutputStream(inStream, null, -1, false, false, null, task.getRequestOptions());
                        } catch (final IOException ex) {
                        } catch (StorageException e) {
                        } finally {
                            inStream.close();
                        }
                    }
                }
                Logger.info(opContext, LogConstants.COMPLETE);
                return result;
            } else {
                Logger.warn(opContext, LogConstants.UNEXPECTED_RESULT_OR_EXCEPTION);
                // The task may have already parsed an exception.
                translatedException = task.materializeException(task.getConnection(), opContext);
                task.getResult().setException(translatedException);
                // throw on non retryable status codes: 501, 505, blob type mismatch
                if (task.getResult().getStatusCode() == HttpURLConnection.HTTP_NOT_IMPLEMENTED || task.getResult().getStatusCode() == HttpURLConnection.HTTP_VERSION || translatedException.getErrorCode().equals(StorageErrorCodeStrings.INVALID_BLOB_TYPE)) {
                    throw translatedException;
                }
            }
        } catch (final TimeoutException e) {
            Logger.warn(opContext, LogConstants.RETRYABLE_EXCEPTION, e.getClass().getName(), e.getMessage());
            translatedException = StorageException.translateException(task.getConnection(), e, opContext);
            task.getResult().setException(translatedException);
        } catch (final SocketTimeoutException e) {
            Logger.warn(opContext, LogConstants.RETRYABLE_EXCEPTION, e.getClass().getName(), e.getMessage());
            translatedException = new StorageException(StorageErrorCodeStrings.OPERATION_TIMED_OUT, "The operation did not complete in the specified time.", -1, null, e);
            task.getResult().setException(translatedException);
        } catch (final IOException e) {
            if (e.getCause() instanceof TimeoutException) {
                translatedException = new StorageException(StorageErrorCodeStrings.OPERATION_TIMED_OUT, SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION, Constants.HeaderConstants.HTTP_UNUSED_306, null, (Exception) e.getCause());
                task.getResult().setException(translatedException);
                Logger.error(opContext, LogConstants.UNRETRYABLE_EXCEPTION, e.getCause().getClass().getName(), e.getCause().getMessage());
                throw translatedException;
            } else {
                Logger.warn(opContext, LogConstants.RETRYABLE_EXCEPTION, e.getClass().getName(), e.getMessage());
                translatedException = StorageException.translateException(task.getConnection(), e, opContext);
                task.getResult().setException(translatedException);
            }
        } catch (final NetworkOnMainThreadException e) {
            translatedException = new StorageException("NetworkOnMainThreadException", SR.NETWORK_ON_MAIN_THREAD_EXCEPTION, -1, null, e);
            task.getResult().setException(translatedException);
            Logger.error(opContext, LogConstants.UNRETRYABLE_EXCEPTION, e.getClass().getName(), e.getMessage());
            throw translatedException;
        } catch (final InvalidKeyException e) {
            translatedException = StorageException.translateException(task.getConnection(), e, opContext);
            task.getResult().setException(translatedException);
            Logger.error(opContext, LogConstants.UNRETRYABLE_EXCEPTION, e.getClass().getName(), e.getMessage());
            throw translatedException;
        } catch (final URISyntaxException e) {
            translatedException = StorageException.translateException(task.getConnection(), e, opContext);
            task.getResult().setException(translatedException);
            Logger.error(opContext, LogConstants.UNRETRYABLE_EXCEPTION, e.getClass().getName(), e.getMessage());
            throw translatedException;
        } catch (final TableServiceException e) {
            task.getResult().setStatusCode(e.getHttpStatusCode());
            task.getResult().setStatusMessage(e.getMessage());
            task.getResult().setException(e);
            if (!e.isRetryable()) {
                Logger.error(opContext, LogConstants.UNRETRYABLE_EXCEPTION, e.getClass().getName(), e.getMessage());
                throw e;
            } else {
                Logger.warn(opContext, LogConstants.RETRYABLE_EXCEPTION, e.getClass().getName(), e.getMessage());
                translatedException = e;
            }
        } catch (final StorageException e) {
            task.getResult().setException(e);
            Logger.error(opContext, LogConstants.UNRETRYABLE_EXCEPTION, e.getClass().getName(), e.getMessage());
            throw e;
        } catch (final Exception e) {
            translatedException = StorageException.translateException(task.getConnection(), e, opContext);
            task.getResult().setException(translatedException);
            Logger.error(opContext, LogConstants.UNRETRYABLE_EXCEPTION, e.getClass().getName(), e.getMessage());
            throw translatedException;
        } finally {
            opContext.setClientTimeInMs(new Date().getTime() - startTime);
            // 10. Fire RequestCompleted Event
            if (task.isSent()) {
                ExecutionEngine.fireRequestCompletedEvent(opContext, request, task.getResult());
            }
        }
        // Evaluate Retry Policy
        Logger.info(opContext, LogConstants.RETRY_CHECK, currentRetryCount, task.getResult().getStatusCode(), translatedException == null ? null : translatedException.getMessage());
        task.setCurrentLocation(getNextLocation(task.getCurrentLocation(), task.getLocationMode()));
        Logger.info(opContext, LogConstants.NEXT_LOCATION, task.getCurrentLocation(), task.getLocationMode());
        RetryContext retryContext = new RetryContext(currentRetryCount++, task.getResult(), task.getCurrentLocation(), task.getLocationMode());
        RetryInfo retryInfo = policy.evaluate(retryContext, opContext);
        if (retryInfo == null) {
            // policy does not allow for retry
            Logger.error(opContext, LogConstants.DO_NOT_RETRY_POLICY, translatedException == null ? null : translatedException.getMessage());
            throw translatedException;
        } else if (Utility.validateMaxExecutionTimeout(task.getRequestOptions().getOperationExpiryTimeInMs(), retryInfo.getRetryInterval())) {
            // maximum execution time would be exceeded by current time plus retry interval delay
            TimeoutException timeoutException = new TimeoutException(SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION);
            translatedException = new StorageException(StorageErrorCodeStrings.OPERATION_TIMED_OUT, SR.MAXIMUM_EXECUTION_TIMEOUT_EXCEPTION, Constants.HeaderConstants.HTTP_UNUSED_306, null, timeoutException);
            task.initialize(opContext);
            task.getResult().setException(translatedException);
            Logger.error(opContext, LogConstants.DO_NOT_RETRY_TIMEOUT, translatedException == null ? null : translatedException.getMessage());
            throw translatedException;
        } else {
            // attempt to retry
            task.setCurrentLocation(retryInfo.getTargetLocation());
            task.setLocationMode(retryInfo.getUpdatedLocationMode());
            Logger.info(opContext, LogConstants.RETRY_INFO, task.getCurrentLocation(), task.getLocationMode());
            try {
                ExecutionEngine.fireRetryingEvent(opContext, task.getConnection(), task.getResult(), retryContext);
                Logger.info(opContext, LogConstants.RETRY_DELAY, retryInfo.getRetryInterval());
                Thread.sleep(retryInfo.getRetryInterval());
            } catch (final InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }
    }
}
Example 11
Project: RhymeCity-master  File: SafeCompositeSubscription.java View source code
public void clear() {
    try {
        subscriptions.clear();
    } catch (NetworkOnMainThreadException exception) {
    }
}
Example 12
Project: droidparts-master  File: HTTPWorker.java View source code
public static void throwIfNetworkOnMainThreadException(Exception e) {
    if (e.getClass().getName().equals("android.os.NetworkOnMainThreadException")) {
        throw (RuntimeException) e;
    }
}
Example 13
Project: android-job-master  File: DemoSyncEngine.java View source code
@WorkerThread
public boolean sync() {
    if (Looper.myLooper() == Looper.getMainLooper()) {
        throw new NetworkOnMainThreadException();
    }
    SystemClock.sleep(1_000);
    // successful 90% of the time
    boolean success = Math.random() > 0.1;
    saveSuccess(success);
    return success;
}
Example 14
Project: VBoxManager-master  File: InfoFragment.java View source code
private void safePopulate() {
    try {
        populateViews();
    } catch (NetworkOnMainThreadException e) {
        Log.e(TAG, "Populate error", e);
        new LoadInfoTask().execute(_machine);
    }
}