List of usage examples for java.io DataOutputStream writeBytes
public final void writeBytes(String s) throws IOException
From source file:Messenger.TorLib.java
/** * This method Creates a socket, then sends the inital SOCKS request info * It stops before reading so that other methods may * differently interpret the results. It returns the open socket. * * @param targetHostname The hostname of the destination host. * @param targetPort The port to connect to * @param req SOCKS/TOR request code/* w w w . ja v a2s. c o m*/ * @return An open Socket that has been sent the SOCK4a init codes. * @throws IOException from any Socket problems */ static Socket TorSocketPre(String targetHostname, int targetPort, byte req) throws IOException { Socket s; // System.out.println("Opening connection to "+targetHostname+":"+targetPort+ // " via proxy "+proxyAddr+":"+proxyPort+" of type "+req); s = new Socket(proxyAddr, proxyPort); DataOutputStream os = new DataOutputStream(s.getOutputStream()); os.writeByte(SOCKS_VERSION); os.writeByte(req); // 2 bytes os.writeShort(targetPort); // 4 bytes, high byte first os.writeInt(SOCKS4A_FAKEIP); os.writeByte(SOCKS_DELIM); os.writeBytes(targetHostname); os.writeByte(SOCKS_DELIM); return (s); }
From source file:org.apache.hadoop.mapred.TestTaskChildsKilling.java
private static void createInput(Path inDir, Configuration conf) throws IOException { String input = "Hadoop is framework for data intensive distributed " + "applications.\n Hadoop enables applications" + " to work with thousands of nodes."; FileSystem fs = inDir.getFileSystem(conf); if (!fs.mkdirs(inDir)) { throw new IOException("Failed to create the input directory:" + inDir.toString()); }/*w w w . j a v a 2 s . c o m*/ fs.setPermission(inDir, new FsPermission(FsAction.ALL, FsAction.ALL, FsAction.ALL)); DataOutputStream file = fs.create(new Path(inDir, "data.txt")); int i = 0; while (i < 10) { file.writeBytes(input); i++; } file.close(); }
From source file:info.magnolia.cms.exchange.simple.Transporter.java
/** * http form multipart form post/*from ww w . j a v a2 s . co m*/ * @param connection * @param activationContent * @throws ExchangeException */ public static void transport(URLConnection connection, ActivationContent activationContent) throws ExchangeException { FileInputStream fis = null; DataOutputStream outStream = null; try { byte[] buffer = new byte[BUFFER_SIZE]; connection.setDoOutput(true); connection.setDoInput(true); connection.setUseCaches(false); connection.setRequestProperty("Content-type", "multipart/form-data; boundary=" + BOUNDARY); connection.setRequestProperty("Cache-Control", "no-cache"); outStream = new DataOutputStream(connection.getOutputStream()); outStream.writeBytes("--" + BOUNDARY + "\r\n"); // set all resources from activationContent Iterator fileNameIterator = activationContent.getFiles().keySet().iterator(); while (fileNameIterator.hasNext()) { String fileName = (String) fileNameIterator.next(); fis = new FileInputStream(activationContent.getFile(fileName)); outStream.writeBytes("content-disposition: form-data; name=\"" + fileName + "\"; filename=\"" + fileName + "\"\r\n"); outStream.writeBytes("content-type: application/octet-stream" + "\r\n\r\n"); while (true) { synchronized (buffer) { int amountRead = fis.read(buffer); if (amountRead == -1) { break; } outStream.write(buffer, 0, amountRead); } } fis.close(); outStream.writeBytes("\r\n" + "--" + BOUNDARY + "\r\n"); } outStream.flush(); outStream.close(); log.debug("Activation content sent as multipart/form-data"); } catch (Exception e) { throw new ExchangeException( "Simple exchange transport failed: " + ClassUtils.getShortClassName(e.getClass()), e); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { log.error("Exception caught", e); } } if (outStream != null) { try { outStream.close(); } catch (IOException e) { log.error("Exception caught", e); } } } }
From source file:com.chiorichan.util.WebUtils.java
public static boolean sendTracking(String category, String action, String label) { String url = "http://www.google-analytics.com/collect"; try {//from www. j av a 2 s . c om URL urlObj = new URL(url); HttpURLConnection con = (HttpURLConnection) urlObj.openConnection(); con.setRequestMethod("POST"); String urlParameters = "v=1&tid=UA-60405654-1&cid=" + Loader.getClientId() + "&t=event&ec=" + category + "&ea=" + action + "&el=" + label; con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); Loader.getLogger().fine("Analytics Response [" + category + "]: " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); return true; } catch (IOException e) { return false; } }
From source file:org.apache.giraph.rexster.io.formats.TestRexsterLongDoubleFloatIOFormat.java
private static void insertDbData() throws Exception { for (int i = 0; i < DATABASES.length; ++i) { URL obj = new URL("http://127.0.0.1:18182/graphs/" + DATABASES[i] + "/tp/giraph/vertices"); HttpURLConnection conn = (HttpURLConnection) obj.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Accept", "*/*"); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setDoOutput(true);//from w w w . j a v a2 s. co m DataOutputStream wr = new DataOutputStream(conn.getOutputStream()); /* write the JSON to be sent */ wr.writeBytes("{ \"vlabel\":\"_vid\", \"tx\":[ "); wr.writeBytes("{ \"value\":0,\"_vid\":0 },"); wr.writeBytes("{ \"value\":0,\"_vid\":1 },"); wr.writeBytes("{ \"value\":0,\"_vid\":2 },"); wr.writeBytes("{ \"value\":0,\"_vid\":3 },"); wr.writeBytes("{ \"value\":0,\"_vid\":4 }"); wr.writeBytes(" ] }"); int responseCode = conn.getResponseCode(); if (responseCode != 200) { throw new RuntimeException("Unable to insert data in " + DATABASES[i] + " code: " + responseCode); } BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); obj = new URL("http://127.0.0.1:18182/graphs/" + DATABASES[i] + "/tp/giraph/edges"); conn = (HttpURLConnection) obj.openConnection(); conn.setRequestMethod("POST"); conn.setRequestProperty("Accept", "*/*"); conn.setRequestProperty("Content-Type", "application/json; charset=UTF-8"); conn.setDoOutput(true); wr = new DataOutputStream(conn.getOutputStream()); /* write the JSON to be sent */ wr.writeBytes("{ \"vlabel\":\"_vid\", \"tx\":[ "); wr.writeBytes("{ \"value\": 1, \"_outV\": 0, \"_inV\": 1 },"); wr.writeBytes("{ \"value\": 3, \"_outV\": 0, \"_inV\": 3 },"); wr.writeBytes("{ \"value\": 1, \"_outV\": 1, \"_inV\": 0 },"); wr.writeBytes("{ \"value\": 2, \"_outV\": 1, \"_inV\": 2 },"); wr.writeBytes("{ \"value\": 1, \"_outV\": 1, \"_inV\": 3 },"); wr.writeBytes("{ \"value\": 5, \"_outV\": 2, \"_inV\": 1 },"); wr.writeBytes("{ \"value\": 4, \"_outV\": 2, \"_inV\": 4 },"); wr.writeBytes("{ \"value\": 3, \"_outV\": 3, \"_inV\": 0 },"); wr.writeBytes("{ \"value\": 1, \"_outV\": 3, \"_inV\": 1 },"); wr.writeBytes("{ \"value\": 4, \"_outV\": 3, \"_inV\": 4 },"); wr.writeBytes("{ \"value\": 4, \"_outV\": 4, \"_inV\": 3 },"); wr.writeBytes("{ \"value\": 4, \"_outV\": 4, \"_inV\": 2 }"); wr.writeBytes(" ] }"); wr.flush(); wr.close(); responseCode = conn.getResponseCode(); if (responseCode != 200) { throw new RuntimeException("Unable to insert data in " + DATABASES[i] + " code: " + responseCode); } in = new BufferedReader(new InputStreamReader(conn.getInputStream())); response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } }
From source file:org.dcm4che3.tool.stowrs.StowRS.java
private static StowRSResponse sendDicomFile(String url, File f) throws IOException { int rspCode = 0; String rspMessage = null;/* w w w . ja va 2s .c om*/ URL newUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) newUrl.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "multipart/related; type=application/dicom; boundary=" + MULTIPART_BOUNDARY); connection.setRequestProperty("Accept", "application/dicom+xml"); connection.setRequestProperty("charset", "utf-8"); connection.setUseCaches(false); DataOutputStream wr; wr = new DataOutputStream(connection.getOutputStream()); wr.writeBytes("\r\n--" + MULTIPART_BOUNDARY + "\r\n"); wr.writeBytes("Content-Disposition: inline; name=\"file[]\"; filename=\"" + f.getName() + "\"\r\n"); wr.writeBytes("Content-Type: application/dicom \r\n"); wr.writeBytes("\r\n"); FileInputStream fis = new FileInputStream(f); StreamUtils.copy(fis, wr); fis.close(); wr.writeBytes("\r\n--" + MULTIPART_BOUNDARY + "--\r\n"); wr.flush(); wr.close(); String response = connection.getResponseMessage(); rspCode = connection.getResponseCode(); rspMessage = connection.getResponseMessage(); LOG.info("response: " + response); Attributes responseAttrs = null; try { InputStream in; boolean isErrorCase = rspCode >= HttpURLConnection.HTTP_BAD_REQUEST; if (!isErrorCase) { in = connection.getInputStream(); } else { in = connection.getErrorStream(); } if (!isErrorCase || rspCode == HttpURLConnection.HTTP_CONFLICT) responseAttrs = SAXReader.parse(in); } catch (SAXException e) { throw new IOException(e); } catch (ParserConfigurationException e) { throw new IOException(e); } connection.disconnect(); return new StowRSResponse(rspCode, rspMessage, responseAttrs); }
From source file:org.alfresco.webservice.util.ContentUtils.java
/** * Streams content into the repository. Once done a content details string is returned and this can be used to update * a content property in a CML statement. * //w w w .ja v a 2s. c o m * @param file the file to stream into the repository * @param host the host name of the destination repository * @param port the port name of the destination repository * @param webAppName the name of the target web application (default 'alfresco') * @param mimetype the mimetype of the file, ignored if null * @param encoding the encoding of the file, ignored if null * @return the content data that can be used to set the content property in a CML statement */ @SuppressWarnings("deprecation") public static String putContent(File file, String host, int port, String webAppName, String mimetype, String encoding) { String result = null; try { String url = "/" + webAppName + "/upload/" + URLEncoder.encode(file.getName(), "UTF-8") + "?ticket=" + AuthenticationUtils.getTicket(); if (mimetype != null) { url = url + "&mimetype=" + mimetype; } if (encoding != null) { url += "&encoding=" + encoding; } String request = "PUT " + url + " HTTP/1.1\n" + "Cookie: JSESSIONID=" + AuthenticationUtils.getAuthenticationDetails().getSessionId() + ";\n" + "Content-Length: " + file.length() + "\n" + "Host: " + host + ":" + port + "\n" + "Connection: Keep-Alive\n" + "\n"; // Open sockets and streams Socket socket = new Socket(host, port); DataOutputStream os = new DataOutputStream(socket.getOutputStream()); DataInputStream is = new DataInputStream(socket.getInputStream()); try { if (socket != null && os != null && is != null) { // Write the request header os.writeBytes(request); // Stream the content onto the server InputStream fileInputStream = new FileInputStream(file); int byteCount = 0; byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = -1; while ((bytesRead = fileInputStream.read(buffer)) != -1) { os.write(buffer, 0, bytesRead); byteCount += bytesRead; } os.flush(); fileInputStream.close(); // Read the response and deal with any errors that might occur boolean firstLine = true; String responseLine; while ((responseLine = is.readLine()) != null) { if (firstLine == true) { if (responseLine.contains("200") == true) { firstLine = false; } else if (responseLine.contains("401") == true) { throw new RuntimeException( "Content could not be uploaded because invalid credentials have been supplied."); } else if (responseLine.contains("403") == true) { throw new RuntimeException( "Content could not be uploaded because user does not have sufficient privileges."); } else { throw new RuntimeException( "Error returned from upload servlet (" + responseLine + ")"); } } else if (responseLine.contains("contentUrl") == true) { result = responseLine; break; } } } } finally { try { // Close the streams and socket if (os != null) { os.close(); } if (is != null) { is.close(); } if (socket != null) { socket.close(); } } catch (Exception e) { throw new RuntimeException("Error closing sockets and streams", e); } } } catch (Exception e) { throw new RuntimeException("Error writing content to repository server", e); } return result; }
From source file:Main.java
private static byte[] ExecuteCommand(String command, Boolean useroot, boolean forcenew) throws Exception { Process p;/*from www .j a v a 2s . co m*/ DataOutputStream stdin; InputStream stdout; ByteArrayOutputStream baos; int read; byte[] buffer; /* * If for any reason the command does not print anything we are stuck forever. * Make sure that we print SOMETHING ALWAYS! */ command = "RESULT=$(" + command + "); if [[ $RESULT == '' ]]; then echo '#null#';else echo $RESULT;fi\n"; p = getProcess(useroot, forcenew); stdin = new DataOutputStream(p.getOutputStream()); stdout = p.getInputStream(); buffer = new byte[BUFF_LEN]; baos = new ByteArrayOutputStream(); stdin.writeBytes(command); while (true) { read = stdout.read(buffer); baos.write(buffer, 0, read); if (read < BUFF_LEN) { //we have read everything break; } } if (forcenew) { stdin.writeBytes("exit\n"); stdin.flush(); stdin.close(); } //p.waitFor(); return baos.toByteArray(); }
From source file:com.doctoror.surprise.SurpriseService.java
private static Result execute(final List<String> commands, final boolean surpriseBinary) { final Result result = new Result(); Process process = null;//from w w w . j a va2 s . co m DataOutputStream os = null; BufferedReader is = null; try { process = new ProcessBuilder().command(surpriseBinary ? COMMAND_SURPRISE : COMMAND_SU) .redirectErrorStream(true).start(); os = new DataOutputStream(process.getOutputStream()); is = new BufferedReader(new InputStreamReader(process.getInputStream())); for (final String command : commands) { os.writeBytes(command + "\n"); } os.flush(); os.writeBytes("exit\n"); os.flush(); final StringBuilder output = new StringBuilder(); String line; try { while ((line = is.readLine()) != null) { if (output.length() != 0) { output.append('\n'); } output.append(line); } } catch (EOFException ignored) { } result.output = output.toString(); result.exitCode = process.waitFor(); } catch (Exception e) { e.printStackTrace(); result.exitCode = -666; result.output = e.getMessage(); } finally { if (os != null) { try { os.close(); } catch (Exception ignored) { } } if (is != null) { try { is.close(); } catch (Exception ignored) { } } if (process != null) { try { process.destroy(); } catch (Exception ignored) { } } } return result; }
From source file:org.forgerock.openam.doc.jwt.bearer.Main.java
private static void post(String idToken) throws Exception { URL token = new URL(tokenEndpoint); HttpURLConnection connection = (HttpURLConnection) token.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setDoOutput(true);//w w w .ja v a 2s.co m // This client is of type confidential, so authentication is required // according to http://tools.ietf.org/html/rfc6749#section-3.2.1 String clientAssertionType = URLEncoder.encode("urn:ietf:params:oauth:client-assertion-type:jwt-bearer", "UTF-8"); String grantType = URLEncoder.encode("urn:ietf:params:oauth:grant-type:jwt-bearer", "UTF-8"); String data = "client_assertion_type=" + clientAssertionType + "&client_assertion=" + idToken + "&grant_type=" + grantType + "&assertion=" + idToken; DataOutputStream dataOutputStream = new DataOutputStream(connection.getOutputStream()); if (curlOut) { System.out.print("curl --request POST -H 'Content-Type=application/x-www-form-urlencoded' "); System.out.print("-d '" + data + "\' "); System.out.println("'" + tokenEndpoint + "'"); } dataOutputStream.writeBytes(data); dataOutputStream.flush(); dataOutputStream.close(); int responseCode = connection.getResponseCode(); BufferedReader input; if (responseCode == 200) { input = new BufferedReader(new InputStreamReader(connection.getInputStream())); } else { input = new BufferedReader(new InputStreamReader(connection.getErrorStream())); } StringBuilder response = new StringBuilder(); if (input != null) { String line; while ((line = input.readLine()) != null) { response.append(line); } input.close(); } else { response.append("No input stream from reader."); } System.out.println("Response code: " + responseCode); System.out.println(response.toString()); }