List of usage examples for java.io DataOutputStream flush
public void flush() throws IOException
From source file:com.vimc.ahttp.HurlWorker.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private void addBodyIfExists(HttpURLConnection connection, Request request) throws IOException { if (request.containsMutilpartData()) { connection.setDoOutput(true);/* w w w.j av a 2s .com*/ connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); if (request.getStringParams().size() > 0) { writeStringFields(request.getStringParams(), out, request.getBoundray()); } if (request.getFileParams().size() > 0) { writeFiles(request.getFileParams(), out, request.getBoundray()); } if (request.getByteParams().size() > 0) { writeBytes(request.getByteParams(), out, request.getBoundray()); } out.flush(); out.close(); } else { byte[] body = request.getStringBody(); if (body != null) { connection.setDoOutput(true); connection.addRequestProperty(HEADER_CONTENT_TYPE, request.getBodyContentType()); DataOutputStream out = new DataOutputStream(connection.getOutputStream()); out.write(body); out.flush(); out.close(); } } }
From source file:com.kyne.webby.rtk.web.WebServer.java
/** * Print the given String as plain text//w w w.j a va 2s . c o m * @param text the text to print * @param clientSocket the client-side socket */ public void printPlainText(final String text, final Socket clientSocket) { try { final DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream()); out.writeBytes("HTTP/1.1 200 OK\r\n"); out.writeBytes("Content-Type: text/plain; charset=utf-8\r\n"); out.writeBytes("Cache-Control: no-cache \r\n"); out.writeBytes("Server: Bukkit Webby\r\n"); out.writeBytes("Connection: Close\r\n\r\n"); out.writeBytes(text); out.flush(); out.close(); } catch (final SocketException e) { /* .. */ } catch (final Exception e) { LogHelper.error(e.getMessage(), e); } }
From source file:com.kyne.webby.rtk.web.WebServer.java
public void printJSONObject(final JSONObject data, final Socket clientSocket) { try {//from w w w . j a v a 2s.c o m final DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream()); out.writeBytes("HTTP/1.1 200 OK\r\n"); out.writeBytes("Content-Type: application/json; charset=utf-8\r\n"); out.writeBytes("Cache-Control: no-cache \r\n"); out.writeBytes("Server: Bukkit Webby\r\n"); out.writeBytes("Connection: Close\r\n\r\n"); out.writeBytes(data.toJSONString()); out.flush(); out.close(); } catch (final SocketException e) { /* .. */ } catch (final Exception e) { LogHelper.error(e.getMessage(), e); } }
From source file:info.fetter.logstashforwarder.protocol.LumberjackClient.java
private int sendDataFrame(DataOutputStream output, Map<String, byte[]> keyValues) throws IOException { output.writeByte(PROTOCOL_VERSION);//ww w .j a v a 2s . com output.writeByte(FRAME_DATA); output.writeInt(sequence++); output.writeInt(keyValues.size()); int bytesSent = 10; for (String key : keyValues.keySet()) { int keyLength = key.length(); output.writeInt(keyLength); bytesSent += 4; output.write(key.getBytes()); bytesSent += keyLength; byte[] value = keyValues.get(key); output.writeInt(value.length); bytesSent += 4; output.write(value); bytesSent += value.length; } output.flush(); return bytesSent; }
From source file:copter.ServerConnection.java
private String postToServer(String postUrl, Map<String, String> parameters) { String serverHost = Config.getInstance().getString("main", "server_host"); URL url;/*from w w w . j a v a 2s . com*/ try { url = new URL("http://" + serverHost + postUrl); HttpURLConnection con = (HttpURLConnection) url.openConnection(); //add reuqest header con.setRequestMethod("POST"); //con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); String urlParameters = ""; for (Map.Entry<String, String> entry : parameters.entrySet()) { String paramName = entry.getKey(); String paramValue = entry.getValue(); String encodedParamValue = URLEncoder.encode(paramValue, "UTF-8"); urlParameters += paramName + "=" + encodedParamValue + "&"; } if (urlParameters.endsWith("&")) { urlParameters = urlParameters.substring(0, urlParameters.length() - 1); } wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); //logger.log("\nSending 'POST' request to URL : " + url); //logger.log("Post parameters : " + urlParameters); //logger.log("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); String serverResponse = response.toString(); return serverResponse; } catch (Exception ex) { logger.log(ex.getMessage()); return null; } }
From source file:it.unimi.dsi.sux4j.io.ChunkedHashStore.java
/** Returns an iterator over the chunks of this chunked hash store. * * @return an iterator over the chunks of this chunked hash store. *//* ww w.ja va 2 s. c o m*/ public Iterator<Chunk> iterator() { if (closed) throw new IllegalStateException("This " + getClass().getSimpleName() + " has been closed "); for (DataOutputStream d : dos) try { d.flush(); } catch (IOException e) { throw new RuntimeException(e); } int m = 0; for (int i = 0; i < virtualDiskChunks; i++) { int s = 0; for (int j = 0; j < diskChunkStep; j++) s += count[i * diskChunkStep + j]; if (s > m) m = s; } final int maxCount = m; return new AbstractObjectIterator<Chunk>() { private int chunk; private FastBufferedInputStream fbis; private int last; private int chunkSize; private final long[] buffer0 = new long[maxCount]; private final long[] buffer1 = new long[maxCount]; private final long[] buffer2 = new long[maxCount]; private final long[] data = hashMask != 0 ? null : new long[maxCount]; public boolean hasNext() { return chunk < chunks; } @SuppressWarnings("unchecked") public Chunk next() { if (!hasNext()) throw new NoSuchElementException(); final long[] buffer0 = this.buffer0; if (chunk % (chunks / virtualDiskChunks) == 0) { final int diskChunk = (int) (chunk / (chunks / virtualDiskChunks)); final long[] buffer1 = this.buffer1, buffer2 = this.buffer2; chunkSize = 0; try { if (diskChunkStep == 1) { fbis = new FastBufferedInputStream(new FileInputStream(file[diskChunk])); chunkSize = count[diskChunk]; } else { final FileInputStream[] fis = new FileInputStream[diskChunkStep]; for (int i = 0; i < fis.length; i++) { fis[i] = new FileInputStream(file[diskChunk * diskChunkStep + i]); chunkSize += count[diskChunk * diskChunkStep + i]; } fbis = new FastBufferedInputStream(new SequenceInputStream( new IteratorEnumeration(Arrays.asList(fis).iterator()))); } final DataInputStream dis = new DataInputStream(fbis); final long triple[] = new long[3]; int count = 0; for (int j = 0; j < chunkSize; j++) { triple[0] = dis.readLong(); triple[1] = dis.readLong(); triple[2] = dis.readLong(); if (DEBUG) System.err.println("From disk: " + Arrays.toString(triple)); if (filter == null || filter.evaluate(triple)) { buffer0[count] = triple[0]; buffer1[count] = triple[1]; buffer2[count] = triple[2]; if (hashMask == 0) data[count] = dis.readLong(); count++; } else if (hashMask == 0) dis.readLong(); // Discard data } chunkSize = count; dis.close(); } catch (IOException e) { throw new RuntimeException(e); } it.unimi.dsi.fastutil.Arrays.quickSort(0, chunkSize, new AbstractIntComparator() { private static final long serialVersionUID = 0L; public int compare(final int x, final int y) { int t = Long.signum(buffer0[x] - buffer0[y]); if (t != 0) return t; t = Long.signum(buffer1[x] - buffer1[y]); if (t != 0) return t; return Long.signum(buffer2[x] - buffer2[y]); } }, new Swapper() { public void swap(final int x, final int y) { final long e0 = buffer0[x], e1 = buffer1[x], e2 = buffer2[x]; buffer0[x] = buffer0[y]; buffer1[x] = buffer1[y]; buffer2[x] = buffer2[y]; buffer0[y] = e0; buffer1[y] = e1; buffer2[y] = e2; if (hashMask == 0) { final long v = data[x]; data[x] = data[y]; data[y] = v; } } }); if (DEBUG) { for (int i = 0; i < chunkSize; i++) System.err.println(buffer0[i] + ", " + buffer1[i] + ", " + buffer2[i]); } if (!checkedForDuplicates && chunkSize > 1) for (int i = chunkSize - 1; i-- != 0;) if (buffer0[i] == buffer0[i + 1] && buffer1[i] == buffer1[i + 1] && buffer2[i] == buffer2[i + 1]) throw new ChunkedHashStore.DuplicateException(); if (chunk == chunks - 1) checkedForDuplicates = true; last = 0; } final int start = last; while (last < chunkSize && (chunkShift == Long.SIZE ? 0 : buffer0[last] >>> chunkShift) == chunk) last++; chunk++; return new Chunk(buffer0, buffer1, buffer2, data, hashMask, start, last); } }; }
From source file:bobs.is.compress.sevenzip.SevenZOutputFile.java
private void writeFileNames(final DataOutput header) throws IOException { header.write(NID.kName);/*from ww w .j a v a 2 s. c om*/ final ByteArrayOutputStream baos = new ByteArrayOutputStream(); final DataOutputStream out = new DataOutputStream(baos); out.write(0); for (final SevenZArchiveEntry entry : files) { out.write(entry.getName().getBytes("UTF-16LE")); out.writeShort(0); } out.flush(); final byte[] contents = baos.toByteArray(); writeUint64(header, contents.length); header.write(contents); }
From source file:com.chummy.jezebel.material.dark.activities.Main.java
public void RunAsRoot(String[] cmds) { try {/*from w w w.j a va 2 s .c om*/ Process p = Runtime.getRuntime().exec("su"); DataOutputStream os = new DataOutputStream(p.getOutputStream()); for (String tmpCmd : cmds) { os.writeBytes(tmpCmd + "\n"); } os.writeBytes("exit\n"); os.flush(); } catch (IOException e) { e.printStackTrace(); Toast toast = Toast.makeText(getApplicationContext(), "Failed", Toast.LENGTH_LONG); toast.show(); } }
From source file:edu.ku.brc.specify.tools.StrLocaleFile.java
/** * Save as Ascii.// w w w .j a va 2s . co m */ public boolean save() { FileOutputStream fos = null; DataOutputStream dos = null; try { fos = new FileOutputStream(dstPath); dos = new DataOutputStream(fos);//, "UTF-8"); for (StrLocaleEntry entry : items) { String str = ""; if (entry.getKey() == null) { } else if (entry.getKey().equals("#")) { str = entry.getSrcStr(); } else { str = entry.getKey() + "=" + (entry.getDstStr() == null ? "" : entry.getDstStr()); } str += '\n'; dos.writeBytes(str); } dos.flush(); dos.close(); return true; } catch (Exception e) { System.out.println("e: " + e); } return false; }
From source file:net.larry1123.elec.util.logger.EELogger.java
/** * Will Log a StackTrace and Post it on to http://paste.larry1123.net/ * Will return true if it was able to post and false if it was not able to post * Throws with the Level given/*from www . j a v a 2 s. co m*/ * * @param lvl The Level to be thrown with * @param message Message to be Logged * @param thrown Throwable Error To be logged * * @return {@code true} if paste was made of stackTrace; {@code falase} if it failed for any reason */ public boolean logStackTraceToPasteBin(Level lvl, String message, Throwable thrown) { if (getConfig().isPastingAllowed()) { EELogger eeLogger = FactoryManager.getFactoryManager().getEELoggerFactory().getSubLogger("EEUtil", "PasteBinLog"); try { URL url = new URL("https://paste.larry1123.net/api/xml/create"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", "Mozilla/5.0"); con.setRequestProperty("Accept-Language", "en-US,en;q=0.5"); String urlParameters = "data=" + "[" + lvl.getName() + "] " + message + "\n" + org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(thrown); urlParameters += "&"; String title = "[" + lvl.getName() + "] " + message; urlParameters += "title=" + (title.length() > 30 ? title.substring(0, 30) : title); urlParameters += "&"; urlParameters += "language=Java"; // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); if (con.getResponseCode() == 200) { DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbFactory.newDocumentBuilder(); Document document = dBuilder.parse(con.getInputStream()); document.getDocumentElement().normalize(); NodeList nodeList = document.getElementsByTagName("id"); Node node = nodeList.item(0); String id = node.getTextContent(); eeLogger.info("Logger " + getName() + ": https://paste.larry1123.net/" + id); return true; } return false; } catch (MalformedURLException e) { eeLogger.error("Failed to send: Malformed", e); return false; } catch (IOException e) { eeLogger.error("Failed to send: IOException", e); return false; } catch (ParserConfigurationException e) { eeLogger.error("Failed to send: ParserConfigurationException", e); return false; } catch (SAXException e) { eeLogger.error("Failed to send: SAXException", e); return false; } } else { return false; } }