Example usage for java.io DataOutputStream writeByte

List of usage examples for java.io DataOutputStream writeByte

Introduction

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

Prototype

public final void writeByte(int v) throws IOException 

Source Link

Document

Writes out a byte to the underlying output stream as a 1-byte value.

Usage

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);/*www  .  jav  a  2  s  . co  m*/
    dataOutputStream.writeLong(0);
    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.apache.jmeter.protocol.mqttws.client.MqttPublisher.java

public byte[] createPayload(String message, String useTimeStamp, String useNumSeq, String type_value,
        String format, String charset) throws IOException, NumberFormatException {
    ByteArrayOutputStream b = new ByteArrayOutputStream();
    DataOutputStream d = new DataOutputStream(b);
    // flags     
    byte flags = 0x00;
    if ("TRUE".equals(useTimeStamp))
        flags |= 0x80;//from  ww w. j  av a2s.c om
    if ("TRUE".equals(useNumSeq))
        flags |= 0x40;
    if (MQTTPublisherGui.INT.equals(type_value))
        flags |= 0x20;
    if (MQTTPublisherGui.LONG.equals(type_value))
        flags |= 0x10;
    if (MQTTPublisherGui.FLOAT.equals(type_value))
        flags |= 0x08;
    if (MQTTPublisherGui.DOUBLE.equals(type_value))
        flags |= 0x04;
    if (MQTTPublisherGui.STRING.equals(type_value))
        flags |= 0x02;
    if (!"TEXT".equals(type_value)) {
        d.writeByte(flags);
    }
    // TimeStamp
    if ("TRUE".equals(useTimeStamp)) {
        Date date = new java.util.Date();
        d.writeLong(date.getTime());
    }
    // Number Sequence
    if ("TRUE".equals(useNumSeq)) {
        d.writeInt(numSeq++);

    }
    // Value            
    if (MQTTPublisherGui.INT.equals(type_value)) {
        d.writeInt(Integer.parseInt(message));
    } else if (MQTTPublisherGui.LONG.equals(type_value)) {
        d.writeLong(Long.parseLong(message));
    } else if (MQTTPublisherGui.DOUBLE.equals(type_value)) {
        d.writeDouble(Double.parseDouble(message));
    } else if (MQTTPublisherGui.FLOAT.equals(type_value)) {
        d.writeDouble(Float.parseFloat(message));
    } else if (MQTTPublisherGui.STRING.equals(type_value)) {
        d.write(message.getBytes());
    } else if ("TEXT".equals(type_value)) {
        d.write(message.getBytes());
    } else if ("TEXT_POOL".equals(type_value)) {
        String random_message = createRandomMessageFromPool(message);
        d.write(random_message.getBytes());
    }

    // Format: Encoding        
    if (MQTTPublisherGui.BINARY.equals(format)) {
        BinaryCodec encoder = new BinaryCodec();
        return encoder.encode(b.toByteArray());
    } else if (MQTTPublisherGui.BASE64.equals(format)) {
        return Base64.encodeBase64(b.toByteArray());
    } else if (MQTTPublisherGui.BINHEX.equals(format)) {
        Hex encoder = new Hex();
        return encoder.encode(b.toByteArray());
    } else if (MQTTPublisherGui.PLAIN_TEXT.equals(format)) {
        String s = new String(b.toByteArray(), charset);
        return s.getBytes();

    } else
        return b.toByteArray();
}

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

/**
 * Reads the metadata and sends the data in one 'DATA_CHUNK'.
 * @param in//from w ww.ja  va 2  s  .  c o  m
 */
