java.io.DataOutputStream Java Examples

The following examples show how to use java.io.DataOutputStream. 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
Source Project: XKik   Author: xkik-dev   File: Util.java    License: GNU General Public License v3.0 6 votes vote down vote up
private static boolean killKIKService(Activity activity) throws IOException {
    ActivityManager activityManager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo serviceInfo : activityManager.getRunningServices(Integer.MAX_VALUE)) {
        String packageName = serviceInfo.service.getPackageName();

        if (packageName.equals("kik.android")) {
            Process suProcess = Runtime.getRuntime().exec("su");
            DataOutputStream os = new DataOutputStream(suProcess.getOutputStream());
            os.writeBytes("adb shell" + "\n");
            os.flush();
            os.writeBytes("am force-stop kik.android" + "\n");
            os.flush();
            return true;
        }
    }
    return false;
}
 
Example #2
Source Project: TencentKona-8   Author: Tencent   File: ProxyGenerator.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Generate the constructor method for the proxy class.
 */
private MethodInfo generateConstructor() throws IOException {
    MethodInfo minfo = new MethodInfo(
        "<init>", "(Ljava/lang/reflect/InvocationHandler;)V",
        ACC_PUBLIC);

    DataOutputStream out = new DataOutputStream(minfo.code);

    code_aload(0, out);

    code_aload(1, out);

    out.writeByte(opc_invokespecial);
    out.writeShort(cp.getMethodRef(
        superclassName,
        "<init>", "(Ljava/lang/reflect/InvocationHandler;)V"));

    out.writeByte(opc_return);

    minfo.maxStack = 10;
    minfo.maxLocals = 2;
    minfo.declaredExceptions = new short[0];

    return minfo;
}
 
Example #3
Source Project: big-c   Author: yncxcw   File: TestTupleWritable.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Tests compatibility with pre-0.21 versions of TupleWritable
 */
public void testPreVersion21Compatibility() throws Exception {
  Writable[] manyWrits = makeRandomWritables(64);
  PreVersion21TupleWritable oldTuple = new PreVersion21TupleWritable(manyWrits);
  
  for (int i =0; i<manyWrits.length; i++) {
    if (i % 3 == 0) {
      oldTuple.setWritten(i);
    }
  }
  ByteArrayOutputStream out = new ByteArrayOutputStream();
  oldTuple.write(new DataOutputStream(out));
  ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
  TupleWritable dTuple = new TupleWritable();
  dTuple.readFields(new DataInputStream(in));
  assertTrue("Tuple writable is unable to read pre-0.21 versions of TupleWritable", oldTuple.isCompatible(dTuple));
  assertEquals("All tuple data has not been read from the stream",-1,in.read());
}
 
Example #4
Source Project: deeplearning4j   Author: eclipse   File: CompressedDataBuffer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void write(DataOutputStream out) throws IOException {
    //        logger.info("Writing out CompressedDataBuffer");
    // here we should mimic to usual DataBuffer array
    out.writeUTF(allocationMode.name());
    out.writeLong(compressionDescriptor.getCompressedLength());
    out.writeUTF(DataType.COMPRESSED.name());
    // at this moment we don't care about mimics anymore
    //ByteIndexer indexer = ByteIndexer.create((BytePointer) pointer);
    out.writeUTF(compressionDescriptor.getCompressionAlgorithm());
    out.writeLong(compressionDescriptor.getCompressedLength());
    out.writeLong(compressionDescriptor.getOriginalLength());
    out.writeLong(compressionDescriptor.getNumberOfElements());
    out.writeInt(compressionDescriptor.getOriginalDataType().ordinal());
    //        out.write(((BytePointer) pointer).getStringBytes());
    for (int x = 0; x < pointer.capacity() * pointer.sizeof(); x++) {
        byte b = pointer.asByteBuffer().get(x);
        out.writeByte(b);
    }
}
 
Example #5
Source Project: nifi   Author: apache   File: TestStandardTocReader.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testGetBlockIndexV2() throws IOException {
    final File file = new File("target/" + UUID.randomUUID().toString());
    try (final OutputStream out = new FileOutputStream(file);
            final DataOutputStream dos = new DataOutputStream(out)) {
        out.write(2);
        out.write(0);

        for (int i=0; i < 1024; i++) {
            dos.writeLong(i * 1024L);
            dos.writeLong(0L);
        }
    }

    try {
        try(final StandardTocReader reader = new StandardTocReader(file)) {
            assertFalse(reader.isCompressed());

            for (int i=0; i < 1024; i++) {
                assertEquals(i * 1024, reader.getBlockOffset(i));
            }
        }
    } finally {
        file.delete();
    }
}
 
