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:org.exist.dom.ElementImpl.java

/**
 * Serializes a (persistent DOM) Element to a byte array
 *
 * data = signature childCount nodeIdUnitsLength nodeId attributesCount localNameId namespace? prefixData?
 *
 * signature = 0x20 | localNameLength | hasNamespace? | isDirty?
 *
 * localNameLength = noContent OR intContent OR shortContent OR byteContent
 * noContent = 0x0// w ww  .j a v a2  s .  c  o  m
 * intContent = 0x1
 * shortContent = 0x2
 * byteContent = 0x3
 *
 * hasNamespace = 0x10
 *
 * isDirty = 0x8
 *
 * childCount = [int] (4 bytes) The number of child nodes
 * nodeIdUnitsLength = [short] (2 bytes) The number of units of the element's NodeId
 * nodeId = @see org.exist.numbering.DLNBase#serialize(byte[], int)
 * attributesCount = [short] (2 bytes) The number of attributes
 *
 * localNameId = [int] (4 bytes) | [short] (2 bytes) | [byte] 1 byte. The Id of the element's local name from SymbolTable (symbols.dbx)
 *
 * namespace = namespaceUriId namespacePrefixLength elementNamespacePrefix?
 * namespaceUriId = [short] (2 bytes) The Id of the namespace URI from SymbolTable (symbols.dbx)
 * namespacePrefixLength = [short] (2 bytes)
 * elementNamespacePrefix = eUtf8
 *
 * eUtf8 = @see org.exist.util.UTF8#encode(java.lang.String, byte[], int)
 *
 * prefixData = namespaceMappingsCount namespaceMapping+
 * namespaceMappingsCount = [short] (2 bytes)
 * namespaceMapping = namespacePrefix namespaceUriId
 * namespacePrefix = jUtf8
 *
 * jUtf8 = @see java.io.DataOutputStream#writeUTF(java.lang.String)
 */
@Override
public byte[] serialize() {
    if (nodeId == null) {
        throw new RuntimeException("nodeId = null for element: " + getQName().getStringValue());
    }
    try {
        final SymbolTable symbols = ownerDocument.getBrokerPool().getSymbols();
        byte[] prefixData = null;
        // serialize namespace prefixes declared in this element
        if (declaresNamespacePrefixes()) {
            final ByteArrayOutputStream bout = new ByteArrayOutputStream();
            final DataOutputStream out = new DataOutputStream(bout);
            out.writeShort(namespaceMappings.size());
            for (final Iterator<Map.Entry<String, String>> i = namespaceMappings.entrySet().iterator(); i
                    .hasNext();) {
                final Map.Entry<String, String> entry = i.next();
                out.writeUTF(entry.getKey());
                final short nsId = symbols.getNSSymbol(entry.getValue());
                out.writeShort(nsId);
            }
            prefixData = bout.toByteArray();
        }

        final short id = symbols.getSymbol(this);
        final boolean hasNamespace = nodeName.needsNamespaceDecl();
        short nsId = 0;
        if (hasNamespace) {
            nsId = symbols.getNSSymbol(nodeName.getNamespaceURI());
        }
        final byte idSizeType = Signatures.getSizeType(id);
        byte signature = (byte) ((Signatures.Elem << 0x5) | idSizeType);
        int prefixLen = 0;
        if (hasNamespace) {
            if (nodeName.getPrefix() != null && nodeName.getPrefix().length() > 0) {
                prefixLen = UTF8.encoded(nodeName.getPrefix());
            }
            signature |= 0x10;
        }
        if (isDirty) {
            signature |= 0x8;
        }
        final int nodeIdLen = nodeId.size();
        final byte[] data = ByteArrayPool.getByteArray(
                StoredNode.LENGTH_SIGNATURE_LENGTH + LENGTH_ELEMENT_CHILD_COUNT + NodeId.LENGTH_NODE_ID_UNITS
                        + nodeIdLen + LENGTH_ATTRIBUTES_COUNT + Signatures.getLength(idSizeType)
                        + (hasNamespace ? prefixLen + 4 : 0) + (prefixData != null ? prefixData.length : 0));
        int next = 0;
        data[next] = signature;
        next += StoredNode.LENGTH_SIGNATURE_LENGTH;
        ByteConversion.intToByte(children, data, next);
        next += LENGTH_ELEMENT_CHILD_COUNT;
        ByteConversion.shortToByte((short) nodeId.units(), data, next);
        next += NodeId.LENGTH_NODE_ID_UNITS;
        nodeId.serialize(data, next);
        next += nodeIdLen;
        ByteConversion.shortToByte(attributes, data, next);
        next += LENGTH_ATTRIBUTES_COUNT;
        Signatures.write(idSizeType, id, data, next);
        next += Signatures.getLength(idSizeType);
        if (hasNamespace) {
            ByteConversion.shortToByte(nsId, data, next);
            next += LENGTH_NS_ID;
            ByteConversion.shortToByte((short) prefixLen, data, next);
            next += LENGTH_PREFIX_LENGTH;
            if (nodeName.getPrefix() != null && nodeName.getPrefix().length() > 0) {
                UTF8.encode(nodeName.getPrefix(), data, next);
            }
            next += prefixLen;
        }
        if (prefixData != null) {
            System.arraycopy(prefixData, 0, data, next, prefixData.length);
        }
        return data;
    } catch (final IOException e) {
        return null;
    }
}

