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.almalence.googsharing.Thumbnail.java

public void saveTo(File file) {
    FileOutputStream f = null;// www  . j  a v a  2  s . co  m
    BufferedOutputStream b = null;
    DataOutputStream d = null;
    try {
        f = new FileOutputStream(file);
        b = new BufferedOutputStream(f, BUFSIZE);
        d = new DataOutputStream(b);
        d.writeUTF(mUri.toString());
        mBitmap.compress(Bitmap.CompressFormat.JPEG, 90, d);
        d.close();
    } catch (IOException e) {
        Log.e(TAG, "Fail to store bitmap. path=" + file.getPath(), e);
    } finally {
        Util.closeSilently(f);
        Util.closeSilently(b);
        Util.closeSilently(d);
    }
}

From source file:org.hyperic.hq.agent.db.DiskList.java

/**
 * Add the string to the list of data being stored in the DiskList.
 *
 * @param data Data to add to the end of the list
 */// ww  w . j a v  a 2 s  .c  om
public void addToList(String data) throws IOException {
    if (this.closed) {
        throw new IOException("Datafile already closed");
    }
    ByteArrayOutputStream bOs = new ByteArrayOutputStream(this.recordSize);
    DataOutputStream dOs = new DataOutputStream(bOs);
    dOs.writeUTF(data);
    if (bOs.size() > this.recordSize) {
        throw new IOException(
                "Data length(" + bOs.size() + ") exceeds " + "maximum record length(" + this.recordSize + ")");
    }
    final long start = now();
    bOs.write(this.padBytes, 0, this.recordSize - bOs.size());
    byte[] bytes = bOs.toByteArray();

    synchronized (this.dataFile) {
        Long firstFreeL;
        long firstFree;

        this.modNum = this.rand.nextInt();

        try {
            firstFreeL = (Long) this.freeList.first();
            firstFree = firstFreeL.longValue();
            this.freeList.remove(firstFreeL);
        } catch (NoSuchElementException exc) {
            // Else we're adding to the end
            firstFree = this.indexFile.length() / IDX_REC_LEN;
        }

        // Write the record to the data file
        this.dataFile.seek(firstFree * this.recordSize);
        this.dataFile.write(bytes);

        bOs.reset();
        dOs.writeBoolean(true); // Is Used
        dOs.writeLong(this.lastRec); // Previous record idx
        dOs.writeLong(-1); // Next record idx

        // Write the index for the record we just made
        this.indexFile.seek(firstFree * IDX_REC_LEN);
        bytes = bOs.toByteArray();
        this.indexFile.write(bytes, 0, bytes.length);

        // Update the previous 'last' record to point to us
        if (this.lastRec != -1) {
            this.indexFile.seek((this.lastRec * IDX_REC_LEN) + 1 + 8);
            this.indexFile.writeLong(firstFree);
        }

        this.lastRec = firstFree;
        if (this.firstRec == -1) {
            this.firstRec = firstFree;
        }
    }

    if (this.dataFile.length() > this.maxLength) {
        this.log.error("Maximum file size for data file: " + this.fileName + " reached (" + this.maxLength
                + " bytes), truncating.");
        deleteAllRecords();
    }
    long duration = now() - start;
    statsCollector.addStat(duration, DISK_LIST_ADD_TO_LIST_TIME);
}

From source file:org.jboss.as.test.integration.security.common.AbstractKrb5ConfServerSetupTask.java

/**
 * Creates a keytab file for given principal.
 *
 * @param principalName/* w  ww  . j  a va2 s. co  m*/
 * @param passPhrase
 * @param keytabFile
 * @throws IOException
 */
