Search in sources :

Example 1 with UnsynchronizedByteArrayInputStream

use of org.apache.commons.io.input.UnsynchronizedByteArrayInputStream in project exist by eXist-db.

the class ElementImpl method deserialize.

public static StoredNode deserialize(final byte[] data, final int start, final int len, final DocumentImpl doc, final boolean pooled) {
    final int end = start + len;
    int pos = start;
    final byte idSizeType = (byte) (data[pos] & 0x03);
    boolean isDirty = (data[pos] & 0x8) == 0x8;
    final boolean hasNamespace = (data[pos] & 0x10) == 0x10;
    pos += StoredNode.LENGTH_SIGNATURE_LENGTH;
    final int children = ByteConversion.byteToInt(data, pos);
    pos += LENGTH_ELEMENT_CHILD_COUNT;
    final int dlnLen = ByteConversion.byteToShort(data, pos);
    pos += NodeId.LENGTH_NODE_ID_UNITS;
    final NodeId dln = doc.getBrokerPool().getNodeFactory().createFromData(dlnLen, data, pos);
    pos += dln.size();
    final short attributes = ByteConversion.byteToShort(data, pos);
    pos += LENGTH_ATTRIBUTES_COUNT;
    final short id = (short) Signatures.read(idSizeType, data, pos);
    pos += Signatures.getLength(idSizeType);
    short nsId = 0;
    String prefix = null;
    if (hasNamespace) {
        nsId = ByteConversion.byteToShort(data, pos);
        pos += LENGTH_NS_ID;
        int prefixLen = ByteConversion.byteToShort(data, pos);
        pos += LENGTH_PREFIX_LENGTH;
        if (prefixLen > 0) {
            prefix = UTF8.decode(data, pos, prefixLen).toString();
        }
        pos += prefixLen;
    }
    final String name = doc.getBrokerPool().getSymbols().getName(id);
    String namespace = XMLConstants.NULL_NS_URI;
    if (nsId != 0) {
        namespace = doc.getBrokerPool().getSymbols().getNamespace(nsId);
    }
    final ElementImpl node;
    if (pooled) {
        node = (ElementImpl) NodePool.getInstance().borrowNode(Node.ELEMENT_NODE);
    } else {
        node = new ElementImpl();
    }
    node.setNodeId(dln);
    node.nodeName = doc.getBrokerPool().getSymbols().getQName(Node.ELEMENT_NODE, namespace, name, prefix);
    node.children = children;
    node.attributes = attributes;
    node.isDirty = isDirty;
    node.setOwnerDocument(doc);
    // TO UNDERSTAND : why is this code here ?
    if (end > pos) {
        final byte[] pfxData = new byte[end - pos];
        System.arraycopy(data, pos, pfxData, 0, end - pos);
        final InputStream bin = new UnsynchronizedByteArrayInputStream(pfxData);
        final DataInputStream in = new DataInputStream(bin);
        try {
            final short prefixCount = in.readShort();
            for (int i = 0; i < prefixCount; i++) {
                prefix = in.readUTF();
                nsId = in.readShort();
                node.addNamespaceMapping(prefix, doc.getBrokerPool().getSymbols().getNamespace(nsId));
            }
        } catch (final IOException e) {
            LOG.error(e);
        }
    }
    return node;
}
Also used : DataInputStream(java.io.DataInputStream) UnsynchronizedByteArrayInputStream(org.apache.commons.io.input.UnsynchronizedByteArrayInputStream) InputStream(java.io.InputStream) NodeId(org.exist.numbering.NodeId) UnsynchronizedByteArrayInputStream(org.apache.commons.io.input.UnsynchronizedByteArrayInputStream) IOException(java.io.IOException) DataInputStream(java.io.DataInputStream)

Example 2 with UnsynchronizedByteArrayInputStream

use of org.apache.commons.io.input.UnsynchronizedByteArrayInputStream in project exist by eXist-db.

the class BinaryDoc method eval.

