Example usage for java.io DataOutputStream writeShort

List of usage examples for java.io DataOutputStream writeShort

Introduction

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

Prototype

public final void writeShort(int v) throws IOException 

Source Link

Document

Writes a short to the underlying output stream as two bytes, high byte first.

Usage

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

/**
 * Creates a keytab file for given principal.
 *
 * @param principalName/*  w w w  .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:RealFunctionValidation.java

public static Object readAndWritePrimitiveValue(final DataInputStream in, final DataOutputStream out,
        final Class<?> type) throws IOException {

    if (!type.isPrimitive()) {
        throw new IllegalArgumentException("type must be primitive");
    }/*from  w w  w .j  a  v  a2 s  .  c  o  m*/
    if (type.equals(Boolean.TYPE)) {
        final boolean x = in.readBoolean();
        out.writeBoolean(x);
        return Boolean.valueOf(x);
    } else if (type.equals(Byte.TYPE)) {
        final byte x = in.readByte();
        out.writeByte(x);
        return Byte.valueOf(x);
    } else if (type.equals(Character.TYPE)) {
        final char x = in.readChar();
        out.writeChar(x);
        return Character.valueOf(x);
    } else if (type.equals(Double.TYPE)) {
        final double x = in.readDouble();
        out.writeDouble(x);
        return Double.valueOf(x);
    } else if (type.equals(Float.TYPE)) {
        final float x = in.readFloat();
        out.writeFloat(x);
        return Float.valueOf(x);
    } else if (type.equals(Integer.TYPE)) {
        final int x = in.readInt();
        out.writeInt(x);
        return Integer.valueOf(x);
    } else if (type.equals(Long.TYPE)) {
        final long x = in.readLong();
        out.writeLong(x);
        return Long.valueOf(x);
    } else if (type.equals(Short.TYPE)) {
        final short x = in.readShort();
        out.writeShort(x);
        return Short.valueOf(x);
    } else {
        // This should never occur.
        throw new IllegalStateException();
    }
}

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

@Override
public void downloadMenuText(InputStream is, OutputStream os, String serializerName, String locale) {
    DataOutputStream dos = new DataOutputStream(os);

    try {/*w ww. j a v  a  2s  .c om*/
        List<MobileMenuText> text = utilityService.getMobileMenuText(locale);
        if (text == null || text.size() == 0)
            dos.writeShort(0);
        else {
            dos.writeShort(text.size());
            for (MobileMenuText txt : text) {
                dos.writeShort(txt.getMenuId());
                dos.writeUTF(txt.getMenuText());
            }
        }
    } catch (Exception ex) {
        throw new UnexpectedException(ex);
    }
}

From source file:org.apache.hadoop.hdfs.server.datanode.DataXceiver.java

/**
 * Utility function for sending a response.
 * @param s socket to write to/*from   www  .j  a v  a  2s . c  om*/
 * @param opStatus status message to write
 * @param timeout send timeout
 **/
private void sendResponse(Socket s, short opStatus, long timeout) throws IOException {
    DataOutputStream reply = new DataOutputStream(NetUtils.getOutputStream(s, timeout));
    try {
        reply.writeShort(opStatus);
        reply.flush();
    } finally {
        IOUtils.closeStream(reply);
    }
}

From source file:org.apache.hadoop.io.TestArrayOutputStream.java

private void runComparison(ArrayOutputStream aos, DataOutputStream dos, ByteArrayOutputStream bos)
        throws IOException {
    Random r = new Random();
    // byte/*from w  w  w .j  a va 2  s  . co  m*/
    int b = r.nextInt(128);
    aos.write(b);
    dos.write(b);

    // byte[]
    byte[] bytes = new byte[10];
    r.nextBytes(bytes);
    aos.write(bytes, 0, 10);
    dos.write(bytes, 0, 10);

    // Byte
    aos.writeByte(b);
    dos.writeByte(b);

    // boolean
    boolean bool = r.nextBoolean();
    aos.writeBoolean(bool);
    dos.writeBoolean(bool);

    // short
    short s = (short) r.nextInt();
    aos.writeShort(s);
    dos.writeShort(s);

    // char
    int c = r.nextInt();
    aos.writeChar(c);
    dos.writeChar(c);

    // int
    int i = r.nextInt();
    aos.writeInt(i);
    dos.writeInt(i);

    // long
    long l = r.nextLong();
    aos.writeLong(l);
    dos.writeLong(l);

    // float
    float f = r.nextFloat();
    aos.writeFloat(f);
    dos.writeFloat(f);

    // double
    double d = r.nextDouble();
    aos.writeDouble(d);
    dos.writeDouble(d);

    // strings
    String str = RandomStringUtils.random(20);
    aos.writeBytes(str);
    aos.writeChars(str);
    aos.writeUTF(str);
    dos.writeBytes(str);
    dos.writeChars(str);
    dos.writeUTF(str);

    byte[] expected = bos.toByteArray();
    assertEquals(expected.length, aos.size());

    byte[] actual = new byte[aos.size()];
    System.arraycopy(aos.getBytes(), 0, actual, 0, actual.length);
    // serialized bytes should be the same
    assertTrue(Arrays.equals(expected, actual));
}

