Example usage for java.io DataOutputStream close

List of usage examples for java.io DataOutputStream close

Introduction

In this page you can find the example usage for java.io DataOutputStream close.

Prototype

@Override
public void close() throws IOException 

Source Link

Document

Closes this output stream and releases any system resources associated with the stream.

Usage

From source file:com.netflix.zeno.examples.BasicSerializationExample.java

public byte[] createSnapshot() {
    /// We add each of our object instances to the state engine.
    /// This operation is thread safe and can be called from multiple processing threads.
    stateEngine.add("A", getExampleA1());
    stateEngine.add("A", getExampleA2());

    /// The following lets the state engine know that we have finished adding all of our
    /// objects to the state.
    stateEngine.prepareForWrite();/* ww  w . j  av  a 2 s .  co m*/

    /// Create a writer, which will be responsible for creating snapshot and/or delta blobs.
    FastBlobWriter writer = new FastBlobWriter(stateEngine);

    /// Create an output stream to somewhere.  This can be to a local file on disk
    /// or directly to the blob destination.  The VMS team writes this data directly
    /// to disk, and then spawns a new thread to upload the data to S3.
    /// We need to pass a DataOutputStream.  Remember that DataOutputStream is not buffered,
    /// so if you write to a FileOutputStream or other non-buffered source, you likely want to
    /// make the DataOutputStream wrap a BufferedOutputStream
    /// (e.g. new DataOutputStream(new BufferedOutputStream(new FileOutputStream(destinationFile))))
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream outputStream = new DataOutputStream(baos);

    try {
        /// write the snapshot to the output stream.
        writer.writeSnapshot(outputStream);
    } catch (IOException e) {
        /// the FastBlobWriter throws an IOException if it is
        /// unable to write to the provided OutputStream
    } finally {
        /// it is your responsibility to close the stream.  The FastBlobWriter will not do this.
        try {
            outputStream.close();
        } catch (IOException ignore) {
        }
    }

    byte snapshot[] = baos.toByteArray();

    return snapshot;
}

From source file:cd.education.data.collector.android.tasks.FormLoaderTask.java

/**
 * Write the FormDef to the file system as a binary blog.
 *
 * @param filepath/*ww  w .  ja  v a  2  s .c om*/
 *          path to the form file
 */
