List of usage examples for java.io DataOutputStream write
public synchronized void write(int b) throws IOException
b
) to the underlying output stream. From source file:com.cisco.gerrit.plugins.slack.client.WebhookClient.java
/** * Initiates an HTTP POST to the provided Webhook URL. * * @param message The message payload./* w w w .j a va 2s .co m*/ * @param webhookUrl The URL to post to. * @return The response payload from Slack. */ private String postRequest(String message, String webhookUrl) { String response; HttpURLConnection connection; connection = null; try { connection = openConnection(webhookUrl); try { connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("charset", "utf-8"); connection.setDoInput(true); connection.setDoOutput(true); DataOutputStream request; request = new DataOutputStream(connection.getOutputStream()); request.write(message.getBytes(StandardCharsets.UTF_8)); request.flush(); request.close(); } catch (IOException e) { throw new RuntimeException("Error posting message to Slack: [" + e.getMessage() + "].", e); } response = getResponse(connection); } finally { if (connection != null) { connection.disconnect(); } } return response; }
From source file:org.apache.hama.bsp.message.compress.SnappyCompressor.java
@Override public byte[] compress(byte[] bytes) { ByteArrayOutputStream bos = null; SnappyOutputStream sos = null;/*from www . j a va 2 s.co m*/ DataOutputStream dos = null; byte[] compressedBytes = null; try { bos = new ByteArrayOutputStream(); sos = new SnappyOutputStream(bos); dos = new DataOutputStream(sos); dos.write(bytes); dos.close(); // Flush the stream as no more data will be sent. compressedBytes = bos.toByteArray(); } catch (IOException ioe) { LOG.error("Unable to compress", ioe); } finally { try { sos.close(); bos.close(); } catch (IOException e) { LOG.warn("Failed to close compression streams.", e); } } return compressedBytes; }
From source file:org.openecomp.sdnc.sli.resource.mdsal.RestService.java
private Document send(String urlString, byte[] msgBytes, String method) { Document response = null;/*from w w w. j av a 2 s. co m*/ String fullUrl = protocol + "://" + host + ":" + port + "/" + urlString; LOG.info("Sending REST " + method + " to " + fullUrl); if (msgBytes != null) { LOG.info("Message body:\n" + msgBytes); } try { HttpURLConnection conn = getRestConnection(fullUrl, method); if (conn instanceof HttpsURLConnection) { HostnameVerifier hostnameVerifier = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; ((HttpsURLConnection) conn).setHostnameVerifier(hostnameVerifier); } // Write message if (msgBytes != null) { conn.setRequestProperty("Content-Length", "" + msgBytes.length); DataOutputStream outStr = new DataOutputStream(conn.getOutputStream()); outStr.write(msgBytes); outStr.close(); } else { conn.setRequestProperty("Content-Length", "0"); } // Read response BufferedReader respRdr; LOG.info("Response: " + conn.getResponseCode() + " " + conn.getResponseMessage()); if (conn.getResponseCode() < 300) { respRdr = new BufferedReader(new InputStreamReader(conn.getInputStream())); } else { respRdr = new BufferedReader(new InputStreamReader(conn.getErrorStream())); } StringBuffer respBuff = new StringBuffer(); String respLn; while ((respLn = respRdr.readLine()) != null) { respBuff.append(respLn + "\n"); } respRdr.close(); String respString = respBuff.toString(); LOG.info("Response body :\n" + respString); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); response = db.parse(new ByteArrayInputStream(respString.getBytes())); } catch (Exception e) { LOG.error("Caught exception executing REST command", e); } return (response); }
From source file:de.ingrid.communication.authentication.BasicSchemeConnector.java
public boolean connect(Socket socket, String host, int port) throws IOException { DataInputStream dataInput = createInput(socket); DataOutputStream dataOutput = createOutput(socket); StringBuffer errorBuffer = new StringBuffer(); String command = createConnectCommand(host, port); errorBuffer.append(command);//from w ww . ja v a2 s. co m dataOutput.write(command.getBytes()); dataOutput.flush(); boolean success = readMessageFromHttpProxy(dataInput, errorBuffer); if (!success) { if (LOG.isEnabledFor(Level.WARN)) { LOG.error(errorBuffer); } } return success; }
From source file:com.opensoc.json.serialization.JSONKafkaSerializer.java
private void putJSON(DataOutputStream data, JSONObject value) throws IOException { // JSON ID is 2 data.writeByte(JSONKafkaSerializer.JSONObjectID); data.write(toBytes(value)); }
From source file:com.datatorrent.stram.FSRecoveryHandler.java
public void writeConnectUri(String uri) throws IOException { DataOutputStream out = fs.create(heartbeatPath, true); try {/* ww w. j a v a 2s.c o m*/ out.write(uri.getBytes()); } finally { out.close(); } LOG.debug("Connect address: {} written to {} ", uri, heartbeatPath); }
From source file:org.apache.hadoop.streaming.TestMultipleArchiveFiles.java
protected void createInput() throws IOException { fileSys.delete(new Path(INPUT_DIR), true); DataOutputStream dos = fileSys.create(new Path(INPUT_FILE)); String inputFileString = "symlink1" + File.separator + "cacheArchive1\nsymlink2" + File.separator + "cacheArchive2"; dos.write(inputFileString.getBytes("UTF-8")); dos.close();//from ww w. j a v a 2 s.co m DataOutputStream out = fileSys.create(new Path(CACHE_ARCHIVE_1.toString())); ZipOutputStream zos = new ZipOutputStream(out); ZipEntry ze = new ZipEntry(CACHE_FILE_1.toString()); zos.putNextEntry(ze); zos.write(input.getBytes("UTF-8")); zos.closeEntry(); zos.close(); out = fileSys.create(new Path(CACHE_ARCHIVE_2.toString())); zos = new ZipOutputStream(out); ze = new ZipEntry(CACHE_FILE_2.toString()); zos.putNextEntry(ze); zos.write(input.getBytes("UTF-8")); zos.closeEntry(); zos.close(); }
From source file:com.msopentech.thali.utilities.universal.HttpKeySocksProxyClientConnOperator.java
@Override public void openConnection(final OperatedClientConnection conn, final HttpHost target, final InetAddress local, final HttpContext context, final HttpParams params) throws IOException { Socket socket = null;//w w w . ja va 2s .co m Socket sslSocket = null; try { if (conn == null || target == null || params == null) { throw new IllegalArgumentException("Required argument may not be null"); } if (conn.isOpen()) { throw new IllegalStateException("Connection must not be open"); } // The original NetCipher code uses a SchemeSocketFactory class that isn't supported by the version // of Apache that ships standard with Android. It also doesn't support the layered socket factory // interface either. We work around this later on but for now we just get our HttpKeySSLSocketFactory Scheme scheme = schemeRegistry.getScheme(target.getSchemeName()); HttpKeySSLSocketFactory httpKeySSLSocketFactory = (HttpKeySSLSocketFactory) scheme.getSocketFactory(); int port = scheme.resolvePort(target.getPort()); String host = target.getHostName(); // Perform explicit SOCKS4a connection request. SOCKS4a supports remote host name resolution // (i.e., Tor resolves the hostname, which may be an onion address). // The Android (Apache Harmony) Socket class appears to support only SOCKS4 and throws an // exception on an address created using INetAddress.createUnresolved() -- so the typical // technique for using Java SOCKS4a/5 doesn't appear to work on Android: // https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/java/net/PlainSocketImpl.java // See also: http://www.mit.edu/~foley/TinFoil/src/tinfoil/TorLib.java, for a similar implementation // From http://en.wikipedia.org/wiki/SOCKS#SOCKS4a: // // field 1: SOCKS version number, 1 byte, must be 0x04 for this version // field 2: command code, 1 byte: // 0x01 = establish a TCP/IP stream connection // 0x02 = establish a TCP/IP port binding // field 3: network byte order port number, 2 bytes // field 4: deliberate invalid IP address, 4 bytes, first three must be 0x00 and the last one must not be 0x00 // field 5: the user ID string, variable length, terminated with a null (0x00) // field 6: the domain name of the host we want to contact, variable length, terminated with a null (0x00) socket = new Socket(); conn.opening(socket, target); socket.setSoTimeout(READ_TIMEOUT_MILLISECONDS); socket.connect(proxy.address(), CONNECT_TIMEOUT_MILLISECONDS); DataOutputStream outputStream = new DataOutputStream(socket.getOutputStream()); outputStream.write((byte) 0x04); outputStream.write((byte) 0x01); outputStream.writeShort((short) port); outputStream.writeInt(0x01); outputStream.write((byte) 0x00); outputStream.write(host.getBytes()); outputStream.write((byte) 0x00); DataInputStream inputStream = new DataInputStream(socket.getInputStream()); if (inputStream.readByte() != (byte) 0x00 || inputStream.readByte() != (byte) 0x5a) { throw new IOException("SOCKS4a connect failed"); } inputStream.readShort(); inputStream.readInt(); // In the NetCipher code we cast to SchemeLayeredSocketFactory and call createLayeredSocket which amongst // other things takes 'params' as an argument. But none of this is supported in Android. When I looked in // Java at what createLayeredSocket was actually doing it was just calling createSocket with exactly the // arguments used below (it ignored params completely). So we should be good. sslSocket = ((HttpKeySSLSocketFactory) httpKeySSLSocketFactory).createSocket(socket, host, port, true); conn.opening(sslSocket, target); sslSocket.setSoTimeout(READ_TIMEOUT_MILLISECONDS); prepareSocket(sslSocket, context, params); conn.openCompleted(httpKeySSLSocketFactory.isSecure(sslSocket), params); // TODO: clarify which connection throws java.net.SocketTimeoutException? } catch (IOException e) { try { if (sslSocket != null) { sslSocket.close(); } if (socket != null) { socket.close(); } } catch (IOException ioe) { } throw e; } }
From source file:buildhappy.tools.DownloadFile.java
/** * ?filepath???/* w w w . j av a 2 s.c o m*/ */ private void saveToLocal(byte[] data, String filePath) { FileOutputStream fileOut = null; DataOutputStream dataOut = null; try { fileOut = new FileOutputStream(new File(filePath)); dataOut = new DataOutputStream(fileOut); for (int i = 0; i < data.length; i++) { dataOut.write(data[i]); } dataOut.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (dataOut != null) { try { dataOut.close(); } catch (IOException e) { e.printStackTrace(); } } } }
From source file:org.apache.hadoop.io.TestArrayOutputStream.java
private void runComparison(ArrayOutputStream aos, DataOutputStream dos, ByteArrayOutputStream bos) throws IOException { Random r = new Random(); // byte/*from w w w . jav a2s .c o m*/ int b = r.nextInt(128); aos.write(b); dos.write(b); // byte[] byte[] bytes = new byte[10]; r.nextBytes(bytes); aos.write(bytes, 0, 10); dos.write(bytes, 0, 10); // Byte aos.writeByte(b); dos.writeByte(b); // boolean boolean bool = r.nextBoolean(); aos.writeBoolean(bool); dos.writeBoolean(bool); // short short s = (short) r.nextInt(); aos.writeShort(s); dos.writeShort(s); // char int c = r.nextInt(); aos.writeChar(c); dos.writeChar(c); // int int i = r.nextInt(); aos.writeInt(i); dos.writeInt(i); // long long l = r.nextLong(); aos.writeLong(l); dos.writeLong(l); // float float f = r.nextFloat(); aos.writeFloat(f); dos.writeFloat(f); // double double d = r.nextDouble(); aos.writeDouble(d); dos.writeDouble(d); // strings String str = RandomStringUtils.random(20); aos.writeBytes(str); aos.writeChars(str); aos.writeUTF(str); dos.writeBytes(str); dos.writeChars(str); dos.writeUTF(str); byte[] expected = bos.toByteArray(); assertEquals(expected.length, aos.size()); byte[] actual = new byte[aos.size()]; System.arraycopy(aos.getBytes(), 0, actual, 0, actual.length); // serialized bytes should be the same assertTrue(Arrays.equals(expected, actual)); }