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 File: IAcr1255UBinder.java    From external-nfc-api with 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 #2
Source File: Util.java    From XKik with 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 #3
Source File: ProxyGenerator.java    From TencentKona-8 with 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 #4
Source File: TestTupleWritable.java    From big-c with 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 #5
Source File: CompressedDataBuffer.java    From deeplearning4j with 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 #6
Source File: TestStandardTocReader.java    From nifi with 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 #7
Source File: DTDBuilder.java    From hottub with 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 #8
Source File: TestMRAppWithCombiner.java    From hadoop with 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 #9
Source File: ZMsg.java    From aion with 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 #10
Source File: EngineIRWriter.java    From birt with 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 #11
Source File: TextIOJobBuilder.java    From hiped2 with 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 #12
Source File: DataXceiver.java    From hadoop with 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 #13
Source File: PRNGFixes.java    From EasyVPN-Free with 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 #14
Source File: DTDBuilder.java    From jdk8u-jdk with 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 #15
Source File: BinaryAttribute.java    From jdk8u-jdk with 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 #16
Source File: SchematicaControl.java    From AACAdditionPro with 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 #17
Source File: LoadSimulationController.java    From pulsar with 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 #18
Source File: ReportContent.java    From birt with 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 #19
Source File: MDNSDiscover.java    From tinydnssd with 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 #20
Source File: ProxyMessageCodec.java    From terracotta-platform with 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 #21
Source File: BigEndianShortCoder.java    From beam with 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 #22
Source File: WindowCheckVanish.java    From ehacks-pro with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void run() {
    //YouAlwaysWinClickGui.log("[LegacyPingCV] Updating");
    ServerData serverData = Wrapper.INSTANCE.mc().func_147104_D();
    if (serverData == null) {
        lastLpResult = -2;
        lpThreadStarted.set(false);
        return;
    }
    ServerAddress address = ServerAddress.func_78860_a(serverData.serverIP);
    try {
        String[] data;
        //clientSocket.connect(new InetSocketAddress("n5.streamcraft.net", 25666), 7000);
        try (Socket clientSocket = new Socket()) {
            //clientSocket.connect(new InetSocketAddress("n5.streamcraft.net", 25666), 7000);
            clientSocket.connect(new InetSocketAddress(address.getIP(), address.getPort()), 7000);
            clientSocket.setSoTimeout(7000);
            DataOutputStream dos = new DataOutputStream(clientSocket.getOutputStream());
            BufferedReader br = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            dos.write(payload, 0, payload.length);
            data = br.readLine().split("\u0000\u0000\u0000");
        }
        if (data.length < 2) {
            lastLpResult = -2;
            lpThreadStarted.set(false);
            return;
        }
        lastLpResult = Integer.valueOf(data[data.length - 2].replace("\u0000", ""));
        //YouAlwaysWinClickGui.log("[LegacyPingCV] Updated");
    } catch (Exception e) {
        lastLpResult = -1;
        //YouAlwaysWinClickGui.log("[LegacyPingCV] Error on updating: " + e.getMessage());
    }
    lpThreadStarted.set(false);
}
 
Example #23
Source File: DoubleSupplierTest.java    From Lightweight-Stream-API with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setUp() throws IOException {
    final ByteArrayOutputStream baos = new ByteArrayOutputStream(15);
    final DataOutputStream dos = new DataOutputStream(baos);
    dos.writeDouble(0.16);
    dos.writeDouble(3.20);
    dos.writeDouble(5000);
    input = baos.toByteArray();
}
 
Example #24
Source File: ExternalizableJsonEntity.java    From parse4cn1 with Apache License 2.0 5 votes vote down vote up
/**
 * @see com.codename1.io.Externalizable
 */
public void externalize(DataOutputStream out) throws IOException {
    Util.writeUTF(type.toString(), out);
    if (type == EJsonEntityType.JSON_ARRAY) {
       Util.writeObject(ParseDecoder.convertJSONArrayToList((JSONArray)object), out); 
    } else if (type == EJsonEntityType.JSON_OBJECT) {
       Util.writeObject(ParseDecoder.convertJSONObjectToMap((JSONObject)object), out);
    }
}
 
Example #25
Source File: GetKeyOwnerRequest.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
public void writeWire(final DataOutputStream out) throws IOException {

      super.writeWire(out);
      SerializerUtils.writeString(cacheName, out);
      out.writeInt(storageNumber);
      out.writeShort(bucketNumber);
   }
 
