Example usage for java.io DataInputStream readChar

List of usage examples for java.io DataInputStream readChar

Introduction

In this page you can find the example usage for java.io DataInputStream readChar.

Prototype

public final char readChar() throws IOException 

Source Link

Document

See the general contract of the readChar method of DataInput.

Usage

From source file:net.sf.keystore_explorer.crypto.x509.X509ExtensionSet.java

private static Map<String, byte[]> loadExtensions(DataInputStream dis) throws IOException {
    Map<String, byte[]> extensions = new HashMap<String, byte[]>();

    int extensionCnt = dis.readInt();

    for (int i = 0; i < extensionCnt; i++) {
        int oidLen = dis.readInt();

        char[] oidChars = new char[oidLen];

        for (int j = 0; j < oidLen; j++) {
            oidChars[j] = dis.readChar();
        }/*from   w w w  . j a va  2 s. c om*/

        String oid = new String(oidChars);

        int valueLen = dis.readInt();
        byte[] value = new byte[valueLen];

        dis.readFully(value);

        extensions.put(oid, value);
    }

    return extensions;
}

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. ja va  2  s.c om
    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.tacografo.file.FileBlockTGD.java

/**
 * Lectura de los bloques con formato :tag(fid)-longitud-value
 * /*www.  j a v  a 2  s  .c o  m*/
 * @param entrada
 * @throws IOException
 * @throws ErrorFile ocurrido cuando no es un fichero tgd o falla en la lectura de algun bloque
 * porque no encuentre el tag(fid)
 */
private void lectura_bloque(DataInputStream entrada) throws IOException, ErrorFile {
    boolean existe_fid = true;
    while (existe_fid) {
        // la lectura tiene que ser con readUnsignedShort debido a que
        // los fid c108 y c100
        // los detecta con signo y me los rellenas como ffffc108 y
        // ffffc100
        int fid = entrada.readUnsignedShort();

        existe_fid = this.existe_Fid(fid);
        if (existe_fid) {
            // tipo de archivo 0 = bloque de dato -- 1 = certificado
            byte tipo = entrada.readByte();
            Integer longitud = Integer.valueOf(entrada.readChar());
            byte[] datos = new byte[longitud];

            entrada.read(datos, 0, longitud);
            // tipo de bloque
            if (tipo == 0) {
                CardBlock block = FactoriaBloques.getFactoria(fid, datos);
                if (block != null) {
                    this.lista_bloque.put(block.getFID(), block);
                }

            }
        } else {
            throw new ErrorFile();
        }
    }
}

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

public void readPosAndMinorAllele(DataInputStream is) throws IOException, DataInconsistencyException {
    //TODO: Only solves homegrown case atm;
    // @David I changed this to an IllegalArgumentException because the other one was unknown on my system
    // id_ is already read 

    //String curChr = chr_;
    //int curStart = start_;
    //int curEnd = end_;

    chr_ = is.readUTF();//from w ww  .  j a  v a  2  s .  c o  m
    start_ = is.readInt();
    end_ = is.readInt();
    //if (curChr != null || curStart != -1 || curEnd != -1){
    //   if (!chr_.equals(curChr) || start_ != curStart || end_ != curEnd){
    //   throw new RuntimeException("snp seems to have been set before to another value");
    //}
    //}
    posStrand_ = is.readBoolean();
    minorAllele_ = is.readChar();
}

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

public void readPosAndAllele(DataInputStream is) throws IOException, DataInconsistencyException {
    //TODO: Only solves homegrown case atm;
    // @David I changed this to an IllegalArgumentException because the other one was unknown on my system
    // id_ is already read 

    //String curChr = chr_;
    //int curStart = start_;
    //int curEnd = end_;

    chr_ = is.readUTF();//w  ww  .  j ava2 s.  co m
    start_ = is.readInt();
    end_ = is.readInt();
    //if (curChr != null || curStart != -1 || curEnd != -1){
    //   if (!chr_.equals(curChr) || start_ != curStart || end_ != curEnd){
    //   throw new RuntimeException("snp seems to have been set before to another value");
    //}
    //}
    posStrand_ = is.readBoolean();
    char minorAllele = is.readChar();

    boolean snpHasBeenSeenInGWAS = false;
    if (minorAllele_ != 'N' || majorAllele_ != 'N') {
        snpHasBeenSeenInGWAS = true;
    }
    if (Pascal.set.withZScore_ && minorAllele_ != minorAllele) {
        if (minorAllele != majorAllele_ && snpHasBeenSeenInGWAS) {
            throw new DataInconsistencyException(
                    "different minor allele of reference population not found GWAS data. Snp left out.");
        }
        zscore_ *= -1;
        char minorAlleleSummaryFile = minorAllele_;
        char majorAlleleSummaryFile = majorAllele_;
        minorAllele_ = majorAlleleSummaryFile;
        majorAllele_ = minorAlleleSummaryFile;
    }
}

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

