Example usage for java.io DataOutputStream writeUTF

List of usage examples for java.io DataOutputStream writeUTF

Introduction

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

Prototype

public final void writeUTF(String str) throws IOException 

Source Link

Document

Writes a string to the underlying output stream using modified UTF-8 encoding in a machine-independent manner.

Usage

From source file:com.ryan.ryanreader.cache.PersistentCookieStore.java

public synchronized byte[] toByteArray() {

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

    try {//w  ww . j  av  a 2  s.  co  m

        dos.writeInt(cookies.size());

        for (final Cookie cookie : cookies) {

            dos.writeUTF(cookie.getName());
            dos.writeUTF(cookie.getValue());
            dos.writeUTF(cookie.getDomain());
            dos.writeUTF(cookie.getPath());
            dos.writeBoolean(cookie.isSecure());
        }

        dos.flush();
        dos.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return baos.toByteArray();
}

From source file:J2MESortMixedRecordDataTypeExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);//from  w w w. ja va2s .c o  m
        notifyDestroyed();
    } else if (command == start) {
        try {
            recordstore = RecordStore.openRecordStore("myRecordStore", true);
            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();

            String[] inputString = new String[3];
            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();
            recordstore.closeRecordStore();
            if (RecordStore.listRecordStores() != null) {
                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:org.openmrs.module.odkconnector.serialization.serializer.openmrs.ObsSerializer.java

/**
 * Write the data to the output stream./*from   w w w.  j a  va 2s .  c o m*/
 *
 * @param stream the output stream
 * @param data   the data that need to be written to the output stream
 * @throws java.io.IOException thrown when the writing process encounter is failing
 */
@Override
public void write(final OutputStream stream, final Object data) throws IOException {
    try {
        Obs obs = (Obs) data;

        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
        DataOutputStream outputStream = new DataOutputStream(stream);
        // write the person id of the observation
        outputStream.writeInt(obs.getPersonId());
        // write the concept name of the observation
        outputStream.writeUTF(obs.getConcept().getDisplayString());
        // write the data type and the value of the observation
        if (obs.getValueDatetime() != null) {
            outputStream.writeByte(TYPE_DATE);
            outputStream.writeUTF(dateFormat.format(obs.getValueDatetime()));
        } else if (obs.getValueCoded() != null) {
            outputStream.writeByte(TYPE_STRING);
            outputStream.writeUTF(obs.getValueCoded().getDisplayString());
        } else if (obs.getValueNumeric() != null) {
            outputStream.writeByte(TYPE_DOUBLE);
            outputStream.writeDouble(obs.getValueNumeric());
        } else {
            outputStream.writeByte(TYPE_STRING);
            outputStream.writeUTF(obs.getValueAsString(Context.getLocale()));
        }
        // write the datetime of the observation
        outputStream.writeUTF(dateFormat.format(obs.getObsDatetime()));
    } catch (IOException e) {
        log.info("Writing obs information failed!", e);
    }
}

From source file:org.openmrs.module.odkconnector.serialization.web.PatientWebConnectorTest.java

@Test
public void serialize_shouldDisplayAllPatientInformation() throws Exception {

    // compose url
    URL u = new URL(SERVER_URL + "/module/odkconnector/download/patients.form");

    // setup http url connection
    HttpURLConnection connection = (HttpURLConnection) u.openConnection();
    connection.setDoOutput(true);/*from  www  . j  a  v  a  2  s  . c o m*/
    connection.setRequestMethod("POST");
    connection.setConnectTimeout(10000);
    connection.setReadTimeout(10000);
    connection.addRequestProperty("Content-type", "application/octet-stream");

    // write auth details to connection
    DataOutputStream outputStream = new DataOutputStream(new GZIPOutputStream(connection.getOutputStream()));
    outputStream.writeUTF("admin");
    outputStream.writeUTF("test");
    outputStream.writeBoolean(true);
    outputStream.writeInt(2);
    outputStream.writeInt(1);
    outputStream.close();

    DataInputStream inputStream = new DataInputStream(new GZIPInputStream(connection.getInputStream()));
    Integer responseStatus = inputStream.readInt();

    ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();

    int count = 0;
    byte[] buffer = new byte[1024];
    while ((count = inputStream.read(buffer)) > 0) {
        arrayOutputStream.write(buffer, 0, count);
    }
    arrayOutputStream.close();
    inputStream.close();

    File file = new File("/home/nribeka/connector.data");
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(arrayOutputStream.toByteArray());
    fos.close();

    inputStream = new DataInputStream(new FileInputStream(file));

    if (responseStatus == HttpURLConnection.HTTP_OK) {

        // total number of patients
        Integer patientCounter = inputStream.readInt();
        System.out.println("Patient Counter: " + patientCounter);
        for (int j = 0; j < patientCounter; j++) {
            System.out.println("=================Patient=====================");
            System.out.println("Patient Id: " + inputStream.readInt());
            System.out.println("Family Name: " + inputStream.readUTF());
            System.out.println("Middle Name: " + inputStream.readUTF());
            System.out.println("Last Name: " + inputStream.readUTF());
            System.out.println("Gender: " + inputStream.readUTF());
            System.out.println("Birth Date: " + inputStream.readUTF());
            System.out.println("Identifier: " + inputStream.readUTF());
            System.out.println("Patients: " + j + " out of " + patientCounter);
        }

        Integer obsCounter = inputStream.readInt();
        System.out.println("Observation Counter: " + obsCounter);
        for (int j = 0; j < obsCounter; j++) {
            System.out.println("==================Observation=================");
            System.out.println("Patient Id: " + inputStream.readInt());
            System.out.println("Concept Name: " + inputStream.readUTF());

            byte type = inputStream.readByte();
            if (type == ObsSerializer.TYPE_STRING)
                System.out.println("Value: " + inputStream.readUTF());
            else if (type == ObsSerializer.TYPE_INT)
                System.out.println("Value: " + inputStream.readInt());
            else if (type == ObsSerializer.TYPE_DOUBLE)
                System.out.println("Value: " + inputStream.readDouble());
            else if (type == ObsSerializer.TYPE_DATE)
                System.out.println("Value: " + inputStream.readUTF());
            System.out.println("Time: " + inputStream.readUTF());
            System.out.println("Obs: " + j + " out of: " + obsCounter);
        }
        Integer formCounter = inputStream.readInt();
        System.out.println("Form Counter: " + formCounter);
        for (int j = 0; j < formCounter; j++) {
            System.out.println("==================Observation=================");
            System.out.println("Patient Id: " + inputStream.readInt());
            System.out.println("Concept Name: " + inputStream.readUTF());

            byte type = inputStream.readByte();
            if (type == ObsSerializer.TYPE_STRING)
                System.out.println("Value: " + inputStream.readUTF());
            else if (type == ObsSerializer.TYPE_INT)
                System.out.println("Value: " + inputStream.readInt());
            else if (type == ObsSerializer.TYPE_DOUBLE)
                System.out.println("Value: " + inputStream.readDouble());
            else if (type == ObsSerializer.TYPE_DATE)
                System.out.println("Value: " + inputStream.readUTF());
            System.out.println("Time: " + inputStream.readUTF());
            System.out.println("Form: " + j + " out of: " + formCounter);
        }
    }
    inputStream.close();
}

From source file:MixedRecordEnumerationExample.java

public void commandAction(Command command, Displayable displayable) {
    if (command == exit) {
        destroyApp(true);//  ww  w . j a  va2s.  com
        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[] = { "First Record", "Second Record", "Third Record" };
            int outputInteger[] = { 15, 10, 5 };
            boolean outputBoolean[] = { true, false, true };
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            DataOutputStream outputDataStream = new DataOutputStream(outputStream);
            for (int x = 0; x < 3; x++) {
                outputDataStream.writeUTF(outputString[x]);
                outputDataStream.writeBoolean(outputBoolean[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 {
            StringBuffer buffer = new StringBuffer();
            byte[] byteInputData = new byte[300];
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);
            DataInputStream inputDataStream = new DataInputStream(inputStream);
            recordEnumeration = recordstore.enumerateRecords(null, null, false);
            while (recordEnumeration.hasNextElement()) {
                recordstore.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0);
                buffer.append(inputDataStream.readUTF());
                buffer.append("\n");
                buffer.append(inputDataStream.readBoolean());
                buffer.append("\n");
                buffer.append(inputDataStream.readInt());
                buffer.append("\n");
                alert = new Alert("Reading", buffer.toString(), 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");
                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:com.github.terma.m.server.Repo.java

public void storeMetricCodes(final Map<String, Short> metricCodes) throws IOException {
    DataOutputStream dos = null;
    try {/*from   www  .j a  v a2  s  .c  o m*/
        dos = new DataOutputStream(new FileOutputStream(eventCodesFile));
        for (Map.Entry<String, Short> metricCode : metricCodes.entrySet()) {
            dos.writeUTF(metricCode.getKey());
            dos.writeShort(metricCode.getValue());
        }
    } finally {
        IOUtils.closeQuietly(dos);
    }
}

From source file:bankingclient.TaoTaiKhoanFrame.java

public TaoTaiKhoanFrame(NewOrOldAccFrame acc) {

    initComponents();//from   w  ww  .j a  v  a2s.co m
    this.jText_ten_tk.setText("");
    this.jText_sd.setText("");

    this.noAcc = acc;
    this.mainCustomerName = null;
    this.setVisible(false);

    jBt_ht.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            if (NumberUtils.isNumber(jText_sd.getText()) && (Long.parseLong(jText_sd.getText()) > 0)) {
                try {
                    Socket client = new Socket("113.22.46.207", 6013);
                    DataOutputStream dout = new DataOutputStream(client.getOutputStream());
                    dout.writeByte(3);
                    dout.writeUTF(jText_ten_tk.getText() + "\n" + mainCustomerName + "\n" + jText_sd.getText());
                    dout.flush();
                    DataInputStream din = new DataInputStream(client.getInputStream());
                    byte check = din.readByte();
                    if (check == 1) {
                        JOptionPane.showMessageDialog(rootPane, "da tao tai khoan thanh cong");
                    } else {
                        JOptionPane.showMessageDialog(rootPane, "tao tai khoan khong thanh cong");
                    }
                    client.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                noAcc.setVisible(true);
                TaoTaiKhoanFrame.this.setVisible(false);
            } else {
                JOptionPane.showMessageDialog(rootPane, "Can nhap lai so tien gui");
            }

        }
    });
    jBt_ql.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            noAcc.setVisible(true);
            TaoTaiKhoanFrame.this.setVisible(false);

        }
    });
}

From source file:com.rapidminer.cryptography.hashing.DigesterProvider.java

/**
 * Writes the provided value to the provided {@link DataOutputStream}.
 *///  ww  w.j av  a 2  s .  co  m
private void writeBytes(Object value, DataOutputStream dos) throws IOException, JEPFunctionException {
    if (value instanceof String) {
        dos.writeUTF((String) value);
    } else if (value instanceof Integer) {
        dos.writeInt((int) value);
    } else if (value instanceof Long) {
        dos.writeLong((long) value);
    } else if (value instanceof Float) {
        dos.writeFloat((float) value);
    } else if (value instanceof GregorianCalendar) {
        dos.writeLong(((GregorianCalendar) value).getTimeInMillis());
    } else if (value instanceof Date) {
        dos.writeLong(((Date) value).getTime());
    } else if (value instanceof Double) {
        dos.writeDouble((double) value);
    } else if (value instanceof UnknownValue) {
        dos.writeDouble(Double.NaN);
    } else {
        // should not happen
        throw new JEPFunctionException("Unknown input type: " + value.getClass());
    }
}

From source file:com.bigdata.dastor.db.RowMutation.java

public void serialize(RowMutation rm, DataOutputStream dos) throws IOException {
    dos.writeUTF(rm.getTable());
    dos.writeUTF(rm.key());/*from  w w w . j  a va2  s . c  o  m*/

    /* serialize the modifications_ in the mutation */
    freezeTheMaps(rm.modifications_, dos);
}

From source file:org.openxdata.server.serializer.JavaRosaXformSerializer.java

/**
 * //from  ww  w.j ava2s  .  com
 * @param dos
 * @param data
 */
@Override
public void serializeForms(OutputStream os, List<String> xforms, Integer studyId, String studyName,
        String studyKey) {
    //This is always a list of strings.
    DataOutputStream dos = new DataOutputStream(os);

    for (String xml : xforms) {
        try {
            String xhtml = XformUtil.fromXform2Xhtml(xml);
            dos.writeUTF(xhtml.trim());
        } catch (Exception e) {
            throw new UnexpectedException(e);
        }
    }
}