List of usage examples for java.net SocketTimeoutException printStackTrace
public void printStackTrace()
From source file:net.sf.sahi.util.Utils.java
public static byte[] getBytes(final InputStream in, final int contentLength) throws IOException { BufferedInputStream bin = new BufferedInputStream(in, BUFFER_SIZE); if (contentLength != -1) { int totalBytesRead = 0; byte[] buffer = new byte[contentLength]; while (totalBytesRead < contentLength) { int bytesRead = -1; try { bytesRead = bin.read(buffer, totalBytesRead, contentLength - totalBytesRead); } catch (EOFException e) { }//w ww . j ava 2s.c om if (bytesRead == -1) { break; } totalBytesRead += bytesRead; } return buffer; } else { ByteArrayOutputStream byteArOut = new ByteArrayOutputStream(); BufferedOutputStream bout = new BufferedOutputStream(byteArOut); try { int totalBytesRead = 0; byte[] buffer = new byte[BUFFER_SIZE]; while (true) { int bytesRead = -1; try { bytesRead = bin.read(buffer); } catch (EOFException e) { } if (bytesRead == -1) { break; } bout.write(buffer, 0, bytesRead); totalBytesRead += bytesRead; } } catch (SocketTimeoutException ste) { ste.printStackTrace(); } bout.flush(); bout.close(); return byteArOut.toByteArray(); } }
From source file:net.arccotangent.pacchat.net.KeyUpdateClient.java
public void run() { Socket socket;//from w w w . j a v a 2 s . co m BufferedReader input; BufferedWriter output; kuc_log.i("Connecting to server at " + server_ip); try { socket = new Socket(); socket.connect(new InetSocketAddress(InetAddress.getByName(server_ip), Server.PORT), 1000); input = new BufferedReader(new InputStreamReader(socket.getInputStream())); output = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); } catch (SocketTimeoutException e) { kuc_log.e("Connection to server timed out!"); e.printStackTrace(); return; } catch (ConnectException e) { kuc_log.e("Connection to server was refused!"); e.printStackTrace(); return; } catch (UnknownHostException e) { kuc_log.e("You entered an invalid IP address!"); e.printStackTrace(); return; } catch (IOException e) { kuc_log.e("Error connecting to server!"); e.printStackTrace(); return; } try { kuc_log.i("Requesting a key update."); output.write("302 request key update"); output.newLine(); output.flush(); kuc_log.i("Awaiting response from server."); String update = input.readLine(); switch (update) { case "303 update": kuc_log.i("Server accepted update request, sending public key."); String pubkeyB64 = Base64.encodeBase64String(Main.getKeypair().getPublic().getEncoded()); output.write(pubkeyB64); output.newLine(); output.flush(); output.close(); break; case "304 no update": kuc_log.i("Server rejected update request, closing connection."); input.close(); output.close(); break; case "305 update unavailable": kuc_log.i("Server cannot update at this time, try again later."); input.close(); output.close(); break; default: kuc_log.i("Server sent back invalid response"); input.close(); output.close(); break; } } catch (IOException e) { kuc_log.e("Error in key update request!"); e.printStackTrace(); } }
From source file:com.dimasdanz.kendalipintu.util.JSONParser.java
public JSONObject makeHttpRequest(String url, String method, List<NameValuePair> params) { try {// w w w .j a v a2 s .c om HttpParams httpParameters = new BasicHttpParams(); HttpConnectionParams.setSoTimeout(httpParameters, so_timeout); HttpConnectionParams.setConnectionTimeout(httpParameters, co_timeout); if (method == "POST") { DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); HttpPost httpPost = new HttpPost(url); httpPost.setEntity(new UrlEncodedFormEntity(params)); HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } else if (method == "GET") { DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters); String paramString = URLEncodedUtils.format(params, "utf-8"); url += "?" + paramString; HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); HttpEntity httpEntity = httpResponse.getEntity(); is = httpEntity.getContent(); } } catch (SocketTimeoutException e) { Log.e("SocketTimeoutException", "SocketTimeoutException"); e.printStackTrace(); return null; } catch (UnsupportedEncodingException e) { Log.e("UnsupportedEncodingException", "UnsupportedEncodingException"); e.printStackTrace(); return null; } catch (ClientProtocolException e) { Log.e("ClientProtocolException", "ClientProtocolException"); e.printStackTrace(); return null; } catch (IOException e) { Log.e("IOException", "IOException"); e.printStackTrace(); return null; } try { BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); StringBuilder sb = new StringBuilder(); String line = null; while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } is.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Buffer Error : " + e.toString()); return null; } try { jObj = new JSONObject(json); } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); return null; } return jObj; }
From source file:org.digitalcampus.oppia.task.CourseSizeTask.java
@Override protected String doInBackground(Payload... params) { payload = params[0];/* ww w . j a va 2 s .com*/ 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) { fileSize = String.format("%.2f", megabyte) + "MB"; } else { fileSize = String.format("%.2f", kilobytes) + "KB"; } } 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 fileSize; }
From source file:com.concentricsky.android.khanacademy.util.CaptionManager.java
/** * Get a {@link WebResourceResponse} with subtitles for the video with the given youtube id. * /* ww w .java 2s. c om*/ * The response contains a UTF-8 encoded json object with the subtitles received * from universalsubtitles.org. * * @param youtubeId The youtube id of the video whose subtitles we need. * @return The {@link WebResourceResponse} with the subtitles, or {@code null} in case of error or if none are found. */ public WebResourceResponse fetchRawCaptionResponse(String youtubeId) { Log.d(LOG_TAG, "fetchRawCaptionResponse"); String youtube_url = "http://www.youtube.com/watch?v=" + youtubeId; try { URL url = new URL(String.format(subtitleFormat, youtube_url, "en")); URLConnection connection = url.openConnection(); connection.setConnectTimeout(CONNECT_TIMEOUT); connection.setUseCaches(true); InputStream in = null; try { in = connection.getInputStream(); } catch (SocketTimeoutException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); //various exceptions including at least ConnectException and UnknownHostException can happen if we're offline } return in == null ? null : new WebResourceResponse("application/json", "UTF-8", in); } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; }
From source file:com.boundary.camel.component.url.UrlClient.java
protected void connect() { try {//from w ww. j a v a 2s . co m URL url = configuration.toURL(); LOG.info("attempting connection with url: {}", url); connection = (HttpURLConnection) url.openConnection(); configureConnection(connection); connection.connect(); setResponseCode(connection.getResponseCode()); setInputStream(connection.getInputStream()); BufferedReader is = new BufferedReader(new InputStreamReader(getInputStream())); String line; StringBuffer sb = new StringBuffer(); while ((line = is.readLine()) != null) { sb.append(line); } setResponseBody(sb.toString()); setURLStatus(OK); } catch (UnknownHostException u) { setURLStatus(UNKNOWN_HOST); setResponseCode(HTTP_BAD_GATEWAY); if (LOG.isDebugEnabled()) { u.printStackTrace(); } } catch (SocketTimeoutException s) { setURLStatus(TIME_OUT); setResponseCode(HTTP_INTERNAL_ERROR); if (LOG.isDebugEnabled()) { s.printStackTrace(); } } catch (IOException i) { setURLStatus(ERROR); setResponseCode(HTTP_INTERNAL_ERROR); if (LOG.isDebugEnabled()) { i.printStackTrace(); } } catch (Exception e) { setURLStatus(ERROR); setResponseCode(HTTP_INTERNAL_ERROR); if (LOG.isDebugEnabled()) { e.printStackTrace(); } } }
From source file:net.nym.library.http.HttpRequest.java
/** * Override this method to perform a computation on a background thread. The * specified parameters are the parameters passed to {@link #execute} * by the caller of this task./*from ww w .j ava 2s. com*/ * <p/> * This method can call {@link #publishProgress} to publish updates * on the UI thread. * * @param params The parameters of the task. * @return A result, defined by the subclass of this task. * @see #onPreExecute() * @see #onPostExecute * @see #publishProgress */ @Override protected String doInBackground(Object... params) { String result = null; try { switch (mMethod) { case GET: result = Request.get(mUrl, mParams, maxRetry); break; case POST: result = Request.post(mUrl, mParams, mFiles, maxRetry); break; case PUT: break; case TRACE: break; case Options: break; case Delete: break; } } catch (SocketTimeoutException e) { e.printStackTrace(); mErrorHandler.sendEmptyMessage(RequestListener.TIMEOUT_ERROR); } catch (ConnectTimeoutException e) { e.printStackTrace(); mErrorHandler.sendEmptyMessage(RequestListener.TIMEOUT_ERROR); } catch (MalformedURLException e) { e.printStackTrace(); mErrorHandler.sendEmptyMessage(RequestListener.TIMEOUT_ERROR); } catch (IOException e) { e.printStackTrace(); mErrorHandler.sendEmptyMessage(RequestListener.IO_ERROR); } Log.i("result=%s", result + ""); android.util.Log.i("result", String.format("result=%s", result + "")); return result; }
From source file:org.digitalcampus.oppia.task.DownloadCourseTask.java
@Override protected Payload doInBackground(Payload... params) { Payload payload = params[0];/*from ww w .j av a 2 s .co m*/ Course dm = (Course) payload.getData().get(0); DownloadProgress 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); HttpURLConnection 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(); String localFileName = dm.getShortname() + "-" + String.format("%.0f", dm.getVersionId()) + ".zip"; dp.setMessage(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.framework.testcase.testrail.APIClient.java
private Object sendRequest(String method, String uri, Object data) throws MalformedURLException, IOException { URL url = new URL(this.m_url + uri); // Create the connection object and set the required HTTP method // (GET/POST) and headers (content type and basic auth). HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.addRequestProperty("Content-Type", "application/json"); String auth = getAuthorization(this.m_user, this.m_password); conn.addRequestProperty("Authorization", "Basic " + auth); if (method.equalsIgnoreCase("POST")) { // Add the POST arguments, if any. We just serialize the passed // data object (i.e. a dictionary) and then add it to the // request body. if (data != null) { byte[] block = JSONValue.toJSONString(data).getBytes("UTF-8"); conn.setDoOutput(true);/*w w w.java2 s . co m*/ OutputStream ostream = conn.getOutputStream(); ostream.write(block); ostream.flush(); } } // Execute the actual web request (if it wasn't already initiated // by getOutputStream above) and record any occurred errors (we use // the error stream in this case). int status = 0; try { status = conn.getResponseCode(); } catch (SocketTimeoutException e) { e.printStackTrace(); System.err.println("the request is timeout from the server ,we quite the test"); } catch (SSLHandshakeException ex) { ex.printStackTrace(); System.err.println("the request is Remote host closed connection during handshake"); } InputStream istream; if (status != 200) { istream = conn.getErrorStream(); if (istream == null) { new Exception("TestRail API return HTTP " + status + " (No additional error message received)"); } } else { istream = conn.getInputStream(); } // Read the response body, if any, and deserialize it from JSON. String text = ""; if (istream != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(istream, "UTF-8")); String line; while ((line = reader.readLine()) != null) { text += line; text += System.getProperty("line.separator"); } reader.close(); } Object result; if (text != "") { result = JSONValue.parse(text); } else { result = new JSONObject(); } // Check for any occurred errors and add additional details to // the exception message, if any (e.g. the error message returned // by TestRail). if (status != 200) { String error = "No additional error message received"; if (result != null && result instanceof JSONObject) { JSONObject obj = (JSONObject) result; if (obj.containsKey("error")) { error = '"' + (String) obj.get("error") + '"'; } } new Exception("TestRail API returned HTTP " + status + "(" + error + ")"); } return result; }
From source file:com.haulmont.cuba.uberjar.ServerRunner.java
protected void stop(int port, String key) { try {//from w w w.j a v a 2s .c o m try (Socket s = new Socket(InetAddress.getByName("127.0.0.1"), port)) { s.setSoTimeout(STOP_TIMEOUT * 1000); try (OutputStream out = s.getOutputStream()) { out.write((key + "\r\nstop\r\n").getBytes(StandardCharsets.UTF_8)); out.flush(); System.out.println(String.format("Waiting %,d seconds for server to stop", STOP_TIMEOUT)); LineNumberReader lin = new LineNumberReader( new InputStreamReader(s.getInputStream(), StandardCharsets.UTF_8)); String response; while ((response = lin.readLine()) != null) { System.out.println(String.format("Received \"%s\"", response)); if ("Stopped".equals(response)) { System.out.println("Server reports itself as Stopped"); } } } } } catch (SocketTimeoutException e) { System.out.println("Timed out waiting for stop confirmation"); } catch (Exception e) { e.printStackTrace(); } }