List of usage examples for java.net HttpURLConnection setReadTimeout
public void setReadTimeout(int timeout)
From source file:com.adaptris.core.http.JdkHttpProducer.java
@Override protected AdaptrisMessage doRequest(AdaptrisMessage msg, ProduceDestination destination, long timeout) throws ProduceException { AdaptrisMessage reply = defaultIfNull(getMessageFactory()).newMessage(); ThreadLocalCredentials threadLocalCreds = null; try {/* w w w .j ava 2 s. com*/ URL url = new URL(destination.getDestination(msg)); if (getPasswordAuthentication() != null) { Authenticator.setDefault(AdapterResourceAuthenticator.getInstance()); threadLocalCreds = ThreadLocalCredentials.getInstance(url.toString()); threadLocalCreds.setThreadCredentials(getPasswordAuthentication()); AdapterResourceAuthenticator.getInstance().addAuthenticator(threadLocalCreds); } HttpURLConnection http = (HttpURLConnection) url.openConnection(); http.setRequestMethod(methodToUse(msg).name()); http.setInstanceFollowRedirects(handleRedirection()); http.setDoInput(true); http.setConnectTimeout(Long.valueOf(timeout).intValue()); http.setReadTimeout(Long.valueOf(timeout).intValue()); // ProxyUtil.applyBasicProxyAuthorisation(http); addHeaders(msg, http); if (getContentTypeKey() != null && msg.containsKey(getContentTypeKey())) { http.setRequestProperty(CONTENT_TYPE, msg.getMetadataValue(getContentTypeKey())); } // if (getAuthorisation() != null) { // http.setRequestProperty(AUTHORIZATION, getAuthorisation()); // } // logHeaders("Request Information", "Request Method : " + http.getRequestMethod(), http.getRequestProperties().entrySet()); sendMessage(msg, http); readResponse(http, reply); // logHeaders("Response Information", http.getResponseMessage(), http.getHeaderFields().entrySet()); } catch (IOException e) { throw new ProduceException(e); } catch (CoreException e) { if (e instanceof ProduceException) { throw (ProduceException) e; } else { throw new ProduceException(e); } } finally { if (threadLocalCreds != null) { threadLocalCreds.removeThreadCredentials(); AdapterResourceAuthenticator.getInstance().removeAuthenticator(threadLocalCreds); } } return reply; }
From source file:com.ivanbratoev.festpal.datamodel.db.external.ExternalDatabaseHandler.java
private HttpURLConnection setupConnection(URL url, Map<String, String> parameters) throws IOException { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(10_000); connection.setConnectTimeout(15_000); connection.setRequestMethod("POST"); connection.setDoInput(true);//from w w w . j a v a2 s . c o m connection.setDoOutput(true); OutputStream os = connection.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); writer.write(buildParametersList(parameters)); writer.flush(); writer.close(); os.close(); return connection; }
From source file:de.alosdev.android.customerschoice.CustomersChoice.java
private void internalConfigureByNetwork(final Context context, String fileAddress) { new AsyncTask<String, Void, Void>() { @Override/*from w w w .j a v a2 s. co m*/ protected Void doInBackground(String... args) { String value = args[0]; try { final SharedPreferences preferences = getPreferences(context); final URL url = new URL(value); log.d(TAG, "read from: ", value); final HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); // set etag header if existing final String fieldEtag = preferences.getString(getPreferencesKey(value, FIELD_ETAG), null); if (null != fieldEtag) { conn.setRequestProperty("If-None-Match", fieldEtag); } // set modified since header if existing final long fieldLastModified = preferences .getLong(getPreferencesKey(value, FIELD_LAST_MODIFIED), 0); if (fieldLastModified > 0) { conn.setIfModifiedSince(fieldLastModified); } conn.connect(); final int response = conn.getResponseCode(); if (HttpStatus.SC_OK == response) { log.d(TAG, "found file"); readFromInputStream(conn.getInputStream()); // writing caching information into preferences final Editor editor = preferences.edit(); editor.putString(getPreferencesKey(value, FIELD_ETAG), conn.getHeaderField("ETag")); editor.putLong(getPreferencesKey(value, FIELD_LAST_MODIFIED), conn.getHeaderFieldDate("Last-Modified", 0)); editor.commit(); } else if (HttpStatus.SC_NOT_MODIFIED == response) { log.i(TAG, "no updates, file not modified: ", value); } else { log.e(TAG, "cannot read from: ", value, " and get following response code:", response); } } catch (MalformedURLException e) { log.e(TAG, e, "the given URL is malformed: ", value); } catch (IOException e) { log.e(TAG, e, "Error during reading the file: ", value); } return null; } }.execute(fileAddress); }
From source file:com.googlecode.jmxtrans.model.output.LibratoWriter.java
private void writeToLibrato(Server server, Query query, List<Result> results) { HttpURLConnection urlConnection = null; try {/*from w ww. j a v a2 s . c o m*/ if (proxy == null) { urlConnection = (HttpURLConnection) url.openConnection(); } else { urlConnection = (HttpURLConnection) url.openConnection(proxy); } urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setReadTimeout(libratoApiTimeoutInMillis); urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8"); urlConnection.setRequestProperty("Authorization", "Basic " + basicAuthentication); urlConnection.setRequestProperty("User-Agent", httpUserAgent); serialize(server, query, results, urlConnection.getOutputStream()); int responseCode = urlConnection.getResponseCode(); if (responseCode != 200) { logger.warn("Failure {}:'{}' to send result to Librato server '{}' with proxy {}, username {}", responseCode, urlConnection.getResponseMessage(), url, proxy, username); } if (logger.isTraceEnabled()) { StringWriter out = new StringWriter(); IOUtils.copy(urlConnection.getInputStream(), out); logger.trace(out.toString()); } } catch (Exception e) { logger.warn("Failure to send result to Librato server '{}' with proxy {}, username {}", url, proxy, username, e); } finally { if (urlConnection != null) { try { InputStream in = urlConnection.getInputStream(); IOUtils.copy(in, NullOutputStream.NULL_OUTPUT_STREAM); IOUtils.closeQuietly(in); InputStream err = urlConnection.getErrorStream(); if (err != null) { IOUtils.copy(err, NullOutputStream.NULL_OUTPUT_STREAM); IOUtils.closeQuietly(err); } } catch (IOException e) { logger.warn("Exception flushing http connection", e); } } } }
From source file:com.db.comserv.main.utilities.HttpCaller.java
@Override @edu.umd.cs.findbugs.annotations.SuppressWarnings(value = "DM_DEFAULT_ENCODING") public HttpResult runRequest(String type, String methodType, URL url, List<Map<String, String>> headers, String requestBody, String sslByPassOption, int connTimeOut, int readTimeout, HttpServletRequest req) throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException, UnsupportedEncodingException, IOException, UnknownHostException, URISyntaxException { StringBuffer response = new StringBuffer(); HttpResult httpResult = new HttpResult(); boolean gzip = false; final long startNano = System.nanoTime(); try {//w ww . j a v a 2 s. c o m URL encodedUrl = new URL(Utility.encodeUrl(url.toString())); HttpURLConnection con = (HttpURLConnection) encodedUrl.openConnection(); TrustModifier.relaxHostChecking(con, sslByPassOption); // connection timeout 5s con.setConnectTimeout(connTimeOut); // read timeout 10s con.setReadTimeout(readTimeout * getQueryCost(req)); methodType = methodType.toUpperCase(); con.setRequestMethod(methodType); sLog.debug("Performing '{}' to '{}'", methodType, ServletUtil.filterUrl(url.toString())); // Get headers & set request property for (int i = 0; i < headers.size(); i++) { Map<String, String> header = headers.get(i); con.setRequestProperty(header.get("headerKey").toString(), header.get("headerValue").toString()); sLog.debug("Setting Header '{}' with value '{}'", header.get("headerKey").toString(), ServletUtil.filterHeaderValue(header.get("headerKey").toString(), header.get("headerValue").toString())); } if (con.getRequestProperty("Accept-Encoding") == null) { con.setRequestProperty("Accept-Encoding", "gzip"); } if (requestBody != null && !requestBody.equals("")) { con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.write(Utility.toUtf8Bytes(requestBody)); wr.flush(); wr.close(); } // push response BufferedReader in = null; String inputLine; List<String> contentEncoding = con.getHeaderFields().get("Content-Encoding"); if (contentEncoding != null) { for (String val : contentEncoding) { if ("gzip".equalsIgnoreCase(val)) { sLog.debug("Gzip enabled response"); gzip = true; break; } } } sLog.debug("Response: '{} {}' with headers '{}'", con.getResponseCode(), con.getResponseMessage(), ServletUtil.buildHeadersForLog(con.getHeaderFields())); if (con.getResponseCode() != 200 && con.getResponseCode() != 201) { if (con.getErrorStream() != null) { if (gzip) { in = new BufferedReader( new InputStreamReader(new GZIPInputStream(con.getErrorStream()), "UTF-8")); } else { in = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8")); } } } else { String[] urlParts = url.toString().split("\\."); if (urlParts.length > 1) { String ext = urlParts[urlParts.length - 1]; if (ext.equalsIgnoreCase("png") || ext.equalsIgnoreCase("jpg") || ext.equalsIgnoreCase("jpeg") || ext.equalsIgnoreCase("gif")) { BufferedImage imBuff; if (gzip) { imBuff = ImageIO.read(new GZIPInputStream(con.getInputStream())); } else { BufferedInputStream bfs = new BufferedInputStream(con.getInputStream()); imBuff = ImageIO.read(bfs); } BufferedImage newImage = new BufferedImage(imBuff.getWidth(), imBuff.getHeight(), BufferedImage.TYPE_3BYTE_BGR); // converting image to greyScale int width = imBuff.getWidth(); int height = imBuff.getHeight(); for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { Color c = new Color(imBuff.getRGB(j, i)); int red = (int) (c.getRed() * 0.21); int green = (int) (c.getGreen() * 0.72); int blue = (int) (c.getBlue() * 0.07); int sum = red + green + blue; Color newColor = new Color(sum, sum, sum); newImage.setRGB(j, i, newColor.getRGB()); } } ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(newImage, "jpg", out); byte[] bytes = out.toByteArray(); byte[] encodedBytes = Base64.encodeBase64(bytes); String base64Src = new String(encodedBytes); int imageSize = ((base64Src.length() * 3) / 4) / 1024; int initialImageSize = imageSize; int maxImageSize = Integer.parseInt(properties.getValue("Reduced_Image_Size")); float quality = 0.9f; if (!(imageSize <= maxImageSize)) { //This means that image size is greater and needs to be reduced. sLog.debug("Image size is greater than " + maxImageSize + " , compressing image."); while (!(imageSize < maxImageSize)) { base64Src = compress(base64Src, quality); imageSize = ((base64Src.length() * 3) / 4) / 1024; quality = quality - 0.1f; DecimalFormat df = new DecimalFormat("#.0"); quality = Float.parseFloat(df.format(quality)); if (quality <= 0.1) { break; } } } sLog.debug("Initial image size was : " + initialImageSize + " Final Image size is : " + imageSize + "Url is : " + url + "quality is :" + quality); String src = "data:image/" + urlParts[urlParts.length - 1] + ";base64," + new String(base64Src); JSONObject joResult = new JSONObject(); joResult.put("Image", src); out.close(); httpResult.setResponseCode(con.getResponseCode()); httpResult.setResponseHeader(con.getHeaderFields()); httpResult.setResponseBody(joResult.toString()); httpResult.setResponseMsg(con.getResponseMessage()); return httpResult; } } if (gzip) { in = new BufferedReader( new InputStreamReader(new GZIPInputStream(con.getInputStream()), "UTF-8")); } else { in = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8")); } } if (in != null) { while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } httpResult.setResponseCode(con.getResponseCode()); httpResult.setResponseHeader(con.getHeaderFields()); httpResult.setResponseBody(response.toString()); httpResult.setResponseMsg(con.getResponseMessage()); } catch (Exception e) { sLog.error("Failed to received HTTP response after timeout", e); httpResult.setTimeout(true); httpResult.setResponseCode(500); httpResult.setResponseMsg("Internal Server Error Timeout"); return httpResult; } return httpResult; }
From source file:com.google.glassware.NotifyServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Respond with OK and status 200 in a timely fashion to prevent redelivery response.setContentType("text/html"); Writer writer = response.getWriter(); writer.append("OK"); writer.close();/*from w w w. j av a 2 s . co m*/ // Get the notification object from the request body (into a string so we // can log it) BufferedReader notificationReader = new BufferedReader(new InputStreamReader(request.getInputStream())); String notificationString = ""; String responseStringForFaceDetection = null; // Count the lines as a very basic way to prevent Denial of Service attacks int lines = 0; String line; while ((line = notificationReader.readLine()) != null) { notificationString += line; lines++; // No notification would ever be this long. Something is very wrong. if (lines > 1000) { throw new IOException("Attempted to parse notification payload that was unexpectedly long."); } } notificationReader.close(); LOG.info("got raw notification " + notificationString); JsonFactory jsonFactory = new JacksonFactory(); // If logging the payload is not as important, use // jacksonFactory.fromInputStream instead. Notification notification = jsonFactory.fromString(notificationString, Notification.class); LOG.info("Got a notification with ID: " + notification.getItemId()); // Figure out the impacted user and get their credentials for API calls String userId = notification.getUserToken(); Credential credential = AuthUtil.getCredential(userId); Mirror mirrorClient = MirrorClient.getMirror(credential); if (notification.getCollection().equals("locations")) { LOG.info("Notification of updated location"); Mirror glass = MirrorClient.getMirror(credential); // item id is usually 'latest' Location location = glass.locations().get(notification.getItemId()).execute(); LOG.info("New location is " + location.getLatitude() + ", " + location.getLongitude()); MirrorClient.insertTimelineItem(credential, new TimelineItem() .setText("Java Quick Start says you are now at " + location.getLatitude() + " by " + location.getLongitude()) .setNotification(new NotificationConfig().setLevel("DEFAULT")).setLocation(location) .setMenuItems(Lists.newArrayList(new MenuItem().setAction("NAVIGATE")))); // This is a location notification. Ping the device with a timeline item // telling them where they are. } else if (notification.getCollection().equals("timeline")) { // Get the impacted timeline item TimelineItem timelineItem = mirrorClient.timeline().get(notification.getItemId()).execute(); LOG.info("Notification impacted timeline item with ID: " + timelineItem.getId()); // If it was a share, and contains a photo, update the photo's caption to // acknowledge that we got it. if (notification.getUserActions().contains(new UserAction().setType("SHARE")) && timelineItem.getAttachments() != null && timelineItem.getAttachments().size() > 0) { String finalresponseForCard = null; String questionString = timelineItem.getText(); if (!questionString.isEmpty()) { String[] questionStringArray = questionString.split(" "); LOG.info(timelineItem.getText() + " is the questions asked by the user"); LOG.info("A picture was taken"); if (questionString.toLowerCase().contains("search") || questionString.toLowerCase().contains("tag") || questionString.toLowerCase().contains("train") || questionString.toLowerCase().contains("mark") || questionString.toLowerCase().contains("recognize") || questionString.toLowerCase().contains("what is")) { //Fetching the image from the timeline InputStream inputStream = downloadAttachment(mirrorClient, notification.getItemId(), timelineItem.getAttachments().get(0)); //converting the image to Base64 Base64 base64Object = new Base64(false); String encodedImageToBase64 = base64Object.encodeToString(IOUtils.toByteArray(inputStream)); //byteArrayForOutputStream.toByteArray() // byteArrayForOutputStream.close(); encodedImageToBase64 = java.net.URLEncoder.encode(encodedImageToBase64, "ISO-8859-1"); //sending the API request LOG.info("Sending request to API"); //For initial protoype we're calling the Alchemy API for detecting the number of Faces using web API call try { String urlParameters = ""; String tag = ""; if (questionString.toLowerCase().contains("tag") || questionString.toLowerCase().contains("mark")) { tag = extractTagFromQuestion(questionString); urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_add&name_space=recognizeObject&user_id=user1&tag=" + tag + "&base64=" + encodedImageToBase64; } else if (questionString.toLowerCase().contains("train")) { urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_train&name_space=recognizeObject&user_id=user1"; } else if (questionString.toLowerCase().contains("search")) { urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_search&name_space=recognizeObject&user_id=user1&base64=" + encodedImageToBase64; } else if (questionString.toLowerCase().contains("recognize") || questionString.toLowerCase().contains("what is")) { urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_recognize&name_space=recognizeObject&user_id=user1&base64=" + encodedImageToBase64; } byte[] postData = urlParameters.getBytes(Charset.forName("UTF-8")); int postDataLength = postData.length; String newrequest = "http://rekognition.com/func/api/"; URL url = new URL(newrequest); HttpURLConnection connectionFaceDetection = (HttpURLConnection) url.openConnection(); // Increase the timeout for reading the response connectionFaceDetection.setReadTimeout(15000); connectionFaceDetection.setDoOutput(true); connectionFaceDetection.setDoInput(true); connectionFaceDetection.setInstanceFollowRedirects(false); connectionFaceDetection.setRequestMethod("POST"); connectionFaceDetection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connectionFaceDetection.setRequestProperty("X-Mashape-Key", "pzFbNRvNM4mshgWJvvdw0wpLp5N1p1X3AX9jsnOhjDUkn5Lvrp"); connectionFaceDetection.setRequestProperty("charset", "utf-8"); connectionFaceDetection.setRequestProperty("Accept", "application/json"); connectionFaceDetection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); connectionFaceDetection.setUseCaches(false); DataOutputStream outputStreamForFaceDetection = new DataOutputStream( connectionFaceDetection.getOutputStream()); outputStreamForFaceDetection.write(postData); BufferedReader inputStreamForFaceDetection = new BufferedReader( new InputStreamReader((connectionFaceDetection.getInputStream()))); StringBuilder responseForFaceDetection = new StringBuilder(); while ((responseStringForFaceDetection = inputStreamForFaceDetection .readLine()) != null) { responseForFaceDetection.append(responseStringForFaceDetection); } //closing all the connections inputStreamForFaceDetection.close(); outputStreamForFaceDetection.close(); connectionFaceDetection.disconnect(); responseStringForFaceDetection = responseForFaceDetection.toString(); LOG.info(responseStringForFaceDetection); JSONObject responseJSONObjectForFaceDetection = new JSONObject( responseStringForFaceDetection); if (questionString.toLowerCase().contains("train") || questionString.contains("tag") || questionString.toLowerCase().contains("mark")) { JSONObject usageKeyFromResponse = responseJSONObjectForFaceDetection .getJSONObject("usage"); finalresponseForCard = usageKeyFromResponse.getString("status"); if (!tag.equals("")) finalresponseForCard = "Object is tagged as " + tag; } else { JSONObject sceneUnderstandingObject = responseJSONObjectForFaceDetection .getJSONObject("scene_understanding"); JSONArray matchesArray = sceneUnderstandingObject.getJSONArray("matches"); JSONObject firstResultFromArray = matchesArray.getJSONObject(0); double percentSureOfObject; //If an score has value 1, then the value type is Integer else the value type is double if (firstResultFromArray.get("score") instanceof Integer) { percentSureOfObject = (Integer) firstResultFromArray.get("score") * 100; } else percentSureOfObject = (Double) firstResultFromArray.get("score") * 100; finalresponseForCard = "The object is " + firstResultFromArray.getString("tag") + ". Match score is" + percentSureOfObject; } //section where if it doesn't contain anything about tag or train } catch (Exception e) { LOG.warning(e.getMessage()); } } else finalresponseForCard = "Could not understand your words"; } else finalresponseForCard = "Could not understand your words"; TimelineItem responseCardForSDKAlchemyAPI = new TimelineItem(); responseCardForSDKAlchemyAPI.setText(finalresponseForCard); responseCardForSDKAlchemyAPI .setMenuItems(Lists.newArrayList(new MenuItem().setAction("READ_ALOUD"))); responseCardForSDKAlchemyAPI.setSpeakableText(finalresponseForCard); responseCardForSDKAlchemyAPI.setSpeakableType("Results are as follows"); responseCardForSDKAlchemyAPI.setNotification(new NotificationConfig().setLevel("DEFAULT")); mirrorClient.timeline().insert(responseCardForSDKAlchemyAPI).execute(); LOG.info("New card added to the timeline"); } else if (notification.getUserActions().contains(new UserAction().setType("LAUNCH"))) { LOG.info("It was a note taken with the 'take a note' voice command. Processing it."); // Grab the spoken text from the timeline card and update the card with // an HTML response (deleting the text as well). String noteText = timelineItem.getText(); String utterance = CAT_UTTERANCES[new Random().nextInt(CAT_UTTERANCES.length)]; timelineItem.setText(null); timelineItem.setHtml(makeHtmlForCard( "<p class='text-auto-size'>" + "Oh, did you say " + noteText + "? " + utterance + "</p>")); timelineItem.setMenuItems(Lists.newArrayList(new MenuItem().setAction("DELETE"))); mirrorClient.timeline().update(timelineItem.getId(), timelineItem).execute(); } else { LOG.warning("I don't know what to do with this notification, so I'm ignoring it."); } } }
From source file:org.jmxtrans.embedded.output.StackdriverWriter.java
/** * Send given metrics to the Stackdriver server using HTTP * //w ww. ja va 2 s . com * @param results * Iterable collection of data points */ @Override public void write(Iterable<QueryResult> results) { logger.debug("Export to '{}', proxy {} metrics {}", url, proxy, results); HttpURLConnection urlConnection = null; try { if (proxy == null) { urlConnection = (HttpURLConnection) url.openConnection(); } else { urlConnection = (HttpURLConnection) url.openConnection(proxy); } urlConnection.setRequestMethod("POST"); urlConnection.setDoInput(true); urlConnection.setDoOutput(true); urlConnection.setReadTimeout(stackdriverApiTimeoutInMillis); urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8"); urlConnection.setRequestProperty("x-stackdriver-apikey", apiKey); serialize(results, urlConnection.getOutputStream()); int responseCode = urlConnection.getResponseCode(); if (responseCode != 200 && responseCode != 201) { exceptionCounter.incrementAndGet(); logger.warn("Failure {}:'{}' to send result to Stackdriver server '{}' with proxy {}", responseCode, urlConnection.getResponseMessage(), url, proxy); } if (logger.isTraceEnabled()) { IoUtils2.copy(urlConnection.getInputStream(), System.out); } } catch (Exception e) { exceptionCounter.incrementAndGet(); logger.warn("Failure to send result to Stackdriver server '{}' with proxy {}", url, proxy, e); } finally { if (urlConnection != null) { try { InputStream in = urlConnection.getInputStream(); IoUtils2.copy(in, IoUtils2.nullOutputStream()); IoUtils2.closeQuietly(in); InputStream err = urlConnection.getErrorStream(); if (err != null) { IoUtils2.copy(err, IoUtils2.nullOutputStream()); IoUtils2.closeQuietly(err); } urlConnection.disconnect(); } catch (IOException e) { logger.warn("Error flushing http connection for one result, continuing"); logger.debug("Stack trace for the http connection, usually a network timeout", e); } } } }
From source file:be.wimsymons.intellij.polopolyimport.PPImporter.java
private void postData(final String name, final Reader reader, final String contentType, final String extraParams) throws IOException { Writer writer = null;/* www .ja v a 2 s. c om*/ LOGGER.info("Doing HTTP POST for " + name); try { URL httpURL = buildURL(target, extraParams); HttpURLConnection httpConnection = (HttpURLConnection) httpURL.openConnection(); httpConnection.setDoInput(true); httpConnection.setDoOutput(true); httpConnection.setUseCaches(false); httpConnection.setRequestMethod("PUT"); httpConnection.setRequestProperty("Content-Type", contentType); httpConnection.setConnectTimeout(2000); httpConnection.setReadTimeout(60000); httpConnection.connect(); if (contentType.contains("UTF-8")) { copyAndFlush(reader, httpConnection.getOutputStream()); } else { writer = new OutputStreamWriter(httpConnection.getOutputStream()); CharStreams.copy(reader, writer); writer.flush(); } int responseCode = httpConnection.getResponseCode(); String responseMessage = httpConnection.getResponseMessage(); if (responseCode < 200 || responseCode >= 300) { failureCount++; PPImportPlugin.doNotify("Import of " + name + " failed: " + responseCode + " - " + responseMessage + "\nCheck the server log for more details.", NotificationType.ERROR); } else { successCount++; } } catch (IOException e) { failureCount++; PPImportPlugin.doNotify("Import of " + name + " failed: " + e.getMessage(), NotificationType.ERROR); } finally { Closeables.close(reader, true); Closeables.close(writer, true); } }
From source file:com.workfront.api.StreamClient.java
private HttpURLConnection createConnection(String spec, String method) throws IOException { URL url = new URL(spec); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if (conn instanceof HttpsURLConnection) { ((HttpsURLConnection) conn).setHostnameVerifier(HOSTNAME_VERIFIER); }/*from www .j a va 2 s .c o m*/ conn.setAllowUserInteraction(false); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); conn.setConnectTimeout(60000); conn.setReadTimeout(300000); return conn; }
From source file:it.acubelab.batframework.systemPlugins.TagmeAnnotator.java
@Override public HashSet<ScoredAnnotation> solveSa2W(String text) throws AnnotationException { // System.out.println(text.length()+ " "+text.substring(0, // Math.min(text.length(), 15))); // TODO: workaround for a bug in tagme. should be deleted afterwards. String newText = ""; for (int i = 0; i < text.length(); i++) newText += (text.charAt(i) > 127 ? ' ' : text.charAt(i)); text = newText;/*from w w w .ja v a 2 s. c o m*/ // avoid crashes for empty documents int j = 0; while (j < text.length() && text.charAt(j) == ' ') j++; if (j == text.length()) return new HashSet<ScoredAnnotation>(); HashSet<ScoredAnnotation> res; String params = null; try { res = new HashSet<ScoredAnnotation>(); params = "key=" + this.key; params += "&lang=en"; if (epsilon >= 0) params += "&epsilon=" + epsilon; if (minComm >= 0) params += "&min_comm=" + minComm; if (minLink >= 0) params += "&min_link=" + minLink; params += "&text=" + URLEncoder.encode(text, "UTF-8"); URL wikiApi = new URL(url); HttpURLConnection slConnection = (HttpURLConnection) wikiApi.openConnection(); slConnection.setRequestProperty("accept", "text/xml"); slConnection.setDoOutput(true); slConnection.setDoInput(true); slConnection.setRequestMethod("POST"); slConnection.setRequestProperty("charset", "utf-8"); slConnection.setRequestProperty("Content-Length", Integer.toString(params.getBytes().length)); slConnection.setUseCaches(false); slConnection.setReadTimeout(0); DataOutputStream wr = new DataOutputStream(slConnection.getOutputStream()); wr.writeBytes(params); wr.flush(); wr.close(); Scanner s = new Scanner(slConnection.getInputStream()); Scanner s2 = s.useDelimiter("\\A"); String resultStr = s2.hasNext() ? s2.next() : ""; s.close(); JSONObject obj = (JSONObject) JSONValue.parse(resultStr); lastTime = (Long) obj.get("time"); JSONArray jsAnnotations = (JSONArray) obj.get("annotations"); for (Object js_ann_obj : jsAnnotations) { JSONObject js_ann = (JSONObject) js_ann_obj; System.out.println(js_ann); int start = ((Long) js_ann.get("start")).intValue(); int end = ((Long) js_ann.get("end")).intValue(); int id = ((Long) js_ann.get("id")).intValue(); float rho = Float.parseFloat((String) js_ann.get("rho")); System.out.println(text.substring(start, end) + "->" + id + " (" + rho + ")"); res.add(new ScoredAnnotation(start, end - start, id, (float) rho)); } } catch (Exception e) { e.printStackTrace(); throw new AnnotationException("An error occurred while querying TagMe API. Message: " + e.getMessage() + " Parameters:" + params); } return res; }