List of usage examples for java.io DataOutputStream writeBytes
public final void writeBytes(String s) throws IOException
From source file:com.microsoft.valda.oms.OmsAppender.java
private void sendLog(LoggingEvent event) throws NoSuchAlgorithmException, InvalidKeyException, IOException, HTTPException { //create JSON message JSONObject obj = new JSONObject(); obj.put("LOGBACKLoggerName", event.getLoggerName()); obj.put("LOGBACKLogLevel", event.getLevel().toString()); obj.put("LOGBACKMessage", event.getFormattedMessage()); obj.put("LOGBACKThread", event.getThreadName()); if (event.getCallerData() != null && event.getCallerData().length > 0) { obj.put("LOGBACKCallerData", event.getCallerData()[0].toString()); } else {/*from w w w. java 2 s .co m*/ obj.put("LOGBACKCallerData", ""); } if (event.getThrowableProxy() != null) { obj.put("LOGBACKStackTrace", ThrowableProxyUtil.asString(event.getThrowableProxy())); } else { obj.put("LOGBACKStackTrace", ""); } if (inetAddress != null) { obj.put("LOGBACKIPAddress", inetAddress.getHostAddress()); } else { obj.put("LOGBACKIPAddress", "0.0.0.0"); } String json = obj.toJSONString(); String Signature = ""; String encodedHash = ""; String url = ""; // Todays date input for OMS Log Analytics Calendar calendar = Calendar.getInstance(); SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US); dateFormat.setTimeZone(TimeZone.getTimeZone("GMT")); String timeNow = dateFormat.format(calendar.getTime()); // String for signing the key String stringToSign = "POST\n" + json.length() + "\napplication/json\nx-ms-date:" + timeNow + "\n/api/logs"; byte[] decodedBytes = Base64.decodeBase64(sharedKey); Mac hasher = Mac.getInstance("HmacSHA256"); hasher.init(new SecretKeySpec(decodedBytes, "HmacSHA256")); byte[] hash = hasher.doFinal(stringToSign.getBytes()); encodedHash = DatatypeConverter.printBase64Binary(hash); Signature = "SharedKey " + customerId + ":" + encodedHash; url = "https://" + customerId + ".ods.opinsights.azure.com/api/logs?api-version=2016-04-01"; URL objUrl = new URL(url); HttpsURLConnection con = (HttpsURLConnection) objUrl.openConnection(); con.setDoOutput(true); con.setRequestMethod("POST"); con.setRequestProperty("Content-Type", "application/json"); con.setRequestProperty("Log-Type", logType); con.setRequestProperty("x-ms-date", timeNow); con.setRequestProperty("Authorization", Signature); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(json); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); if (responseCode != 200) { throw new HTTPException(responseCode); } }
From source file:pl.edu.agh.ServiceConnection.java
/** * 1. Sends data to service: console password | service password | service id *//*from w w w .jav a 2 s .co m*/ public void connect(Service service) { try { LOGGER.info("Connecting to service: " + service); Socket socket = new Socket(service.getHost(), service.getPort()); socket.setSoTimeout(300); DataOutputStream out = new DataOutputStream(socket.getOutputStream()); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out.writeBytes(service.getPassword() + "|" + service.getId() + "\r\n"); String response = in.readLine(); in.close(); out.close(); socket.close(); LOGGER.info("Service response: " + response); } catch (Exception e) { LOGGER.error("Error connecting with daemon: " + e.getMessage()); } }
From source file:eu.crushedpixel.littlstar.api.upload.S3Uploader.java
/** * Executes a multipart form upload to the S3 Bucket as described in * <a href="http://docs.aws.amazon.com/AmazonS3/latest/dev/HTTPPOSTExamples.html">the AWS Documentation</a>. * @param s3UploadProgressListener An S3UploadProgressListener which is called whenever * bytes are written to the outgoing connection. May be null. * @throws IOException in case of a problem or the connection was aborted * @throws ClientProtocolException in case of an http protocol error *//* ww w . j a v a 2 s . c o m*/ public void uploadFileToS3(S3UploadProgressListener s3UploadProgressListener) throws IOException, ClientProtocolException { //unfortunately, we can't use Unirest to execute the call, because there is no support //for Progress listeners (yet). See https://github.com/Mashape/unirest-java/issues/26 int bufferSize = 1024; //opening a connection to the S3 Bucket HttpURLConnection urlConnection = (HttpURLConnection) new URL(s3_bucket).openConnection(); urlConnection.setUseCaches(false); urlConnection.setDoOutput(true); urlConnection.setRequestMethod("POST"); urlConnection.setChunkedStreamingMode(bufferSize); urlConnection.setRequestProperty("Connection", "Keep-Alive"); urlConnection.setRequestProperty("Cache-Control", "no-cache"); String boundary = "*****"; urlConnection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); //writing the request headers DataOutputStream dos = new DataOutputStream(urlConnection.getOutputStream()); String newline = "\r\n"; String twoHyphens = "--"; dos.writeBytes(twoHyphens + boundary + newline); String attachmentName = "file"; String attachmentFileName = "file"; dos.writeBytes("Content-Disposition: form-data; name=\"" + attachmentName + "\";filename=\"" + attachmentFileName + "\"" + newline); dos.writeBytes(newline); //sending the actual file byte[] buf = new byte[bufferSize]; FileInputStream fis = new FileInputStream(file); long totalBytes = fis.getChannel().size(); long writtenBytes = 0; int len; while ((len = fis.read(buf)) != -1) { dos.write(buf); writtenBytes += len; s3UploadProgressListener.onProgressUpdated(new S3UpdateProgressEvent(writtenBytes, totalBytes, (float) ((double) writtenBytes / totalBytes))); if (interrupt) { fis.close(); dos.close(); return; } } fis.close(); //finish the call dos.writeBytes(newline); dos.writeBytes(twoHyphens + boundary + twoHyphens + newline); dos.close(); urlConnection.disconnect(); }
From source file:org.opendatakit.aggregate.servlet.EnketoApiHandlerServlet.java
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String enketo_api_url = null; HttpURLConnection con = null; BufferedReader in = null;/*from www . j ava 2 s . c o m*/ String message = null; String enketoURL = null; try { enketo_api_url = req.getParameter("enketo_api_url"); String enketo_api_token = req.getParameter("enketo_api_token"); String form_id = req.getParameter("form_id"); CallingContext cc = ContextFactory.getCallingContext(this, req); String aggregate_server_url = cc.getSecureServerURL(); enketo_api_token += ":"; byte[] encoded = Base64.encodeBase64(enketo_api_token.getBytes()); String urlParameters = "server_url=" + aggregate_server_url + "&form_id=" + form_id; URL obj = new URL(enketo_api_url); con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Authorization", "Basic " + new String(encoded)); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept", "*/*"); con.setRequestProperty("Accept-Charset", "UTF-8"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); logger.info("Enketo API response code : " + responseCode); try { in = new BufferedReader(new InputStreamReader(con.getInputStream())); logger.info("Getting the Enketo URL from InputStream"); } catch (Exception io) { in = new BufferedReader(new InputStreamReader(con.getErrorStream())); logger.info("Getting the Error Message from ErrorStream"); } String inputLine = null; StringBuffer response = new StringBuffer(); String responseURL = null; logger.info("BufferReader Object : " + in); if (in != null) { logger.info("BufferReader Object : Not Null "); while ((inputLine = in.readLine()) != null) { if (inputLine.contains("message")) { message = inputLine; System.out.println(message); } if (inputLine.contains("https")) { responseURL = inputLine; } else if (inputLine.contains("http")) { logger.error("Enketo api token is compromised! Enketo URL should specify https"); responseURL = inputLine; } response.append(inputLine); } in.close(); } if (message != null) { String messageArry[] = message.split("\""); if (messageArry.length >= 3) message = messageArry[3]; resp.setStatus(412); resp.setHeader("error", "There was an error obtaining the webform. (message:" + message + ")"); } else if (responseURL != null) { String arryResponseURL[] = responseURL.toString().split(" "); for (String token : arryResponseURL) { if (!token.contains("http")) { continue; } token = token.replace("\\", ""); token = token.replace("\"", ""); token = token.replace(",", ""); enketoURL = token; } resp.setStatus(responseCode); resp.setHeader("enketo_url", enketoURL); logger.info("Enketo API response URL :" + enketoURL); } else { resp.setStatus(responseCode); } } catch (java.net.SocketTimeoutException socketTimeoutException) { logger.info("Exception caught while calling enketo api :" + socketTimeoutException.toString()); resp.setStatus(412); resp.setHeader("error", "API at " + enketo_api_url + " is not available"); } catch (Exception exception) { logger.info("Exception caught while calling enketo api :" + exception.toString()); resp.setStatus(412); if (message == null || message.equals("")) { message = RESPONSE_ERROR; } resp.setHeader("error", "There was an error obtaining the webform. (message:" + message + ")"); } finally { if (con != null) con.disconnect(); } }
From source file:org.coltram.nsd.bonjour.BonjourProcessor.java
public void callAction(JSONObject object, String serviceId, final AtomConnection connection, String callBack) throws JSONException { final DiscoveredZCService bonjourService = topManager.getServiceManager().findBonjourService(serviceId); if (bonjourService == null) { log.info("no service with id " + serviceId + " in callAction"); return;//from w ww . j a va2 s .c om } if (bonjourService.isLocal()) { // find the LocalExposedBonjourService in question LocalExposedBonjourService localcbs = LocalExposedBonjourService.getServiceById(serviceId); // send the info to that service object.put("originAtom", connection.getId()); localcbs.notifyListeners(object.toString()); } else { try { Socket socket = bonjourService.getSocket(); int replyPort = -1; final InetAddress inetAddress = socket.getInetAddress(); if (callBack != null) { // wait for reply on the same socket ServerSocket serverSocket = connection.getServerSocket(); replyPort = serverSocket.getLocalPort(); log.finer("start server for reply " + serverSocket.getLocalPort()); new Thread(new ReplyListener(serverSocket, connection.getConnection())).start(); Thread.yield(); } String ia = inetAddress.toString(); if (ia.startsWith("/")) { ia = ia.substring(1); } object.put("address", LocalHost.name); object.put("replyPort", replyPort + ""); object.put("originAtom", connection.getId()); DataOutputStream dos = bonjourService.getSocketDOS(); dos.writeBytes(object.toString() + "\n"); dos.flush(); } catch (IOException e) { e.printStackTrace(); } } }
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 va 2 s. co 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; }
From source file:org.wso2.carbon.appmgt.sample.deployer.http.HttpHandler.java
/** * This method is used to do a http post request * * @param url request url// www . j ava2 s. c o m * @param payload Content of the post request * @param sessionId sessionId for authentication * @param contentType content type of the post request * @return response * @throws java.io.IOException - Throws this when failed to fulfill a http post request */ public String doPostHttp(String url, String payload, String sessionId, String contentType) throws IOException { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); //con.setRequestProperty("User-Agent", USER_AGENT); if (!sessionId.equals("") && !sessionId.equals("none")) { con.setRequestProperty("Cookie", "JSESSIONID=" + sessionId); } con.setRequestProperty("Content-Type", contentType); con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(payload); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); if (responseCode == 200) { BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); if (sessionId.equals("")) { String session_id = response.substring((response.lastIndexOf(":") + 3), (response.lastIndexOf("}") - 2)); return session_id; } else if (sessionId.equals("appmSamlSsoTokenId")) { return con.getHeaderField("Set-Cookie").split(";")[0].split("=")[1]; } else if (sessionId.equals("header")) { return con.getHeaderField("Set-Cookie").split("=")[1].split(";")[0]; } else { return response.toString(); } } return null; }
From source file:org.wso2.carbon.appmgt.sample.deployer.http.HttpHandler.java
/** * This method is used to do a https post request * * @param url request url/*from w ww .ja v a 2 s.c o m*/ * @param payload Content of the post request * @param sessionId sessionId for authentication * @param contentType content type of the post request * @return response * @throws java.io.IOException - Throws this when failed to fulfill a https post request */ public String doPostHttps(String url, String payload, String sessionId, String contentType) throws IOException { URL obj = new URL(url); HttpsURLConnection con = (HttpsURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); if (!sessionId.equals("")) { con.setRequestProperty("Cookie", "JSESSIONID=" + sessionId); } if (!contentType.equals("")) { con.setRequestProperty("Content-Type", contentType); } con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(payload); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); if (responseCode == 200) { BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); if (sessionId.equals("")) { String session_id = response.substring((response.lastIndexOf(":") + 3), (response.lastIndexOf("}") - 2)); return session_id; } else if (sessionId.equals("header")) { return con.getHeaderField("Set-Cookie"); } return response.toString(); } return null; }
From source file:org.aankor.animenforadio.api.WebsiteGate.java
private JSONObject request(EnumSet<Subscription> subscriptions) throws IOException, JSONException { // fetchCookies(); // TODO: fetch peice by piece URL url = new URL("https://www.animenfo.com/radio/index.php?t=" + (new Date()).getTime()); // URL url = new URL("http://192.168.0.2:12345/"); String body = "{\"ajaxcombine\":true,\"pages\":[{\"uid\":\"nowplaying\",\"page\":\"nowplaying.php\",\"args\":{\"mod\":\"playing\"}}" + ",{\"uid\":\"queue\",\"page\":\"nowplaying.php\",\"args\":{\"mod\":\"queue\"}},{\"uid\":\"recent\",\"page\":\"nowplaying.php\",\"args\":{\"mod\":\"recent\"}}]}"; HttpsURLConnection con = (HttpsURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("Accept", "application/json"); con.setRequestProperty("Accept-Encoding", "gzip, deflate"); con.setRequestProperty("Content-Type", "application/json"); if (!phpSessID.equals("")) con.setRequestProperty("Cookie", "PHPSESSID=" + phpSessID); con.setRequestProperty("Host", "www.animenfo.com"); con.setRequestProperty("Referer", "https://www.animenfo.com/radio/nowplaying.php"); con.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Linux x86_64; rv:31.0) Gecko/20100101 Firefox/31.0 Iceweasel/31.1.0"); // con.setUseCaches (false); con.setDoInput(true);/*from w ww . jav a 2 s. c om*/ con.setDoOutput(true); //Send request DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(body); wr.flush(); wr.close(); InputStream is = con.getInputStream(); BufferedReader rd = new BufferedReader(new InputStreamReader(is)); String line; StringBuilder response = new StringBuilder(); while ((line = rd.readLine()) != null) { response.append(line); } rd.close(); // updateCookies(con); return new JSONObject(response.toString()); }
From source file:org.coltram.nsd.bonjour.BonjourProcessor.java
public void xscribe(JSONObject object, String serviceId, AtomConnection connection) throws JSONException { final DiscoveredZCService bonjourService = topManager.getServiceManager().findBonjourService(serviceId); if (bonjourService == null) { log.info("no service with id " + serviceId + " in un/subscribe"); return;/*from w ww . jav a 2 s .c o m*/ } log.finer("xscribe Bonjour " + object.getString("eventName") + " local?" + bonjourService.isLocal()); if (bonjourService.isLocal()) { // find the LocalExposedBonjourService in question LocalExposedBonjourService localcbs = LocalExposedBonjourService.getServiceById(serviceId); // send the info to that service object.put("address", "localhost"); object.put("port", bonjourService.getPort()); object.put("originAtom", connection.getId()); if ("subscribe".equals(object.optString("purpose"))) { localcbs.subscribe(object); } else { localcbs.unsubscribe(object); } } else { try { Socket socket = bonjourService.getSocket(); final int port = socket.getPort(); int listenerPort = 0; String callback = object.optString("callback"); if ("subscribe".equals(object.optString("purpose"))) { EventListener eventListener = new EventListener(connection, callback); listeners.add(eventListener); listenerPort = eventListener.getListenerPort(); } else { for (EventListener l : listeners) { if (l.is(connection, callback)) { // todo implement pool of listener ports listeners.remove(l); listenerPort = l.getListenerPort(); l.stop(); break; } } } object.put("address", LocalHost.name); object.put("port", port + ""); object.put("listenerPort", listenerPort + ""); object.put("originAtom", connection.getId()); DataOutputStream dos = bonjourService.getSocketDOS(); dos.writeBytes(object.toString() + "\n"); dos.flush(); } catch (IOException e) { e.printStackTrace(); } } }