Java Code Examples for java.io.DataOutputStream#flush()

The following examples show how to use java.io.DataOutputStream#flush() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private void writeMethodBody (Method m, DataOutputStream os)
   throws IOException
{
   os.writeShort (m.maxStack);
   os.writeShort (m.maxLocals);

   ByteArrayOutputStream cbs = new ByteArrayOutputStream ();
   DataOutputStream cos = new DataOutputStream (cbs);

   writeMethodCode (m, cos);
   
   cos.flush ();
   byte [] code = cbs.toByteArray ();
   os.writeInt (code.length); // Code len
   os.write (code); // Code
   os.writeShort (0); // No exceptions
   os.writeShort (0); // No attributes
}
 
Example 2
Source Project: phoenix   File: ColumnExpressionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSerializationWithNullScale() throws Exception {
    int maxLen = 30;
    PName colName = PNameFactory.newName("c1");
    PColumn column = new PColumnImpl(colName, PNameFactory.newName("f1"), PBinary.INSTANCE, maxLen, null,
            true, 20, SortOrder.getDefault(), 0, null, false, null, false, false, colName.getBytes(), HConstants.LATEST_TIMESTAMP);
    ColumnExpression colExp = new KeyValueColumnExpression(column);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dOut = new DataOutputStream(baos);
    colExp.write(dOut);
    dOut.flush();

    ColumnExpression colExp2 = new KeyValueColumnExpression();
    byte[] bytes = baos.toByteArray();
    DataInputStream dIn = new DataInputStream(new ByteArrayInputStream(bytes, 0, bytes.length));
    colExp2.readFields(dIn);
    assertEquals(maxLen, colExp2.getMaxLength().intValue());
    assertNull(colExp2.getScale());
    assertEquals(PBinary.INSTANCE, colExp2.getDataType());
}
 
Example 3
/**
 * 用app_process执行带root权限的Java命令
 *
 * @param context context.getPackageResourcePath()所需
 * @param cls     class.getName()
 * @param args    传入参数
 */
public static void runSuJavaWithAppProcess(Context context, Class cls, @NonNull String... args) {
    final String packageResourcePath = context.getPackageResourcePath();
    final String className = cls.getName();
    try {
        String argLine = "";
        for (String s : args)
            //noinspection StringConcatenationInLoop
            argLine += s + " ";
        Process process = Runtime.getRuntime().exec("su");
        DataOutputStream stream = new DataOutputStream(process.getOutputStream());
        stream.writeBytes("export CLASSPATH=" + packageResourcePath + '\n');
        stream.writeBytes("exec app_process /system/bin " + className + " " + argLine + '\n');
        stream.flush();
    } catch (IOException ignored) {
    } finally {
        new DebugLog("runSuJavaWithAppProcess: packageResourcePath:" + packageResourcePath +
                " className:" + className + " args:" + Arrays.toString(args));
    }
}
 