Example #26
Source File: UnaryFilter.java    From incubator-iotdb with 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 #27
Source File: GOTO.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Dump instruction as byte code to stream out.
 * @param out Output stream
 */
@Override
public void dump( final DataOutputStream out ) throws IOException {
    super.setIndex(getTargetOffset());
    final short _opcode = getOpcode();
    if (_opcode == com.sun.org.apache.bcel.internal.Const.GOTO) {
        super.dump(out);
    } else { // GOTO_W
        super.setIndex(getTargetOffset());
        out.writeByte(_opcode);
        out.writeInt(super.getIndex());
    }
}
 
Example #28
Source File: TestSocketClientTransaction.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
@Test
public void testReceiveWithInvalidChecksum() throws IOException {

    ByteArrayOutputStream serverResponseBos = new ByteArrayOutputStream();
    DataOutputStream serverResponse = new DataOutputStream(serverResponseBos);
    ResponseCode.MORE_DATA.writeResponse(serverResponse);
    codec.encode(createDataPacket("contents on server 1"), serverResponse);
    ResponseCode.CONTINUE_TRANSACTION.writeResponse(serverResponse);
    codec.encode(createDataPacket("contents on server 2"), serverResponse);
    ResponseCode.FINISH_TRANSACTION.writeResponse(serverResponse);
    ResponseCode.BAD_CHECKSUM.writeResponse(serverResponse);


    ByteArrayInputStream bis = new ByteArrayInputStream(serverResponseBos.toByteArray());
    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    SocketClientTransaction transaction = getClientTransaction(bis, bos, TransferDirection.RECEIVE);

    execReceiveWithInvalidChecksum(transaction);

    // Verify what client has sent.
    DataInputStream sentByClient = new DataInputStream(new ByteArrayInputStream(bos.toByteArray()));
    assertEquals(RequestType.RECEIVE_FLOWFILES, RequestType.readRequestType(sentByClient));
    Response confirmResponse = Response.read(sentByClient);
    assertEquals(ResponseCode.CONFIRM_TRANSACTION, confirmResponse.getCode());
    assertEquals("Checksum should be calculated at client", "2969091230", confirmResponse.getMessage());
    assertEquals(-1, sentByClient.read());
}
 
Example #29
Source File: AvroUtils.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
/**
 * Write a schema to a file
 * @param schema the schema
 * @param filePath the target file
 * @param tempFilePath if not null then this path is used for a temporary file used to stage the write
 * @param fs a {@link FileSystem}
 * @param overwrite should any existing target file be overwritten?
 * @param perm permissions
 * @throws IOException
 */
public static void writeSchemaToFile(Schema schema, Path filePath, Path tempFilePath, FileSystem fs, boolean overwrite,
    FsPermission perm)
    throws IOException {
  boolean fileExists = fs.exists(filePath);

  if (!overwrite) {
    Preconditions.checkState(!fileExists, filePath + " already exists");
  } else {
    // delete the target file now if not using a staging file
    if (fileExists && null == tempFilePath) {
      HadoopUtils.deletePath(fs, filePath, true);
      // file has been removed
      fileExists = false;
    }
  }

  // If the file exists then write to a temp file to make the replacement as close to atomic as possible
  Path writeFilePath = fileExists ? tempFilePath : filePath;

  try (DataOutputStream dos = fs.create(writeFilePath)) {
    dos.writeChars(schema.toString());
  }
  fs.setPermission(writeFilePath, perm);

  // Replace existing file with the staged file
  if (fileExists) {
    if (!fs.delete(filePath, true)) {
      throw new IOException(
          String.format("Failed to delete %s while renaming %s to %s", filePath, tempFilePath, filePath));
    }

    HadoopUtils.movePath(fs, tempFilePath, fs, filePath, true, fs.getConf());
  }
}
 
Example #30
Source File: Row.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
public static final byte[] extractData( Row row ) {
  try {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    DataOutputStream dataOutputStream = new DataOutputStream( byteArrayOutputStream );
    row.writeData( dataOutputStream );
    dataOutputStream.close();
    byteArrayOutputStream.close();
    return byteArrayOutputStream.toByteArray();
  } catch ( Exception e ) {
    throw new RuntimeException( BaseMessages.getString( PKG, "Row.ErrorSerializing" ) + row, e );
  }
}