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.envirover.spl.SPLGroungControlTest.java
@Test public void testMTMessagePipeline() { System.out.println("MT TEST: Testing MT message pipeline..."); Socket client = null;/* w ww . ja v a 2s.c o m*/ DataOutputStream out = null; try { System.out.printf("MT TEST: Connecting to tcp://%s:%d", InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort()); System.out.println(); client = new Socket(InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort()); System.out.printf("MT TEST: Connected to tcp://%s:%d", InetAddress.getLocalHost().getHostAddress(), config.getMAVLinkPort()); System.out.println(); out = new DataOutputStream(client.getOutputStream()); MAVLinkPacket packet = getSamplePacket(); out.write(packet.encodePacket()); out.flush(); System.out.printf("MT TEST: MAVLink message sent: msgid = %d", packet.msgid); System.out.println(); Thread.sleep(5000); System.out.println("MT TEST: Complete."); } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (out != null) out.close(); if (client != null) client.close(); } catch (IOException e) { e.printStackTrace(); } } }
From source file:com.threeti.proxy.RequestFilter.java
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; String path = request.getServletPath(); String pathInfo = path.substring(path.lastIndexOf("/")); if (pathInfo == null) { response.getWriter().write("error"); } else {//from w w w. j av a 2 s. c o m if (path.contains("/proxy")) { pathInfo = path.substring(path.lastIndexOf("/proxy") + 6); if ("POST".equals(request.getMethod())) { // POST String urlString = this.baseURL + pathInfo; logger.info(urlString); String s = this.getParams(req).substring(0, this.getParams(req).length() - 1); byte[] data = s.getBytes("utf-8"); HttpURLConnection conn = null; DataOutputStream outStream = null; URL httpUrl = new URL(urlString); conn = (HttpURLConnection) httpUrl.openConnection(); conn.setConnectTimeout(7000); conn.setReadTimeout(7000); conn.setUseCaches(false); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("Charset", "utf-8"); conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty("Content-Length", String.valueOf(data.length)); outStream = new DataOutputStream(conn.getOutputStream()); outStream.write(data); outStream.flush(); if (conn.getResponseCode() == 200) { InputStream in = conn.getInputStream(); IOUtils.copy(in, response.getOutputStream()); } else { try { throw new Exception("ResponseCode=" + conn.getResponseCode()); } catch (Exception e) { e.printStackTrace(); } } } else if ("DELETE".equals(request.getMethod())) { String urlString = this.baseURL + pathInfo + "?" + this.getParams(req); logger.info(urlString); HttpURLConnection conn = null; URL url = new URL(urlString); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(7000); conn.setReadTimeout(7000); conn.setUseCaches(false); conn.setDoOutput(true); conn.setRequestMethod("DELETE"); if (conn.getResponseCode() == 200) { InputStream in = conn.getInputStream(); IOUtils.copy(in, response.getOutputStream()); } else { try { throw new Exception("ResponseCode=" + conn.getResponseCode()); } catch (Exception e) { e.printStackTrace(); } } } else { String urlString = this.baseURL + pathInfo + "?" + this.getParams(req); logger.info(urlString); URL url = new URL(urlString); InputStream input = url.openStream(); IOUtils.copy(input, response.getOutputStream()); } } else { chain.doFilter(req, res); } } }
From source file:org.apache.jackrabbit.core.persistence.mem.InMemBundlePersistenceManager.java
/** * Writes the content of the hash maps stores to the file system. * * @throws Exception if an error occurs//from w ww . j a va 2s. com */ public synchronized void storeContents() throws Exception { // write bundles FileSystemResource fsRes = new FileSystemResource(wspFS, BUNDLE_FILE_PATH); fsRes.makeParentDirs(); BufferedOutputStream bos = new BufferedOutputStream(fsRes.getOutputStream()); DataOutputStream out = new DataOutputStream(bos); try { out.writeInt(bundleStore.size()); // number of entries // entries for (NodeId id : bundleStore.keySet()) { out.writeUTF(id.toString()); // id byte[] data = bundleStore.get(id); out.writeInt(data.length); // data length out.write(data); // data } } finally { out.close(); } // write references fsRes = new FileSystemResource(wspFS, REFS_FILE_PATH); fsRes.makeParentDirs(); bos = new BufferedOutputStream(fsRes.getOutputStream()); out = new DataOutputStream(bos); try { out.writeInt(refsStore.size()); // number of entries // entries for (NodeId id : refsStore.keySet()) { out.writeUTF(id.toString()); // target id byte[] data = refsStore.get(id); out.writeInt(data.length); // data length out.write(data); // data } } finally { out.close(); } if (!useFileBlobStore) { // write blobs fsRes = new FileSystemResource(wspFS, BLOBS_FILE_PATH); fsRes.makeParentDirs(); bos = new BufferedOutputStream(fsRes.getOutputStream()); out = new DataOutputStream(bos); try { out.writeInt(blobs.size()); // number of entries // entries for (String id : blobs.keySet()) { out.writeUTF(id); // id byte[] data = blobs.get(id); out.writeInt(data.length); // data length out.write(data); // data } } finally { out.close(); } } }
From source file:com.clearspring.analytics.stream.cardinality.TestHyperLogLogPlus.java
@Test public void testLegacyCodec_sparse() throws IOException { int bits = 18; int cardinality = 5000; HyperLogLogPlus baseline = new HyperLogLogPlus(bits, 25); for (int j = 0; j < cardinality; j++) { double val = Math.random(); baseline.offer(val); }/*from w w w . ja v a 2 s. c o m*/ ByteArrayOutputStream baos = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(baos); dos.writeInt(bits); dos.writeInt(25); dos.writeInt(1); baseline.mergeTempList(); int[] sparseSet = baseline.getSparseSet(); List<byte[]> sparseBytes = new ArrayList<byte[]>(sparseSet.length); int prevDelta = 0; for (int k : sparseSet) { sparseBytes.add(Varint.writeUnsignedVarInt(k - prevDelta)); prevDelta = k; } for (byte[] bytes : sparseBytes) { dos.writeInt(bytes.length); dos.write(bytes); } dos.writeInt(-1); byte[] legacyBytes = baos.toByteArray(); // decode legacy HyperLogLogPlus decoded = HyperLogLogPlus.Builder.build(legacyBytes); assertEquals(baseline.cardinality(), decoded.cardinality()); byte[] newBytes = baseline.getBytes(); assertTrue(newBytes.length < legacyBytes.length); }
From source file:org.alfresco.repo.web.scripts.activities.SiteActivitySystemTest.java
private String callInOutWeb(String urlString, String method, String ticket, String data, String contentType, String soapAction) throws MalformedURLException, URISyntaxException, IOException { URL url = new URL(urlString); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(method);/*from w ww.j av a2 s.c om*/ conn.setRequestProperty("Content-type", contentType); conn.setDoOutput(true); conn.setDoInput(true); conn.setUseCaches(false); if (soapAction != null) { conn.setRequestProperty("SOAPAction", soapAction); } if (ticket != null) { // add Base64 encoded authorization header // refer to: http://wiki.alfresco.com/wiki/Web_Scripts_Framework#HTTP_Basic_Authentication conn.addRequestProperty("Authorization", "Basic " + Base64.encodeBytes(ticket.getBytes())); } String result = null; BufferedReader br = null; DataOutputStream wr = null; OutputStream os = null; InputStream is = null; try { os = conn.getOutputStream(); wr = new DataOutputStream(os); wr.write(data.getBytes()); wr.flush(); } finally { if (wr != null) { wr.close(); } ; if (os != null) { os.close(); } ; } try { is = conn.getInputStream(); br = new BufferedReader(new InputStreamReader(is)); String line = null; StringBuffer sb = new StringBuffer(); while (((line = br.readLine()) != null)) { sb.append(line); } result = sb.toString(); } finally { if (br != null) { br.close(); } ; if (is != null) { is.close(); } ; } return result; }
From source file:com.linkedin.pinot.core.common.datatable.DataTableImplV2.java
private byte[] serializeDictionaryMap() throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream); dataOutputStream.writeInt(_dictionaryMap.size()); for (Entry<String, Map<Integer, String>> dictionaryMapEntry : _dictionaryMap.entrySet()) { String columnName = dictionaryMapEntry.getKey(); Map<Integer, String> dictionary = dictionaryMapEntry.getValue(); byte[] bytes = columnName.getBytes(UTF_8); dataOutputStream.writeInt(bytes.length); dataOutputStream.write(bytes); dataOutputStream.writeInt(dictionary.size()); for (Entry<Integer, String> dictionaryEntry : dictionary.entrySet()) { dataOutputStream.writeInt(dictionaryEntry.getKey()); byte[] valueBytes = dictionaryEntry.getValue().getBytes(UTF_8); dataOutputStream.writeInt(valueBytes.length); dataOutputStream.write(valueBytes); }// w w w. j a v a 2 s .c om } return byteArrayOutputStream.toByteArray(); }
From source file:com.jivesoftware.os.amza.service.AmzaService.java
@Override public void availableRowsStream(boolean system, ChunkWriteable writeable, RingMember remoteRingMember, TimestampedRingHost remoteTimestampedRingHost, long takeSessionId, long sharedKey, long heartbeatIntervalMillis) throws Exception { ringStoreWriter.register(remoteRingMember, remoteTimestampedRingHost.ringHost, remoteTimestampedRingHost.timestampId, false); ByteArrayOutputStream out = new ByteArrayOutputStream(); DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new SnappyOutputStream(out), 8192)); takeCoordinator.availableRowsStream(system, ringStoreReader, partitionStripeProvider, remoteRingMember, takeSessionId, sharedKey, heartbeatIntervalMillis, (partitionName, txId) -> { dos.write(1); byte[] bytes = partitionName.toBytes(); dos.writeInt(bytes.length); dos.write(bytes);/*w w w . ja v a2s . co m*/ dos.writeLong(txId); }, () -> { if (dos.size() > 0) { dos.flush(); byte[] chunk = out.toByteArray(); writeable.write(chunk); /*LOG.info("Offered rows for {} length={}", remoteRingMember, chunk.length);*/ out.reset(); } return null; }, () -> { dos.write(1); dos.writeInt(0); dos.flush(); writeable.write(out.toByteArray()); out.reset(); return null; }); dos.write(0); dos.flush(); writeable.write(out.toByteArray()); }
From source file:Main.java
@SuppressWarnings("resource") public static String post(String targetUrl, Map<String, String> params, String file, byte[] data) { Logd(TAG, "Starting post..."); String html = ""; Boolean cont = true;/*from www. j a v a2 s . c om*/ URL url = null; try { url = new URL(targetUrl); } catch (MalformedURLException e) { Log.e(TAG, "Invalid url: " + targetUrl); cont = false; throw new IllegalArgumentException("Invalid url: " + targetUrl); } if (cont) { if (!targetUrl.startsWith("https") || gVALID_SSL.equals("true")) { HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.STRICT_HOSTNAME_VERIFIER; HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier); } else { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { // TODO Auto-generated method stub } } }; // Install the all-trusting trust manager SSLContext sc; try { sc = SSLContext.getInstance("SSL"); sc.init(null, trustAllCerts, new java.security.SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); // Create all-trusting host name verifier HostnameVerifier allHostsValid = new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }; // Install the all-trusting host verifier HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid); } catch (NoSuchAlgorithmException e) { Logd(TAG, "Error: " + e.getLocalizedMessage()); } catch (KeyManagementException e) { Logd(TAG, "Error: " + e.getLocalizedMessage()); } } Logd(TAG, "Filename: " + file); Logd(TAG, "URL: " + targetUrl); HttpURLConnection connection = null; DataOutputStream outputStream = null; String pathToOurFile = file; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024; try { connection = (HttpURLConnection) url.openConnection(); // Allow Inputs & Outputs connection.setDoInput(true); connection.setDoOutput(true); connection.setUseCaches(false); //Don't use chunked post requests (nginx doesn't support requests without a Content-Length header) //connection.setChunkedStreamingMode(1024); // Enable POST method connection.setRequestMethod("POST"); setBasicAuthentication(connection, url); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); outputStream = new DataOutputStream(connection.getOutputStream()); //outputStream.writeBytes(twoHyphens + boundary + lineEnd); Iterator<Entry<String, String>> iterator = params.entrySet().iterator(); while (iterator.hasNext()) { Entry<String, String> param = iterator.next(); outputStream.writeBytes(twoHyphens + boundary + lineEnd); outputStream.writeBytes("Content-Disposition: form-data;" + "name=\"" + param.getKey() + "\"" + lineEnd + lineEnd); outputStream.write(param.getValue().getBytes("UTF-8")); outputStream.writeBytes(lineEnd); } String connstr = null; if (!file.equals("")) { FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile)); outputStream.writeBytes(twoHyphens + boundary + lineEnd); connstr = "Content-Disposition: form-data; name=\"upfile\";filename=\"" + pathToOurFile + "\"" + lineEnd; outputStream.writeBytes(connstr); outputStream.writeBytes(lineEnd); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // Read file bytesRead = fileInputStream.read(buffer, 0, bufferSize); Logd(TAG, "File length: " + bytesAvailable); try { while (bytesRead > 0) { try { outputStream.write(buffer, 0, bufferSize); } catch (OutOfMemoryError e) { e.printStackTrace(); html = "Error: outofmemoryerror"; return html; } bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } } catch (Exception e) { Logd(TAG, "Error: " + e.getLocalizedMessage()); html = "Error: Unknown error"; return html; } outputStream.writeBytes(lineEnd); fileInputStream.close(); } else if (data != null) { outputStream.writeBytes(twoHyphens + boundary + lineEnd); connstr = "Content-Disposition: form-data; name=\"upfile\";filename=\"tmp\"" + lineEnd; outputStream.writeBytes(connstr); outputStream.writeBytes(lineEnd); bytesAvailable = data.length; Logd(TAG, "File length: " + bytesAvailable); try { outputStream.write(data, 0, data.length); } catch (OutOfMemoryError e) { e.printStackTrace(); html = "Error: outofmemoryerror"; return html; } catch (Exception e) { Logd(TAG, "Error: " + e.getLocalizedMessage()); html = "Error: Unknown error"; return html; } outputStream.writeBytes(lineEnd); } outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) int serverResponseCode = connection.getResponseCode(); String serverResponseMessage = connection.getResponseMessage(); Logd(TAG, "Server Response Code " + serverResponseCode); Logd(TAG, "Server Response Message: " + serverResponseMessage); if (serverResponseCode == 200) { InputStreamReader in = new InputStreamReader(connection.getInputStream()); BufferedReader br = new BufferedReader(in); String decodedString; while ((decodedString = br.readLine()) != null) { html += decodedString; } in.close(); } outputStream.flush(); outputStream.close(); outputStream = null; } catch (Exception ex) { // Exception handling html = "Error: Unknown error"; Logd(TAG, "Send file Exception: " + ex.getMessage()); } } if (html.startsWith("success:")) Logd(TAG, "Server returned: success:HIDDEN"); else Logd(TAG, "Server returned: " + html); return html; }
From source file:com.linkedin.pinot.common.utils.DataTable.java
private byte[] serializeDictionary() throws Exception { if (dictionary != null) { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DataOutputStream out = new DataOutputStream(baos); out.writeInt(dictionary.size()); for (String key : dictionary.keySet()) { byte[] bytes = key.getBytes(UTF8); out.writeInt(bytes.length);//from www .j a va 2 s. co m out.write(bytes); Map<Integer, String> map = dictionary.get(key); out.writeInt(map.size()); for (Entry<Integer, String> entry : map.entrySet()) { out.writeInt(entry.getKey()); byte[] valueBytes = entry.getValue().getBytes(UTF8); out.writeInt(valueBytes.length); out.write(valueBytes); } } return baos.toByteArray(); } return new byte[0]; }
From source file:com.linkedin.pinot.core.startree.OffHeapStarTreeBuilder.java
private void appendToBuffer(DataOutputStream dos, DimensionBuffer dimensions, MetricBuffer metricHolder) throws IOException { for (int i = 0; i < numDimensions; i++) { dos.writeInt(dimensions.getDimension(i)); }//from ww w.j a v a 2 s. c o m dos.write(metricHolder.toBytes(metricSizeBytes)); }