Example 4
Source Project: deeplearning4j   File: Gzip.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public DataBuffer compress(DataBuffer buffer) {
    try {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        GZIPOutputStream gzip = new GZIPOutputStream(stream);
        DataOutputStream dos = new DataOutputStream(gzip);

        buffer.write(dos);
        dos.flush();
        dos.close();

        byte[] bytes = stream.toByteArray();
        //            logger.info("Bytes: {}", Arrays.toString(bytes));
        BytePointer pointer = new BytePointer(bytes);
        CompressionDescriptor descriptor = new CompressionDescriptor(buffer, this);
        descriptor.setCompressedLength(bytes.length);

        CompressedDataBuffer result = new CompressedDataBuffer(pointer, descriptor);

        return result;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 5
Source Project: datawave   File: UniqueTransform.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Get a sequence of bytes that uniquely identifies this document using the configured unique fields.
 * 
 * @param document
 * @return A document signature
 * @throws IOException
 *             if we failed to generate the byte array
 */
private byte[] getBytes(Document document) throws IOException {
    // we need to pull the fields out of the document.
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    DataOutputStream output = new DataOutputStream(bytes);
    List<FieldSet> fieldSets = getOrderedFieldSets(document);
    int count = 0;
    for (FieldSet fieldSet : fieldSets) {
        String separator = "f" + (count++) + ":";
        for (Map.Entry<String,String> entry : fieldSet.entrySet()) {
            output.writeChars(separator);
            output.writeChars(entry.getKey());
            output.writeChar('=');
            output.writeChars(entry.getValue());
            separator = ",";
        }
    }
    output.flush();
    return bytes.toByteArray();
}
 
Example 6
Source Project: phoenix   File: ColumnExpressionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSerializationWithNullMaxLength() throws Exception {
    int scale = 5;
    PColumn column = new PColumnImpl(PNameFactory.newName("c1"), PNameFactory.newName("f1"), PVarchar.INSTANCE, null, scale,
            true, 20, SortOrder.getDefault(), 0, null, false, null);
    ColumnExpression colExp = new KeyValueColumnExpression(column);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dOut = new DataOutputStream(baos);
    colExp.write(dOut);
    dOut.flush();

    ColumnExpression colExp2 = new KeyValueColumnExpression();
    byte[] bytes = baos.toByteArray();
    DataInputStream dIn = new DataInputStream(new ByteArrayInputStream(bytes, 0, bytes.length));
    colExp2.readFields(dIn);
    assertNull(colExp2.getMaxLength());
    assertEquals(scale, colExp2.getScale().intValue());
    assertEquals(PVarchar.INSTANCE, colExp2.getDataType());
}
 
Example 7
public static void requestRoot(final Context context) {
    // Don't request root when read logs permission is already granted
    if(haveReadLogsPermission(context)) {
        failedToObtainRoot = true;
        return;
    }

    Handler handler = new Handler(Looper.getMainLooper());
    Runnable toastRunnable = () -> Toast.makeText(context, R.string.toast_request_root, Toast.LENGTH_LONG).show();
    handler.postDelayed(toastRunnable, 200);

    Process process = null;
    try {
        // Preform su to get root privileges
        process = Runtime.getRuntime().exec("su");

        // confirm that we have root
        DataOutputStream outputStream = new DataOutputStream(process.getOutputStream());
        outputStream.writeBytes("echo hello\n");

        // Close the terminal
        outputStream.writeBytes("exit\n");
        outputStream.flush();

        process.waitFor();
        if (process.exitValue() != 0) {
            showWarningDialog(context);
            failedToObtainRoot = true;
        } else {
            // success
            PreferenceHelper.setJellybeanRootRan(context);
        }

    } catch (IOException | InterruptedException e) {
        log.w(e, "Cannot obtain root");
        showWarningDialog(context);
        failedToObtainRoot = true;
    }
    handler.removeCallbacks(toastRunnable);
}
 
Example 8
Source Project: tomee   File: HttpResponseImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Takes care of sending the response line, headers and body
 *
 * HTTP/1.1 200 OK
 * Server: Netscape-Enterprise/3.6 SP3
 * Date: Thu, 07 Jun 2001 17:30:42 GMT
 * Content-Type: text/html
 * Connection: close
 *
 * @param output the output to send the response to
 * @throws java.io.IOException if an exception is thrown
 */
protected void writeMessage(final OutputStream output, final boolean indent) throws IOException {
    flushBuffer();

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final DataOutputStream out = new DataOutputStream(baos);
    closeMessage();
    writeResponseLine(out);
    writeHeaders(out);
    writeBody(out, indent);
    out.flush();
    output.write(baos.toByteArray());
    output.flush();
}
 
Example 9
public static JSONObject queryNode(JSONObject request) throws ZCashException {
  HttpsURLConnection conn;
  conn = getNodeConnection();
  try {
    DataOutputStream os = new DataOutputStream(conn.getOutputStream());
    os.writeBytes(request.toString());
    os.flush();
    os.close();
    conn.connect();
  } catch (IOException e) {
    throw new ZCashException("Cannot query node.", e);
  }

  return getResponseObject(conn);
}
 
Example 10
Source Project: AnimatedFrames   File: Metrics.java    License: MIT License 5 votes vote down vote up
/**
 * Sends the data to the bStats server.
 *
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(JSONObject data) throws Exception {
	if (data == null) {
		throw new IllegalArgumentException("Data cannot be null!");
	}
	if (Bukkit.isPrimaryThread()) {
		throw new IllegalAccessException("This method must not be called from the main thread!");
	}
	HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

	// Compress the data to save bandwidth
	byte[] compressedData = compress(data.toString());

	// Add headers
	connection.setRequestMethod("POST");
	connection.addRequestProperty("Accept", "application/json");
	connection.addRequestProperty("Connection", "close");
	connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
	connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
	connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
	connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

	// Send data
	connection.setDoOutput(true);
	DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
	outputStream.write(compressedData);
	outputStream.flush();
	outputStream.close();

	connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}
 
Example 11
Source Project: hadoop-gpu   File: Balancer.java    License: Apache License 2.0 5 votes vote down vote up
private void sendRequest(DataOutputStream out) throws IOException {
  out.writeShort(DataTransferProtocol.DATA_TRANSFER_VERSION);
  out.writeByte(DataTransferProtocol.OP_REPLACE_BLOCK);
  out.writeLong(block.getBlock().getBlockId());
  out.writeLong(block.getBlock().getGenerationStamp());
  Text.writeString(out, source.getStorageID());
  proxySource.write(out);
  out.flush();
}
 
Example 12
Source Project: jelectrum   File: LobstackNode.java    License: MIT License 5 votes vote down vote up
public ByteBuffer serialize()
{
  try
  {
    ByteArrayOutputStream b_out = new ByteArrayOutputStream();
    DataOutputStream d_out = new DataOutputStream(b_out);

    SerialUtil.writeString(d_out, prefix);
    d_out.writeInt(NODE_VERSION);
    d_out.writeInt(children.size());
    for(Map.Entry<String, NodeEntry> me : children.entrySet())
    {
      String sub = me.getKey();
      NodeEntry ne = me.getValue();
      String subsub = sub.substring(prefix.length());
      SerialUtil.writeString(d_out, subsub);
      d_out.writeBoolean(ne.node);
      d_out.writeLong(ne.location);
      d_out.writeInt(ne.min_file_number);
    }
    

    d_out.flush();
    d_out.close();

    return ByteBuffer.wrap(b_out.toByteArray());
  }
  catch(Exception e) { throw new RuntimeException(e);}
  
}
 
Example 13
/** Serializes {@code action} type and data into the {@code output}. */
public static void serializeToStream(DownloadAction action, OutputStream output)
    throws IOException {
  // Don't close the stream as it closes the underlying stream too.
  DataOutputStream dataOutputStream = new DataOutputStream(output);
  dataOutputStream.writeUTF(action.type);
  dataOutputStream.writeInt(action.version);
  action.writeToStream(dataOutputStream);
  dataOutputStream.flush();
}
 
Example 14
/**
 * Sends the data to the bStats server.
 *
 * @param data The data to send.
 * @throws Exception If the request failed.
 */
private static void sendData(JSONObject data) throws Exception {
    if (data == null) {
        throw new IllegalArgumentException("Data cannot be null!");
    }
    if (Bukkit.isPrimaryThread()) {
        throw new IllegalAccessException("This method must not be called from the main thread!");
    }
    HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection();

    // Compress the data to save bandwidth
    byte[] compressedData = compress(data.toString());

    // Add headers
    connection.setRequestMethod("POST");
    connection.addRequestProperty("Accept", "application/json");
    connection.addRequestProperty("Connection", "close");
    connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request
    connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length));
    connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format
    connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION);

    // Send data
    connection.setDoOutput(true);
    DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream());
    outputStream.write(compressedData);
    outputStream.flush();
    outputStream.close();

    connection.getInputStream().close(); // We don't care about the response - Just send our data :)
}
 
