Example usage for java.io ByteArrayInputStream available

List of usage examples for java.io ByteArrayInputStream available

Introduction

In this page you can find the example usage for java.io ByteArrayInputStream available.

Prototype

public synchronized int available() 

Source Link

Document

Returns the number of remaining bytes that can be read (or skipped over) from this input stream.

Usage

From source file:com.github.devnied.emvnfccard.utils.TlvUtil.java

/**
 * Method used to get Tag value// ww w . ja va 2 s.co m
 * 
 * @param pData
 *            data
 * @param pTag
 *            tag to find
 * @return tag value or null
 */
public static byte[] getValue(final byte[] pData, final ITag... pTag) {

    byte[] ret = null;

    if (pData != null) {
        ByteArrayInputStream stream = new ByteArrayInputStream(pData);

        while (stream.available() > 0) {

            TLV tlv = TlvUtil.getNextTLV(stream);
            if (ArrayUtils.contains(pTag, tlv.getTag())) {
                return tlv.getValueBytes();
            } else if (tlv.getTag().isConstructed()) {
                ret = TlvUtil.getValue(tlv.getValueBytes(), pTag);
                if (ret != null) {
                    break;
                }
            }
        }
    }

    return ret;
}

From source file:com.github.devnied.emvnfccard.utils.TlvUtil.java

public static String getFormattedTagAndLength(final byte[] data, final int indentLength) {
    StringBuilder buf = new StringBuilder();
    String indent = getSpaces(indentLength);
    ByteArrayInputStream stream = new ByteArrayInputStream(data);

    boolean firstLine = true;
    while (stream.available() > 0) {
        if (firstLine) {
            firstLine = false;/*  w  ww.j  a  v a 2s.  c om*/
        } else {
            buf.append("\n");
        }
        buf.append(indent);

        ITag tag = searchTagById(stream);
        int length = TlvUtil.readTagLength(stream);

        buf.append(prettyPrintHex(tag.getTagBytes()));
        buf.append(" ");
        buf.append(String.format("%02x", length));
        buf.append(" -- ");
        buf.append(tag.getName());
    }
    return buf.toString();
}

From source file:com.github.devnied.emvnfccard.utils.TlvUtil.java

public static String prettyPrintAPDUResponse(final byte[] data, final int indentLength) {
    StringBuilder buf = new StringBuilder();

    ByteArrayInputStream stream = new ByteArrayInputStream(data);

    while (stream.available() > 0) {
        buf.append("\n");
        if (stream.available() == 2) {
            stream.mark(0);/*from  w  ww. ja v a  2 s  .  c om*/
            byte[] value = new byte[2];
            try {
                stream.read(value);
            } catch (IOException e) {
            }
            SwEnum sw = SwEnum.getSW(value);
            if (sw != null) {
                buf.append(getSpaces(0));
                buf.append(BytesUtils.bytesToString(value)).append(" -- ");
                buf.append(sw.getDetail());
                continue;
            }
            stream.reset();
        }

        buf.append(getSpaces(indentLength));

        TLV tlv = TlvUtil.getNextTLV(stream);

        byte[] tagBytes = tlv.getTagBytes();
        byte[] lengthBytes = tlv.getRawEncodedLengthBytes();
        byte[] valueBytes = tlv.getValueBytes();

        ITag tag = tlv.getTag();

        buf.append(prettyPrintHex(tagBytes));
        buf.append(" ");
        buf.append(prettyPrintHex(lengthBytes));
        buf.append(" -- ");
        buf.append(tag.getName());

        int extraIndent = (lengthBytes.length + tagBytes.length) * 3;

        if (tag.isConstructed()) {
            // indentLength += extraIndent; //TODO check this
            // Recursion
            buf.append(prettyPrintAPDUResponse(valueBytes, indentLength + extraIndent));
        } else {
            buf.append("\n");
            if (tag.getTagValueType() == TagValueTypeEnum.DOL) {
                buf.append(TlvUtil.getFormattedTagAndLength(valueBytes, indentLength + extraIndent));
            } else {
                buf.append(getSpaces(indentLength + extraIndent));
                buf.append(prettyPrintHex(BytesUtils.bytesToStringNoSpace(valueBytes),
                        indentLength + extraIndent));
                buf.append(" (");
                buf.append(TlvUtil.getTagValueAsString(tag, valueBytes));
                buf.append(")");
            }
        }
    }
    return buf.toString();
}

From source file:com.github.devnied.emvnfccard.utils.TlvUtil.java