@Override
public Sequence eval(final Sequence[] args, final Sequence contextSequence) throws XPathException {
    final Sequence emptyParamReturnValue = (isCalledAs(FS_BINARY_DOC_NAME) || isCalledAs(FS_BINARY_DOC_CONTENT_DIGEST_NAME)) ? Sequence.EMPTY_SEQUENCE : BooleanValue.FALSE;
    if (args[0].isEmpty()) {
        return emptyParamReturnValue;
    }
    final String path = args[0].getStringValue();
    try (final LockedDocument lockedDoc = context.getBroker().getXMLResource(XmldbURI.xmldbUriFor(path), LockMode.READ_LOCK)) {
        if (lockedDoc == null) {
            return emptyParamReturnValue;
        }
        final DocumentImpl doc = lockedDoc.getDocument();
        if (doc.getResourceType() != DocumentImpl.BINARY_FILE) {
            return emptyParamReturnValue;
        } else if (isCalledAs(FS_BINARY_DOC_NAME)) {
            try (final Txn transaction = context.getBroker().continueOrBeginTransaction()) {
                final BinaryDocument bin = (BinaryDocument) doc;
                final InputStream is = context.getBroker().getBinaryResource(transaction, bin);
                final Base64BinaryDocument b64doc = Base64BinaryDocument.getInstance(context, is);
                b64doc.setUrl(path);
                transaction.commit();
                return b64doc;
            }
        } else if (isCalledAs(FS_BINARY_DOC_CONTENT_DIGEST_NAME)) {
            final String algorithm = args[1].getStringValue();
            final DigestType digestType;
            try {
                digestType = DigestType.forCommonName(algorithm);
            } catch (final IllegalArgumentException e) {
                throw new XPathException(this, "Invalid algorithm: " + algorithm, e);
            }
            try (final Txn transaction = context.getBroker().getBrokerPool().getTransactionManager().beginTransaction()) {
                final BinaryDocument bin = (BinaryDocument) doc;
                final MessageDigest messageDigest = context.getBroker().getBinaryResourceContentDigest(transaction, bin, digestType);
                final InputStream is = new UnsynchronizedByteArrayInputStream(messageDigest.getValue());
                final Sequence result = BinaryValueFromInputStream.getInstance(context, new HexBinaryValueType(), is);
                transaction.commit();
                return result;
            }
        } else {
            return BooleanValue.TRUE;
        }
    } catch (final URISyntaxException e) {
        logger.error("Invalid resource URI", e);
        throw new XPathException(this, "Invalid resource uri", e);
    } catch (final PermissionDeniedException e) {
        logger.error("{}: permission denied to read resource", path, e);
        throw new XPathException(this, path + ": permission denied to read resource");
    } catch (final IOException | TransactionException e) {
        logger.error("{}: I/O error while reading resource", path, e);
        throw new XPathException(this, path + ": I/O error while reading resource", e);
    }
}
Also used : XPathException(org.exist.xquery.XPathException) UnsynchronizedByteArrayInputStream(org.apache.commons.io.input.UnsynchronizedByteArrayInputStream) InputStream(java.io.InputStream) Txn(org.exist.storage.txn.Txn) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) DocumentImpl(org.exist.dom.persistent.DocumentImpl) BinaryDocument(org.exist.dom.persistent.BinaryDocument) TransactionException(org.exist.storage.txn.TransactionException) DigestType(org.exist.util.crypto.digest.DigestType) LockedDocument(org.exist.dom.persistent.LockedDocument) UnsynchronizedByteArrayInputStream(org.apache.commons.io.input.UnsynchronizedByteArrayInputStream) PermissionDeniedException(org.exist.security.PermissionDeniedException) MessageDigest(org.exist.util.crypto.digest.MessageDigest)

Example 3 with UnsynchronizedByteArrayInputStream

use of org.apache.commons.io.input.UnsynchronizedByteArrayInputStream in project exist by eXist-db.

the class DatabaseInsertResources_WithValidation_Test method validDocumentSystemCatalog.

/**
 * Test for inserting hamlet.xml, while validating using default registered
 * DTD set in system catalog.
 *
 * First the string
 *     <!--!DOCTYPE PLAY PUBLIC "-//PLAY//EN" "play.dtd"-->
 * needs to be modified into
 *     <!DOCTYPE PLAY PUBLIC "-//PLAY//EN" "play.dtd">
 */
@Test
public void validDocumentSystemCatalog() throws IOException {
    String hamletWithValid = getHamletXml();
    hamletWithValid = hamletWithValid.replaceAll("\\Q<!\\E.*DOCTYPE.*\\Q-->\\E", "<!DOCTYPE PLAY PUBLIC \"-//PLAY//EN\" \"" + getPlayDtdUrl() + "\">");
    TestTools.insertDocumentToURL(new UnsynchronizedByteArrayInputStream(hamletWithValid.getBytes(UTF_8)), "xmldb:exist://" + VALIDATION_HOME_COLLECTION_URI + "/" + TestTools.VALIDATION_TMP_COLLECTION + "/hamlet_valid.xml");
}
Also used : UnsynchronizedByteArrayInputStream(org.apache.commons.io.input.UnsynchronizedByteArrayInputStream) Test(org.junit.Test)

Example 4 with UnsynchronizedByteArrayInputStream

use of org.apache.commons.io.input.UnsynchronizedByteArrayInputStream in project exist by eXist-db.

the class IndexingTest method irregularilyStructured.