From source file:com.trigger_context.Main_Service.java

public void senderSync(DataInputStream in, DataOutputStream out, String folder) {
    String tfolder = folder + (folder.charAt(folder.length() - 1) == '/' ? "" : "/");
    File f = new File(folder);
    File file[] = f.listFiles();//  w w  w .  ja v  a 2s.co  m
    // noti(file.toString(),"");
    String md5 = null;
    HashMap<String, File> hm = new HashMap<String, File>();

    HashSet<String> A = new HashSet<String>();
    for (File element : file) {
        hm.put(md5 = calculateMD5(element), element);
        A.add(md5);
    }
    // noti(hm.toString(),"");
    int numB = 0;
    try {
        numB = in.readInt();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        noti("error reading 1st int in sendersync", "");
        e.printStackTrace();
    }
    HashSet<String> B = new HashSet<String>();
    for (int i = 0; i < numB; i++) {
        try {
            B.add(in.readUTF());
        } catch (IOException e1) {
            noti("error in readins md5", "");
            e1.printStackTrace();
        }
    }
    HashSet<String> aMb = new HashSet<String>(A);
    aMb.removeAll(B);
    int l1 = aMb.size();
    try {
        out.writeInt(l1);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        noti("error in writing 1st int", "");
        e.printStackTrace();
    }
    Iterator<String> itr = aMb.iterator();
    while (itr.hasNext()) {
        f = hm.get(itr.next());
        sendFile(out, f.getPath());
    }
    HashSet<String> bMa = new HashSet<String>(B);
    bMa.removeAll(A);
    int l2 = bMa.size();
    try {
        out.writeInt(l2);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        noti("error in writing 2nd int", "");
        e.printStackTrace();
    }
    itr = bMa.iterator();
    while (itr.hasNext()) {
        md5 = itr.next();
        try {
            out.writeUTF(md5);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            noti("error in sending md5", "");
            e.printStackTrace();
        }
        recvFile(in, folder);
    }
}

From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java

public void accept(OutputStream out, InputStream in, byte epType, int qSize,
        CommunicationMode communicationMode, Principal principal) throws IOException {
    DataOutputStream dos = new DataOutputStream(out);
    DataInputStream dis;//  w  w  w. j av a2  s  . c  o  m
    if (clientVersion.compareTo(Version.CURRENT) < 0) {
        dis = new VersionedDataInputStream(in, clientVersion);
        dos = new VersionedDataOutputStream(dos, clientVersion);
    } else {
        dis = new DataInputStream(in);
    }
    // Write ok reply
    if (communicationMode.isWAN() && principal != null) {
        dos.writeByte(REPLY_WAN_CREDENTIALS);
    } else {
        dos.writeByte(REPLY_OK);// byte 59
    }

    // additional byte of wan site needs to send for Gateway BC
    if (communicationMode.isWAN()) {
        Version.writeOrdinal(dos, ServerHandShakeProcessor.currentServerVersion.ordinal(), true);
    }

    dos.writeByte(epType);
    dos.writeInt(qSize);

    // Write the server's member
    DistributedMember member = this.system.getDistributedMember();
    ServerHandShakeProcessor.writeServerMember(member, dos);

    // Write no message
    dos.writeUTF("");

    // Write delta-propagation property value if this is not WAN.
    if (!communicationMode.isWAN() && this.clientVersion.compareTo(Version.GFE_61) >= 0) {
        dos.writeBoolean(((InternalDistributedSystem) this.system).getConfig().getDeltaPropagation());
    }

    // Neeraj: Now if the communication mode is GATEWAY_TO_GATEWAY
    // and principal not equal to null then send the credentials also
    if (communicationMode.isWAN() && principal != null) {
        sendCredentialsForWan(dos, dis);
    }

    // Write the distributed system id if this is a 6.6 or greater client
    // on the remote side of the gateway
    if (communicationMode.isWAN() && this.clientVersion.compareTo(Version.GFE_66) >= 0
            && ServerHandShakeProcessor.currentServerVersion.compareTo(Version.GFE_66) >= 0) {
        dos.writeByte(
                ((InternalDistributedSystem) this.system).getDistributionManager().getDistributedSystemId());
    }

    if ((communicationMode.isWAN()) && this.clientVersion.compareTo(Version.GFE_80) >= 0
            && ServerHandShakeProcessor.currentServerVersion.compareTo(Version.GFE_80) >= 0) {
        int pdxSize = PeerTypeRegistration.getPdxRegistrySize();
        dos.writeInt(pdxSize);
    }

    // Flush
    dos.flush();
}