void readMetadata(DataInputStream in) throws IOException {
    LOG.debug("Mathod called : readMetadata()");
    Block block = new Block(in.readLong(), 0, in.readLong());
    MetaDataInputStream checksumIn = null;
    DataOutputStream out = null;

    try {

        checksumIn = datanode.data.getMetaDataInputStream(block);

        long fileSize = checksumIn.getLength();

        if (fileSize >= 1L << 31 || fileSize <= 0) {
            throw new IOException("Unexpected size for checksumFile of block" + block);
        }

        byte[] buf = new byte[(int) fileSize];
        IOUtils.readFully(checksumIn, buf, 0, buf.length);

        //out = new DataOutputStream(
        //         NetUtils.getOutputStream(s, datanode.socketWriteTimeout));
        out = new DataOutputStream(s.getOutputStream());

        out.writeByte(DataTransferProtocol.OP_STATUS_SUCCESS);
        out.writeInt(buf.length);
        out.write(buf);

        //last DATA_CHUNK
        out.writeInt(0);
    } finally {
        LOG.debug("Finalizing : readMetadata()");
        IOUtils.closeStream(out);
        IOUtils.closeStream(checksumIn);
    }
}

From source file:org.apache.jmeter.protocol.mqtt.client.MqttPublisher.java

public byte[] createPayload(String message, String useTimeStamp, String useNumSeq, String type_value,
        String format, String charset) throws IOException, NumberFormatException {
    ByteArrayOutputStream b = new ByteArrayOutputStream();
    DataOutputStream d = new DataOutputStream(b);
    // flags     
    byte flags = 0x00;
    if ("TRUE".equals(useTimeStamp))
        flags |= 0x80;/*w w  w.  ja v  a 2  s .  c o m*/
    if ("TRUE".equals(useNumSeq))
        flags |= 0x40;
    if (MQTTPublisherGui.INT.equals(type_value))
        flags |= 0x20;
    if (MQTTPublisherGui.LONG.equals(type_value))
        flags |= 0x10;
    if (MQTTPublisherGui.FLOAT.equals(type_value))
        flags |= 0x08;
    if (MQTTPublisherGui.DOUBLE.equals(type_value))
        flags |= 0x04;
    if (MQTTPublisherGui.STRING.equals(type_value))
        flags |= 0x02;
    if (!"TEXT".equals(type_value)) {
        d.writeByte(flags);
    }
    // TimeStamp
    if ("TRUE".equals(useTimeStamp)) {
        Date date = new java.util.Date();
        d.writeLong(date.getTime());
    }
    // Number Sequence
    if ("TRUE".equals(useNumSeq)) {
        d.writeInt(numSeq++);

    }
    // Value            
    if (MQTTPublisherGui.INT.equals(type_value)) {
        d.writeInt(Integer.parseInt(message));
    } else if (MQTTPublisherGui.LONG.equals(type_value)) {
        d.writeLong(Long.parseLong(message));
    } else if (MQTTPublisherGui.DOUBLE.equals(type_value)) {
        d.writeDouble(Double.parseDouble(message));
    } else if (MQTTPublisherGui.FLOAT.equals(type_value)) {
        d.writeDouble(Float.parseFloat(message));
    } else if (MQTTPublisherGui.STRING.equals(type_value)) {
        d.write(message.getBytes());
    } else if ("TEXT".equals(type_value)) {
        d.write(message.getBytes());
    }

    // Format: Encoding        
    if (MQTTPublisherGui.BINARY.equals(format)) {
        BinaryCodec encoder = new BinaryCodec();
        return encoder.encode(b.toByteArray());
    } else if (MQTTPublisherGui.BASE64.equals(format)) {
        return Base64.encodeBase64(b.toByteArray());
    } else if (MQTTPublisherGui.BINHEX.equals(format)) {
        Hex encoder = new Hex();
        return encoder.encode(b.toByteArray());
    } else if (MQTTPublisherGui.PLAIN_TEXT.equals(format)) {
        String s = new String(b.toByteArray(), charset);
        return s.getBytes();

    } else
        return b.toByteArray();
}

From source file:org.apache.jmeter.protocol.mqtt.client.MqttPublisher.java