Example #6
Source Project: hottub   Author: dsrg-uoft   File: DTDBuilder.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Save to a stream as a Java class. Instantiating this class will
 * reproduce a (virtually) identical DTD.
 */
void save(DataOutputStream out, String className) throws IOException {

    out.writeInt(DTD.FILE_VERSION);

    buildNamesTable();
    int numNames = namesVector.size();
    out.writeShort((short) (namesVector.size()));
    for (int i = 0; i < namesVector.size(); i++) {
        String nm = namesVector.elementAt(i);
        out.writeUTF(nm);
    }

    saveEntities(out);

    out.writeShort((short) (elements.size()));
    for (Enumeration<Element> e = elements.elements() ; e.hasMoreElements() ; ) {
        saveElement(out, e.nextElement());
    }

    if (namesVector.size() != numNames) {
        System.err.println("!!! ERROR!  Names were added to the list!");
        Thread.dumpStack();
        System.exit(1);
    }
}
 
Example #7
Source Project: hadoop   Author: naver   File: TestMRAppWithCombiner.java    License: Apache License 2.0 6 votes vote down vote up
static void createInputOutPutFolder(Path inDir, Path outDir, int numMaps)
    throws Exception {
  FileSystem fs = FileSystem.get(conf);
  if (fs.exists(outDir)) {
    fs.delete(outDir, true);
  }
  if (!fs.exists(inDir)) {
    fs.mkdirs(inDir);
  }
  String input = "The quick brown fox\n" + "has many silly\n"
      + "red fox sox\n";
  for (int i = 0; i < numMaps; ++i) {
    DataOutputStream file = fs.create(new Path(inDir, "part-" + i));
    file.writeBytes(input);
    file.close();
  }
}
 
Example #8
Source Project: aion   Author: aionnetwork   File: ZMsg.java    License: MIT License 6 votes vote down vote up
/**
 * Save message to an open data output stream. Data saved as: 4 bytes:
 * number of frames For every frame: 4 bytes: byte size of frame data + n
 * bytes: frame byte data
 * @param msg
 *            ZMsg to save
 * @param file
 *            DataOutputStream
 * @return True if saved OK, else false
 */
public static boolean save(ZMsg msg, DataOutputStream file)
{
    if (msg == null)
        return false;

    try {
        // Write number of frames
        file.writeInt(msg.size());
        if (msg.size() > 0) {
            for (ZFrame f : msg) {
                // Write byte size of frame
                file.writeInt(f.size());
                // Write frame byte data
                file.write(f.getData());
            }
        }
        return true;
    }
    catch (IOException e) {
        return false;
    }
}
 
Example #9
Source Project: birt   Author: eclipse   File: EngineIRWriter.java    License: Eclipse Public License 1.0 6 votes vote down vote up
protected void writeListing( DataOutputStream out, ListingDesign listing )
		throws IOException
{
	writeReportItem( out, listing );

	boolean repeatHeader = listing.isRepeatHeader( );
	int pageBreakInterval = listing.getPageBreakInterval( );

	if ( repeatHeader == true )
	{
		IOUtil.writeShort( out, FIELD_REPEAT_HEADER );
		IOUtil.writeBool( out, repeatHeader );
	}
	if ( pageBreakInterval != -1 )
	{
		IOUtil.writeShort( out, FIELD_PAGE_BREAK_INTERVAL );
		IOUtil.writeInt( out, pageBreakInterval );
	}
}
 
Example #10
Source Project: hiped2   Author: alexholmes   File: TextIOJobBuilder.java    License: Apache License 2.0 6 votes vote down vote up
public TextIOJobBuilder writeInputs()
    throws IOException {

  if (fs.exists(outputPath)) {
    fs.delete(outputPath, true);
  }
  if (fs.exists(inputPath)) {
    fs.delete(inputPath, true);
  }
  fs.mkdirs(inputPath);

  DataOutputStream stream = fs.create(new Path(inputPath, "part-0"));

  IOUtils.writeLines(inputs, String.format("%n"), stream);

  stream.close();

  return this;
}
 