@Override
public void replaceBlock(final ExtendedBlock block, final Token<BlockTokenIdentifier> blockToken,
        final String delHint, final DatanodeInfo proxySource) throws IOException {
    updateCurrentThreadName("Replacing block " + block + " from " + delHint);

    /* read header */
    block.setNumBytes(dataXceiverServer.estimateBlockSize);
    if (datanode.isBlockTokenEnabled) {
        try {//ww  w  .j  a  v  a 2s.c o m
            datanode.blockPoolTokenSecretManager.checkAccess(blockToken, null, block,
                    BlockTokenSecretManager.AccessMode.REPLACE);
        } catch (InvalidToken e) {
            LOG.warn("Invalid access token in request from " + remoteAddress
                    + " for OP_REPLACE_BLOCK for block " + block + " : " + e.getLocalizedMessage());
            sendResponse(s, ERROR_ACCESS_TOKEN, "Invalid access token", dnConf.socketWriteTimeout);
            return;
        }
    }

    if (!dataXceiverServer.balanceThrottler.acquire()) { // not able to start
        String msg = "Not able to receive block " + block.getBlockId() + " from " + s.getRemoteSocketAddress()
                + " because threads quota is exceeded.";
        LOG.warn(msg);
        sendResponse(s, ERROR, msg, dnConf.socketWriteTimeout);
        return;
    }

    Socket proxySock = null;
    DataOutputStream proxyOut = null;
    Status opStatus = SUCCESS;
    String errMsg = null;
    BlockReceiver blockReceiver = null;
    DataInputStream proxyReply = null;

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

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

        /* send request to the proxy */
        new Sender(proxyOut).copyBlock(block, blockToken);

        // receive the response from the proxy
        proxyReply = new DataInputStream(
                new BufferedInputStream(NetUtils.getInputStream(proxySock), HdfsConstants.IO_FILE_BUFFER_SIZE));
        BlockOpResponseProto copyResponse = BlockOpResponseProto
                .parseFrom(HdfsProtoUtil.vintPrefixed(proxyReply));

        if (copyResponse.getStatus() != SUCCESS) {
            if (copyResponse.getStatus() == 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");
        }

        // get checksum info about the block we're copying
        ReadOpChecksumInfoProto checksumInfo = copyResponse.getReadOpChecksumInfo();
        DataChecksum remoteChecksum = DataTransferProtoUtil.fromProto(checksumInfo.getChecksum());
        // open a block receiver and check if the block does not exist
        blockReceiver = new BlockReceiver(block, proxyReply, proxySock.getRemoteSocketAddress().toString(),
                proxySock.getLocalSocketAddress().toString(), null, 0, 0, 0, "", null, datanode,
                remoteChecksum);

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

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

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

    } catch (IOException ioe) {
        opStatus = ERROR;
        errMsg = "opReplaceBlock " + block + " received exception " + ioe;
        LOG.info(errMsg);
        throw ioe;
    } finally {
        // receive the last byte that indicates the proxy released its thread resource
        if (opStatus == SUCCESS) {
            try {
                proxyReply.readChar();
            } catch (IOException ignored) {
            }
        }

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

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

    // update metrics
    datanode.metrics.addReplaceBlockOp(elapsed());
}

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.//from w w w  .j  a v  a2 s .  c  om
 * 
 * @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:org.apache.hadoop.hdfs.server.datanode.DWRRDataXceiver.java

@Override
public void replaceBlock(final ExtendedBlock block, final Token<BlockTokenIdentifier> blockToken,
        final String delHint, final DatanodeInfo proxySource) throws IOException {
    updateCurrentThreadName("Replacing block " + block + " from " + delHint);

    /* read header */
    block.setNumBytes(DataXceiverServer.estimateBlockSize);
    if (datanode.isBlockTokenEnabled) {
        try {//from  www  .  j a v  a 2s .com
            datanode.blockPoolTokenSecretManager.checkAccess(blockToken, null, block,
                    BlockTokenSecretManager.AccessMode.REPLACE);
        } catch (InvalidToken e) {
            LOG.warn("Invalid access token in request from " + remoteAddress
                    + " for OP_REPLACE_BLOCK for block " + block + " : " + e.getLocalizedMessage());
            sendResponse(ERROR_ACCESS_TOKEN, "Invalid access token");
            return;
        }
    }

    if (!DataXceiverServer.balanceThrottler.acquire()) { // not able to start
        String msg = "Not able to receive block " + block.getBlockId() + " from "
                + peer.getRemoteAddressString() + " because threads " + "quota is exceeded.";
        LOG.warn(msg);
        sendResponse(ERROR, msg);
        return;
    }

    Socket proxySock = null;
    DataOutputStream proxyOut = null;
    Status opStatus = SUCCESS;
    String errMsg = null;
    BlockReceiver blockReceiver = null;
    DataInputStream proxyReply = null;

    try {
        // get the output stream to the proxy
        final String dnAddr = proxySource.getXferAddr(connectToDnViaHostname);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Connecting to datanode " + dnAddr);
        }
        InetSocketAddress proxyAddr = NetUtils.createSocketAddr(dnAddr);
        proxySock = datanode.newSocket();
        NetUtils.connect(proxySock, proxyAddr, dnConf.socketTimeout);
        proxySock.setSoTimeout(dnConf.socketTimeout);

        OutputStream unbufProxyOut = NetUtils.getOutputStream(proxySock, dnConf.socketWriteTimeout);
        InputStream unbufProxyIn = NetUtils.getInputStream(proxySock);
        if (dnConf.encryptDataTransfer
                && !dnConf.trustedChannelResolver.isTrusted(proxySock.getInetAddress())) {
            IOStreamPair encryptedStreams = DataTransferEncryptor.getEncryptedStreams(unbufProxyOut,
                    unbufProxyIn,
                    datanode.blockPoolTokenSecretManager.generateDataEncryptionKey(block.getBlockPoolId()));
            unbufProxyOut = encryptedStreams.out;
            unbufProxyIn = encryptedStreams.in;
        }

        proxyOut = new DataOutputStream(
                new BufferedOutputStream(unbufProxyOut, HdfsConstants.SMALL_BUFFER_SIZE));
        proxyReply = new DataInputStream(
                new BufferedInputStream(unbufProxyIn, HdfsConstants.IO_FILE_BUFFER_SIZE));

        /* send request to the proxy */
        new Sender(proxyOut).copyBlock(block, blockToken);

        // receive the response from the proxy

        BlockOpResponseProto copyResponse = BlockOpResponseProto.parseFrom(PBHelper.vintPrefixed(proxyReply));

        if (copyResponse.getStatus() != SUCCESS) {
            if (copyResponse.getStatus() == 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");
        }

        // get checksum info about the block we're copying
        ReadOpChecksumInfoProto checksumInfo = copyResponse.getReadOpChecksumInfo();
        DataChecksum remoteChecksum = DataTransferProtoUtil.fromProto(checksumInfo.getChecksum());
        // open a block receiver and check if the block does not exist
        blockReceiver = new BlockReceiver(block, proxyReply, proxySock.getRemoteSocketAddress().toString(),
                proxySock.getLocalSocketAddress().toString(), null, 0, 0, 0, "", null, datanode, remoteChecksum,
                CachingStrategy.newDropBehind());

        // receive a block
        blockReceiver.receiveBlock(null, null, null, null, DataXceiverServer.balanceThrottler, null);

        // notify name node
        datanode.notifyNamenodeReceivedBlock(block, delHint, blockReceiver.getStorageUuid());

        LOG.info("Moved " + block + " from " + peer.getRemoteAddressString() + ", delHint=" + delHint);

    } catch (IOException ioe) {
        opStatus = ERROR;
        errMsg = "opReplaceBlock " + block + " received exception " + ioe;
        LOG.info(errMsg);
        throw ioe;
    } finally {
        // receive the last byte that indicates the proxy released its thread resource
        if (opStatus == SUCCESS) {
            try {
                proxyReply.readChar();
            } catch (IOException ignored) {
            }
        }

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

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

    //update metrics
    datanode.metrics.addReplaceBlockOp(elapsed());
}

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 w ww . j  a v  a  2s .c om
 * 
 * @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.nuxeo.theme.presets.PhotoshopPaletteParser.java

public static Map<String, String> parse(byte[] bytes) {
    Map<String, String> entries = new LinkedHashMap<String, String>();
    ByteArrayInputStream is = new ByteArrayInputStream(bytes);
    DataInputStream dis = new DataInputStream(is);

    char[] words = new char[bytes.length];
    int size = 0;
    while (true) {
        try {//ww w . j  av  a 2  s  . c  o m
            words[size] = dis.readChar();
            size++;
        } catch (Exception e) {
            break;
        }
    }

    try {
        is.close();
        dis.close();
    } catch (IOException e) {
        log.error(e, e);
    }

    int offset = 1;
    int version = words[0] & 0xffff;
    int nc = words[1] & 0xffff;

    // get version 2 if it exists
    if (version == 1 && size > nc * 5 + 2) {
        offset += nc * 5 + 2;
        version = words[offset - 1] & 0xffff;
        nc = words[offset] & 0xffff;
    }

    if (version == 1) {
        log.debug("Found ACO v1 color file (Photoshop < 7.0)");
    } else if (version == 2) {
        log.debug("Found ACO v2 color file (Photoshop >= 7.0)");
    } else {
        log.error("Unknown ACO file version: " + version);
        return entries;
    }

    log.debug("Found " + nc + " colors.");

    int counter = 1;
    for (int j = 0; j < nc; j++) {
        String value = null;
        int colorSpace = words[offset + 1] & 0xff;
        int w = words[offset + 2] & 0xffff;
        int x = words[offset + 3] & 0xffff;
        int y = words[offset + 4] & 0xffff;
        int z = words[offset + 5] & 0xffff;

        if (colorSpace == RGB) {
            value = rgbToHex(w / 256, x / 256, y / 256);

        } else if (colorSpace == HSB) {
            float hue = w / 65535F; // [0.0-1.0]
            float saturation = x / 65535F; // [0.0-1.0]
            float brightness = y / 65535F; // [0.0-1.0]
            Color color = Color.getHSBColor(hue, saturation, brightness);
            value = rgbToHex(color.getRed(), color.getGreen(), color.getBlue());

        } else if (colorSpace == CMYK) {
            float cyan = 1F - w / 65535F; // [0.0-1.0]
            float magenta = 1F - x / 65535F; // [0.0-1.0]
            float yellow = 1F - y / 65535F; // [0.0-1.0]
            float black = 1F - z / 65535F; // [0.0-1.0]
            // TODO: do the conversion to RGB. An ICC profile is required.
            log.warn("Unsupported color space: CMYK");

        } else if (colorSpace == GRAYSCALE) {
            int gray = (int) (w * 256F / 10000F); // [0-256]
            value = rgbToHex(gray, gray, gray);

        } else if (colorSpace == LAB) {
            float l = w / 100F;
            float a = x / 100F;
            float b = y / 100F;
            // TODO: do the conversion to RGB. An ICC profile is required.
            log.warn("Unsupported color space: CIE Lab");

        } else if (colorSpace == WIDE_CMYK) {
            float cyan = w / 10000F; // [0.0-1.0]
            float magenta = x / 10000F; // [0.0-1.0]
            float yellow = y / 10000F; // [0.0-1.0]
            float black = z / 10000F; // [0.0-1.0]
            // TODO: do the conversion to RGB. An ICC profile is required.
            log.warn("Unsupported color space: Wide CMYK");

        } else {
            log.warn("Unknown color space: " + colorSpace);
        }

        String name = "";
        if (version == 1) {
            name = String.format("Color %s", counter);
        }

        else if (version == 2) {
            int len = (words[offset + 7] & 0xffff) - 1;
            name = String.copyValueOf(words, offset + 8, len);
            offset += len + 3;

            String n = name;
            int c = 2;
            while (entries.containsKey(n)) {
                n = String.format("%s %s", name, c);
                c++;
            }
            name = n;
        }

        if (value != null) {
            entries.put(name, value);
        }

        offset += 5;
        counter++;
    }

    return entries;
}