public static TLV getNextTLV(final ByteArrayInputStream stream) {
    if (stream.available() < 2) {
        throw new TlvException("Error parsing data. Available bytes < 2 . Length=" + stream.available());
    }//from   w  w  w.  jav  a 2 s . c  o  m

    // ISO/IEC 7816 uses neither '00' nor 'FF' as tag value.
    // Before, between, or after TLV-coded data objects,
    // '00' or 'FF' bytes without any meaning may occur
    // (for example, due to erased or modified TLV-coded data objects).

    stream.mark(0);
    int peekInt = stream.read();
    byte peekByte = (byte) peekInt;
    // peekInt == 0xffffffff indicates EOS
    while (peekInt != -1 && (peekByte == (byte) 0xFF || peekByte == (byte) 0x00)) {
        stream.mark(0); // Current position
        peekInt = stream.read();
        peekByte = (byte) peekInt;
    }
    stream.reset(); // Reset back to the last known position without 0x00 or 0xFF

    if (stream.available() < 2) {
        throw new TlvException("Error parsing data. Available bytes < 2 . Length=" + stream.available());
    }

    byte[] tagIdBytes = TlvUtil.readTagIdBytes(stream);

    // We need to get the raw length bytes.
    // Use quick and dirty workaround
    stream.mark(0);
    int posBefore = stream.available();
    // Now parse the lengthbyte(s)
    // This method will read all length bytes. We can then find out how many bytes was read.
    int length = TlvUtil.readTagLength(stream); // Decoded
    // Now find the raw (encoded) length bytes
    int posAfter = stream.available();
    stream.reset();
    byte[] lengthBytes = new byte[posBefore - posAfter];

    if (lengthBytes.length < 1 || lengthBytes.length > 4) {
        throw new TlvException("Number of length bytes must be from 1 to 4. Found " + lengthBytes.length);
    }

    stream.read(lengthBytes, 0, lengthBytes.length);

    int rawLength = BytesUtils.byteArrayToInt(lengthBytes);

    byte[] valueBytes;

    ITag tag = searchTagById(tagIdBytes);

    // Find VALUE bytes
    if (rawLength == 128) { // 1000 0000
        // indefinite form
        stream.mark(0);
        int prevOctet = 1;
        int curOctet;
        int len = 0;
        while (true) {
            len++;
            curOctet = stream.read();
            if (curOctet < 0) {
                throw new TlvException(
                        "Error parsing data. TLV " + "length byte indicated indefinite length, but EOS "
                                + "was reached before 0x0000 was found" + stream.available());
            }
            if (prevOctet == 0 && curOctet == 0) {
                break;
            }
            prevOctet = curOctet;
        }
        len -= 2;
        valueBytes = new byte[len];
        stream.reset();
        stream.read(valueBytes, 0, len);
        length = len;
    } else {
        if (stream.available() < length) {
            throw new TlvException("Length byte(s) indicated " + length + " value bytes, but only "
                    + stream.available() + " " + (stream.available() > 1 ? "are" : "is") + " available");
        }
        // definite form
        valueBytes = new byte[length];
        stream.read(valueBytes, 0, length);
    }

    // Remove any trailing 0x00 and 0xFF
    stream.mark(0);
    peekInt = stream.read();
    peekByte = (byte) peekInt;
    while (peekInt != -1 && (peekByte == (byte) 0xFF || peekByte == (byte) 0x00)) {
        stream.mark(0);
        peekInt = stream.read();
        peekByte = (byte) peekInt;
    }
    stream.reset(); // Reset back to the last known position without 0x00 or 0xFF

    return new TLV(tag, length, lengthBytes, valueBytes);
}

From source file:android.framework.util.jar.Manifest.java

/**
 * Returns a byte[] containing all the bytes from a ByteArrayInputStream.
 * Where possible, this returns the actual array rather than a copy.
 *//*from  www  .j  a v  a 2 s  . c  o m*/
private static byte[] exposeByteArrayInputStreamBytes(ByteArrayInputStream bais) {
    byte[] buffer;
    synchronized (bais) {
        byte[] buf;
        int pos;
        try {
            buf = (byte[]) BAIS_BUF.get(bais);
            pos = BAIS_POS.getInt(bais);
        } catch (IllegalAccessException iae) {
            throw new AssertionError(iae);
        }
        int available = bais.available();
        if (pos == 0 && buf.length == available) {
            buffer = buf;
        } else {
            buffer = new byte[available];
            System.arraycopy(buf, pos, buffer, 0, available);
        }
        bais.skip(available);
    }
    return buffer;
}

From source file:deployer.TestUtils.java