protected void createKeytab(final String principalName, final String passPhrase, final File keytabFile)
        throws IOException {
    LOGGER.trace("Principal name: " + principalName);
    final KerberosTime timeStamp = new KerberosTime();

    DataOutputStream dos = null;
    try {
        dos = new DataOutputStream(new FileOutputStream(keytabFile));
        dos.write(Keytab.VERSION_0X502_BYTES);

        for (Map.Entry<EncryptionType, EncryptionKey> keyEntry : KerberosKeyFactory
                .getKerberosKeys(principalName, passPhrase).entrySet()) {
            final EncryptionKey key = keyEntry.getValue();
            final byte keyVersion = (byte) key.getKeyVersion();
            // entries.add(new KeytabEntry(principalName, principalType, timeStamp, keyVersion, key));

            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DataOutputStream entryDos = new DataOutputStream(baos);
            // handle principal name
            String[] spnSplit = principalName.split("@");
            String nameComponent = spnSplit[0];
            String realm = spnSplit[1];

            String[] nameComponents = nameComponent.split("/");
            try {
                // increment for v1
                entryDos.writeShort((short) nameComponents.length);
                entryDos.writeUTF(realm);
                // write components
                for (String component : nameComponents) {
                    entryDos.writeUTF(component);
                }

                entryDos.writeInt(1); // principal type: KRB5_NT_PRINCIPAL
                entryDos.writeInt((int) (timeStamp.getTime() / 1000));
                entryDos.write(keyVersion);

                entryDos.writeShort((short) key.getKeyType().getValue());

                byte[] data = key.getKeyValue();
                entryDos.writeShort((short) data.length);
                entryDos.write(data);
            } finally {
                IOUtils.closeQuietly(entryDos);
            }
            final byte[] entryBytes = baos.toByteArray();
            dos.writeInt(entryBytes.length);
            dos.write(entryBytes);
        }
        // } catch (IOException ioe) {
    } finally {
        IOUtils.closeQuietly(dos);
    }
}

From source file:com.chaosinmotion.securechat.server.messages.NotificationSocket.java

/**
 * Internal method for sending a message to the specified device. This
 * encodes the message as a binary array and transmits it as a single 
 * packet to the listening device. This allows users to receive messages
 * during chat as soon as we are able to, for (more or less) just in time
 * messaging./*ww w. j  a  v  a2 s . c o m*/
 * 
 * The packet returned here is similar to the packet returned by the
 * getmessages api, except we serialize as binary.
 * 
 * @param messageid
 * @param senderid
 * @param sendername
 * @param ts
 * @param message
 * @throws IOException 
 */
void sendMessage(int messageid, int senderid, String sendername, boolean toflag, Timestamp ts, byte[] message)
        throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);

    /*
     * Encode. First byte is 0x20
     */

    String date;
    synchronized (format) {
        date = format.format(ts);
    }

    /*
     * Formulate packet in expected format
     */
    dos.writeByte(0x20); // marker
    dos.writeBoolean(toflag);
    dos.writeInt(messageid);
    dos.writeInt(senderid);
    dos.writeUTF(date);
    dos.writeUTF(sendername);
    dos.writeInt(message.length);
    dos.write(message);

    /*
     * Flush and write packet to device. Our protocol does not depend on
     * the device actually receiving this message, as we wait until the
     * device deletes the messages by a separate command.
     */
    dos.flush();
    out.writeData(baos.toByteArray());
}

From source file:com.adito.notification.Notifier.java

void write(Message message) throws IOException {
    if (log.isDebugEnabled())
        log.debug("Writing message " + message.getId() + " '" + message.getSubject() + "' to disk");
    FileOutputStream fout = new FileOutputStream(
            new File(queueDirectory, String.valueOf(message.getId()) + ".msg"));
    try {/*from  w  w w.j  a  v  a2s. c  o  m*/
        DataOutputStream dout = new DataOutputStream(fout);
        dout.writeLong(message.getId());
        dout.writeUTF(message.getSinkName());
        dout.writeBoolean(message.isUrgent());
        dout.writeUTF(message.getSubject());
        for (Iterator i = message.getRecipients().iterator(); i.hasNext();) {
            Recipient r = (Recipient) i.next();
            dout.writeInt(r.getRecipientType());
            dout.writeUTF(r.getRecipientAlias() == null ? "" : r.getRecipientAlias());
            dout.writeUTF(r.getRealmName() == null ? "" : r.getRealmName());
        }
        dout.writeInt(0);
        for (Iterator i = message.getParameterNames(); i.hasNext();) {
            String key = (String) i.next();
            dout.writeInt(1);
            dout.writeUTF(key);
            dout.writeUTF(message.getParameter(key));
        }
        dout.writeInt(0);
        dout.writeUTF(message.getContent());
        dout.writeUTF(message.getLastMessage());
    } finally {
        fout.close();
    }
}

From source file:ch.unil.genescore.vegas.Snp.java

public void writePosAndAllele(DataOutputStream os) throws IOException {

    // NOTE: ALSO CHANGE readBinary() IF YOU CHANGE THIS
    os.writeUTF(id_);
    os.writeUTF(chr_);/*from   w  ww  .  ja  v a2s.  co  m*/
    os.writeInt(start_);
    os.writeInt(end_);
    os.writeBoolean(posStrand_);
    os.writeChar(minorAllele_);
}