From source file:org.apache.jxtadoop.hdfs.server.datanode.DataXceiver.java

/**
 * Utility function for sending a response.
 * @param s socket to write to//from w w  w  . ja v  a  2s .co  m
 * @param opStatus status message to write
 * @param timeout send timeout
 **/
private void sendResponse(JxtaSocket s, short opStatus, long timeout) throws IOException {
    LOG.debug("Mathod called : sendResponse()");
    //DataOutputStream reply = 
    //  new DataOutputStream(NetUtils.getOutputStream(s, timeout));
    ReliableOutputStream ros = (ReliableOutputStream) s.getOutputStream();
    DataOutputStream reply = new DataOutputStream(s.getOutputStream());

    try {
        reply.writeShort(opStatus);
        reply.flush();
    } finally {
        LOG.debug("Finalizing : sendResponse()");
        LOG.debug("sendReponse stream queue empty : " + ros.isQueueEmpty());
        // IOUtils.closeStream(reply);
    }
}

From source file:edu.umn.cs.spatialHadoop.nasa.StockQuadTree.java

/**
 * Merges multiple trees of the same spatial resolution into one tree of
 * lower temporal resolution (larger time) and the same spatial resolution.
 * @param inTrees//from   ww  w  .  j a  v  a2s  .  c o  m
 * @param outTree
 * @throws IOException 
 */
public static void merge(DataInputStream[] inTrees, DataOutputStream outTree) throws IOException {
    // Write the spatial resolution of the output as the same of all input trees
    int resolution = inTrees[0].readInt();
    short fillValue = inTrees[0].readShort();
    for (int iTree = 1; iTree < inTrees.length; iTree++) {
        int iResolution = inTrees[iTree].readInt();
        int iFillValue = inTrees[iTree].readShort();
        if (resolution != iResolution || fillValue != iFillValue)
            throw new RuntimeException("Tree #0 has a resolution of " + resolution
                    + " not compatible with resolution" + iResolution + " of Tree #" + iTree);
    }
    outTree.writeInt(resolution);
    outTree.writeShort(fillValue);

    // Sum up the cardinality of all input trees
    int cardinality = 0;
    int cardinalities[] = new int[inTrees.length];
    for (int iTree = 0; iTree < inTrees.length; iTree++)
        cardinality += (cardinalities[iTree] = inTrees[iTree].readInt());
    outTree.writeInt(cardinality);

    // Write timestamps of all trees
    for (int iTree = 0; iTree < inTrees.length; iTree++) {
        outTree.writeLong(inTrees[iTree].readLong());
    }

    // Merge sorted values in all input trees
    byte[] buffer = new byte[1024 * 1024];
    int size = resolution * resolution;
    while (size-- > 0) {
        for (int iTree = 0; iTree < inTrees.length; iTree++) {
            int sizeToRead = ValueSize * cardinalities[iTree]; // sizeof(short) * c
            while (sizeToRead > 0) {
                int bytesRead = inTrees[iTree].read(buffer, 0, Math.min(sizeToRead, buffer.length));
                outTree.write(buffer, 0, bytesRead);
                sizeToRead -= bytesRead;
            }
        }
    }

    // Merge aggregate values of all nodes
    Node treeNode = new Node();
    StockQuadTree stockQuadTree = getOrCreateStockQuadTree(resolution);
    int numOfNodes = stockQuadTree.nodesID.length;
    for (int iNode = 0; iNode < numOfNodes; iNode++) {
        Node outputNode = new Node();
        for (int iTree = 0; iTree < inTrees.length; iTree++) {
            treeNode.readFields(inTrees[iTree]);
            outputNode.accumulate(treeNode);
        }
        outputNode.write(outTree);
    }
}

From source file:com.p2p.misc.DeviceUtility.java