Example 15
Source Project: big-c   File: SaslRpcClient.java    License: Apache License 2.0 5 votes vote down vote up
private void sendSaslMessage(DataOutputStream out, RpcSaslProto message)
    throws IOException {
  if (LOG.isDebugEnabled()) {
    LOG.debug("Sending sasl message "+message);
  }
  RpcRequestMessageWrapper request =
      new RpcRequestMessageWrapper(saslHeader, message);
  out.writeInt(request.getLength());
  request.write(out);
  out.flush();    
}
 
Example 16
Source Project: gemfirexd-oss   File: EventErrorLogger.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Get the value of a column in current row in ResultSet as a string.
 * 
 * For binary data this returns hex-encoded string of the bytes.
 * 
 * For a java object this returns hex-encoded string of the serialized bytes
 * for the object.
 */
public static final String getColumnAsString(ResultSet rs, int columnIndex,
    int jdbcType) throws SQLException {
  byte[] bytes;
  switch (jdbcType) {
    case Types.BINARY:
    case Types.BLOB:
    case Types.LONGVARBINARY:
    case Types.VARBINARY:
      // convert to hex for binary columns
      bytes = rs.getBytes(columnIndex);
      if (bytes != null) {
        return ClientSharedUtils.toHexString(bytes, 0, bytes.length);
      }
      else {
        return null;
      }
    case Types.JAVA_OBJECT:
      // for java object type, serialize and then convert to hex
      Object v = rs.getObject(columnIndex);
      if (v != null) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(bos);
        try {
          DataSerializer.writeObject(v, dos);
          dos.flush();
        } catch (IOException ioe) {
          // not expected to happen
          throw new SQLException(ioe.getMessage(), "XJ001", 0, ioe);
        }
        bytes = bos.toByteArray();
        return ClientSharedUtils.toHexString(bytes, 0, bytes.length);
      }
      else {
        return null;
      }
    default:
      return rs.getString(columnIndex);
  }
}
 