From source file:com.android.launcher2.Launcher.java

private static void writeConfiguration(Context context, LocaleConfiguration configuration) {
    DataOutputStream out = null;
    try {//w w  w.j a va 2  s . co  m
        out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE));
        out.writeUTF(configuration.locale);
        out.writeInt(configuration.mcc);
        out.writeInt(configuration.mnc);
        out.flush();
    } catch (FileNotFoundException e) {
        // Ignore
    } catch (IOException e) {
        //noinspection ResultOfMethodCallIgnored
        context.getFileStreamPath(PREFERENCES).delete();
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                // Ignore
            }
        }
    }
}

From source file:org.alfresco.repo.search.impl.lucene.index.IndexInfo.java

/**
 * @param id String//from  w ww .java  2  s . com
 * @param toDelete Set<String>
 * @param fileName String
 * @throws IOException
 * @throws FileNotFoundException
 */
private void persistDeletions(String id, Set<String> toDelete, String fileName)
        throws IOException, FileNotFoundException {
    File location = new File(indexDirectory, id).getCanonicalFile();
    if (!location.exists()) {
        if (!location.mkdirs()) {
            throw new IndexerException("Failed to make index directory " + location);
        }
    }
    // Write deletions
    DataOutputStream os = new DataOutputStream(
            new BufferedOutputStream(new FileOutputStream(new File(location, fileName).getCanonicalFile())));
    os.writeInt(toDelete.size());
    for (String ref : toDelete) {
        os.writeUTF(ref);
    }
    os.flush();
    os.close();
}

From source file:org.motechproject.mobile.web.OXDFormUploadServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w ww .  jav  a 2 s.  c  o m*/
 * 
 * @param request
 *            servlet request
 * @param response
 *            servlet response
 * @throws ServletException
 *             if a servlet-specific error occurs
 * @throws IOException
 *             if an I/O error occurs
 */
@RequestMapping(method = RequestMethod.POST)
public void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    long startTime = System.currentTimeMillis();

    IMPService impService = (IMPService) appCtx.getBean("impService");
    StudyProcessor studyProcessor = (StudyProcessor) appCtx.getBean("studyProcessor");

    InputStream input = request.getInputStream();
    OutputStream output = response.getOutputStream();

    ZOutputStream zOutput = null; // Wrap the streams for compression

    // Wrap the streams so for logical types
    DataInputStream dataInput = null;
    DataOutputStream dataOutput = null;

    // Set the MIME type so clients don't misinterpret
    response.setContentType("application/octet-stream");

    try {
        zOutput = new ZOutputStream(output, JZlib.Z_BEST_COMPRESSION);
        dataInput = new DataInputStream(input);
        dataOutput = new DataOutputStream(zOutput);

        if (rawUploadLog.isInfoEnabled()) {
            byte[] rawPayload = IOUtils.toByteArray(dataInput);
            String hexEncodedPayload = Hex.encodeHexString(rawPayload);
            rawUploadLog.info(hexEncodedPayload);
            // Replace the original input stream with one using read payload
            dataInput.close();
            dataInput = new DataInputStream(new ByteArrayInputStream(rawPayload));
        }

        String name = dataInput.readUTF();
        String password = dataInput.readUTF();
        String serializer = dataInput.readUTF();
        String locale = dataInput.readUTF();

        byte action = dataInput.readByte();

        // TODO Authentication of usename and password. Possible M6
        // enhancement
        log.info("uploading: name=" + name + ", password=" + password + ", serializer=" + serializer
                + ", locale=" + locale + ", action=" + action);

        EpihandyXformSerializer serObj = new EpihandyXformSerializer();
        serObj.addDeserializationListener(studyProcessor);

        try {
            Map<Integer, String> formVersionMap = formService.getXForms();
            serObj.deserializeStudiesWithEvents(dataInput, formVersionMap);
        } catch (FormNotFoundException fne) {
            String msg = "failed to deserialize forms: ";
            log.error(msg + fne.getMessage());
            dataOutput.writeByte(ResponseHeader.STATUS_FORMS_STALE);
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        } catch (Exception e) {
            String msg = "failed to deserialize forms";
            log.error(msg, e);
            dataOutput.writeByte(ResponseHeader.STATUS_ERROR);
            response.setStatus(HttpServletResponse.SC_OK);
            return;
        }

        String[][] studyForms = studyProcessor.getConvertedStudies();
        int numForms = studyProcessor.getNumForms();

        log.debug("upload contains: studies=" + studyForms.length + ", forms=" + numForms);

        // Starting processing here, only process until we run out of time
        int processedForms = 0;
        int faultyForms = 0;
        if (studyForms != null && numForms > 0) {
            formprocessing: for (int i = 0; i < studyForms.length; i++) {
                for (int j = 0; j < studyForms[i].length; j++, processedForms++) {

                    if (maxProcessingTime > 0 && System.currentTimeMillis() - startTime > maxProcessingTime)
                        break formprocessing;

                    try {
                        studyForms[i][j] = impService.processXForm(studyForms[i][j]);
                    } catch (Exception ex) {
                        log.error("processing form failed", ex);
                        studyForms[i][j] = ex.getMessage();
                    }
                    if (!impService.getFormProcessSuccess().equalsIgnoreCase(studyForms[i][j])) {
                        faultyForms++;
                    }
                }
            }
        }

        // Write out usual upload response
        dataOutput.writeByte(ResponseHeader.STATUS_SUCCESS);

        dataOutput.writeInt(processedForms);
        dataOutput.writeInt(faultyForms);

        for (int s = 0; s < studyForms.length; s++) {
            for (int f = 0; f < studyForms[s].length; f++) {
                if (!impService.getFormProcessSuccess().equalsIgnoreCase(studyForms[s][f])) {
                    dataOutput.writeByte((byte) s);
                    dataOutput.writeShort((short) f);
                    dataOutput.writeUTF(studyForms[s][f]);
                }
            }
        }

        response.setStatus(HttpServletResponse.SC_OK);
    } catch (Exception e) {
        log.error("failure during upload", e);
    } finally {
        if (dataOutput != null)
            dataOutput.flush();
        if (zOutput != null)
            zOutput.finish();
        response.flushBuffer();
    }
}