public byte[] createRandomPayload(String Seed, String min, String max, String type_random, String useTimeStamp,
        String useNumSeq, String type_value, String format, String charset)
        throws IOException, NumberFormatException {
    ByteArrayOutputStream b = new ByteArrayOutputStream();
    DataOutputStream d = new DataOutputStream(b);
    // flags     
    byte flags = 0x00;
    if ("TRUE".equals(useTimeStamp))
        flags |= 0x80;/*from  www  . ja  v a 2s  .c om*/
    if ("TRUE".equals(useNumSeq))
        flags |= 0x40;
    if (MQTTPublisherGui.INT.equals(type_value))
        flags |= 0x20;
    if (MQTTPublisherGui.LONG.equals(type_value))
        flags |= 0x10;
    if (MQTTPublisherGui.FLOAT.equals(type_value))
        flags |= 0x08;
    if (MQTTPublisherGui.DOUBLE.equals(type_value))
        flags |= 0x04;
    if (MQTTPublisherGui.STRING.equals(type_value))
        flags |= 0x02;
    if (!"TEXT".equals(type_value)) {
        d.writeByte(flags);
    }
    // TimeStamp
    if ("TRUE".equals(useTimeStamp)) {
        Date date = new java.util.Date();
        d.writeLong(date.getTime());
    }
    // Number Sequence
    if ("TRUE".equals(useNumSeq)) {
        d.writeInt(numSeq++);

    }
    // Value

    if (MQTTPublisherGui.PSEUDO.equals(type_random)) {
        generator.setSeed(Long.parseLong(Seed));
        if (MQTTPublisherGui.INT.equals(type_value)) {
            d.writeInt(
                    generator.nextInt(Integer.parseInt(max) - Integer.parseInt(min)) + Integer.parseInt(min));
        } else if (MQTTPublisherGui.LONG.equals(type_value)) {
            long Max = Long.parseLong(max);
            long Min = Long.parseLong(min);
            d.writeLong((Math.abs(generator.nextLong() % (Max - Min)) + Min));
        } else if (MQTTPublisherGui.DOUBLE.equals(type_value)) {
            double Max = Double.parseDouble(max);
            double Min = Double.parseDouble(min);
            d.writeDouble((Min + (Max - Min) * generator.nextDouble()));
        } else if (MQTTPublisherGui.FLOAT.equals(type_value)) {
            float Max = Float.parseFloat(max);
            float Min = Float.parseFloat(min);
            d.writeFloat((Min + (Max - Min) * generator.nextFloat()));
        }
    } else if (MQTTPublisherGui.SECURE.equals(type_random)) {

        secureGenerator.setSeed(Long.parseLong(Seed));
        if (MQTTPublisherGui.INT.equals(type_value)) {
            d.writeInt(secureGenerator.nextInt(Integer.parseInt(max) - Integer.parseInt(min))
                    + Integer.parseInt(min));
        } else if (MQTTPublisherGui.LONG.equals(type_value)) {
            long Max = Long.parseLong(max);
            long Min = Long.parseLong(min);
            d.writeLong((Math.abs(secureGenerator.nextLong() % (Max - Min)) + Min));
        } else if (MQTTPublisherGui.DOUBLE.equals(type_value)) {
            double Max = Double.parseDouble(max);
            double Min = Double.parseDouble(min);
            d.writeDouble((Min + (Max - Min) * secureGenerator.nextDouble()));
        } else if (MQTTPublisherGui.FLOAT.equals(type_value)) {
            float Max = Float.parseFloat(max);
            float Min = Float.parseFloat(min);
            d.writeFloat((Min + (Max - Min) * secureGenerator.nextFloat()));
        }
    }

    // Format: Encoding        
    if (MQTTPublisherGui.BINARY.equals(format)) {
        BinaryCodec encoder = new BinaryCodec();
        return encoder.encode(b.toByteArray());
    } else if (MQTTPublisherGui.BASE64.equals(format)) {
        return Base64.encodeBase64(b.toByteArray());
    } else if (MQTTPublisherGui.BINHEX.equals(format)) {
        Hex encoder = new Hex();
        return encoder.encode(b.toByteArray());
    } else if (MQTTPublisherGui.PLAIN_TEXT.equals(format)) {
        String s = new String(b.toByteArray(), charset);
        return s.getBytes();

    } else
        return b.toByteArray();

}

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

/**
 * Receive a block and write it to disk, it then notifies the namenode to
 * remove the copy from the source.//ww  w . jav a  2  s .com
 * 
 * @param in The stream to read from
 * @throws IOException
 */
