Example usage for java.io ByteArrayInputStream ByteArrayInputStream

List of usage examples for java.io ByteArrayInputStream ByteArrayInputStream

Introduction

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

Prototype

public ByteArrayInputStream(byte buf[]) 

Source Link

Document

Creates a ByteArrayInputStream so that it uses buf as its buffer array.

Usage

From source file:ZipDemo.java

public static final String uncompress(final byte[] compressed) throws IOException {
    String uncompressed = "";

    try {/*from   w w  w. j a v  a2 s.c  o  m*/
        ByteArrayInputStream bais = new ByteArrayInputStream(compressed);
        GZIPInputStream zis = new GZIPInputStream(bais);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int numBytesRead = 0;
        byte[] tempBytes = new byte[DEFAULT_BUFFER_SIZE];
        while ((numBytesRead = zis.read(tempBytes, 0, tempBytes.length)) != -1) {
            baos.write(tempBytes, 0, numBytesRead);
        }

        uncompressed = new String(baos.toByteArray());
    } catch (ZipException e) {
        e.printStackTrace(System.err);
    }

    return uncompressed;
}

From source file:Main.java

public static Serializable toSerializable(byte[] bytes) {
    if (bytes == null) {
        return null;
    }/*  ww w  . jav a2 s. co  m*/
    try {
        final ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        final ObjectInputStream ois = new ObjectInputStream(bais);
        try {
            return (Serializable) ois.readObject();
        } finally {
            ois.close();
        }
    } catch (Exception e) {
        String msg = "Failed to convert the object to binary: bytes.length=" + bytes.length;
        throw new IllegalStateException(msg, e);
    }
}

From source file:Util.java

public static Object decompress(byte[] data) {
    if (data == null) {
        return null;
    }/*w ww  . j av  a  2s  .  c om*/
    try {
        ByteArrayInputStream bais = new ByteArrayInputStream(data);
        GZIPInputStream gin = new GZIPInputStream(bais);
        ObjectInputStream ois = new ObjectInputStream(gin);
        return ois.readObject();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:Main.java

public static String prettyPrintXML(String xml, int indentAmount)
        throws TransformerConfigurationException, TransformerException {

    Transformer serializer = SAXTransformerFactory.newInstance().newTransformer();

    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", String.valueOf(indentAmount));
    Source xmlSource = new SAXSource(new InputSource(new ByteArrayInputStream(xml.getBytes())));
    StreamResult res = new StreamResult(new ByteArrayOutputStream());
    serializer.transform(xmlSource, res);

    return new String(((ByteArrayOutputStream) res.getOutputStream()).toByteArray());
}

From source file:Main.java

/**
 * Creates a document from the given xml bytes.
 * @return The desired document. Never returns null but throws some Exception.
 * @throws ParserConfigurationException, IOException, SAXException  
 *///from www.  j  a va 2 s.c  o  m
public static Document getDocument(byte[] xml) throws ParserConfigurationException, IOException, SAXException {
    if (xml != null) {
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        // factory.setNamespaceAware( true );
        // factory.setValidating( true );
        final DocumentBuilder builder = factory.newDocumentBuilder();
        final Document document = builder.parse(new ByteArrayInputStream(xml));
        return document;
    }
    throw new IOException("No xml data");
}

From source file:Main.java

/**
 * Convert XML data to a bean using JAXB.
 * // w w  w .  j a va  2 s. c  om
 * @param b
 *            The bean, represented as XML.
 * @param implClass
 *            The implementation class of the bean.
 * @param bc
 *            Additional classes to add to the JAXB context.
 * @return The bean, unmarshalled from the XML data using JAXB.
 */
public static <T> T unmarshal(String b, Class<T> implClass, Class<?>... bc) {
    Class<?>[] bind;
    if (bc.length > 1) {
        bind = new Class<?>[bc.length + 1];
        bind[0] = implClass;
        for (int i = 0; i < bc.length; i++) {
            bind[i + 1] = bc[i];
        }
    } else {
        bind = new Class<?>[] { implClass, };
    }
    ByteArrayInputStream bais = new ByteArrayInputStream(b.getBytes());
    try {
        JAXBContext jaxbContext = JAXBContext.newInstance(bind);
        Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
        return implClass.cast(unmarshaller.unmarshal(bais));
    } catch (JAXBException e) {
        throw new IllegalStateException("Error unmarshalling", e);
    }
}

From source file:Main.java

private static Element getRootNodeFromXmlStr(String xmlStr) {
    Element element = null;/*from w ww .j  a v a 2s  . c  o m*/
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputStream is = new ByteArrayInputStream(xmlStr.getBytes("UTF-8"));
        Document document = db.parse(is);
        element = document.getDocumentElement();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return element;
}

From source file:Main.java

public static Node getNode(String xmlStr, String nodeName, Map<String, String> attributesMap) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    Node returnNode = null;/*from  w w w . j  a  v  a 2s .  com*/
    try {
        DocumentBuilder db = dbf.newDocumentBuilder();
        InputStream inStream = new ByteArrayInputStream(xmlStr.getBytes(StandardCharsets.UTF_8));
        // or InputSource inputSource = new InputSource( new StringReader(
        // xmlStr ) );
        Document doc = db.parse(inStream);
        DocumentTraversal dt = (DocumentTraversal) doc;
        NodeIterator i = dt.createNodeIterator(doc, NodeFilter.SHOW_ELEMENT, null, false);
        Node node = i.nextNode();
        while (node != null) {
            if (node.getNodeName().equals(nodeName)) {
                if (attributesExist(node, attributesMap)) {
                    returnNode = node;
                    break;
                }
            }
            node = i.nextNode();
        }
    } catch (Exception ex) {
        logger.error(ex);
    }
    return returnNode;
}

From source file:Main.java

/**
 * Validate xml file using specific schema
 * @param sourceXmlBytes/*  ww w .ja  v  a 2s  . c o  m*/
 *        the byte array reading from xml file
 * @param schemaUrl   
 *         schema url used for validation
 * @return  byte[]
 */
public static void validate(byte[] sourceXmlBytes, URL schemaUrl) throws IOException, SAXException {
    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
    try {
        Schema schema = factory.newSchema(schemaUrl);
        Validator validator = schema.newValidator();
        Source source = new StreamSource(new ByteArrayInputStream(sourceXmlBytes));
        validator.validate(source);
    } catch (SAXException ex) {
        throw ex;
    } catch (IOException e) {
        throw e;
    }
}

From source file:net.es.nsi.topology.translator.http.Decoder.java

public static Document decode(String source) throws IOException {
    byte[] encoded = Base64.getDecoder().decode(source);
    byte[] xml = decompress(encoded);

    try {/*from w  w  w. ja v  a 2 s. c o m*/
        Document doc = DomParser.xml2Dom(new ByteArrayInputStream(xml));
        return doc;
    } catch (ParserConfigurationException | SAXException ex) {
        log.error("decode: failed to parse document", ex);
        throw new IOException(ex.getMessage(), ex.getCause());
    }
}