private void irregularilyStructured(boolean getContentAsDOM) throws XMLDBException, ParserConfigurationException, SAXException, IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
    Database database = null;
    final String testName = "IrregularilyStructured";
    startTime = System.currentTimeMillis();
    Collection coll = DatabaseManager.getCollection(baseURI, username, password);
    XMLResource resource = (XMLResource) coll.createResource(name, XMLResource.RESOURCE_TYPE);
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    effectiveSiblingCount = populate(doc);
    resource.setContentAsDOM(doc);
    coll.storeResource(resource);
    coll.close();
    coll = DatabaseManager.getCollection(baseURI, username, password);
    resource = (XMLResource) coll.getResource(name);
    Node n;
    if (getContentAsDOM) {
        n = resource.getContentAsDOM();
    } else {
        String s = (String) resource.getContent();
        byte[] bytes = s.getBytes(UTF_8);
        UnsynchronizedByteArrayInputStream bais = new UnsynchronizedByteArrayInputStream(bytes);
        DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        n = db.parse(bais);
    }
    Element documentElement = null;
    if (n instanceof Element) {
        documentElement = (Element) n;
    } else if (n instanceof Document) {
        documentElement = ((Document) n).getDocumentElement();
    }
    assertions(documentElement);
    coll.removeResource(resource);
}
Also used : DocumentBuilder(javax.xml.parsers.DocumentBuilder) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) Database(org.xmldb.api.base.Database) Collection(org.xmldb.api.base.Collection) UnsynchronizedByteArrayInputStream(org.apache.commons.io.input.UnsynchronizedByteArrayInputStream) Document(org.w3c.dom.Document) XMLResource(org.xmldb.api.modules.XMLResource)

Example 5 with UnsynchronizedByteArrayInputStream

use of org.apache.commons.io.input.UnsynchronizedByteArrayInputStream in project exist by eXist-db.

the class DOMTest method _test4.

private void _test4(boolean getContentAsDOM) throws TransformerException, ParserConfigurationException, XMLDBException, IOException, SAXException {
    Collection coll = existEmbeddedServer.getRoot();
    XMLResource resource = (XMLResource) coll.createResource(name, XMLResource.RESOURCE_TYPE);
    Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Element rootElem = doc.createElement("element");
    Element propertyElem = doc.createElement("property");
    propertyElem.setAttribute("key", "value");
    propertyElem.appendChild(doc.createTextNode("text"));
    rootElem.appendChild(propertyElem);
    doc.appendChild(rootElem);
    resource.setContentAsDOM(doc);
    coll.storeResource(resource);
    coll.close();
    coll = DatabaseManager.getCollection(XmldbURI.LOCAL_DB, "admin", "");
    resource = (XMLResource) coll.getResource(name);
    Node n;
    if (getContentAsDOM) {
        n = resource.getContentAsDOM();
    } else {
        String s = (String) resource.getContent();
        byte[] bytes;
        bytes = s.getBytes(UTF_8);
        try (final UnsynchronizedByteArrayInputStream bais = new UnsynchronizedByteArrayInputStream(bytes)) {
            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            n = db.parse(bais);
        }
    }
    Transformer t = TransformerFactory.newInstance().newTransformer();
    DOMSource source = new DOMSource(n);
    SAXResult result = new SAXResult(new DOMTest.SAXHandler());
    t.transform(source, result);
    coll.removeResource(resource);
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Transformer(javax.xml.transform.Transformer) Element(org.w3c.dom.Element) Node(org.w3c.dom.Node) Document(org.w3c.dom.Document) XMLResource(org.xmldb.api.modules.XMLResource) SAXResult(javax.xml.transform.sax.SAXResult) DocumentBuilder(javax.xml.parsers.DocumentBuilder) UnsynchronizedByteArrayInputStream(org.apache.commons.io.input.UnsynchronizedByteArrayInputStream)

Aggregations

UnsynchronizedByteArrayInputStream (org.apache.commons.io.input.UnsynchronizedByteArrayInputStream)114 InputStream (java.io.InputStream)102 Test (org.junit.Test)93 MarkShieldInputStream (org.apache.commons.io.input.MarkShieldInputStream)31 UnsynchronizedByteArrayOutputStream (org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream)10 IOException (java.io.IOException)8 FilterInputStream (java.io.FilterInputStream)7 CachingFilterInputStream (org.exist.util.io.CachingFilterInputStream)7 XMLResource (org.xmldb.api.modules.XMLResource)6 DBBroker (org.exist.storage.DBBroker)5 Txn (org.exist.storage.txn.Txn)5 Element (org.w3c.dom.Element)4 Collection (org.xmldb.api.base.Collection)4 NodeProxy (org.exist.dom.persistent.NodeProxy)3 PermissionDeniedException (org.exist.security.PermissionDeniedException)3 DigestInputStream (org.exist.util.crypto.digest.DigestInputStream)3 Base64BinaryValueType (org.exist.xquery.value.Base64BinaryValueType)3 BooleanValue (org.exist.xquery.value.BooleanValue)3 DoubleValue (org.exist.xquery.value.DoubleValue)3 StringValue (org.exist.xquery.value.StringValue)3