Example 17
Source Project: LibreTasks   File: ActivityMain.java    License: Apache License 2.0 5 votes vote down vote up
private boolean testForRoot(){
    boolean hasRoot=false;
    try {
        // Perform su to get root privilege
        Process p = Runtime.getRuntime().exec("su");

        // Attempt to write a file to a root-only 
        DataOutputStream os = new DataOutputStream(p.getOutputStream());
        // we may try to run id here and check that user id is 0. Let's hope for the best :)
        
        // Close the terminal
        os.writeBytes("exit\n");
        os.flush();

        p.waitFor();
        if (p.exitValue() != 255) { 
            Toast.makeText(this, "ROOT Granted", Toast.LENGTH_LONG).show();
            hasRoot=true;
        }
        else {
            Toast.makeText(this, "ROOT Refused", Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Toast.makeText(this, "ROOT Refused", Toast.LENGTH_LONG).show();
    }
    return hasRoot;
}
 
Example 18
@Override
public void addBlockOffset(final long offset, final long firstEventId) throws IOException {
    final BufferedOutputStream bos = new BufferedOutputStream(fos);
    final DataOutputStream dos = new DataOutputStream(bos);
    dos.writeLong(offset);
    dos.writeLong(firstEventId);
    dos.flush();
    index++;
    logger.debug("Adding block {} at offset {}", index, offset);

    if ( alwaysSync ) {
        sync();
    }
}
 
Example 19
Source Project: android-netdiag   File: DnsMessage.java    License: MIT License 5 votes vote down vote up
public static byte[] buildQuery(String domain, int id) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
        DataOutputStream dos = new DataOutputStream(baos);
        int bits = 0;
        //        recursionDesired
        bits |= (1 << 8);

        try {
            dos.writeShort((short) id);
            dos.writeShort((short) bits);

//        questions count
            dos.writeShort(1);

//      no  answer
            dos.writeShort(0);

//      no nameserverRecords
            dos.writeShort(0);

//      no  additionalResourceRecords
            dos.writeShort(0);

            dos.flush();
            writeQuestion(baos, domain);
        } catch (IOException e) {
            throw new AssertionError(e);
        }

        return baos.toByteArray();
    }
 
Example 20
Source Project: LoboBrowser   File: ReuseServer.java    License: MIT License 4 votes vote down vote up
public void run() {
  for (;;) {
    try {
      ServerSocket ss;
      synchronized (this) {
        while (this.serverSocket == null) {
          this.wait();
        }
        ss = this.serverSocket;
      }
      try (
        final Socket s = ss.accept()) {
        s.setSoTimeout(10000);
        s.setTcpNoDelay(true);
        try (
          final InputStream in = s.getInputStream()) {
          final Reader reader = new InputStreamReader(in);
          final BufferedReader br = new BufferedReader(reader);
          String line;
          while ((line = br.readLine()) != null) {
            final int blankIdx = line.indexOf(' ');
            final String command = blankIdx == -1 ? line : line.substring(0, blankIdx).trim();
            if ("LAUNCH".equals(command)) {
              if (blankIdx == -1) {
                LoboBrowser.getInstance().launch();
              } else {
                final String path = line.substring(blankIdx + 1).trim();
                LoboBrowser.getInstance().launch(path);
              }
            } else if ("LAUNCH_BLANK".equals(command)) {
              LoboBrowser.getInstance().launch();
            } else if ("GRINDER".equals(command)) {
              final DataOutputStream dos = new DataOutputStream(s.getOutputStream());
              if (blankIdx != -1) {
                @SuppressWarnings("null")
                final @NonNull String key = line.substring(blankIdx + 1).trim();
                if (LoboBrowser.getInstance().verifyAuth(ss.getLocalPort(), key)) {
                  final NavigatorFrame frame = LoboBrowser.getInstance().launch("cobra:blank");
                  final GrinderServer gs = new GrinderServer(frame);
                  final int gsPort = gs.getPort();
                  dos.writeInt(gsPort);
                  dos.flush();
                } else {
                  dos.writeInt(-1);
                  dos.flush();
                }
              } else {
                dos.writeInt(-1);
                dos.flush();
              }
              // Wait for ACK
              br.readLine();
            }
          }
        }
      }
    } catch (final Exception t) {
      t.printStackTrace(System.err);
    }
  }
}