List of usage examples for java.net SocketTimeoutException printStackTrace
public void printStackTrace()
From source file:org.digitalcampus.oppia.task.DownloadAllCourseTask.java
@Override protected Payload doInBackground(Payload... params) { payload = params[0];//from w w w. j a v a 2 s . c o m dm = (Course) payload.getData().get(0); dp = new DownloadProgress(); try { HTTPConnectionUtils client = new HTTPConnectionUtils(ctx); String url = client.createUrlWithCredentials(dm.getDownloadUrl()); Log.d(TAG, "Downloading:" + url); URL u = new URL(url); c = (HttpURLConnection) u.openConnection(); c.setRequestMethod("GET"); c.setDoOutput(true); c.connect(); c.setConnectTimeout( Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_connection), ctx.getString(R.string.prefServerTimeoutConnection)))); c.setReadTimeout(Integer.parseInt(prefs.getString(ctx.getString(R.string.prefs_server_timeout_response), ctx.getString(R.string.prefServerTimeoutResponse)))); int fileLength = c.getContentLength(); long size = fileLength; double kilobytes = 0; double megabyte = 0; kilobytes = (size / 1024); megabyte = (kilobytes / 1024); String localFileName = dm.getShortname() + "-" + String.format("%.0f", dm.getVersionId()) + ".zip"; if (kilobytes > 1000) { //size_value=String.valueOf(megabyte); dp.setMessage("This file is " + String.format("%.2f", megabyte) + "MB" + "\n" + localFileName); } else { //size_value=String.valueOf(kilobytes); dp.setMessage("This file is " + String.format("%.2f", kilobytes) + "KB" + "\n" + localFileName); } dp.setProgress(0); publishProgress(dp); Log.d(TAG, "saving to: " + localFileName); FileOutputStream f = new FileOutputStream(new File(MobileLearning.DOWNLOAD_PATH, localFileName)); InputStream in = c.getInputStream(); byte[] buffer = new byte[1024]; int len1 = 0; long total = 0; int progress = 0; while ((len1 = in.read(buffer)) > 0) { total += len1; progress = (int) (total * 100) / fileLength; if (progress > 0) { dp.setProgress(progress); publishProgress(dp); } f.write(buffer, 0, len1); } f.close(); dp.setProgress(100); publishProgress(dp); dp.setMessage(ctx.getString(R.string.download_complete)); publishProgress(dp); payload.setResult(true); } catch (ClientProtocolException cpe) { if (!MobileLearning.DEVELOPER_MODE) { BugSenseHandler.sendException(cpe); } else { cpe.printStackTrace(); } payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_connection)); } catch (SocketTimeoutException ste) { if (!MobileLearning.DEVELOPER_MODE) { BugSenseHandler.sendException(ste); } else { ste.printStackTrace(); } payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_connection)); } catch (IOException ioe) { if (!MobileLearning.DEVELOPER_MODE) { BugSenseHandler.sendException(ioe); } else { ioe.printStackTrace(); } payload.setResult(false); payload.setResultResponse(ctx.getString(R.string.error_connection)); } return payload; }
From source file:com.predic8.membrane.core.transport.http.HttpServerRunnable.java
public void run() { try {/*from w ww. ja v a2 s . co m*/ while (true) { srcReq = new Request(); srcReq.read(srcIn, true); exchange.setTimeReqReceived(System.currentTimeMillis()); if (srcReq.getHeader().getProxyConnection() != null) { srcReq.getHeader().add(Header.CONNECTION, srcReq.getHeader().getProxyConnection()); srcReq.getHeader().removeFields(Header.PROXY_CONNECTION); } process(); if (srcReq.isCONNECTRequest()) { log.debug("stopping HTTP Server Thread after establishing an HTTP connect"); return; } if (!srcReq.isKeepAlive() || !exchange.getResponse().isKeepAlive()) { if (exchange.getTargetConnection() != null) { exchange.getTargetConnection().close(); exchange.setTargetConnection(null); } break; } if (exchange.getResponse().isRedirect()) { break; } exchange = new Exchange(); exchange.setServerThread(this); } } catch (SocketTimeoutException e) { log.debug("Socket of thread " + counter + " timed out"); } catch (SocketException se) { log.info("client socket closed"); } catch (IOException e) { e.printStackTrace(); } catch (EndOfStreamException e) { log.info("stream closed"); } catch (AbortException e) { log.info("exchange aborted."); } catch (ErrorReadingStartLineException e) { log.info("Client connection terminated before start line was read. Start line so far: (" + e.getStartLine() + ")"); } catch (Exception e) { e.printStackTrace(); } finally { if (srcReq.isCONNECTRequest()) return; closeConnections(); } }
From source file:info.varden.irclinqed.dcc.FileSendThread.java
@Override public void onIPSelected(String ipAddress) { try {/*w w w . j ava 2s . c o m*/ if (!this.file.exists()) { return; } this.server = new ServerSocket(0); this.server.setSoTimeout(60000); DCCRequestPacket packet = null; String filename = this.file.getName(); if (filename.split(" ").length > 1) { filename = "\"" + filename + "\""; } if (this.thread instanceof IRCThread) { packet = new DCCRequestPacket(this.il, (IRCThread) this.thread, this.target, DCCType.SEND, filename, ipAddress, server.getLocalPort(), this.totalSize); } else if (this.thread instanceof DCCThread) { VirtualIRCThread thrd = new VirtualIRCThread(this.il, (DCCThread) this.thread); packet = new DCCRequestPacket(this.il, thrd, this.target, DCCType.SEND, filename, ipAddress, server.getLocalPort(), this.totalSize); } else { this.server.close(); return; } packet.send(); if (this.cancel) { this.server.close(); return; } this.message = "Waiting for connection..."; Socket s = this.server.accept(); this.overlay.unload(); this.gfp = new GuiFileProgress(this.il, this); this.il.guiQueue.add(this.gfp); InputStream i = new FileInputStream(this.file); this.cos = new CountingOutputStream(s.getOutputStream()); byte[] buff = new byte[1024]; int k = -1; while ((k = i.read(buff)) > -1 && !this.cancel) { this.cos.write(buff, 0, k); s.getInputStream().read(new byte[4]); } s.shutdownInput(); s.shutdownOutput(); s.close(); this.server.close(); i.close(); this.gfp.unload(); } catch (SocketTimeoutException e) { this.overlay.unload(); Util.extractUtil(this.thread).writeToChat(MessageType.DCC_ERROR, "File send timed out."); } catch (IOException e) { e.printStackTrace(); } this.overlay.unload(); }
From source file:com.ovrhere.android.careerstack.model.CareersStackOverflowModel.java
@SuppressWarnings("unused") @Override/*from w w w .j ava 2 s . c om*/ public void onException(Exception exception) { if (DEBUG) { Log.d(LOGTAG, "Exception in object: " + this.hashCode()); } try { throw exception; } catch (SocketTimeoutException e) { if (DEBUG && VERBOSE) { Log.e(LOGTAG, "Timeout: " + e); e.printStackTrace(); } notifyHandlers(ERROR_REQUEST_TIMEOUT, null); } catch (IOException e) { if (DEBUG && VERBOSE) { Log.e(LOGTAG, "IO exception, likely the xml giving up: " + e); e.printStackTrace(); } notifyHandlers(ERROR_REQUEST_FAILED, null); } catch (Exception e) { if (DEBUG && VERBOSE) { Log.e(LOGTAG, "This. This should not be happening... " + e); e.printStackTrace(); } notifyHandlers(ERROR_REQUEST_FAILED, null); } }
From source file:com.exampleka.jksonlib.JacksonNetwork.java
@Override public NetworkResponse performRequest(Request<?> request) throws VolleyError { try {// www. j a v a 2 s . c om HttpResponse httpResponse = mHttpStack.performRequest(request, new HashMap<String, String>()); final int statusCode = httpResponse.getStatusLine().getStatusCode(); HttpEntity entity = httpResponse.getEntity(); if (statusCode == -1) { throw new NoConnectionError(); } else if (statusCode == HttpStatus.SC_NOT_MODIFIED && request.getCacheEntry().data != null) { return new JacksonNetworkResponse(statusCode, request.getCacheEntry().data, null, convertHeaders(httpResponse.getAllHeaders())); } else { Map<String, String> headers = convertHeaders(httpResponse.getAllHeaders()); byte[] data = null; InputStream inputStream = null; if (request.shouldCache()) { if (entity != null) { data = entityToBytes(entity); } else { data = new byte[0]; } } else { inputStream = entity.getContent(); } if (((JacksonRequest) request).getAcceptedStatusCodes().contains(statusCode)) { return new JacksonNetworkResponse(statusCode, data, inputStream, headers); } else { VolleyLog .d("Unacceptable statusCode: " + statusCode + " returned for url: " + request.getUrl()); throw new NetworkError(new JacksonNetworkResponse(statusCode, data, inputStream, headers)); } } } catch (SocketTimeoutException e) { throw new TimeoutError(); } catch (ConnectTimeoutException e) { throw new TimeoutError(); } catch (MalformedURLException e) { throw new RuntimeException("Bad URL " + request.getUrl(), e); } catch (IOException e) { e.printStackTrace(); throw new NoConnectionError(e); } }
From source file:org.odk.collect.android.tasks.DownloadFormsTask.java
@Override protected HashMap<String, String> doInBackground(ArrayList<FormDetails>... values) { ArrayList<FormDetails> toDownload = values[0]; int total = toDownload.size(); int count = 1; HashMap<String, String> result = new HashMap<String, String>(); for (int i = 0; i < total; i++) { FormDetails fd = toDownload.get(i); publishProgress(fd.formName, Integer.valueOf(count).toString(), Integer.valueOf(total).toString()); String message = ""; try {//from w w w . j a va 2 s. c o m // get the xml file // if we've downloaded a duplicate, this gives us the file File dl = downloadXform(fd.formName, fd.downloadUrl); String[] projection = { FormsColumns._ID, FormsColumns.FORM_FILE_PATH }; String[] selectionArgs = { dl.getAbsolutePath() }; String selection = FormsColumns.FORM_FILE_PATH + "=?"; Cursor alreadyExists = Collect.getInstance().getContentResolver().query(FormsColumns.CONTENT_URI, projection, selection, selectionArgs, null); Uri uri = null; if (alreadyExists.getCount() <= 0) { // doesn't exist, so insert it ContentValues v = new ContentValues(); v.put(FormsColumns.FORM_FILE_PATH, dl.getAbsolutePath()); HashMap<String, String> formInfo = FileUtils.parseXML(dl); v.put(FormsColumns.DISPLAY_NAME, formInfo.get(FileUtils.TITLE)); v.put(FormsColumns.MODEL_VERSION, formInfo.get(FileUtils.MODEL)); v.put(FormsColumns.UI_VERSION, formInfo.get(FileUtils.UI)); v.put(FormsColumns.JR_FORM_ID, formInfo.get(FileUtils.FORMID)); v.put(FormsColumns.SUBMISSION_URI, formInfo.get(FileUtils.SUBMISSIONURI)); uri = Collect.getInstance().getContentResolver().insert(FormsColumns.CONTENT_URI, v); } else { alreadyExists.moveToFirst(); uri = Uri.withAppendedPath(FormsColumns.CONTENT_URI, alreadyExists.getString(alreadyExists.getColumnIndex(FormsColumns._ID))); } if (fd.manifestUrl != null) { Cursor c = Collect.getInstance().getContentResolver().query(uri, null, null, null, null); if (c.getCount() > 0) { // should be exactly 1 c.moveToFirst(); String error = downloadManifestAndMediaFiles( c.getString(c.getColumnIndex(FormsColumns.FORM_MEDIA_PATH)), fd, count, total); if (error != null) { message += error; } } } else { // TODO: manifest was null? Log.e(t, "Manifest was null. PANIC"); } } catch (SocketTimeoutException se) { se.printStackTrace(); message += se.getMessage(); } catch (Exception e) { e.printStackTrace(); message += e.getMessage(); } count++; if (message.equalsIgnoreCase("")) { message = Collect.getInstance().getString(R.string.success); } result.put(fd.formName, message); } return result; }
From source file:com.mpower.mintel.android.tasks.DownloadFormsTask.java
@Override protected HashMap<String, String> doInBackground(ArrayList<FormDetails>... values) { ArrayList<FormDetails> toDownload = values[0]; int total = toDownload.size(); int count = 1; HashMap<String, String> result = new HashMap<String, String>(); for (int i = 0; i < total; i++) { FormDetails fd = toDownload.get(i); publishProgress(fd.formName, Integer.valueOf(count).toString(), Integer.valueOf(total).toString()); String message = ""; try {/*ww w . j a va 2s. c o m*/ // get the xml file // if we've downloaded a duplicate, this gives us the file File dl = downloadXform(fd.formName, fd.downloadUrl); String[] projection = { FormsColumns._ID, FormsColumns.FORM_FILE_PATH }; String[] selectionArgs = { dl.getAbsolutePath() }; String selection = FormsColumns.FORM_FILE_PATH + "=?"; Cursor alreadyExists = MIntel.getInstance().getContentResolver().query(FormsColumns.CONTENT_URI, projection, selection, selectionArgs, null); Uri uri = null; if (alreadyExists.getCount() <= 0) { // doesn't exist, so insert it ContentValues v = new ContentValues(); v.put(FormsColumns.FORM_FILE_PATH, dl.getAbsolutePath()); HashMap<String, String> formInfo = FileUtils.parseXML(dl); v.put(FormsColumns.DISPLAY_NAME, formInfo.get(FileUtils.TITLE)); v.put(FormsColumns.MODEL_VERSION, formInfo.get(FileUtils.MODEL)); v.put(FormsColumns.UI_VERSION, formInfo.get(FileUtils.UI)); v.put(FormsColumns.JR_FORM_ID, formInfo.get(FileUtils.FORMID)); v.put(FormsColumns.SUBMISSION_URI, formInfo.get(FileUtils.SUBMISSIONURI)); uri = MIntel.getInstance().getContentResolver().insert(FormsColumns.CONTENT_URI, v); } else { alreadyExists.moveToFirst(); uri = Uri.withAppendedPath(FormsColumns.CONTENT_URI, alreadyExists.getString(alreadyExists.getColumnIndex(FormsColumns._ID))); } if (fd.manifestUrl != null) { Cursor c = MIntel.getInstance().getContentResolver().query(uri, null, null, null, null); if (c.getCount() > 0) { // should be exactly 1 c.moveToFirst(); String error = downloadManifestAndMediaFiles( c.getString(c.getColumnIndex(FormsColumns.FORM_MEDIA_PATH)), fd, count, total); if (error != null) { message += error; } } } else { // TODO: manifest was null? Log.e(t, "Manifest was null. PANIC"); } } catch (SocketTimeoutException se) { se.printStackTrace(); message += se.getMessage(); } catch (Exception e) { e.printStackTrace(); if (e.getCause() != null) { message += e.getCause().getMessage(); } else { message += e.getMessage(); } } count++; if (message.equalsIgnoreCase("")) { message = MIntel.getInstance().getString(R.string.success); } result.put(fd.formName, message); } return result; }
From source file:com.ovrhere.android.currencyconverter.model.CurrencyExchangeRateAsyncModel.java
@Override public void onException(Exception exception) { if (DEBUG) {//from w w w.j av a2 s . c o m Log.d(LOGTAG, "Exception in object: " + this.hashCode()); } try { throw exception; } catch (SocketTimeoutException e) { if (DEBUG) { e.printStackTrace(); } notifyHandlers(ERROR_REQUEST_TIMEOUT, null); } catch (IOException e) { if (DEBUG) { e.printStackTrace(); } notifyHandlers(ERROR_REQUEST_FAILED, null); } catch (Exception e) { if (DEBUG) { e.printStackTrace(); } notifyHandlers(ERROR_REQUEST_FAILED, null); } isUpdating = false; disposeHelper(); }
From source file:com.mpower.daktar.android.tasks.DownloadFormsTask.java
@Override protected HashMap<String, String> doInBackground(final ArrayList<FormDetails>... values) { final ArrayList<FormDetails> toDownload = values[0]; final int total = toDownload.size(); int count = 1; final HashMap<String, String> result = new HashMap<String, String>(); for (int i = 0; i < total; i++) { final FormDetails fd = toDownload.get(i); publishProgress(fd.formName, Integer.valueOf(count).toString(), Integer.valueOf(total).toString()); String message = ""; try {//from ww w .j a v a2s .co m // get the xml file // if we've downloaded a duplicate, this gives us the file final File dl = downloadXform(fd.formName, fd.downloadUrl); final String[] projection = { BaseColumns._ID, FormsColumns.FORM_FILE_PATH }; final String[] selectionArgs = { dl.getAbsolutePath() }; final String selection = FormsColumns.FORM_FILE_PATH + "=?"; final Cursor alreadyExists = MIntel.getInstance().getContentResolver() .query(FormsColumns.CONTENT_URI, projection, selection, selectionArgs, null); Uri uri = null; if (alreadyExists.getCount() <= 0) { // doesn't exist, so insert it final ContentValues v = new ContentValues(); v.put(FormsColumns.FORM_FILE_PATH, dl.getAbsolutePath()); final HashMap<String, String> formInfo = FileUtils.parseXML(dl); v.put(FormsColumns.DISPLAY_NAME, formInfo.get(FileUtils.TITLE)); v.put(FormsColumns.MODEL_VERSION, formInfo.get(FileUtils.MODEL)); v.put(FormsColumns.UI_VERSION, formInfo.get(FileUtils.UI)); v.put(FormsColumns.JR_FORM_ID, formInfo.get(FileUtils.FORMID)); v.put(FormsColumns.SUBMISSION_URI, formInfo.get(FileUtils.SUBMISSIONURI)); uri = MIntel.getInstance().getContentResolver().insert(FormsColumns.CONTENT_URI, v); } else { alreadyExists.moveToFirst(); uri = Uri.withAppendedPath(FormsColumns.CONTENT_URI, alreadyExists.getString(alreadyExists.getColumnIndex(BaseColumns._ID))); } if (fd.manifestUrl != null) { final Cursor c = MIntel.getInstance().getContentResolver().query(uri, null, null, null, null); if (c.getCount() > 0) { // should be exactly 1 c.moveToFirst(); final String error = downloadManifestAndMediaFiles( c.getString(c.getColumnIndex(FormsColumns.FORM_MEDIA_PATH)), fd, count, total); if (error != null) { message += error; } } } else { // TODO: manifest was null? Log.e(t, "Manifest was null. PANIC"); } } catch (final SocketTimeoutException se) { se.printStackTrace(); message += se.getMessage(); } catch (final Exception e) { e.printStackTrace(); if (e.getCause() != null) { message += e.getCause().getMessage(); } else { message += e.getMessage(); } } count++; if (message.equalsIgnoreCase("")) { message = MIntel.getInstance().getString(R.string.success); } result.put(fd.formName, message); } return result; }
From source file:com.sandklef.coachapp.http.HttpAccess.java
public void uploadTrainingPhaseVideo(String clubUri, String videoUuid, String fileName) throws HttpAccessException, IOException { HttpURLConnection connection = null; DataOutputStream outputStream = null; DataInputStream inputStream = null; String pathToOurFile = fileName; String urlServer = urlBase + HttpSettings.API_VERSION + HttpSettings.PATH_SEPARATOR + HttpSettings.VIDEO_URL_PATH + HttpSettings.UUID_PATH + videoUuid + HttpSettings.PATH_SEPARATOR + HttpSettings.UPLOAD_PATH;/*from ww w. j a v a 2s. co m*/ Log.d(LOG_TAG, "Upload server url: " + urlServer); Log.d(LOG_TAG, "Upload file: " + fileName); int bytesRead, bytesAvailable, bufferSize; byte[] buffer; FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile)); URL url = new URL(urlServer); connection = (HttpURLConnection) url.openConnection(); Log.d(LOG_TAG, "connection: " + connection + " uploading data to video: " + videoUuid); // Allow Inputs & Outputs connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod(HttpSettings.HTTP_POST); // int timeout = LocalStorage.getInstance().getnetworkTimeout(); Log.d(LOG_TAG, "timeout: " + timeout); connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout); connection.setRequestProperty("X-Token", LocalStorage.getInstance().getLatestUserToken()); connection.addRequestProperty("X-Instance", LocalStorage.getInstance().getCurrentClub()); connection.setRequestProperty("Connection", "close"); Log.d(LOG_TAG, " upload propoerties: " + connection.getRequestProperties()); outputStream = new DataOutputStream(connection.getOutputStream()); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // Read file bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { Log.d(LOG_TAG, " writing data to stream (" + bytesRead + " / " + bytesAvailable + ")"); outputStream.write(buffer, 0, bufferSize); Log.d(LOG_TAG, " writing data to stream -"); bytesAvailable = fileInputStream.available(); Log.d(LOG_TAG, " writing data to stream -"); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } outputStream.flush(); outputStream.close(); // Responses from the server (code and message) fileInputStream.close(); int serverResponseCode = 0; long before = System.currentTimeMillis(); try { Log.d(LOG_TAG, " ... writing done, getting response code"); serverResponseCode = connection.getResponseCode(); Log.d(LOG_TAG, " ... writing done, getting response message"); String serverResponseMessage = connection.getResponseMessage(); Log.d(LOG_TAG, "ServerCode:" + serverResponseCode); Log.d(LOG_TAG, "serverResponseMessage:" + serverResponseMessage); } catch (java.net.SocketTimeoutException e) { Log.d(LOG_TAG, " ... getting response code, got an exception, print stacktrace"); e.printStackTrace(); throw new HttpAccessException("Network timeout reached", e, HttpAccessException.NETWORK_SLOW); } long after = System.currentTimeMillis(); long diff = after - before; Log.d(LOG_TAG, "diff: " + diff + "ms " + diff / 1000 + "s"); if (diff > LocalStorage.getInstance().getnetworkTimeout()) { throw new HttpAccessException("Network timeout reached", HttpAccessException.NETWORK_SLOW); } if (serverResponseCode >= 409) { throw new HttpAccessException("Failed uploading trainingphase video, access denied", HttpAccessException.CONFLICT_ERROR); } if (serverResponseCode < 500 && serverResponseCode >= 400) { throw new HttpAccessException("Failed uploading trainingphase video, access denied", HttpAccessException.ACCESS_ERROR); } try { Log.d(LOG_TAG, " ... disconnecting"); connection.disconnect(); } catch (Exception e) { Log.d(LOG_TAG, " ... disconnecting, got an exception, print stacktrace"); e.printStackTrace(); } }