Search in sources :

Example 1 with UnsynchronizedByteArrayOutputStream

use of org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream in project exist by eXist-db.

the class Configurator method parse.

public static Configuration parse(final Configurable instance, final DBBroker broker, final Collection collection, final XmldbURI fileURL) throws ConfigurationException {
    final FullXmldbURI key = getFullURI(broker.getBrokerPool(), collection.getURI().append(fileURL));
    Configuration conf = hotConfigs.get(key);
    if (conf != null) {
        return conf;
    }
    // XXX: locking required
    DocumentImpl document;
    try {
        document = collection.getDocument(broker, fileURL);
    } catch (final PermissionDeniedException pde) {
        throw new ConfigurationException(pde.getMessage(), pde);
    }
    if (document == null) {
        if (broker.isReadOnly()) {
            // create in memory document & configuration
            try (final UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream();
                final Writer writer = new OutputStreamWriter(os)) {
                final SAXSerializer serializer = new SAXSerializer(writer, null);
                serializer.startDocument();
                serialize(instance, serializer);
                serializer.endDocument();
                if (os.size() == 0) {
                    return null;
                }
                return parse(os.toInputStream());
            } catch (final IOException | SAXException e) {
                throw new ConfigurationException(e.getMessage(), e);
            }
        }
        try {
            document = save(instance, broker, collection, fileURL);
        } catch (final IOException e) {
            LOG.error(e.getMessage(), e);
            // TODO : throw exception ? -pb
            return null;
        }
    }
    if (document == null) {
        // possibly on corrupted database, find better solution (recovery flag?)
        return null;
    }
    final Element confElement = document.getDocumentElement();
    if (confElement == null) {
        // possibly on corrupted database, find better solution (recovery flag?)
        return null;
    }
    conf = new ConfigurationImpl(confElement);
    hotConfigs.put(key, conf);
    return conf;
}
Also used : Element(org.w3c.dom.Element) UnsynchronizedByteArrayOutputStream(org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream) DocumentImpl(org.exist.dom.persistent.DocumentImpl) SAXException(org.xml.sax.SAXException) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) FullXmldbURI(org.exist.xmldb.FullXmldbURI) SAXSerializer(org.exist.util.serializer.SAXSerializer)

Example 2 with UnsynchronizedByteArrayOutputStream

use of org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream in project exist by eXist-db.

the class XMLUtil method getXMLDecl.

public static final String getXMLDecl(final byte[] data) {
    boolean foundTag = false;
    for (int i = 0; i < data.length && !foundTag; i++) {
        if (data[i] == '<') {
            foundTag = true;
            /*
                 * Need to gather the next 4 non-zero values and test them
				 * because greater than 8-bytes character encodings will be
				 * represented with two bits
				 */
            boolean foundQuestionMark = false;
            int placeInDeclString = 0;
            final byte[] declString = new byte[4];
            int x = (i + 1);
            for (; x < data.length; x++) {
                if (data[x] == 0) {
                    continue;
                }
                if (!foundQuestionMark && data[x] != '?') {
                    break;
                } else {
                    foundQuestionMark = true;
                }
                declString[placeInDeclString] = data[x];
                placeInDeclString++;
                if (placeInDeclString >= 4) {
                    break;
                }
            }
            if (placeInDeclString == 4 && declString[0] == '?' && declString[1] == 'x' && declString[2] == 'm' && declString[3] == 'l') {
                final UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream(150);
                out.write('<');
                out.write(declString, 0, 4);
                for (int j = (x + 1); j < data.length; j++) {
                    if (data[j] != 0) {
                        out.write(data[j]);
                    }
                    if (data[j] == '?') {
                        j++;
                        /*
							 * When we find this we have to start looking for the end tag
							 */
                        for (; j < data.length; j++) {
                            if (data[j] == 0) {
                                continue;
                            }
                            out.write(data[j]);
                            if (data[j] != '>') {
                                break;
                            }
                            return new String(out.toByteArray());
                        }
                    }
                }
            }
        }
    }
    return null;
}
Also used : UnsynchronizedByteArrayOutputStream(org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream)

Example 3 with UnsynchronizedByteArrayOutputStream

use of org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream in project exist by eXist-db.

the class DOMFile method getNodeValue.

/**
 * Retrieve the string value of the specified node. This is an optimized low-level method
 * which will directly traverse the stored DOM nodes and collect the string values of
 * the specified root node and all its descendants. By directly scanning the stored
 * node data, we do not need to create a potentially large amount of node objects
 * and thus save memory and time for garbage collection.
 *
 * @param broker the database broker
 * @param node the node
 * @param addWhitespace true if whitespace should be added to the node value
 * @return string value of the specified node
 */