private void WriteData(OutputStream out, int cid, int lac) throws IOException {
    DataOutputStream dataOutputStream = new DataOutputStream(out);
    dataOutputStream.writeShort(21);
    dataOutputStream.writeLong(0);//  w  w w .  j  ava  2s  .com
    dataOutputStream.writeUTF("en");
    dataOutputStream.writeUTF("Android");
    dataOutputStream.writeUTF("1.0");
    dataOutputStream.writeUTF("Mobile");
    dataOutputStream.writeByte(27);
    dataOutputStream.writeInt(0);
    dataOutputStream.writeInt(0);
    dataOutputStream.writeInt(3);
    dataOutputStream.writeUTF("");

    dataOutputStream.writeInt(cid);
    dataOutputStream.writeInt(lac);

    dataOutputStream.writeInt(0);
    dataOutputStream.writeInt(0);
    dataOutputStream.writeInt(0);
    dataOutputStream.writeInt(0);
    dataOutputStream.flush();
}

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

@RequestMapping(Hub.DOCUMENTATION_SERVICE)
@ResponseBody/*from   w w w  .  ja v a  2 s. com*/
public void getDocumentation(@RequestParam(Hub.PARAM_TITLE) String title, OutputStream outputStream) {
    log.info(Hub.DOCUMENTATION_SERVICE);
    DataOutputStream dos = new DataOutputStream(outputStream);
    File docsDirectory = new File(servletContext.getRealPath(DOC_DIR));
    try {
        if (!docsDirectory.isDirectory()) {
            log.fatal("Docs directory not found!");
            dos.writeUTF(Hub.FAILURE);
            dos.writeUTF(Failure.SYSTEM.toString());
            return;
        }
        if (title.isEmpty()) {
            File[] textFiles = docsDirectory.listFiles(new TextFilter());
            dos.writeUTF(Hub.SUCCESS);
            dos.writeUTF(title);
            dos.writeShort(textFiles.length);
            for (File docFile : textFiles) {
                dos.writeUTF(
                        docFile.getName().substring(0, docFile.getName().length() - DOC_FILE_SUFFIX.length()));
            }
        } else {
            File docFile = new File(docsDirectory, title + DOC_FILE_SUFFIX);
            if (!docFile.exists()) {
                dos.writeUTF(Hub.FAILURE);
                dos.writeUTF(Failure.SYSTEM.toString());
                return;
            }
            List<String> lines = getLines(docFile);
            dos.writeUTF(Hub.SUCCESS);
            dos.writeUTF(title);
            dos.writeShort(lines.size());
            for (String line : lines) {
                dos.writeUTF(line);
            }
        }
    } catch (IOException e) {
        log.error("Problem delivering documentation", e);
    }
}

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

private void writeTree(DataOutputStream out, JPNode node) throws IOException {
    int nodeType = node.getType();

    out.writeInt(node.getSubtypeIndex());
    out.writeInt(nodeType);/*from   w  w w .j  a va  2  s .c  o  m*/
    out.writeShort(node.getFileIndex());
    out.writeInt(node.getLine());
    out.writeShort(node.getColumn());
    out.writeInt(node.getSourceNum());

    if (!TokenTypes.hasDefaultText(nodeType)) {
        out.writeInt(NODETEXT);
        out.writeInt(stringIndex(node.getText()));
    }
    String comments = node.getComments();
    if (comments != null) {
        out.writeInt(NODECOMMENTS);
        out.writeInt(stringIndex(comments));
    }
    if (node.attrGet(IConstants.STATEHEAD) == IConstants.TRUE) {
        out.writeInt(IConstants.STATEHEAD);
        out.writeInt(IConstants.TRUE);
        out.writeInt(IConstants.STATE2);
        out.writeInt(node.getState2());
    }
    int attrVal;
    if ((attrVal = node.attrGet(IConstants.STORETYPE)) > 0) {
        out.writeInt(IConstants.STORETYPE);
        out.writeInt(attrVal);
    }
    if (node instanceof ProparseDirectiveNode) {
        out.writeInt(IConstants.PROPARSEDIRECTIVE);
        out.writeInt(stringIndex(((ProparseDirectiveNode) node).getDirectiveText()));
    }
    if ((attrVal = node.attrGet(IConstants.OPERATOR)) > 0) {
        out.writeInt(IConstants.OPERATOR);
        out.writeInt(attrVal);
    }
    if ((attrVal = node.attrGet(IConstants.INLINE_VAR_DEF)) > 0) {
        out.writeInt(IConstants.INLINE_VAR_DEF);
        out.writeInt(attrVal);
    }
    if (nodeType == TokenTypes.TYPE_NAME) {
        out.writeInt(IConstants.QUALIFIED_CLASS_INT);
        out.writeInt(stringIndex(node.attrGetS(IConstants.QUALIFIED_CLASS_STRING)));
    }
    out.writeInt(-1);
    out.writeInt(-1); // Terminate the attribute key/value pairs.
    JPNode next;
    if ((next = node.firstChild()) != null)
        writeTree(out, next);
    else
        out.writeInt(-1);
    if ((next = node.nextSibling()) != null)
        writeTree(out, next);
    else
        out.writeInt(-1);
}