public static ByteBuffer createSampleOpenShiftWebAppTarBall() throws IOException, ArchiveException {
    ByteArrayInputStream bis = new ByteArrayInputStream(createSampleAppTarBall(ArtifactType.WebApp).array());
    CompressorInputStream cis = new GzipCompressorInputStream(bis);
    ArchiveInputStream ais = new TarArchiveInputStream(cis);

    ByteArrayOutputStream bos = new ByteArrayOutputStream(bis.available() + 2048);
    CompressorOutputStream cos = new GzipCompressorOutputStream(bos);
    ArchiveOutputStream aos = new TarArchiveOutputStream(cos);

    ArchiveEntry nextEntry;//from w  ww.j  a va2s  .co m
    while ((nextEntry = ais.getNextEntry()) != null) {
        aos.putArchiveEntry(nextEntry);
        IOUtils.copy(ais, aos);
        aos.closeArchiveEntry();
    }
    ais.close();
    cis.close();
    bis.close();

    TarArchiveEntry entry = new TarArchiveEntry(
            Paths.get(".openshift", CONFIG_DIRECTORY, "/standalone.xml").toFile());
    byte[] xmlData = SAMPLE_STANDALONE_DATA.getBytes();
    entry.setSize(xmlData.length);
    aos.putArchiveEntry(entry);
    IOUtils.write(xmlData, aos);
    aos.closeArchiveEntry();

    aos.finish();
    cos.close();
    bos.flush();
    return ByteBuffer.wrap(bos.toByteArray());
}

From source file:deployer.TestUtils.java

public static ByteBuffer createSampleOpenShiftWebAppTarBallWithEmptyFiles(String[] filepaths)
        throws IOException, ArchiveException {
    ByteArrayInputStream bis = new ByteArrayInputStream(createSampleAppTarBall(ArtifactType.WebApp).array());
    CompressorInputStream cis = new GzipCompressorInputStream(bis);
    ArchiveInputStream ais = new TarArchiveInputStream(cis);

    ByteArrayOutputStream bos = new ByteArrayOutputStream(bis.available() + 2048);
    CompressorOutputStream cos = new GzipCompressorOutputStream(bos);
    ArchiveOutputStream aos = new TarArchiveOutputStream(cos);

    ArchiveEntry nextEntry;//  ww w. j ava  2  s . c o  m
    while ((nextEntry = ais.getNextEntry()) != null) {
        aos.putArchiveEntry(nextEntry);
        IOUtils.copy(ais, aos);
        aos.closeArchiveEntry();
    }
    ais.close();
    cis.close();
    bis.close();

    TarArchiveEntry entry = new TarArchiveEntry(
            Paths.get(".openshift", CONFIG_DIRECTORY, "/standalone.xml").toFile());
    byte[] xmlData = SAMPLE_STANDALONE_DATA.getBytes();
    entry.setSize(xmlData.length);
    aos.putArchiveEntry(entry);
    IOUtils.write(xmlData, aos);

    for (int i = 0; i < filepaths.length; i++) {
        String filepath = filepaths[i];
        TarArchiveEntry emptyEntry = new TarArchiveEntry(Paths.get(filepath).toFile());
        byte[] emptyData = "".getBytes();
        emptyEntry.setSize(emptyData.length);
        aos.putArchiveEntry(emptyEntry);
        IOUtils.write(emptyData, aos);
        aos.closeArchiveEntry();
    }

    aos.finish();
    cos.close();
    bos.flush();
    return ByteBuffer.wrap(bos.toByteArray());
}

From source file:com.cloud.bridge.auth.ec2.AuthenticationHandler.java

/**
 * For EC2 SOAP calls this function's goal is to extract the X509 certificate that is
 * part of the WS-Security wrapped SOAP request.   We need the cert in order to 
 * map it to the user's Cloud API key and Cloud Secret Key.
 *//*from   w  w  w  . j a  va2  s  . com*/