Example #11
Source Project: birt   Author: eclipse   File: ReportContent.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public void writeContent( DataOutputStream out ) throws IOException
{
	if ( acl != null )
	{
		IOUtil.writeShort( out, FIELD_ACL );
		IOUtil.writeObject( out, acl );
	}
	if ( userProperties != null && userProperties.size( ) > 0 )
	{
		IOUtil.writeShort( out, FIELD_USER_PROPERTIES );
		IOUtil.writeMap( out, userProperties );
	}
	if ( extProperties != null && !extProperties.isEmpty( ) )
	{
		IOUtil.writeShort( out, FIELD_EXTENSIONS );
		IOUtil.writeMap( out, extProperties );
	}
}
 
Example #12
Source Project: pulsar   Author: apache   File: LoadSimulationController.java    License: Apache License 2.0 6 votes vote down vote up
private void writeProducerOptions(final DataOutputStream outputStream, final ShellArguments arguments,
        final String topic) throws Exception {
    if (!arguments.rangeString.isEmpty()) {
        // If --rand-rate was specified, extract the bounds by splitting on
        // the comma and parsing the resulting
        // doubles.
        final String[] splits = arguments.rangeString.split(",");
        if (splits.length != 2) {
            log.error("Argument to --rand-rate should be two comma-separated values");
            return;
        }
        final double first = Double.parseDouble(splits[0]);
        final double second = Double.parseDouble(splits[1]);
        final double min = Math.min(first, second);
        final double max = Math.max(first, second);
        arguments.rate = random.nextDouble() * (max - min) + min;
    }
    outputStream.writeUTF(topic);
    outputStream.writeInt(arguments.size);
    outputStream.writeDouble(arguments.rate);
}
 
Example #13
Source Project: AACAdditionPro   Author: Photon-GitHub   File: SchematicaControl.java    License: GNU General Public License v3.0 6 votes vote down vote up
@EventHandler
public void on(final PlayerJoinEvent event)
{
    final User user = UserManager.getUser(event.getPlayer().getUniqueId());

    if (User.isUserInvalid(user, this.getModuleType())) {
        return;
    }

    // Encoding the data
    try (final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
         final DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream))
    {
        dataOutputStream.writeByte(0);

        for (final boolean b : disable) {
            dataOutputStream.writeBoolean(b);
        }

        user.getPlayer().sendPluginMessage(AACAdditionPro.getInstance(),
                                           SCHEMATICA_CHANNEL.getChannel(),
                                           Objects.requireNonNull(byteArrayOutputStream.toByteArray(), "Schematica plugin message is null"));
    } catch (final IOException e) {
        AACAdditionPro.getInstance().getLogger().log(Level.SEVERE, "Could not write the Schematica packet.", e);
    }
}
 
Example #14
Source Project: EasyVPN-Free   Author: MaxSmile   File: PRNGFixes.java    License: GNU General Public License v3.0 6 votes vote down vote up
/**
 * Generates a device- and invocation-specific seed to be mixed into the
 * Linux PRNG.
 */
private static byte[] generateSeed() {
    try {
        ByteArrayOutputStream seedBuffer = new ByteArrayOutputStream();
        DataOutputStream seedBufferOut =
                new DataOutputStream(seedBuffer);
        seedBufferOut.writeLong(System.currentTimeMillis());
        seedBufferOut.writeLong(System.nanoTime());
        seedBufferOut.writeInt(Process.myPid());
        seedBufferOut.writeInt(Process.myUid());
        seedBufferOut.write(BUILD_FINGERPRINT_AND_DEVICE_SERIAL);
        seedBufferOut.close();
        return seedBuffer.toByteArray();
    } catch (IOException e) {
        throw new SecurityException("Failed to generate seed", e);
    }
}
 