From source file:edu.mit.viral.shen.DroidFish.java

private void sendDataLocal(final int sq) {
    new Thread(new Runnable() {
        @Override// w  w  w  .ja  v a2 s  .  c o m
        public void run() {
            Socket socket = null;
            DataOutputStream dataOutputStream = null;
            DataInputStream dataInputStream = null;
            try {
                socket = new Socket(Const.IP_ADD_LOCAL, 8890);
                dataOutputStream = new DataOutputStream(socket.getOutputStream());
                String sq_string = Integer.toString(sq);
                dataOutputStream.writeUTF(sq_string);

            }

            catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }).start();
}

From source file:com.cognizant.trumobi.PersonaLauncher.java

private static void writeConfiguration(Context context, LocaleConfiguration configuration) {
    DataOutputStream out = null;
    try {/*from w ww . j a v a2  s  .  com*/
        out = new DataOutputStream(context.openFileOutput(PREFERENCES, MODE_PRIVATE));
        out.writeUTF(configuration.locale);
        out.writeInt(configuration.mcc);
        out.writeInt(configuration.mnc);
        out.flush();
    } catch (FileNotFoundException e) {
        // Ignore
    } catch (IOException e) {
        // noinspection ResultOfMethodCallIgnored
        context.getFileStreamPath(PREFERENCES).delete();
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                // Ignore
            }
        }
    }
}

From source file:edu.mit.viral.shen.DroidFish.java

private void sendComment(final String comment) {
    new Thread(new Runnable() {
        @Override//from  www . j a v a 2s  .c o m
        public void run() {
            Socket socket = null;
            DataOutputStream dataOutputStream = null;
            DataInputStream dataInputStream = null;
            try {
                // String[] words = longfen.split(" ");
                // String fen=words[0];               
                socket = new Socket(Const.IP_ADD_LOCAL, 8890);
                dataOutputStream = new DataOutputStream(socket.getOutputStream());
                dataOutputStream.writeUTF(comment);

            }

            catch (UnknownHostException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }).start();
}

From source file:org.nd4j.linalg.factory.Nd4j.java

/**
 * Write an ndarray to the specified outputs tream
 *
 * @param arr              the array to write
 * @param dataOutputStream the data output stream to write to
 * @throws IOException/*from w w  w .  java  2s. c  om*/
 */
public static void writeComplex(IComplexNDArray arr, DataOutputStream dataOutputStream) throws IOException {
    dataOutputStream.writeInt(arr.shape().length);
    for (int i = 0; i < arr.shape().length; i++)
        dataOutputStream.writeInt(arr.size(i));
    for (int i = 0; i < arr.stride().length; i++)
        dataOutputStream.writeInt(arr.stride()[i]);
    dataOutputStream.writeUTF(dataType() == DataBuffer.Type.FLOAT ? "float" : "double");

    dataOutputStream.writeUTF("complex");

    if (dataType() == DataBuffer.Type.DOUBLE)
        ArrayUtil.write(arr.data().asDouble(), dataOutputStream);
    else
        ArrayUtil.write(arr.data().asFloat(), dataOutputStream);

}