public String getNodeValue(final DBBroker broker, final IStoredNode node, final boolean addWhitespace) {
    if (LOG.isDebugEnabled() && !lockManager.isBtreeLocked(getLockName())) {
        LOG.debug("The file doesn't own a lock");
    }
    try {
        long address = node.getInternalAddress();
        RecordPos recordPos = null;
        // try to directly locate the root node through its storage address
        if (StorageAddress.hasAddress(address)) {
            recordPos = findRecord(address);
        }
        if (recordPos == null) {
            // fallback to a BTree lookup if the node could not be found
            // by its storage address
            address = findValue(broker, new NodeProxy(node));
            if (address == BTree.KEY_NOT_FOUND) {
                LOG.error("Node value not found: {}", node);
                // TODO : throw exception ? -pb
                return null;
            }
            recordPos = findRecord(address);
            SanityCheck.THROW_ASSERT(recordPos != null, "Node data could not be found!");
        // TODO : throw exception ? -pb
        }
        // we collect the string values in binary format and append them to a ByteArrayOutputStream
        try (final UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream(32)) {
            // now traverse the tree
            getNodeValue(broker.getBrokerPool(), os, recordPos, true, addWhitespace);
            final byte[] data = os.toByteArray();
            final XMLString str = UTF8.decode(data);
            if (str != null) {
                return str.toString();
            } else {
                return "";
            }
        }
    } catch (final BTreeException e) {
        LOG.error("BTree error while reading node value", e);
    // TODO : rethrow exception ? -pb
    } catch (final Exception e) {
        LOG.error("IO error while reading node value", e);
    // TODO : rethrow exception ? -pb
    }
    // TODO : remove if exceptions thrown...
    return null;
}
Also used : BTreeException(org.exist.storage.btree.BTreeException) UnsynchronizedByteArrayOutputStream(org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream) NodeProxy(org.exist.dom.persistent.NodeProxy) JournalException(org.exist.storage.journal.JournalException) TerminatedException(org.exist.xquery.TerminatedException) XMLStreamException(javax.xml.stream.XMLStreamException) DBException(org.exist.storage.btree.DBException) BTreeException(org.exist.storage.btree.BTreeException) IOException(java.io.IOException)

Example 4 with UnsynchronizedByteArrayOutputStream

use of org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream in project exist by eXist-db.

the class TestEXistXMLSerialize method serialize1.

@Test
public void serialize1() throws TransformerException, XMLDBException, ParserConfigurationException, SAXException, IOException, URISyntaxException {
    Collection testCollection = DatabaseManager.getCollection(XmldbURI.LOCAL_DB + "/" + TEST_COLLECTION);
    XMLResource resource = (XMLResource) testCollection.createResource(null, "XMLResource");
    Document doc = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(Paths.get(testFile.toURI()).toFile());
    resource.setContentAsDOM(doc);
    testCollection.storeResource(resource);
    resource = (XMLResource) testCollection.getResource(resource.getId());
    assertNotNull(resource);
    Node node = resource.getContentAsDOM();
    node = node.getOwnerDocument();
    // Attempting serialization
    DOMSource source = new DOMSource(node);
    try (final UnsynchronizedByteArrayOutputStream out = new UnsynchronizedByteArrayOutputStream()) {
        StreamResult result = new StreamResult(out);
        Transformer xformer = TransformerFactory.newInstance().newTransformer();
        xformer.transform(source, result);
    }
}
Also used : DOMSource(javax.xml.transform.dom.DOMSource) Transformer(javax.xml.transform.Transformer) StreamResult(javax.xml.transform.stream.StreamResult) Node(org.w3c.dom.Node) Collection(org.xmldb.api.base.Collection) Document(org.w3c.dom.Document) UnsynchronizedByteArrayOutputStream(org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream) XMLResource(org.xmldb.api.modules.XMLResource) Test(org.junit.Test)

Example 5 with UnsynchronizedByteArrayOutputStream

use of org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream in project exist by eXist-db.

the class GetParameterTest method testRequest.

private void testRequest(final Request request, final String expected) throws IOException {
    final HttpResponse response = request.execute().returnResponse();
    assertEquals(HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
    try (final UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream()) {
        response.getEntity().writeTo(os);
        assertEquals(expected, new String(os.toByteArray(), UTF_8));
    }
}
Also used : HttpResponse(org.apache.http.HttpResponse) UnsynchronizedByteArrayOutputStream(org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream)

Aggregations

UnsynchronizedByteArrayOutputStream (org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream)65 Test (org.junit.Test)24 InputStream (java.io.InputStream)23 IOException (java.io.IOException)20 HttpResponse (org.apache.http.HttpResponse)14 UnsynchronizedByteArrayInputStream (org.apache.commons.io.input.UnsynchronizedByteArrayInputStream)11 XPathException (org.exist.xquery.XPathException)11 FilterInputStream (java.io.FilterInputStream)7 SAXException (org.xml.sax.SAXException)7 CachingFilterInputStream (org.exist.util.io.CachingFilterInputStream)6 Base64BinaryValueType (org.exist.xquery.value.Base64BinaryValueType)6 Path (java.nio.file.Path)5 XmldbURI (org.exist.xmldb.XmldbURI)5 BinaryValue (org.exist.xquery.value.BinaryValue)5 HttpEntity (org.apache.http.HttpEntity)4 Request (org.apache.http.client.fluent.Request)4 PermissionDeniedException (org.exist.security.PermissionDeniedException)4 Image (java.awt.Image)3 BufferedImage (java.awt.image.BufferedImage)3 XmlRpcClient (org.apache.xmlrpc.client.XmlRpcClient)3