From source file:com.serenegiant.media.TLMediaEncoder.java

/**
 * write MediaFormat data into intermediate file
 * @param out/*  www.  j  av  a  2 s.  c  om*/
 * @param output_format
 */
private static final void writeFormat(final DataOutputStream out, final MediaFormat codec_format,
        final MediaFormat output_format) throws IOException {
    if (DEBUG)
        Log.v(TAG_STATIC, "writeFormat:format=" + output_format);
    final String codec_format_str = asString(codec_format);
    final String output_format_str = asString(output_format);
    final int size = (TextUtils.isEmpty(codec_format_str) ? 0 : codec_format_str.length())
            + (TextUtils.isEmpty(output_format_str) ? 0 : output_format_str.length());
    try {
        writeHeader(out, 0, 0, -1, size, 0);
        out.writeUTF(codec_format_str);
        out.writeUTF(output_format_str);
    } catch (IOException e) {
        Log.e(TAG_STATIC, "writeFormat:", e);
        throw e;
    }
}

From source file:org.prorefactor.refactor.PUB.java

private void writeSymbol(DataOutputStream out, Symbol symbol) throws IOException {
    out.writeInt(symbol.getProgressType());
    out.writeUTF(symbol.fullName()); // We write caseAsDefined
    if (symbol instanceof Primative) {
        Primative primative = (Primative) symbol;
        int dataType = primative.getDataType().getTokenType();
        out.writeInt(dataType);// w ww  .j a v a 2  s.  c  om
        if (dataType == TokenTypes.CLASS)
            out.writeUTF(primative.getClassName());
    } else
        out.writeInt(0);
}

From source file:org.openxdata.server.service.impl.FormDownloadServiceImpl.java

@Override
public void submitForms(InputStream is, OutputStream os, String serializerName) {
    //When submitting data, we need all the form versions and not just the default ones
    //because the user can change the default form version which already has data on
    //mobile devices. So getting all versions shields us from such problems.
    List<FormData> formDataList = new ArrayList<FormData>();
    User user = userService.getLoggedInUser();
    XformSerializer formSerializer = serializationService.getFormSerializer(serializerName);
    Map<Integer, String> formsVersionXmlMap = getFormsVersionXmlMap();
    List<String> xforms = (List<String>) formSerializer.deSerialize(is, formsVersionXmlMap);
    if (xforms == null || xforms.size() == 0) {
        throw new UnexpectedException("Problem encountered while deserializing data.");
    }//w  w w  .  j a  va  2  s.  co  m
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        for (String xml : xforms) {
            Document doc = db.parse(IOUtils.toInputStream(xml, "UTF-8"));
            Integer formId = Integer
                    .valueOf(doc.getDocumentElement().getAttribute(OpenXDataConstants.ATTRIBUTE_NAME_FORMID));
            String descTemplate = doc.getDocumentElement()
                    .getAttribute(OpenXDataConstants.ATTRIBUTE_NAME_DESCRIPTION_TEMPLATE);
            FormData formData = saveFormData(formId, xml,
                    XmlUtil.getDescriptionTemplate(doc.getDocumentElement(), descTemplate), user, new Date());
            formDataList.add(formData);
        }
        // serialize the summaries
        DataOutputStream dos = new DataOutputStream(os);
        dos.writeByte(formDataList.size());
        for (FormData fd : formDataList) {
            String description = fd.getDescription();
            if (description != null) {
                dos.writeUTF(description);
            } else {
                dos.writeUTF("form {" + fd.getFormDefVersionId() + "}"); // description can be null
            }
            dos.writeInt(fd.getFormDataId());
        }
    } catch (ParserConfigurationException ex) {
        throw new UnexpectedException(ex);
    } catch (SAXException ex) {
        throw new UnexpectedException(ex);
    } catch (IOException ex) {
        throw new UnexpectedException(ex);
    }
}

From source file:org.openxdata.server.service.impl.FormDownloadServiceImpl.java

@Override
public void downloadLocales(InputStream is, OutputStream os, String serializerName) throws IOException {
    DataOutputStream dos = new DataOutputStream(os);

    List<Locale> locales = localeService.getLocales();
    if (locales == null || locales.size() == 0)
        dos.writeByte(0);//  w  ww .  j av  a  2 s  .  c  o m
    else {
        dos.writeByte(locales.size());
        for (Locale locale : locales) {
            dos.writeUTF(locale.getKey());
            dos.writeUTF(locale.getName());
        }
    }
}