public InvocationResponse invoke(MessageContext msgContext) throws AxisFault {
    // -> the certificate we want is embedded into the soap header
    try {
        SOAPEnvelope soapEnvelope = msgContext.getEnvelope();
        String xmlHeader = soapEnvelope.toString();
        //System.out.println( "entire request: " + xmlHeader );

        InputStream is = new ByteArrayInputStream(xmlHeader.getBytes("UTF-8"));
        DocumentBuilder db = dbf.newDocumentBuilder();
        Document request = db.parse(is);
        NodeList certs = request.getElementsByTagNameNS(
                "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd",
                "BinarySecurityToken");
        if (0 < certs.getLength()) {
            Node item = certs.item(0);
            String result = new String(item.getFirstChild().getNodeValue());
            byte[] certBytes = Base64.decodeBase64(result.getBytes());

            Certificate userCert = null;
            CertificateFactory cf = CertificateFactory.getInstance("X.509");
            ByteArrayInputStream bs = new ByteArrayInputStream(certBytes);
            while (bs.available() > 0)
                userCert = cf.generateCertificate(bs);
            //System.out.println( "cert: " + userCert.toString());              
            String uniqueId = AuthenticationUtils.X509CertUniqueId(userCert);
            logger.debug("X509 cert's uniqueId: " + uniqueId);

            // -> find the Cloud API key and the secret key from the cert's uniqueId 
            /*               UserCredentialsDao credentialDao = new UserCredentialsDao();
                           UserCredentials cloudKeys = credentialDao.getByCertUniqueId( uniqueId );
            */
            UserCredentialsVO cloudKeys = ucDao.getByCertUniqueId(uniqueId);
            if (null == cloudKeys) {
                logger.error("Cert does not map to Cloud API keys: " + uniqueId);
                throw new AxisFault("User not properly registered: Certificate does not map to Cloud API Keys",
                        "Client.Blocked");
            } else
                UserContext.current().initContext(cloudKeys.getAccessKey(), cloudKeys.getSecretKey(),
                        cloudKeys.getAccessKey(), "SOAP Request", null);
            //System.out.println( "end of cert match: " + UserContext.current().getSecretKey());
        }
    } catch (AxisFault e) {
        throw e;
    } catch (Exception e) {
        logger.error("EC2 Authentication Handler: ", e);
        throw new AxisFault("An unknown error occurred.", "Server.InternalError");
    }
    return InvocationResponse.CONTINUE;
}

From source file:com.intuit.autumn.web.InputStreamHttpServletRequestWrapper.java

/**
 * Return wrapped intput stream/*from w w  w  .  j  a va  2s. c  o m*/
 *
 * @return invalid response stream
 * @throws IOException unintended exception
 */

@Override
public ServletInputStream getInputStream() throws IOException {
    final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body);

    return new ServletInputStream() {
        @Override
        public boolean isFinished() {
            return byteArrayInputStream.available() == 0;
        }

        @Override
        public boolean isReady() {
            return true;
        }

        @Override
        public void setReadListener(ReadListener readListener) {
            throw new UnsupportedOperationException("Not implemented");
        }

        @Override
        public int read() throws IOException {
            return byteArrayInputStream.read();
        }
    };
}

From source file:com.betfair.application.util.HttpCallable.java

public HttpUriRequest getMethod(String contentType, Object[] paramValues, int size, HttpCallLogEntry cle) {
    cle.setMethod(name);/*from  ww  w  .  ja v a  2 s  .  c o  m*/
    cle.setProtocol(contentType);
    if (contentType.equals("RPC")) {
        HttpPost pm = new HttpPost(rpcEndpoint);

        final ByteArrayInputStream inputStream = new ByteArrayInputStream(jsonRPCCall.getBytes());
        final InputStreamEntity is = new InputStreamEntity(inputStream, inputStream.available());
        pm.addHeader("Content-Type", "application/json");
        pm.addHeader("Accept", "application/json");
        pm.addHeader("X-ExpectedReturnCode", String.valueOf(expectedHTTP));
        pm.setEntity(is);
        return pm;
    } else if (contentType.equals("SOAP")) {
        HttpPost pm = new HttpPost(soapEndpoint);

        final ByteArrayInputStream inputStream = bodySOAP.buildBodyToBytes(size);
        final InputStreamEntity is = new InputStreamEntity(inputStream, inputStream.available());
        pm.addHeader("Content-Type", "application/soap+xml");
        pm.addHeader("X-ExpectedReturnCode", String.valueOf(expectedHTTP));
        pm.setEntity(is);
        return pm;
    } else {
        if (bodyJSON != null) {
            HttpPost pm = new HttpPost(String.format(restURL, paramValues));
            InputStreamEntity is;
            if (contentType.endsWith("json")) {
                final ByteArrayInputStream inputStream = bodyJSON.buildBody(size);
                is = new InputStreamEntity(inputStream, inputStream.available());
            } else {
                final ByteArrayInputStream inputStream = bodyXML.buildBody(size);
                is = new InputStreamEntity(inputStream, inputStream.available());
            }
            pm.addHeader("Content-Type", contentType);
            pm.addHeader("Accept", contentType);
            pm.setEntity(is);
            return pm;
        } else {
            HttpGet gm = new HttpGet(String.format(restURL, paramValues));
            gm.addHeader("Accept", contentType);
            return gm;
        }
    }
}