Example #15
Source Project: external-nfc-api   Author: skjolber   File: IAcr1255UBinder.java    License: Apache License 2.0 6 votes vote down vote up
private byte[] noReaderException() {
    try {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        DataOutputStream dout = new DataOutputStream(out);

        dout.writeInt(AcrReader.VERSION);
        dout.writeInt(AcrReader.STATUS_EXCEPTION);
        dout.writeUTF("Reader not connected");

        byte[] response = out.toByteArray();

        Log.d(TAG, "Send exception response length " + response.length + ":" + ACRCommands.toHexString(response));

        return response;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example #16
Source Project: jdk8u-jdk   Author: lambdalab-mirror   File: DTDBuilder.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Save to a stream as a Java class. Instantiating this class will
 * reproduce a (virtually) identical DTD.
 */
void save(DataOutputStream out, String className) throws IOException {

    out.writeInt(DTD.FILE_VERSION);

    buildNamesTable();
    int numNames = namesVector.size();
    out.writeShort((short) (namesVector.size()));
    for (int i = 0; i < namesVector.size(); i++) {
        String nm = namesVector.elementAt(i);
        out.writeUTF(nm);
    }

    saveEntities(out);

    out.writeShort((short) (elements.size()));
    for (Enumeration<Element> e = elements.elements() ; e.hasMoreElements() ; ) {
        saveElement(out, e.nextElement());
    }

    if (namesVector.size() != numNames) {
        System.err.println("!!! ERROR!  Names were added to the list!");
        Thread.dumpStack();
        System.exit(1);
    }
}
 
Example #17
Source Project: jdk8u-jdk   Author: frohoff   File: BinaryAttribute.java    License: GNU General Public License v2.0 6 votes vote down vote up
static void write(BinaryAttribute attributes, DataOutputStream out,
                  BinaryConstantPool cpool, Environment env) throws IOException {
    // count the number of attributes
    int attributeCount = 0;
    for (BinaryAttribute att = attributes; att != null; att = att.next)
        attributeCount++;
    out.writeShort(attributeCount);

    // write out each attribute
    for (BinaryAttribute att = attributes; att != null; att = att.next) {
        Identifier name = att.name;
        byte data[] = att.data;
        // write the identifier
        out.writeShort(cpool.indexString(name.toString(), env));
        // write the length
        out.writeInt(data.length);
        // write the data
        out.write(data, 0, data.length);
    }
}
 
Example #18
Source Project: tinydnssd   Author: youviewtv   File: MDNSDiscover.java    License: MIT License 6 votes vote down vote up
static byte[] queryPacket(String serviceName, int qclass, int... qtypes) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);
    dos.writeInt(0);
    dos.writeShort(qtypes.length);  // questions
    dos.writeShort(0);  // answers
    dos.writeShort(0);  // nscount
    dos.writeShort(0);  // arcount
    int fqdnPtr = -1;
    for (int qtype : qtypes) {
        if (fqdnPtr == -1) {
            fqdnPtr = dos.size();
            writeFQDN(serviceName, dos);
        } else {
            // packet compression, string is just a pointer to previous occurrence
            dos.write(0xc0 | (fqdnPtr >> 8));
            dos.write(fqdnPtr & 0xFF);
        }
        dos.writeShort(qtype);
        dos.writeShort(qclass);
    }
    dos.close();
    return bos.toByteArray();
}
 
Example #19
Source Project: terracotta-platform   Author: Terracotta-OSS   File: ProxyMessageCodec.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public byte[] encodeResponse(ProxyEntityResponse r) throws MessageCodecException {
  if (r == null) {
    return new byte[0];
  }
  MessageType messageType = r.getMessageType();
  ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
  DataOutputStream output = new DataOutputStream(byteOut);
  try {
    output.writeByte(messageType.ordinal());
    output.writeByte(messageType == MessageType.ERROR ? 0 : getMessageTypeIdentifier(r));
    output.write(codec.encode(r.getResponseType(), r.getResponse()));
    output.close();
  } catch (Exception e) {
    throw new MessageCodecException("Error encoding ProxyEntityResponse", e);
  }
  return byteOut.toByteArray();
}
 
Example #20
Source Project: hadoop   Author: naver   File: DataXceiver.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void transferBlock(final ExtendedBlock blk,
    final Token<BlockTokenIdentifier> blockToken,
    final String clientName,
    final DatanodeInfo[] targets,
    final StorageType[] targetStorageTypes) throws IOException {
  checkAccess(socketOut, true, blk, blockToken,
      Op.TRANSFER_BLOCK, BlockTokenSecretManager.AccessMode.COPY);
  previousOpClientName = clientName;
  updateCurrentThreadName(Op.TRANSFER_BLOCK + " " + blk);

  final DataOutputStream out = new DataOutputStream(
      getOutputStream());
  try {
    datanode.transferReplicaForPipelineRecovery(blk, targets,
        targetStorageTypes, clientName);
    writeResponse(Status.SUCCESS, null, out);
  } catch (IOException ioe) {
    LOG.info("transferBlock " + blk + " received exception " + ioe);
    incrDatanodeNetworkErrors();
    throw ioe;
  } finally {
    IOUtils.closeStream(out);
  }
}
 
Example #21
Source Project: jdk8u_jdk   Author: JetBrains   File: JdpPacketWriter.java    License: GNU General Public License v2.0 5 votes vote down vote up
/**
 * Create a JDP packet, add mandatory magic and version headers
 *
 * @throws IOException
 */
