public void writeTasks(OutputStream output) { try { output.write("[\n".getBytes()); boolean needComma = false; File[] files = tasksDirectory.listFiles((FileFilter) FileFilterUtils.directoryFileFilter()); List<Integer> numbers = new ArrayList<>(); for (File directory : files) { try { numbers.add(Integer.valueOf(directory.getName())); } catch (Throwable ignored) { } } numbers.sort(Comparator.<Integer>reverseOrder()); numbers = numbers.subList(0, Math.min(100, numbers.size())); for (int taskId : numbers) { File infoFile = new File(new File(tasksDirectory, String.valueOf(taskId)), "info.json"); if (!infoFile.exists()) { continue; } if (needComma) { output.write(",\n".getBytes()); } else { needComma = true; } try (FileInputStream fis = new FileInputStream(infoFile)) { IOUtils.copy(fis, output); } } output.write("]\n".getBytes()); } catch (IOException e) { throw Throwables.propagate(e); } }
/* * Define the client side of the test. * * If the server prematurely exits, serverReady will be set to true * to avoid infinite hangs. */ void doClientSide() throws Exception { /* * Wait for server to get started. */ while (!serverReady) { Thread.sleep(50); } SSLSocketFactory sslsf = (SSLSocketFactory) SSLSocketFactory.getDefault(); SSLSocket sslSocket = (SSLSocket) sslsf.createSocket("localhost", serverPort); InputStream sslIS = sslSocket.getInputStream(); OutputStream sslOS = sslSocket.getOutputStream(); for (int i = 0; i < 10; i++) { sslOS.write(280); sslOS.flush(); sslIS.read(); } for (int i = 0; i < 10; i++) { sslOS.write(280); sslOS.flush(); sslIS.read(); } sslSocket.close(); }
public static void main(String[] args) throws Exception { int N = 6000; if (args.length >= 1) N = Integer.parseInt(args[0]); Crb = new double[N + 7]; Cib = new double[N + 7]; double invN = 2.0 / N; for (int i = 0; i < N; i++) { Cib[i] = i * invN - 1.0; Crb[i] = i * invN - 1.5; } yCt = new AtomicInteger(); out = new byte[N][(N + 7) / 8]; Thread[] pool = new Thread[2 * Runtime.getRuntime().availableProcessors()]; for (int i = 0; i < pool.length; i++) pool[i] = new Thread() { public void run() { int y; while ((y = yCt.getAndIncrement()) < out.length) putLine(y, out[y]); } }; for (Thread t : pool) t.start(); for (Thread t : pool) t.join(); OutputStream stream = new BufferedOutputStream(System.out); stream.write(("P4\n" + N + " " + N + "\n").getBytes()); for (int i = 0; i < N; i++) stream.write(out[i]); stream.close(); }
private void passTcpFileDescriptor( LocalSocket fdSocket, OutputStream outputStream, String socketId, String dstIp, int dstPort, int connectTimeout) throws Exception { Socket sock = new Socket(); sock.setTcpNoDelay(true); // force file descriptor being created if (protect(sock)) { try { sock.connect(new InetSocketAddress(dstIp, dstPort), connectTimeout); ParcelFileDescriptor fd = ParcelFileDescriptor.fromSocket(sock); tcpSockets.put(socketId, sock); fdSocket.setFileDescriptorsForSend(new FileDescriptor[] {fd.getFileDescriptor()}); outputStream.write('*'); outputStream.flush(); fd.detachFd(); } catch (ConnectException e) { LogUtils.e("connect " + dstIp + ":" + dstPort + " failed"); outputStream.write('!'); sock.close(); } catch (SocketTimeoutException e) { LogUtils.e("connect " + dstIp + ":" + dstPort + " failed"); outputStream.write('!'); sock.close(); } finally { outputStream.flush(); } } else { LogUtils.e("protect tcp socket failed"); } }
/** * Copy the given byte range of the given input to the given output. * * @param input The input to copy the given range to the given output for. * @param output The output to copy the given range from the given input for. * @param start Start of the byte range. * @param length Length of the byte range. * @throws IOException If something fails at I/O level. */ private static void copy(RandomAccessFile input, OutputStream output, long start, long length) throws IOException { byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int read; if (input.length() == length) { // Write full range. while ((read = input.read(buffer)) > 0) { output.write(buffer, 0, read); } } else { // Write partial range. input.seek(start); long toRead = length; while ((read = input.read(buffer)) > 0) { if ((toRead -= read) > 0) { output.write(buffer, 0, read); } else { output.write(buffer, 0, (int) toRead + read); break; } } } }
public static int readLine( InputStream in, OutputStream out, Display display, boolean echo, byte[] buf, int maxLen) { // get a line from the input stream into the buffer buf, of max length maxLen // line is terminated with a return character; // echo back to output stream // also write to line 0 of the display, up to 16 characters try { int data; int len = 0; maxLen--; // make room for a null byte while ((data = in.read()) != -1) { if (data == 0) continue; if (data == '\n') continue; if (echo) out.write(data); // echo it back byte ch = (byte) data; if (ch == '\r') { if (echo) out.write('\n'); int dlen = len; // LCD panel display length if (dlen > 16) dlen = 16; byte[] screenBuf = new byte[dlen]; for (int i = 0; i < dlen; i++) screenBuf[i] = buf[i]; display.print(0, screenBuf); // echo it to the display buf[len] = 0; return len; } else if (len < maxLen) { buf[len++] = ch; } } } catch (Exception e) { display.print(0, "oops!"); } return -1; }
/** * This will overlay two documents onto each other. The overlay document is repeatedly overlayed * onto the destination document for every page in the destination. * * @param overlay The document to copy onto the destination * @param destination The file that the overlay should be placed on. * @return The destination pdf, same as argument passed in. * @throws IOException If there is an error accessing data. */ public PDDocument overlay(PDDocument overlay, PDDocument destination) throws IOException { pdfOverlay = overlay; pdfDocument = destination; PDDocumentCatalog overlayCatalog = pdfOverlay.getDocumentCatalog(); collectLayoutPages(overlayCatalog.getAllPages()); COSDictionary saveGraphicsStateDic = new COSDictionary(); saveGraphicsStateStream = new COSStream(saveGraphicsStateDic, pdfDocument.getDocument().getScratchFile()); OutputStream saveStream = saveGraphicsStateStream.createUnfilteredStream(); saveStream.write(" q\n".getBytes("ISO-8859-1")); saveStream.flush(); restoreGraphicsStateStream = new COSStream(saveGraphicsStateDic, pdfDocument.getDocument().getScratchFile()); OutputStream restoreStream = restoreGraphicsStateStream.createUnfilteredStream(); restoreStream.write(" Q\n".getBytes("ISO-8859-1")); restoreStream.flush(); PDDocumentCatalog pdfCatalog = pdfDocument.getDocumentCatalog(); processPages(pdfCatalog.getAllPages()); return pdfDocument; }
/** * Send a message in HTTP 1.0-like format to an output stream. The HTTP message just have two * headers: content-length and x-msdmessagetyp. The very first line of the output is GET /msd * HTTP/1.0, if the message is not a response, and HTTP/1.0 200 OK if it is. * * @param m Message to send * @param out Send the message in this stream * @param net NetworkManager the message will be sent through * @throws java.lang.Exception */ public void send(Message m, OutputStream out, NetworkManager net) throws Exception { // get the content length int contentlength; byte b[] = m.getData(); if (m.getEncode()) { // b=this.encode(b,net); } if (b != null) { contentlength = b.length; } else { contentlength = 0; } // Creates the header StringBuffer send = new StringBuffer("MSD").append(EOL); Hashtable h = m.getAttributes(); for (Enumeration en = h.keys(); en.hasMoreElements(); ) { String v = (String) en.nextElement(); send.append(v).append(":").append(h.get(v)).append(EOL); } send.append("length:").append(contentlength).append(EOL).append(EOL); // writes the header out.write(send.toString().getBytes()); // writes the content if (b != null) { out.write(b); } out.flush(); }
/** Writes Graphic Control Extension */ protected void writeGraphicCtrlExt() throws IOException { out.write(0x21); // extension introducer out.write(0xf9); // GCE label out.write(4); // data block size int transp, disp; if (transparent == null) { transp = 0; disp = 0; // dispose = no action } else { transp = 1; disp = 2; // force clear if using transparent color } if (dispose >= 0) { disp = dispose & 7; // user override } disp <<= 2; // packed fields out.write( 0 | // 1:3 reserved disp | // 4:6 disposal 0 | // 7 user input - 0 = none transp); // 8 transparency flag writeShort(delay); // delay x 1/100 sec out.write(transIndex); // transparent color index out.write(0); // block terminator }
/** Writes color table */ protected void writePalette() throws IOException { out.write(colorTab, 0, colorTab.length); int n = (3 * 256) - colorTab.length; for (int i = 0; i < n; i++) { out.write(0); } }
/** * Unload the given image's data into the given byte stream using the given compression strategy. * Answer the number of bytes written. Method modified to use the passed data if it is not null. */ int unloadData(ImageData image, byte[] data, OutputStream out, int comp) { int totalSize = 0; try { if (comp == 0) return unloadDataNoCompression(image, data, out); int bpl = (image.width * image.depth + 7) / 8; int bmpBpl = (bpl + 3) / 4 * 4; // BMP pads scanlines to multiples of 4 bytes int imageBpl = image.bytesPerLine; // Compression can actually take twice as much space, in worst case byte[] buf = new byte[bmpBpl * 2]; int srcOffset = imageBpl * (image.height - 1); // Start at last line if (data == null) data = image.data; totalSize = 0; byte[] buf2 = new byte[32768]; int buf2Offset = 0; for (int y = image.height - 1; y >= 0; y--) { int lineSize = compress(comp, data, srcOffset, bpl, buf, y == 0); if (buf2Offset + lineSize > buf2.length) { out.write(buf2, 0, buf2Offset); buf2Offset = 0; } System.arraycopy(buf, 0, buf2, buf2Offset, lineSize); buf2Offset += lineSize; totalSize += lineSize; srcOffset -= imageBpl; } if (buf2Offset > 0) out.write(buf2, 0, buf2Offset); } catch (IOException e) { SWT.error(SWT.ERROR_IO, e); } return totalSize; }
private void invokeJsp() throws Exception { Socket sock = new Socket(host, new Integer(port).intValue()); OutputStream os = sock.getOutputStream(); String get = "GET " + contextRoot + "/jsp/test1.jsp" + " HTTP/1.0\n"; System.out.println(get); os.write(get.getBytes()); os.write("\n".getBytes()); InputStream is = sock.getInputStream(); BufferedReader bis = new BufferedReader(new InputStreamReader(is)); String line = null; while ((line = bis.readLine()) != null) { if (line.startsWith("Location:")) { break; } } if (line != null) { System.out.println(line); // Check the path if (line.startsWith("Location: " + PATH)) { fail = false; } else { System.err.println("Wrong path: " + line + ", expected: " + PATH); stat.addStatus(TEST_NAME, stat.FAIL); fail = true; } } else { System.err.println("Missing Location response header"); stat.addStatus(TEST_NAME, stat.FAIL); } }
@BeforeTest(alwaysRun = true) public void setUp() throws Exception { SecureRandom.getInstance("SHA1PRNG").nextBytes(nonEncodableBytesToWrite); String phrase = "all work and no play make Jack a dull boy"; byte[] bytes = phrase.getBytes(); int cursor = 0; while (cursor <= bytesToWrite.length) { System.arraycopy( bytes, 0, bytesToWrite, cursor, (bytes.length + cursor < bytesToWrite.length) ? bytes.length : bytesToWrite.length - cursor); cursor += bytes.length; } ByteArrayOutputStream nonCompressed = new ByteArrayOutputStream(); OutputStream os = new LZFOutputStream(nonCompressed); os.write(nonEncodableBytesToWrite); os.close(); nonCompressableBytes = nonCompressed.toByteArray(); ByteArrayOutputStream compressed = new ByteArrayOutputStream(); os = new LZFOutputStream(compressed); os.write(bytesToWrite); os.close(); compressedBytes = compressed.toByteArray(); }
// Flush the packet to disk, and reset the accumulator void flush_char(OutputStream outs) throws IOException { if (a_count > 0) { outs.write(a_count); outs.write(accum, 0, a_count); a_count = 0; } }
private boolean userPassAuth() throws IOException { int ver = in.read(); int ulen = in.read(); if (ulen <= 0) throw new SocketException("SOCKS protocol error"); byte[] buf = new byte[ulen]; readBuf(in, buf); String uname = new String(buf); String password = null; ulen = in.read(); if (ulen < 0) throw new SocketException("SOCKS protocol error"); if (ulen > 0) { buf = new byte[ulen]; readBuf(in, buf); password = new String(buf); } // Check username/password validity here System.err.println("User: '******'" + password); if (users.containsKey(uname)) { String p1 = users.get(uname); System.err.println("p1 = " + p1); if (p1.equals(password)) { out.write(PROTO_VERS); out.write(REQUEST_OK); out.flush(); return true; } } out.write(PROTO_VERS); out.write(NOT_ALLOWED); out.flush(); return false; }
static void filterArray(InputStream in, OutputStream out, int buffSize) throws IOException { final int ZERO_STATE = 0; final int NUMBER_STATE = 1; byte[] buff = new byte[buffSize]; int count; while ((count = in.read(buff)) != -1) { int state = ZERO_STATE; int previousIndex = 0; for (int index = 0; index < count; index++) { switch (state) { case ZERO_STATE: if (buff[index] == 0) state = ZERO_STATE; else { previousIndex = index; state = NUMBER_STATE; } break; case NUMBER_STATE: if (buff[index] == 0) { out.write(buff, previousIndex, index - previousIndex); state = ZERO_STATE; } else { state = NUMBER_STATE; } break; } } if (state == ZERO_STATE) { state = ZERO_STATE; } else out.write(buff, previousIndex, count - previousIndex); } }
private void doGet(OutputStream os, String url) throws IOException { if ("/".equals(url)) url = "/index.html"; List<String> headers = new ArrayList<String>(); headers.add("HTTP/1.1 200 OK\r\n"); byte[] content = fm.get(url); if (content == null) { returnStatusCode(404, os); return; } ProcessorsList pl = new ProcessorsList(); pl.add(new Compressor(6)); // pl.add(new Chunker(30)); // comment content = pl.process(content, headers); if (content == null) { returnStatusCode(500, os); return; } // uncomment next line headers.add("Content-Length: " + content.length + "\r\n"); headers.add("Connection: close\r\n\r\n"); os.write(getBinaryHeaders(headers)); os.write(content); }
public void secondRun() throws Exception { // Read the JSESSIONID from the previous run FileInputStream fis = new FileInputStream(JSESSIONID); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String jsessionId = br.readLine(); new File(JSESSIONID).delete(); Socket sock = new Socket(host, new Integer(port).intValue()); OutputStream os = sock.getOutputStream(); String get = "GET " + contextRoot + "/ResumeSession" + " HTTP/1.0\n"; System.out.println(get); os.write(get.getBytes()); String cookie = "Cookie: " + jsessionId + "\n"; os.write(cookie.getBytes()); os.write("\n".getBytes()); InputStream is = sock.getInputStream(); br = new BufferedReader(new InputStreamReader(is)); String line = null; boolean found = false; while ((line = br.readLine()) != null) { System.out.println(line); if (line.contains(EXPECTED_RESPONSE)) { found = true; break; } } if (found) { stat.addStatus(TEST_NAME, stat.PASS); } else { throw new Exception("Wrong response. Expected response: " + EXPECTED_RESPONSE + " not found"); } }
public void firstRun() throws Exception { Socket sock = new Socket(host, new Integer(port).intValue()); OutputStream os = sock.getOutputStream(); String get = "GET " + contextRoot + "/test.jsp" + " HTTP/1.0\n"; System.out.println(get); os.write(get.getBytes()); os.write("\n".getBytes()); InputStream is = sock.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); // Get the JSESSIONID from the response String line = null; while ((line = br.readLine()) != null) { System.out.println(line); if (line.startsWith("Set-Cookie:") || line.startsWith("Set-cookie:")) { break; } } if (line == null) { throw new Exception("Missing Set-Cookie response header"); } String jsessionId = getSessionIdFromCookie(line, JSESSIONID); // Store the JSESSIONID in a file FileOutputStream fos = new FileOutputStream(JSESSIONID); OutputStreamWriter osw = new OutputStreamWriter(fos); osw.write(jsessionId); osw.close(); stat.addStatus(TEST_NAME, stat.PASS); }
public void Write(OutputStream output) throws IOException { BitUtils.WriteWord(output, localScreenWidth_); BitUtils.WriteWord(output, localScreenHeight_); output.write(byte_); output.write(backgroundColorIndex_); output.write(pixelAspectRatio_); }
@NotNull public static VirtualFile writeFile( @Nullable File file, @NotNull Object requestor, @Nullable VirtualFile virtualFile, @NotNull BufferExposingByteArrayOutputStream content, @Nullable LineSeparator lineSeparatorIfPrependXmlProlog) throws IOException { AccessToken token = ApplicationManager.getApplication().acquireWriteActionLock(null); try { if (file != null && (virtualFile == null || !virtualFile.isValid())) { virtualFile = getOrCreateVirtualFile(requestor, file); } assert virtualFile != null; OutputStream out = virtualFile.getOutputStream(requestor); try { if (lineSeparatorIfPrependXmlProlog != null) { out.write(XML_PROLOG); out.write(lineSeparatorIfPrependXmlProlog.getSeparatorBytes()); } content.writeTo(out); } finally { out.close(); } return virtualFile; } catch (FileNotFoundException e) { if (virtualFile == null) { throw e; } else { throw new ReadOnlyModificationException(virtualFile); } } finally { token.finish(); } }
public void WriteBits(int bits, int numbits) throws IOException { int bitsWritten = 0; int numBytes = 255; do { if ((index_ == 254 && bitsLeft_ == 0) || index_ > 254) { output_.write(numBytes); output_.write(buffer_, 0, numBytes); buffer_[0] = 0; index_ = 0; bitsLeft_ = 8; } if (numbits <= bitsLeft_) { buffer_[index_] |= (bits & ((1 << numbits) - 1)) << (8 - bitsLeft_); bitsWritten += numbits; bitsLeft_ -= numbits; numbits = 0; } else { buffer_[index_] |= (bits & ((1 << bitsLeft_) - 1)) << (8 - bitsLeft_); bitsWritten += bitsLeft_; bits >>= bitsLeft_; numbits -= bitsLeft_; buffer_[++index_] = 0; bitsLeft_ = 8; } } while (numbits != 0); }
void authenticateDH(String us, String pw) throws Exception { long key = dh.createEncryptionKey(dh_resp); DesCipher des = new DesCipher(DH.longToBytes(key)); byte user[] = new byte[256]; byte passwd[] = new byte[64]; int i; System.arraycopy(us.getBytes(), 0, user, 0, us.length()); if (us.length() < 256) { for (i = us.length(); i < 256; i++) { user[i] = 0; } } System.arraycopy(pw.getBytes(), 0, passwd, 0, pw.length()); if (pw.length() < 64) { for (i = pw.length(); i < 64; i++) { passwd[i] = 0; } } des.encryptText(user, user, DH.longToBytes(key)); des.encryptText(passwd, passwd, DH.longToBytes(key)); os.write(user); os.write(passwd); readSecurityResult("VNC authentication"); }
// find request file according to request.getUri() public void sendStaticResource() throws IOException { byte[] bytes = new byte[BUFFER_SIZE]; FileInputStream fis = null; try { File file = new File(HttpServer.WEB_ROOT, request.getUri()); if (file.exists()) { fis = new FileInputStream(file); int ch = fis.read(bytes, 0, BUFFER_SIZE); while (ch != -1) { output.write(bytes, 0, ch); ch = fis.read(bytes, 0, BUFFER_SIZE); } } else { String errorMessage = "HTTP/1.1 404 File Not Found\r\n" + "Content-Type: text/html\r\n" + "Content-Length: 23\r\n" + "\r\n" + "<h1>File Not Found</h1>"; output.write(errorMessage.getBytes()); } } catch (Exception e) { e.printStackTrace(); } finally { if (fis != null) fis.close(); } }
synchronized void writeFinishedChat() throws Exception { os.write(TextChat); // byte type os.write(0); // byte pad 1 os.write(0); // byte pad 2 os.write(0); // byte pad 2 writeInt(CHAT_FINISHED); // int message length }
synchronized void writeCloseChat() throws Exception { os.write(TextChat); // byte type os.write(0); // byte pad 1 os.write(0); // byte pad 2 os.write(0); // byte pad 2 writeInt(CHAT_CLOSE); // int message length }
private static void writeFile( ByteCodeClass cls, File outputDir, ConcatenatingFileOutputStream writeBufferInstead) throws Exception { OutputStream outMain = writeBufferInstead != null && ByteCodeTranslator.output == ByteCodeTranslator.OutputType.OUTPUT_TYPE_IOS ? writeBufferInstead : new FileOutputStream( new File( outputDir, cls.getClsName() + "." + ByteCodeTranslator.output.extension())); if (outMain instanceof ConcatenatingFileOutputStream) { ((ConcatenatingFileOutputStream) outMain).beginNextFile(cls.getClsName()); } if (ByteCodeTranslator.output == ByteCodeTranslator.OutputType.OUTPUT_TYPE_IOS) { outMain.write(cls.generateCCode(classes).getBytes()); outMain.close(); // we also need to write the header file for iOS String headerName = cls.getClsName() + ".h"; FileOutputStream outHeader = new FileOutputStream(new File(outputDir, headerName)); outHeader.write(cls.generateCHeader().getBytes()); outHeader.close(); } else { outMain.write(cls.generateCSharpCode().getBytes()); outMain.close(); } }
@SuppressWarnings("deprecation") public void writeLogs(String taskId, OutputStream output) { try (FileInputStream input = new FileInputStream(getLogFile(taskId))) { DataInputStream dataInput = new DataInputStream(input); output.write("[\n".getBytes()); byte[] buffer = new byte[4 * 1024]; boolean needComma = false; try { while (true) { IOUtils.skip(input, 1); String line = dataInput.readLine(); if (line == null || line.isEmpty()) { break; } int length = Integer.parseInt(line); if (length > buffer.length) { buffer = new byte[length]; } IOUtils.readFully(input, buffer, 0, length); if (needComma) { output.write(",\n".getBytes()); } else { needComma = true; } output.write(buffer, 0, length); } } catch (EOFException ignored) { // EOF reached } output.write("]\n".getBytes()); } catch (Throwable throwable) { Throwables.propagate(throwable); } }
public void Write(OutputStream output) throws IOException { output.write(separator_); BitUtils.WriteWord(output, leftPosition_); BitUtils.WriteWord(output, topPosition_); BitUtils.WriteWord(output, width_); BitUtils.WriteWord(output, height_); output.write(byte_); }
/** Terminates the line. */ public void println() { try { if (enableCR) out.write('\r'); out.write('\n'); } catch (IOException e) { e.printStackTrace(); } }