public void serializeFormDef(FormDef fd, String filepath) {
    // calculate unique md5 identifier
    String hash = FileUtils.getMd5Hash(new File(filepath));
    File formDef = new File(Collect.CACHE_PATH + File.separator + hash + ".formdef");

    // formdef does not exist, create one.
    if (!formDef.exists()) {
        FileOutputStream fos;
        try {
            fos = new FileOutputStream(formDef);
            DataOutputStream dos = new DataOutputStream(fos);
            fd.writeExternal(dos);
            dos.flush();
            dos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:SearchMixedRecordDataTypeExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);/*from  w w  w .j a v  a2  s.  co m*/
        notifyDestroyed();
    } else if (command == start) {
        try {
            recordstore = RecordStore.openRecordStore("myRecordStore", true);
        } catch (Exception error) {
            alert = new Alert("Error Creating", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            byte[] outputRecord;
            String outputString[] = { "Adam", "Bob", "Mary" };
            int outputInteger[] = { 15, 10, 5 };
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            DataOutputStream outputDataStream = new DataOutputStream(outputStream);
            for (int x = 0; x < 3; x++) {
                outputDataStream.writeUTF(outputString[x]);
                outputDataStream.writeInt(outputInteger[x]);
                outputDataStream.flush();
                outputRecord = outputStream.toByteArray();
                recordstore.addRecord(outputRecord, 0, outputRecord.length);
                outputStream.reset();
            }
            outputStream.close();
            outputDataStream.close();
        } catch (Exception error) {
            alert = new Alert("Error Writing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            String inputString;
            byte[] byteInputData = new byte[300];
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
            DataInputStream inputDataStream = new DataInputStream(inputStream);
            if (recordstore.getNumRecords() > 0) {
                filter = new Filter("Mary");
                recordEnumeration = recordstore.enumerateRecords(filter, null, false);
                while (recordEnumeration.hasNextElement()) {
                    recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0);
                    inputString = inputDataStream.readUTF() + " " + inputDataStream.readInt();
                    alert = new Alert("Reading", inputString, null, AlertType.WARNING);
                    alert.setTimeout(Alert.FOREVER);
                    display.setCurrent(alert);
                }
            }
            inputStream.close();
        } catch (Exception error) {
            alert = new Alert("Error Reading", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            recordstore.closeRecordStore();
        } catch (Exception error) {
            alert = new Alert("Error Closing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        if (RecordStore.listRecordStores() != null) {
            try {
                RecordStore.deleteRecordStore("myRecordStore");
                filter.filterClose();
                recordEnumeration.destroy();
            } catch (Exception error) {
                alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING);
                alert.setTimeout(Alert.FOREVER);
                display.setCurrent(alert);
            }
        }
    }
}

From source file:io.dacopancm.socketdcm.net.StreamSocket.java

public ObservableList<StreamFile> getStreamList() {
    ObservableList<StreamFile> list = FXCollections.observableArrayList();
    try {//  w  ww  .  j  a v a 2  s  .  c  om

        if (ConectType.GET_STREAMLIST.name().equalsIgnoreCase(method)) {
            logger.log(Level.INFO, "get stream list call");
            sock = new Socket(ip, port);

            DataOutputStream dOut = new DataOutputStream(sock.getOutputStream());
            DataInputStream dIn = new DataInputStream(sock.getInputStream());

            dOut.writeUTF(ConectType.STREAM.name());//send stream type
            dOut.writeUTF("uncompressed");//send comprimido o no

            dOut.writeUTF(ConectType.GET_STREAMLIST.toString()); //send type
            dOut.writeUTF("mayra");
            dOut.flush(); // Send off the data
            System.out.println("Request list send");
            String resp = dIn.readUTF();
            dOut.close();
            logger.log(Level.INFO, "resp get streamlist: {0}", resp);
            List<StreamFile> files = HelperUtil.fromJSON(resp);
            list.addAll(files);

        }
    } catch (IOException ex) {
        HelperUtil.showErrorB("No se pudo establecer conexin");
        logger.log(Level.INFO, "get streamlist error no connect:{0}", ex.getMessage());
        try {
            if (sock != null) {
                sock.close();
            }
        } catch (IOException e) {
        }

    }
    return list;
}

From source file:org.darwinathome.server.controller.HubController.java

@RequestMapping(Hub.AUTHENTICATE_SERVICE)
public void authenticate(@RequestParam(Hub.PARAM_BODY_NAME) String bodyName,
        @RequestParam(Hub.PARAM_PASSWORD) String password, OutputStream outputStream) throws IOException {
    log.info(Hub.AUTHENTICATE_SERVICE);/*from   w w  w. j  a v  a  2  s.co  m*/
    DataOutputStream dos = new DataOutputStream(outputStream);
    Player player = storage.authenticate(bodyName, password);
    if (player != null) {
        PlayerSession session = new PlayerSession(player);
        sessionMap.put(session.getToken(), session);
        dos.writeUTF(Hub.SUCCESS);
        dos.writeUTF(session.getToken());
    } else {
        dos.writeUTF(Hub.FAILURE);
        dos.writeUTF(Failure.AUTHENTICATION.toString());
    }
    dos.close();
}

From source file:me.cybermaxke.merchants.v16r3.SMerchant.java

@Override
public boolean addCustomer(Player player) {
    checkNotNull(player, "player");

    if (this.customers.add(player)) {
        EntityPlayer player0 = ((CraftPlayer) player).getHandle();
        Container container0 = null;

        try {/*from w  w w  . j  a va2 s  .  co m*/
            container0 = new SContainerMerchant(player0, this);
            container0 = CraftEventFactory.callInventoryOpenEvent(player0, container0);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (container0 == null) {
            this.customers.remove(player);
            return false;
        }

        int window = player0.nextContainerCounter();

        player0.activeContainer = container0;
        player0.activeContainer.windowId = window;
        player0.activeContainer.addSlotListener(player0);

        // Open the window
        player0.playerConnection.sendPacket(new Packet100OpenWindow(window, 6, this.sendTitle, 3, true));

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream dos = new DataOutputStream(baos);

        try {
            // Write the window id
            dos.writeInt(window);
            // Write the offers
            this.offers.a(dos);
            // Flush and close data stream
            dos.flush();
            dos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // Send the offers
        player0.playerConnection.sendPacket(new Packet250CustomPayload("MC|TrList", baos.toByteArray()));
        return true;
    }

    return false;
}

From source file:com.jfolson.hive.serde.RTypedBytesWritableOutput.java

public void writeWritable(Writable w) throws IOException {
    DataOutputStream dos = null;
    try {/*  w  w  w. j av  a2  s  .c o  m*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        dos = new DataOutputStream(baos);
        WritableUtils.writeString(dos, w.getClass().getName());
        w.write(dos);
        out.writeBytes(baos.toByteArray(), RType.WRITABLE.code);
        dos.close();
        dos = null;
    } finally {
        IOUtils.closeStream(dos);
    }
}

From source file:com.asto.move.util.qcloud.pic.PicCloud.java

/**
 * Download ??//from w  w  w  .  j a  v a2  s  . co m
 *
 * @param url   
 * @param fileName ?
 * @return ?0?
 */
public int Download(String url, String fileName) {
    if (fileName == null || "".equals(fileName)) {
        return SetError(-1, "file name is empty.");
    }
    String rsp = "";
    try {
        URL realUrl = new URL(url);
        HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
        // set header
        connection.setRequestMethod("GET");
        connection.setRequestProperty("Host", "web.image.myqcloud.com");
        connection.setRequestProperty("user-agent", "qcloud-java-sdk");

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.connect();

        InputStream in = new DataInputStream(connection.getInputStream());
        File file = new File(fileName);
        String path = "";
        if (!file.exists()) {
            path = fileName.substring(0, fileName.lastIndexOf("/"));
            File catalogFile = new File(path);
            catalogFile.mkdirs();
        }
        DataOutputStream ops = new DataOutputStream(new FileOutputStream(file));
        int bytes = 0;
        byte[] bufferOut = new byte[1024];
        while ((bytes = in.read(bufferOut)) > 0) {
            ops.write(bufferOut, 0, bytes);
        }
        ops.close();
        in.close();
    } catch (Exception e) {
        return SetError(-1, "url exception, e=" + e.toString());
    }

    return SetError(0, "success");
}

From source file:SortMixedRecordDataTypeExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);//from   w ww  .j ava2s .c  o m
        notifyDestroyed();
    } else if (command == start) {
        try {
            recordstore = RecordStore.openRecordStore("myRecordStore", true);
        } catch (Exception error) {
            alert = new Alert("Error Creating", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            byte[] outputRecord;
            String outputString[] = { "Mary", "Bob", "Adam" };
            int outputInteger[] = { 15, 10, 5 };
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            DataOutputStream outputDataStream = new DataOutputStream(outputStream);
            for (int x = 0; x < 3; x++) {
                outputDataStream.writeUTF(outputString[x]);
                outputDataStream.writeInt(outputInteger[x]);
                outputDataStream.flush();
                outputRecord = outputStream.toByteArray();
                recordstore.addRecord(outputRecord, 0, outputRecord.length);
                outputStream.reset();
            }
            outputStream.close();
            outputDataStream.close();
        } catch (Exception error) {
            alert = new Alert("Error Writing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            String[] inputString = new String[3];
            int z = 0;
            byte[] byteInputData = new byte[300];
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
            DataInputStream inputDataStream = new DataInputStream(inputStream);
            StringBuffer buffer = new StringBuffer();
            comparator = new Comparator();
            recordEnumeration = recordstore.enumerateRecords(null, comparator, false);
            while (recordEnumeration.hasNextElement()) {
                recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0);
                buffer.append(inputDataStream.readUTF());
                buffer.append(inputDataStream.readInt());
                buffer.append("\n");
                inputDataStream.reset();
            }
            alert = new Alert("Reading", buffer.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
            inputDataStream.close();
            inputStream.close();
        } catch (Exception error) {
            alert = new Alert("Error Reading", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        try {
            recordstore.closeRecordStore();
        } catch (Exception error) {
            alert = new Alert("Error Closing", error.toString(), null, AlertType.WARNING);
            alert.setTimeout(Alert.FOREVER);
            display.setCurrent(alert);
        }
        if (RecordStore.listRecordStores() != null) {
            try {
                RecordStore.deleteRecordStore("myRecordStore");
                comparator.compareClose();
                recordEnumeration.destroy();
            } catch (Exception error) {
                alert = new Alert("Error Removing", error.toString(), null, AlertType.WARNING);
                alert.setTimeout(Alert.FOREVER);
                display.setCurrent(alert);
            }
        }
    }
}

From source file:info.magnolia.cms.exchange.simple.Transporter.java

/**
 * http form multipart form post//from   w  ww . j a va  2  s .com
 * @param connection
 * @param activationContent
 * @throws ExchangeException
 */
public static void transport(URLConnection connection, ActivationContent activationContent)
        throws ExchangeException {
    FileInputStream fis = null;
    DataOutputStream outStream = null;
    try {
        byte[] buffer = new byte[BUFFER_SIZE];
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        connection.setRequestProperty("Content-type", "multipart/form-data; boundary=" + BOUNDARY);
        connection.setRequestProperty("Cache-Control", "no-cache");

        outStream = new DataOutputStream(connection.getOutputStream());
        outStream.writeBytes("--" + BOUNDARY + "\r\n");

        // set all resources from activationContent
        Iterator fileNameIterator = activationContent.getFiles().keySet().iterator();
        while (fileNameIterator.hasNext()) {
            String fileName = (String) fileNameIterator.next();
            fis = new FileInputStream(activationContent.getFile(fileName));
            outStream.writeBytes("content-disposition: form-data; name=\"" + fileName + "\"; filename=\""
                    + fileName + "\"\r\n");
            outStream.writeBytes("content-type: application/octet-stream" + "\r\n\r\n");
            while (true) {
                synchronized (buffer) {
                    int amountRead = fis.read(buffer);
                    if (amountRead == -1) {
                        break;
                    }
                    outStream.write(buffer, 0, amountRead);
                }
            }
            fis.close();
            outStream.writeBytes("\r\n" + "--" + BOUNDARY + "\r\n");
        }
        outStream.flush();
        outStream.close();

        log.debug("Activation content sent as multipart/form-data");
    } catch (Exception e) {
        throw new ExchangeException(
                "Simple exchange transport failed: " + ClassUtils.getShortClassName(e.getClass()), e);
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                log.error("Exception caught", e);
            }
        }
        if (outStream != null) {
            try {
                outStream.close();
            } catch (IOException e) {
                log.error("Exception caught", e);
            }
        }
    }

}