public JdpPacketWriter()
        throws IOException {
    baos = new ByteArrayOutputStream();
    pkt = new DataOutputStream(baos);

    pkt.writeInt(JdpGenericPacket.getMagic());
    pkt.writeShort(JdpGenericPacket.getVersion());
}
 
Example #22
Source Project: phoenix   Author: apache   File: PTable.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ColumnValueEncoder getEncoder(int numElements) {
    PDataType type = PVarbinary.INSTANCE;
    int estimatedSize = PArrayDataType.estimateSize(numElements, type);
    TrustedByteArrayOutputStream byteStream = new TrustedByteArrayOutputStream(estimatedSize);
    DataOutputStream oStream = new DataOutputStream(byteStream);
    return new PArrayDataTypeEncoder(byteStream, oStream, numElements, type, SortOrder.ASC, false, getSerializationVersion());
}
 
Example #23
Source Project: incubator-iotdb   Author: apache   File: UnaryFilter.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(DataOutputStream outputStream) {
  try {
    outputStream.write(getSerializeId().ordinal());
    outputStream.write(filterType.ordinal());
    ReadWriteIOUtils.writeObject(value, outputStream);
  } catch (IOException ignored) {
    // ignored
  }
}
 
Example #24
Source Project: beam   Author: apache   File: BigEndianShortCoder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void encode(Short value, OutputStream outStream) throws IOException {
  if (value == null) {
    throw new CoderException("cannot encode a null Short");
  }
  new DataOutputStream(outStream).writeShort(value);
}
 
Example #25
Source Project: weex   Author: Laisly   File: Framer.java    License: Apache License 2.0 5 votes vote down vote up
public Framer(InputStream input, OutputStream output) throws IOException {
  mInput = new DataInputStream(input);
  mMultiplexedOutputStream = new DataOutputStream(output);
  mStdin = new FramingInputStream();
  mStdout = new PrintStream(
      new BufferedOutputStream(
          new FramingOutputStream(STDOUT_FRAME_PREFIX)));
  mStderr = new PrintStream(
      new FramingOutputStream(STDERR_FRAME_PREFIX));
}
 
Example #26
Source Project: document-viewer   Author: SufficientlySecure   File: DocumentCacheFile.java    License: GNU General Public License v3.0 5 votes vote down vote up
void saveCropping(final DataOutputStream out, final int tag, final int index, final RectF cropping)
        throws IOException {
    out.writeByte(tag);
    out.writeShort(index);
    out.writeFloat(cropping.left);
    out.writeFloat(cropping.top);
    out.writeFloat(cropping.right);
    out.writeFloat(cropping.bottom);
}
 
Example #27
Source Project: Alite   Author: CmdrStardust   File: InventoryScreen.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void saveScreenState(DataOutputStream dos) throws IOException {
	dos.writeByte(selection == null ? 0 : selection.getName().length());
	if (selection != null) {
		dos.writeChars(selection.getName());
	}
}
 
Example #28
Source Project: essentials   Author: greenrobot   File: PrimitiveDataChecksumTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateBoolean() throws Exception {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    new DataOutputStream(out).writeBoolean(true);
    long expected = getHashAndReset(out);
    primitiveDataChecksum.updateBoolean(true);
    Assert.assertEquals(expected, primitiveDataChecksum.getValue());
}
 
Example #29
Source Project: cacheonix-core   Author: cacheonix   File: ExecuteAllRequest.java    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
public void writeWire(final DataOutputStream out) throws IOException {

      super.writeWire(out);
      final ObjectOutputStream oos = new ObjectOutputStream(out);
      try {
         oos.writeObject(executable);
         oos.flush();
      } finally {
         IOUtils.closeHard(oos);
      }
   }
 
Example #30
Source Project: product-ei   Author: wso2   File: FileServiceApp.java    License: Apache License 2.0 5 votes vote down vote up
private void doPost(String url, String content) throws IOException {
	URL urlObj = new URL(url);
	URLConnection conn = urlObj.openConnection();
	conn.setDoInput(true);
	conn.setDoOutput(true);
	conn.setUseCaches(false);
	conn.setRequestProperty("Content-Type",	"application/x-www-form-urlencoded");
	DataOutputStream out = new DataOutputStream(conn.getOutputStream());
	out.writeBytes(content);
	out.flush();
	out.close();
	conn.getInputStream().close();
}