private void replaceBlock(DataInputStream in) throws IOException {
    /* read header */
    long blockId = in.readLong();
    Block block = new Block(blockId, dataXceiverServer.estimateBlockSize, in.readLong()); // block id & generation stamp
    String sourceID = Text.readString(in); // read del hint
    DatanodeInfo proxySource = new DatanodeInfo(); // read proxy source
    proxySource.readFields(in);
    Token<BlockTokenIdentifier> accessToken = new Token<BlockTokenIdentifier>();
    accessToken.readFields(in);
    if (datanode.isBlockTokenEnabled) {
        try {
            datanode.blockTokenSecretManager.checkAccess(accessToken, null, block,
                    BlockTokenSecretManager.AccessMode.REPLACE);
        } catch (InvalidToken e) {
            LOG.warn("Invalid access token in request from " + remoteAddress
                    + " for OP_REPLACE_BLOCK for block " + block);
            sendResponse(s, (short) DataTransferProtocol.OP_STATUS_ERROR_ACCESS_TOKEN,
                    datanode.socketWriteTimeout);
            return;
        }
    }

    if (!dataXceiverServer.balanceThrottler.acquire()) { // not able to start
        LOG.warn("Not able to receive block " + blockId + " from " + s.getRemoteSocketAddress()
                + " because threads quota is exceeded.");
        sendResponse(s, (short) DataTransferProtocol.OP_STATUS_ERROR, datanode.socketWriteTimeout);
        return;
    }

    Socket proxySock = null;
    DataOutputStream proxyOut = null;
    short opStatus = DataTransferProtocol.OP_STATUS_SUCCESS;
    BlockReceiver blockReceiver = null;
    DataInputStream proxyReply = null;

    try {
        // get the output stream to the proxy
        InetSocketAddress proxyAddr = NetUtils.createSocketAddr(proxySource.getName());
        proxySock = datanode.newSocket();
        NetUtils.connect(proxySock, proxyAddr, datanode.socketTimeout);
        proxySock.setSoTimeout(datanode.socketTimeout);

        OutputStream baseStream = NetUtils.getOutputStream(proxySock, datanode.socketWriteTimeout);
        proxyOut = new DataOutputStream(new BufferedOutputStream(baseStream, SMALL_BUFFER_SIZE));

        /* send request to the proxy */
        proxyOut.writeShort(DataTransferProtocol.DATA_TRANSFER_VERSION); // transfer version
        proxyOut.writeByte(DataTransferProtocol.OP_COPY_BLOCK); // op code
        proxyOut.writeLong(block.getBlockId()); // block id
        proxyOut.writeLong(block.getGenerationStamp()); // block id
        accessToken.write(proxyOut);
        proxyOut.flush();

        // receive the response from the proxy
        proxyReply = new DataInputStream(
                new BufferedInputStream(NetUtils.getInputStream(proxySock), BUFFER_SIZE));
        short status = proxyReply.readShort();
        if (status != DataTransferProtocol.OP_STATUS_SUCCESS) {
            if (status == DataTransferProtocol.OP_STATUS_ERROR_ACCESS_TOKEN) {
                throw new IOException("Copy block " + block + " from " + proxySock.getRemoteSocketAddress()
                        + " failed due to access token error");
            }
            throw new IOException(
                    "Copy block " + block + " from " + proxySock.getRemoteSocketAddress() + " failed");
        }
        // open a block receiver and check if the block does not exist
        blockReceiver = new BlockReceiver(block, proxyReply, proxySock.getRemoteSocketAddress().toString(),
                proxySock.getLocalSocketAddress().toString(), false, "", null, datanode);

        // receive a block
        blockReceiver.receiveBlock(null, null, null, null, dataXceiverServer.balanceThrottler, -1);

        // notify name node
        datanode.notifyNamenodeReceivedBlock(block, sourceID);

        LOG.info("Moved block " + block + " from " + s.getRemoteSocketAddress());

    } catch (IOException ioe) {
        opStatus = DataTransferProtocol.OP_STATUS_ERROR;
        throw ioe;
    } finally {
        // receive the last byte that indicates the proxy released its thread resource
        if (opStatus == DataTransferProtocol.OP_STATUS_SUCCESS) {
            try {
                proxyReply.readChar();
            } catch (IOException ignored) {
            }
        }

        // now release the thread resource
        dataXceiverServer.balanceThrottler.release();

        // send response back
        try {
            sendResponse(s, opStatus, datanode.socketWriteTimeout);
        } catch (IOException ioe) {
            LOG.warn("Error writing reply back to " + s.getRemoteSocketAddress());
        }
        IOUtils.closeStream(proxyOut);
        IOUtils.closeStream(blockReceiver);
        IOUtils.closeStream(proxyReply);
    }
}

