List of usage examples for java.net HttpURLConnection setUseCaches
public void setUseCaches(boolean usecaches)
From source file:com.ehsy.solr.util.SimplePostTool.java
/** * Reads data from the data stream and posts it to solr, * writes to the response to output//from w w w . j a v a2 s . c om * @return true if success */ public boolean postData(InputStream data, Integer length, OutputStream output, String type, URL url) { if (mockMode) return true; boolean success = true; if (type == null) type = DEFAULT_CONTENT_TYPE; HttpURLConnection urlc = null; try { try { urlc = (HttpURLConnection) url.openConnection(); try { urlc.setRequestMethod("POST"); } catch (ProtocolException e) { fatal("Shouldn't happen: HttpURLConnection doesn't support POST??" + e); } urlc.setDoOutput(true); urlc.setDoInput(true); urlc.setUseCaches(false); urlc.setAllowUserInteraction(false); urlc.setRequestProperty("Content-type", type); if (url.getUserInfo() != null) { String encoding = DatatypeConverter .printBase64Binary(url.getUserInfo().getBytes(StandardCharsets.US_ASCII)); urlc.setRequestProperty("Authorization", "Basic " + encoding); } if (null != length) urlc.setFixedLengthStreamingMode(length); urlc.connect(); } catch (IOException e) { fatal("Connection error (is Solr running at " + solrUrl + " ?): " + e); success = false; } try (final OutputStream out = urlc.getOutputStream()) { pipe(data, out); } catch (IOException e) { fatal("IOException while posting data: " + e); success = false; } try { success &= checkResponseCode(urlc); try (final InputStream in = urlc.getInputStream()) { pipe(in, output); } } catch (IOException e) { warn("IOException while reading response: " + e); success = false; } } finally { if (urlc != null) urlc.disconnect(); } return success; }
From source file:net.myrrix.client.ClientRecommender.java
/** * @param replica host and port of replica to connect to * @param path URL to access (relative to context root) * @param method HTTP method to use/* w w w.j a va2 s .c o m*/ * @param doOutput if true, will need to write data into the request body * @param chunkedStreaming if true, use chunked streaming to accommodate a large upload, if possible * @param requestProperties additional request key/value pairs or {@code null} for none */ private HttpURLConnection buildConnectionToReplica(HostAndPort replica, String path, String method, boolean doOutput, boolean chunkedStreaming, Map<String, String> requestProperties) throws IOException { String contextPath = config.getContextPath(); if (contextPath != null) { path = '/' + contextPath + path; } String protocol = config.isSecure() ? "https" : "http"; URL url; try { url = new URL(protocol, replica.getHostText(), replica.getPort(), path); } catch (MalformedURLException mue) { // can't happen throw new IllegalStateException(mue); } log.debug("{} {}", method, url); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(method); connection.setDoInput(true); connection.setDoOutput(doOutput); connection.setUseCaches(false); connection.setAllowUserInteraction(false); connection.setRequestProperty(HttpHeaders.ACCEPT, DESIRED_RESPONSE_CONTENT_TYPE); if (closeConnection) { connection.setRequestProperty(HttpHeaders.CONNECTION, "close"); } if (chunkedStreaming) { if (needAuthentication) { // Must buffer in memory if using authentication since it won't handle the authorization challenge log.debug("Authentication is enabled, so ingest data must be buffered in memory"); } else { connection.setChunkedStreamingMode(0); // Use default buffer size } } if (requestProperties != null) { for (Map.Entry<String, String> entry : requestProperties.entrySet()) { connection.setRequestProperty(entry.getKey(), entry.getValue()); } } return connection; }
From source file:dj.comprobantes.offline.service.CPanelServiceImp.java
@Override public boolean guardarComprobanteNube(Comprobante comprobante) throws GenericException { boolean guardo = true; UtilitarioCeo utilitario = new UtilitarioCeo(); Map<String, Object> params = new LinkedHashMap<>(); params.put("NOMBRE_USUARIO", comprobante.getCliente().getNombreCliente()); params.put("IDENTIFICACION_USUARIO", comprobante.getCliente().getIdentificacion()); params.put("CORREO_USUARIO", comprobante.getCliente().getCorreo()); params.put("CODIGO_ESTADO", EstadoUsuarioEnum.NUEVO.getCodigo()); params.put("DIRECCION_USUARIO", comprobante.getCliente().getDireccion()); params.put("PK_CODIGO_COMP", comprobante.getCodigocomprobante()); params.put("CODIGO_DOCUMENTO", comprobante.getCoddoc()); params.put("ESTADO", EstadoComprobanteEnum.AUTORIZADO.getDescripcion()); params.put("CLAVE_ACCESO", comprobante.getClaveacceso()); params.put("SECUENCIAL", comprobante.getSecuencial()); params.put("FECHA_EMISION", utilitario.getFormatoFecha(comprobante.getFechaemision())); params.put("NUM_AUTORIZACION", comprobante.getNumAutorizacion()); params.put("FECHA_AUTORIZACION", utilitario.getFormatoFecha(comprobante.getFechaautoriza())); params.put("ESTABLECIM", comprobante.getEstab()); params.put("PTO_EMISION", comprobante.getPtoemi()); params.put("TOTAL", comprobante.getImportetotal()); params.put("CODIGO_EMPR", ParametrosSistemaEnum.CODIGO_EMPR.getCodigo()); params.put("CORREO_DOCUMENTO", comprobante.getCorreo()); //Para guardar el correo que se envio el comprobante byte[] bxml = archivoService.getXml(comprobante); StringBuilder postData = new StringBuilder(); postData.append("{"); for (Map.Entry<String, Object> param : params.entrySet()) { if (postData.length() != 1) { postData.append(','); }//from www . j a v a 2s.c om postData.append("\"").append(param.getKey()).append("\""); postData.append(":\""); postData.append(String.valueOf(param.getValue())).append("\""); } String encodedfileXML = new String(Base64.encodeBase64(bxml)); params.put("ARCHIVO_XML", encodedfileXML); //guarda en la nuebe el comprobante AUTORIZADO String filefield = "pdf"; String fileMimeType = "application/pdf"; HttpURLConnection connection = null; DataOutputStream outputStream = null; InputStream inputStream = null; String twoHyphens = "--"; String boundary = "*****" + Long.toString(System.currentTimeMillis()) + "*****"; String lineEnd = "\r\n"; String result = ""; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; String fileName = comprobante.getClaveacceso() + ".pdf"; try { byte[] bpdf = archivoService.getPdf(comprobante); File file = File.createTempFile(comprobante.getClaveacceso(), ".tmp"); file.deleteOnExit(); try (FileOutputStream outputStream1 = new FileOutputStream(file);) { outputStream1.write(bpdf); //write the bytes and your done. outputStream1.close(); } catch (Exception e) { e.printStackTrace(); } FileInputStream fileInputStream = new FileInputStream(file); URL url = new URL(ParametrosSistemaEnum.CPANEL_WEB_COMPROBANTE.getCodigo()); connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); outputStream = new DataOutputStream(connection.getOutputStream()); outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data; name=\"" + filefield + "\"; filename=\"" + fileName + "\"" + lineEnd); outputStream.writeBytes("Content-Type: " + fileMimeType + lineEnd); outputStream.writeBytes("Content-Transfer-Encoding: binary" + lineEnd); outputStream.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { outputStream.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } outputStream.writeBytes(lineEnd); // Upload POST Data Iterator<String> keys = params.keySet().iterator(); while (keys.hasNext()) { String key = keys.next(); String value = String.valueOf(params.get(key)); outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"" + lineEnd); outputStream.writeBytes("Content-Type: text/plain" + lineEnd); outputStream.writeBytes(lineEnd); outputStream.writeBytes(value); outputStream.writeBytes(lineEnd); } outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); if (200 != connection.getResponseCode()) { throw new Exception("Failed to upload code:" + connection.getResponseCode() + " " + connection.getResponseMessage()); } inputStream = connection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader((inputStream))); String output; while ((output = br.readLine()) != null) { result += output; } System.out.println(result); fileInputStream.close(); inputStream.close(); outputStream.flush(); outputStream.close(); //CAMBIA DE ESTADO A GUARDDADO EN LA NUBE comprobante.setEnNube(true); comprobanteDAO.actualizar(comprobante); } catch (Exception e) { guardo = false; throw new GenericException(e); } if (guardo) { //Guarda el detalle de la factura if (comprobante.getCoddoc().equals(TipoComprobanteEnum.FACTURA.getCodigo())) { for (DetalleComprobante detActual : comprobante.getDetalle()) { guardarDetalleComprobanteNube(detActual); } } } return guardo; }
From source file:com.esri.gpt.control.arcims.ServletConnectorProxy.java
/** * Communicates with redirect url and works as a transparent proxy * /* w ww.j a v a2 s . c om*/ * @param request * the servlet request * @param response * the servlet response * @throws IOException * if an exception occurs */ private void executeProxy(HttpServletRequest request, HttpServletResponse response) throws IOException { HttpURLConnection httpCon = null; URL redirectURL = null; InputStream input = null; OutputStream output = null; InputStream proxyInput = null; OutputStream proxyOutput = null; try { input = request.getInputStream(); output = response.getOutputStream(); String sQueryStr = request.getQueryString(); String sAuthorization = request.getHeader("Authorization"); String requestBody = readInputCharacters(input); String requestMethod = request.getMethod(); String contentType = request.getContentType(); String encoding = request.getCharacterEncoding(); LOGGER.finer(" Request method = " + requestMethod); LOGGER.finer(" Query string = " + sQueryStr); LOGGER.finer(" Authorization header =" + sAuthorization); LOGGER.finer(" Character Encoding = " + encoding); LOGGER.finer(" The redirect URL is " + this._redirectURL + "?" + sQueryStr); redirectURL = new URL(this._redirectURL + "?" + sQueryStr); httpCon = (HttpURLConnection) redirectURL.openConnection(); httpCon.setDoInput(true); httpCon.setDoOutput(true); httpCon.setUseCaches(false); httpCon.setRequestMethod(requestMethod); httpCon.setRequestProperty("Content-type", contentType); if (sAuthorization != null) { httpCon.addRequestProperty("Authorization", sAuthorization); } proxyOutput = httpCon.getOutputStream(); send(requestBody, proxyOutput); String authenticateHdr = httpCon.getHeaderField("WWW-Authenticate"); if (authenticateHdr != null) { LOGGER.finer(" WWW-Authenticate : " + authenticateHdr); response.setHeader("WWW-Authenticate", StringEscapeUtils.escapeHtml4(Val.stripControls(authenticateHdr))); } LOGGER.finer(" Response Code : " + httpCon.getResponseCode()); if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_FORBIDDEN)) { response.sendError(HttpServletResponse.SC_FORBIDDEN); } else if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_UNAUTHORIZED)) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } else if ((httpCon.getResponseCode() == HttpURLConnection.HTTP_INTERNAL_ERROR)) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } else { proxyInput = httpCon.getInputStream(); send(proxyInput, output); } } catch (Exception e) { e.printStackTrace(); } finally { if (input != null) { input.close(); } if (output != null) { output.close(); } if (proxyInput != null) { proxyInput.close(); } if (proxyOutput != null) { proxyOutput.close(); } if (httpCon != null) { httpCon.disconnect(); } } }
From source file:iracing.webapi.IracingWebApi.java
private String doPostRequestUrlEncoded(boolean needForumCookie, String url, String parameters) throws IOException, LoginException { if (!cookieMap.containsKey(JSESSIONID)) { if (login() != LoginResponse.Success) return null; }//from ww w. j a v a 2s .c o m if (needForumCookie && !cookieMap.containsKey(JFORUMSESSIONID)) { if (!forumLoginAndGetCookie()) return null; } String output = null; try { // URL of CGI-Bin script. URL oUrl = new URL(url); // URL connection channel. HttpURLConnection urlConn = (HttpURLConnection) oUrl.openConnection(); // Let the run-time system (RTS) know that we want input. urlConn.setDoInput(true); // Let the RTS know that we want to do output. urlConn.setDoOutput(true); // No caching, we want the real thing. urlConn.setUseCaches(false); urlConn.addRequestProperty(COOKIE, cookie); // request to have the response gzipped (bringing a 3.5Mb response down to 175kb) urlConn.addRequestProperty("Accept-Encoding", "gzip"); urlConn.setRequestMethod("POST"); // Specify the content type. urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8"); DataOutputStream printout = new DataOutputStream(urlConn.getOutputStream()); try { printout.writeBytes(parameters); printout.flush(); } finally { printout.close(); } output = getResponseText(urlConn); // System.out.println(output); urlConn.disconnect(); } catch (Exception ex) { ex.printStackTrace(); } return output; }
From source file:com.polyvi.xface.extension.filetransfer.XFileTransferExt.java
/** * ?/*from ww w .ja v a 2 s . c om*/ * @param appWorkspace ? * @param source ? * @param target ?? * @param args JSONArray * @param callbackCtx nativejs * * args[2] fileKey ?name file? * args[3] fileName ??? image.jpg? * args[4] mimeType ?mimeimage/jpeg? * args[5] params HTTP????/ * args[6] trustEveryone * args[7] chunkedMode ??????true * @return FileUploadResult */ private XExtensionResult upload(String appWorkspace, String source, String target, JSONArray args, XCallbackContext callbackCtx) { XLog.d(CLASS_NAME, "upload " + source + " to " + target); HttpURLConnection conn = null; try { String fileKey = getArgument(args, 2, "file"); String fileName = getArgument(args, 3, "image.jpg"); String mimeType = getArgument(args, 4, "image/jpeg"); JSONObject params = args.optJSONObject(5); if (params == null) { params = new JSONObject(); } boolean trustEveryone = args.optBoolean(6); boolean chunkedMode = args.optBoolean(7) || args.isNull(7); JSONObject headers = args.optJSONObject(8); if (headers == null && params != null) { headers = params.optJSONObject("headers"); } String objectId = args.getString(9); //------------------ URL url = new URL(target); conn = getURLConnection(url, trustEveryone); conn.setDoInput(true); conn.setDoOutput(true); conn.setUseCaches(false); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY); setCookieProperty(conn, target); // ?? handleRequestHeader(headers, conn); byte[] extraBytes = extraBytesFromParams(params, fileKey); String midParams = "\"" + LINE_END + "Content-Type: " + mimeType + LINE_END + LINE_END; String tailParams = LINE_END + LINE_START + BOUNDARY + LINE_START + LINE_END; byte[] fileNameBytes = fileName.getBytes(ENCODING_TYPE); FileInputStream fileInputStream = (FileInputStream) getPathFromUri(appWorkspace, source); int maxBufferSize = XConstant.BUFFER_LEN; if (chunkedMode) { conn.setChunkedStreamingMode(maxBufferSize); } else { int stringLength = extraBytes.length + midParams.length() + tailParams.length() + fileNameBytes.length; XLog.d(CLASS_NAME, "String Length: " + stringLength); int fixedLength = (int) fileInputStream.getChannel().size() + stringLength; XLog.d(CLASS_NAME, "Content Length: " + fixedLength); conn.setFixedLengthStreamingMode(fixedLength); } // ??? OutputStream ouputStream = conn.getOutputStream(); DataOutputStream dos = new DataOutputStream(ouputStream); dos.write(extraBytes); dos.write(fileNameBytes); dos.writeBytes(midParams); XFileUploadResult result = new XFileUploadResult(); FileTransferProgress progress = new FileTransferProgress(); int bytesAvailable = fileInputStream.available(); int bufferSize = Math.min(bytesAvailable, maxBufferSize); byte[] buffer = new byte[bufferSize]; int bytesRead = fileInputStream.read(buffer, 0, bufferSize); long totalBytes = 0; while (bytesRead > 0) { totalBytes += bytesRead; result.setBytesSent(totalBytes); dos.write(buffer, 0, bytesRead); bytesRead = fileInputStream.read(buffer, 0, bufferSize); if (objectId != null) { //?js??object ID? progress.setTotal(bytesAvailable); XLog.d(CLASS_NAME, "total=" + bytesAvailable); progress.setLoaded(totalBytes); progress.setLengthComputable(true); XExtensionResult progressResult = new XExtensionResult(XExtensionResult.Status.OK, progress.toJSONObject()); progressResult.setKeepCallback(true); callbackCtx.sendExtensionResult(progressResult); } synchronized (abortTriggered) { if (objectId != null && abortTriggered.contains(objectId)) { abortTriggered.remove(objectId); throw new AbortException(ABORT_EXCEPTION_UPLOAD_ABORTED); } } } dos.writeBytes(tailParams); fileInputStream.close(); dos.flush(); dos.close(); checkConnection(conn); setUploadResult(result, conn); // if (trustEveryone && url.getProtocol().toLowerCase().equals("https")) { ((HttpsURLConnection) conn).setHostnameVerifier(mDefaultHostnameVerifier); HttpsURLConnection.setDefaultSSLSocketFactory(mDefaultSSLSocketFactory); } XLog.d(CLASS_NAME, "****** About to return a result from upload"); return new XExtensionResult(XExtensionResult.Status.OK, result.toJSONObject()); } catch (AbortException e) { JSONObject error = createFileTransferError(ABORTED_ERR, source, target, conn); return new XExtensionResult(XExtensionResult.Status.ERROR, error); } catch (FileNotFoundException e) { JSONObject error = createFileTransferError(FILE_NOT_FOUND_ERR, source, target, conn); XLog.e(CLASS_NAME, error.toString()); return new XExtensionResult(XExtensionResult.Status.ERROR, error); } catch (MalformedURLException e) { JSONObject error = createFileTransferError(INVALID_URL_ERR, source, target, conn); XLog.e(CLASS_NAME, error.toString()); return new XExtensionResult(XExtensionResult.Status.ERROR, error); } catch (IOException e) { JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn); XLog.e(CLASS_NAME, error.toString()); return new XExtensionResult(XExtensionResult.Status.IO_EXCEPTION, error); } catch (JSONException e) { XLog.e(CLASS_NAME, e.getMessage()); return new XExtensionResult(XExtensionResult.Status.JSON_EXCEPTION); } catch (Throwable t) { JSONObject error = createFileTransferError(CONNECTION_ERR, source, target, conn); XLog.e(CLASS_NAME, error.toString()); return new XExtensionResult(XExtensionResult.Status.IO_EXCEPTION, error); } finally { if (conn != null) { conn.disconnect(); } } }
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 a2s . c om*/ // 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:com.acc.android.network.operator.base.BaseHttpOperator.java
public static String post(String actionUrl, UploadData uploadData) { HttpURLConnection httpURLConnection = null; DataOutputStream dataOutputStream = null; InputStream inputStream = null; String resultString = null;/*from w w w .ja v a 2 s . c o m*/ // if (AppLibConstant.isUseLog()) { LogUtil.info("actionUrl", actionUrl); LogUtil.info("uploadData", uploadData); LogUtil.info("sessionStr", sessionStr); // } try { URL url = new URL(actionUrl); httpURLConnection = (HttpURLConnection) url.openConnection(); // httpURLConnection.setRequestProperty("Cookie", // "JSESSIONID=320C57C083E7F678ED14B8974732225E"); httpURLConnection.setDoInput(true); httpURLConnection.setDoOutput(true); httpURLConnection.setUseCaches(false); httpURLConnection.setRequestMethod("POST"); httpURLConnection.setRequestProperty("Connection", "Keep-Alive"); httpURLConnection.setRequestProperty("Charset", "UTF-8"); httpURLConnection.setRequestProperty("Content-Type", UploadConstant.MULTIPART_FORM_DATA + ";boundary=" + UploadConstant.BOUNDARY); // httpURLConnection.setChunkedStreamingMode(0); sessonInject(httpURLConnection); dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream()); addFormField(uploadData.getParamMap(), dataOutputStream); if (!ListUtil.isEmpty(uploadData.getUploadFiles())) { addUploadDataContent(uploadData.getUploadFiles(), dataOutputStream // , TAGSTRING ); } dataOutputStream.writeBytes(UploadConstant.LINEEND); dataOutputStream.writeBytes(UploadConstant.TWOHYPHENS + UploadConstant.BOUNDARY + UploadConstant.TWOHYPHENS + UploadConstant.LINEEND); // try { dataOutputStream.flush(); // } catch (Exception exception) { // if (dataOutputStream != null) { // dataOutputStream.close(); // } // dataOutputStream = new DataOutputStream( // httpURLConnection.getOutputStream()); // addFormField(uploadData.getParamMap(), dataOutputStream); // if (!ListUtil.isEmpty(uploadData.getUploadFiles())) { // addUploadDataContent(uploadData.getUploadFiles(), // dataOutputStream // // , TAGSTRING // ); // } // dataOutputStream.writeBytes(UploadConstant.LINEEND); // dataOutputStream.writeBytes(UploadConstant.TWOHYPHENS // + UploadConstant.BOUNDARY + UploadConstant.TWOHYPHENS // + UploadConstant.LINEEND); // dataOutputStream.flush(); // } inputStream = httpURLConnection.getInputStream(); InputStreamReader isr = new InputStreamReader(inputStream, "utf-8"); BufferedReader br = new BufferedReader(isr); resultString = br.readLine(); // if (AppLibConstant.isUseLog()) { LogUtil.info("resultString", resultString); // } // LogUtil.systemOut(resultString); } catch (IOException e) { e.printStackTrace(); } finally { try { if (dataOutputStream != null) { dataOutputStream.close(); } if (inputStream != null) { inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } if (httpURLConnection != null) { httpURLConnection.disconnect(); } } return resultString; }
From source file:org.apache.openaz.xacml.admin.util.RESTfulPAPEngine.java
/** * Send a request to the PAP Servlet and get the response. * /*from w w w. j a va 2 s .c o m*/ * The content is either an InputStream to be copied to the Request OutputStream * OR it is an object that is to be encoded into JSON and pushed into the Request OutputStream. * * The Request parameters may be encoded in multiple "name=value" sets, or parameters may be combined by the caller. * * @param method * @param content - EITHER an InputStream OR an Object to be encoded in JSON * @param collectionTypeClass * @param responseContentClass * @param parameters * @return * @throws Exception */ private Object sendToPAP(String method, Object content, Class collectionTypeClass, Class responseContentClass, String... parameters) throws PAPException { HttpURLConnection connection = null; try { String fullURL = papServletURLString; if (parameters != null && parameters.length > 0) { String queryString = ""; for (String p : parameters) { queryString += "&" + p; } fullURL += "?" + queryString.substring(1); } // special case - Status (actually the detailed status) comes from the PDP directly, not the PAP if (method.equals("GET") && content instanceof PDP && responseContentClass == StdPDPStatus.class) { // Adjust the url and properties appropriately fullURL = ((PDP) content).getId() + "?type=Status"; content = null; } URL url = new URL(fullURL); // // Open up the connection // connection = (HttpURLConnection) url.openConnection(); // // Setup our method and headers // connection.setRequestMethod(method); // connection.setRequestProperty("Accept", "text/x-java-properties"); // connection.setRequestProperty("Content-Type", "text/x-java-properties"); connection.setUseCaches(false); // // Adding this in. It seems the HttpUrlConnection class does NOT // properly forward our headers for POST re-direction. It does so // for a GET re-direction. // // So we need to handle this ourselves. // connection.setInstanceFollowRedirects(false); connection.setDoOutput(true); connection.setDoInput(true); if (content != null) { if (content instanceof InputStream) { try { // // Send our current policy configuration // try (OutputStream os = connection.getOutputStream()) { int count = IOUtils.copy((InputStream) content, os); if (logger.isDebugEnabled()) { logger.debug("copied to output, bytes=" + count); } } } catch (Exception e) { logger.error("Failed to write content in '" + method + "'", e); throw e; } } else { // The content is an object to be encoded in JSON ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(connection.getOutputStream(), content); } } // // Do the connect // connection.connect(); if (connection.getResponseCode() == 204) { logger.info("Success - no content."); return null; } else if (connection.getResponseCode() == 200) { logger.info("Success. We have a return object."); // get the response content into a String String json = null; // read the inputStream into a buffer (trick found online scans entire input looking for end-of-file) java.util.Scanner scanner = new java.util.Scanner(connection.getInputStream()); scanner.useDelimiter("\\A"); json = scanner.hasNext() ? scanner.next() : ""; scanner.close(); logger.info("JSON response from PAP: " + json); // convert Object sent as JSON into local object ObjectMapper mapper = new ObjectMapper(); if (collectionTypeClass != null) { // collection of objects expected final CollectionType javaType = mapper.getTypeFactory() .constructCollectionType(collectionTypeClass, responseContentClass); Object objectFromJSON = mapper.readValue(json, javaType); return objectFromJSON; } else { // single value object expected Object objectFromJSON = mapper.readValue(json, responseContentClass); return objectFromJSON; } } else if (connection.getResponseCode() >= 300 && connection.getResponseCode() <= 399) { // redirection String newURL = connection.getHeaderField("Location"); if (newURL == null) { logger.error( "No Location header to redirect to when response code=" + connection.getResponseCode()); throw new IOException( "No redirect Location header when response code=" + connection.getResponseCode()); } int qIndex = newURL.indexOf("?"); if (qIndex > 0) { newURL = newURL.substring(0, qIndex); } logger.info("Redirect seen. Redirecting " + fullURL + " to " + newURL); return newURL; } else { logger.warn("Unexpected response code: " + connection.getResponseCode() + " message: " + connection.getResponseMessage()); throw new IOException("Server Response: " + connection.getResponseCode() + ": " + connection.getResponseMessage()); } } catch (Exception e) { logger.error("HTTP Request/Response to PAP: " + e, e); throw new PAPException("Request/Response threw :" + e); } finally { // cleanup the connection if (connection != null) { try { // For some reason trying to get the inputStream from the connection // throws an exception rather than returning null when the InputStream does not exist. InputStream is = null; try { is = connection.getInputStream(); } catch (Exception e1) { //NOPMD // ignore this } if (is != null) { is.close(); } } catch (IOException ex) { logger.error("Failed to close connection: " + ex, ex); } connection.disconnect(); } } }
From source file:org.apache.hadoop.crypto.key.kms.KMSClientProvider.java
private HttpURLConnection createConnection(final URL url, String method) throws IOException { HttpURLConnection conn; try {//w w w .ja v a 2 s . com final String doAsUser = getDoAsUser(); conn = getActualUgi().doAs(new PrivilegedExceptionAction<HttpURLConnection>() { @Override public HttpURLConnection run() throws Exception { DelegationTokenAuthenticatedURL authUrl = new DelegationTokenAuthenticatedURL(configurator); return authUrl.openConnection(url, authToken, doAsUser); } }); } catch (IOException ex) { if (ex instanceof SocketTimeoutException) { LOG.warn("Failed to connect to {}:{}", url.getHost(), url.getPort()); } throw ex; } catch (UndeclaredThrowableException ex) { throw new IOException(ex.getUndeclaredThrowable()); } catch (Exception ex) { throw new IOException(ex); } conn.setUseCaches(false); conn.setRequestMethod(method); if (method.equals(HTTP_POST) || method.equals(HTTP_PUT)) { conn.setDoOutput(true); } conn = configureConnection(conn); return conn; }