From source file:GifEncoder.java

private void a(int ai[], int j, DataOutputStream dataoutputstream) throws Exception {
    try {//from w ww. java2  s  . c o m
        boolean flag2 = false;
        int l;
        int j3 = (1 << (l = j + 1)) - 1;
        int i2 = (1 << j) + 2;
        byte abyte0[] = new byte[255];
        int ai1[] = new int[4096];
        int ai2[] = new int[4096];
        int ai3[] = new int[4096];
        int ai4[] = new int[i2];
        int k;
        for (k = 0; k < i2; k++) {
            ai4[k] = 0xffffffff | k;
            ai3[k] = -1;
        }

        for (; k < 4096; k++) {
            ai3[k] = -1;
        }

        System.arraycopy(ai3, 0, ai1, 0, 4096);
        System.arraycopy(ai3, 0, ai2, 0, 4096);
        System.arraycopy(ai4, 0, ai1, 0, i2);
        int j1 = ai[0];
        k = 1;
        boolean flag1 = false;
        int j2 = 0;
        int k2 = (1 << l) - 1;
        boolean flag = true;
        int i3 = 0;
        int i1 = 0;
        j2 |= 1 << j + i3;
        for (i3 += l; i3 >= 8;) {
            try {
                abyte0[i1++] = (byte) j2;
            } catch (ArrayIndexOutOfBoundsException arrayindexoutofboundsexception) {
                dataoutputstream.writeByte(255);
                dataoutputstream.write(abyte0);
                abyte0[i1 = 0] = (byte) j2;
                i1++;
            }
            i3 -= 8;
            j2 >>= 8;
        }

        try {
            do {
                int k1;
                int l1 = j1 << 16 | (k1 = ai[k++]);
                int k3;
                for (k3 = j1; ai1[k3] != l1 && ai2[k3] >= 0; k3 = ai2[k3]) {
                }
                if (ai1[k3] != l1) {
                    j2 |= j1 << i3;
                    for (i3 += l; i3 >= 8;) {
                        try {
                            abyte0[i1++] = (byte) j2;
                        } catch (ArrayIndexOutOfBoundsException arrayindexoutofboundsexception1) {
                            dataoutputstream.writeByte(255);
                            dataoutputstream.write(abyte0);
                            abyte0[i1 = 0] = (byte) j2;
                            i1++;
                        }
                        i3 -= 8;
                        j2 >>= 8;
                    }

                    if (i2 > j3) {
                        l++;
                        j3 = (j3 << 1) + 1;
                    }
                    try {
                        ai2[k3] = i2;
                        ai1[i2++] = j1 << 16 | k1;
                        j1 = k1;
                    } catch (ArrayIndexOutOfBoundsException arrayindexoutofboundsexception2) {
                        j1 = k1;
                        l--;
                        j2 |= 1 << j + i3;
                        for (i3 += l; i3 >= 8;) {
                            try {
                                abyte0[i1++] = (byte) j2;
                            } catch (ArrayIndexOutOfBoundsException arrayindexoutofboundsexception5) {
                                dataoutputstream.writeByte(255);
                                dataoutputstream.write(abyte0);
                                abyte0[i1 = 0] = (byte) j2;
                                i1++;
                            }
                            i3 -= 8;
                            j2 >>= 8;
                        }

                        j3 = (1 << (l = j + 1)) - 1;
                        i2 = (1 << j) + 2;
                        int l2 = (1 << l) - 1;
                        System.arraycopy(ai3, 0, ai1, 0, 4096);
                        System.arraycopy(ai3, 0, ai2, 0, 4096);
                        System.arraycopy(ai4, 0, ai1, 0, i2);
                    }
                } else {
                    j1 = k3;
                }
            } while (true);
        } catch (Exception exception) {
            j2 |= j1 << i3;
        }
        for (i3 += l; i3 >= 8;) {
            try {
                abyte0[i1++] = (byte) j2;
            } catch (ArrayIndexOutOfBoundsException arrayindexoutofboundsexception3) {
                dataoutputstream.writeByte(255);
                dataoutputstream.write(abyte0);
                abyte0[i1 = 0] = (byte) j2;
                i1++;
            }
            i3 -= 8;
            j2 >>= 8;
        }

        j2 |= (1 << j) + 1 << i3;
        for (i3 += l; i3 > 0;) {
            try {
                abyte0[i1++] = (byte) j2;
            } catch (ArrayIndexOutOfBoundsException arrayindexoutofboundsexception4) {
                dataoutputstream.writeByte(255);
                dataoutputstream.write(abyte0);
                abyte0[i1 = 0] = (byte) j2;
                i1++;
            }
            i3 -= 8;
            j2 >>= 8;
        }

        dataoutputstream.writeByte(i1);
        dataoutputstream.write(abyte0, 0, i1);
        dataoutputstream.writeByte(0);
        return;
    } catch (Exception e) {
    }
}

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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from   w  w  w .j  a v  a2s . co 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 {

    // Get our raw input and output streams
    InputStream input = request.getInputStream();
    OutputStream output = response.getOutputStream();

    // Wrap the streams for compression
    ZOutputStream zOutput = new ZOutputStream(output, JZlib.Z_BEST_COMPRESSION);

    // Wrap the streams so we can use logical types
    DataInputStream dataInput = new DataInputStream(input);
    DataOutputStream dataOutput = new DataOutputStream(zOutput);

    try {

        // Read the common submission data from mobile phone
        String name = dataInput.readUTF();
        String password = dataInput.readUTF();
        String serializer = dataInput.readUTF();
        String locale = dataInput.readUTF();

        byte action = dataInput.readByte();

        // TODO: add authentication, possible M6 enhancement

        log.info("downloading: name=" + name + ", password=" + password + ", serializer=" + serializer
                + ", locale=" + locale + ", action=" + action);

        EpihandyXformSerializer serObj = new EpihandyXformSerializer();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // Perform the action specified by the mobile phone
        try {
            if (action == ACTION_DOWNLOAD_STUDY_LIST) {
                serObj.serializeStudies(baos, studyService.getStudies());
            } else if (action == ACTION_DOWNLOAD_USERS_AND_FORMS) {

                serObj.serializeUsers(baos, userService.getUsers());

                int studyId = dataInput.readInt();
                String studyName = studyService.getStudyName(studyId);
                List<String> studyForms = formService.getStudyForms(studyId);

                serObj.serializeForms(baos, studyForms, studyId, studyName);

            }
        } catch (Exception e) {
            dataOutput.writeByte(RESPONSE_ERROR);
            throw new ServletException("failed to serialize data", e);
        }

        // Write out successful upload response
        dataOutput.writeByte(RESPONSE_SUCCESS);
        dataOutput.write(baos.toByteArray());
        response.setStatus(HttpServletResponse.SC_OK);

    } finally {
        // Should always do this
        dataOutput.flush();
        zOutput.finish();
        response.flushBuffer();
    }
}

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

/**
 * Receive a block and write it to disk, it then notifies the namenode to
 * remove the copy from the source./*from ww  w  .  j av  a2  s.  c  o  m*/
 * 
 * @param in The stream to read from
 * @throws IOException
 */
private void replaceBlock(DataInputStream in) throws IOException {
    LOG.debug("Mathod called : replaceBlock()");
    /* read header */
    long blockId = in.readLong();
    Block block = new Block(blockId, dataXceiverServer.estimateBlockSize, in.readLong()); // block id & generation stamp
    String sourceID = Text.readString(in); // read del hint
    DatanodeInfo proxySource = new DatanodeInfo(); // read proxy source
    proxySource.readFields(in);

    if (!dataXceiverServer.balanceThrottler.acquire()) { // not able to start
        LOG.warn("Not able to receive block " + blockId + " from " + s.getRemoteSocketAddress()
                + " because threads quota is exceeded.");
        sendResponse(s, (short) DataTransferProtocol.OP_STATUS_ERROR, datanode.socketWriteTimeout);
        return;
    }

    JxtaSocket proxySock = null;
    DataOutputStream proxyOut = null;
    short opStatus = DataTransferProtocol.OP_STATUS_SUCCESS;
    BlockReceiver blockReceiver = null;
    DataInputStream proxyReply = null;
    ReliableOutputStream baseStream = null;
    ReliableInputStream replyStream = null;

    try {
        // get the output stream to the proxy
        //InetSocketAddress proxyAddr = NetUtils.createSocketAddr(
        //    proxySource.getName());
        //proxySock = datanode.newSocket();
        proxySock = datanode.getDnPeer().getInfoSocket(proxySource.getPeerId().toString());

        // NetUtils.connect(proxySock, proxyAddr, datanode.socketTimeout);
        // proxySock.setSoTimeout(datanode.socketTimeout);

        /*OutputStream baseStream = NetUtils.getOutputStream(proxySock, 
            datanode.socketWriteTimeout);
        proxyOut = new DataOutputStream(
             new BufferedOutputStream(baseStream, SMALL_BUFFER_SIZE));
        */
        baseStream = (ReliableOutputStream) proxySock.getOutputStream();
        proxyOut = new DataOutputStream(new BufferedOutputStream(baseStream));

        /* send request to the proxy */
        proxyOut.writeShort(DataTransferProtocol.DATA_TRANSFER_VERSION); // transfer version
        proxyOut.writeByte(DataTransferProtocol.OP_COPY_BLOCK); // op code
        proxyOut.writeLong(block.getBlockId()); // block id
        proxyOut.writeLong(block.getGenerationStamp()); // block id
        proxyOut.flush();

        // receive the response from the proxy
        //proxyReply = new DataInputStream(new BufferedInputStream(
        //    NetUtils.getInputStream(proxySock), BUFFER_SIZE));
        replyStream = (ReliableInputStream) proxySock.getInputStream();
        proxyReply = new DataInputStream(new BufferedInputStream(replyStream));
        // open a block receiver and check if the block does not exist
        blockReceiver = new BlockReceiver(block, proxyReply, proxySock.getRemoteSocketAddress().toString(),
                proxySock.getLocalSocketAddress().toString(), false, "", null, datanode);

        // receive a block
        blockReceiver.receiveBlock(null, null, null, null, dataXceiverServer.balanceThrottler, -1);

        // notify name node
        datanode.notifyNamenodeReceivedBlock(block, sourceID);

        LOG.info("Moved block " + block + " from " + s.getRemoteSocketAddress());

    } catch (IOException ioe) {
        opStatus = DataTransferProtocol.OP_STATUS_ERROR;
        throw ioe;
    } finally {
        // receive the last byte that indicates the proxy released its thread resource
        if (opStatus == DataTransferProtocol.OP_STATUS_SUCCESS) {
            try {
                proxyReply.readChar();
            } catch (IOException ignored) {
            }
        }

        // now release the thread resource
        dataXceiverServer.balanceThrottler.release();

        // send response back
        try {
            sendResponse(s, opStatus, datanode.socketWriteTimeout);
        } catch (IOException ioe) {
            LOG.warn("Error writing reply back to " + s.getRemoteSocketAddress());
        }

        LOG.debug("Finalizing : replaceBlock()");
        LOG.debug("baseStream queue empty : " + baseStream.isQueueEmpty());
        IOUtils.closeStream(proxyOut);
        IOUtils.closeStream(blockReceiver);
        IOUtils.closeStream(proxyReply);
    }
}

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

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w  w  w  . j  a  v  a2  s . c  om*/
 * 
 * @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();
    }
}