Search in sources :

Example 21 with UnsynchronizedByteArrayOutputStream

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

the class Eval method responseBytes.

public byte[] responseBytes() {
    byte[] response;
    if (exception != null) {
        response = errorBytes("eval", Errors.ERR_206, exception.getMessage());
    } else {
        String head = xml_declaration + "<response " + namespaces + "command=\"eval\" " + "success=\"" + isSuccess() + "\" " + "transaction_id=\"" + transactionID + "\">" + "<property>";
        String tail = "</property>" + "</response>";
        Base64Encoder enc = new Base64Encoder();
        enc.translate(result.getBytes());
        UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(head.length() + ((result.length() / 100) * 33) + tail.length());
        try {
            baos.write(head.getBytes());
            baos.write(new String(enc.getCharArray()).getBytes());
            baos.write(tail.getBytes());
        } catch (IOException e) {
        }
        response = baos.toByteArray();
    }
    return response;
}
Also used : IOException(java.io.IOException) UnsynchronizedByteArrayOutputStream(org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream) Base64Encoder(org.exist.util.Base64Encoder)

Example 22 with UnsynchronizedByteArrayOutputStream

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

the class Source method responseBytes.

public byte[] responseBytes() {
    if (exception != null) {
        String url = "NULL";
        if (fileURI != null)
            url = fileURI;
        response = errorBytes("source", Errors.ERR_100, exception.getMessage() + " (URL:" + url + ")");
    } else if (response == null) {
        if (source != null) {
            try {
                String head = xml_declaration + "<response " + namespaces + "command=\"source\" " + "success=\"" + getSuccessString() + "\" " + "encoding=\"base64\" " + "transaction_id=\"" + transactionID + "\"><![CDATA[";
                String tail = "]]></response>";
                Base64Encoder enc = new Base64Encoder();
                enc.translate(source);
                UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream(head.length() + ((source.length / 100) * 33) + tail.length());
                baos.write(head.getBytes());
                baos.write(new String(enc.getCharArray()).getBytes());
                baos.write(tail.getBytes());
                response = baos.toByteArray();
            } catch (IOException e) {
                response = errorBytes("source");
            }
        } else {
            response = errorBytes("source", Errors.ERR_100, Errors.ERR_100_STR);
        }
    }
    return response;
}
Also used : IOException(java.io.IOException) UnsynchronizedByteArrayOutputStream(org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream) Base64Encoder(org.exist.util.Base64Encoder)

Example 23 with UnsynchronizedByteArrayOutputStream

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

the class RestBinariesTest method readAndStreamBinaryRaw.

/**
 * {@see https://github.com/eXist-db/exist/issues/790#error-case-5}
 *
 * response:stream-binary is used to return raw binary.
 */
@Test
public void readAndStreamBinaryRaw() throws IOException, JAXBException {
    // 1MB
    final byte[] data = randomData(1024 * 1024);
    final Path tmpInFile = createTemporaryFile(data);
    final String query = "import module namespace file = \"http://exist-db.org/xquery/file\";\n" + "import module namespace response = \"http://exist-db.org/xquery/response\";\n" + "let $bin := file:read-binary('" + tmpInFile.toAbsolutePath().toString() + "')\n" + "return response:stream-binary($bin, 'media-type=application/octet-stream', ())";
    final HttpResponse response = postXquery(query);
    final HttpEntity entity = response.getEntity();
    try (final UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) {
        entity.writeTo(baos);
        assertArrayEquals(Files.readAllBytes(tmpInFile), baos.toByteArray());
    }
}
Also used : Path(java.nio.file.Path) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) UnsynchronizedByteArrayOutputStream(org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream) Test(org.junit.Test)

Example 24 with UnsynchronizedByteArrayOutputStream

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

the class RestBinariesTest method readAndStreamBinarySax.

/**
 * {@see https://github.com/eXist-db/exist/issues/790#error-case-5}
 *
 * response:stream is used to return Base64 encoded binary.
 */
@Test
public void readAndStreamBinarySax() throws IOException, JAXBException {
    // 1MB
    final byte[] data = randomData(1024 * 1024);
    final Path tmpInFile = createTemporaryFile(data);
    final String query = "import module namespace file = \"http://exist-db.org/xquery/file\";\n" + "import module namespace response = \"http://exist-db.org/xquery/response\";\n" + "let $bin := file:read-binary('" + tmpInFile.toAbsolutePath().toString() + "')\n" + "return response:stream($bin, 'media-type=application/octet-stream')";
    final HttpResponse response = postXquery(query);
    final HttpEntity entity = response.getEntity();
    try (final UnsynchronizedByteArrayOutputStream baos = new UnsynchronizedByteArrayOutputStream()) {
        entity.writeTo(baos);
        assertArrayEquals(Files.readAllBytes(tmpInFile), Base64.decodeBase64(baos.toByteArray()));
    }
}
Also used : Path(java.nio.file.Path) HttpEntity(org.apache.http.HttpEntity) HttpResponse(org.apache.http.HttpResponse) UnsynchronizedByteArrayOutputStream(org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream) Test(org.junit.Test)

Example 25 with UnsynchronizedByteArrayOutputStream

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

the class CropFunction method eval.

/**
 * evaluate the call to the xquery crop() function,
 * it is really the main entry point of this class
 *
 * @param args		arguments from the crop() function call
 * @param contextSequence	the Context Sequence to operate on (not used here internally!)
 * @return		A sequence representing the result of the crop() function call
 *
 * @see org.exist.xquery.BasicFunction#eval(org.exist.xquery.value.Sequence[], org.exist.xquery.value.Sequence)
 */
@Override
public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException {
    // was an image and a mime-type speficifed
    if (args[0].isEmpty() || args[2].isEmpty()) {
        return Sequence.EMPTY_SEQUENCE;
    }
    // get the maximum dimensions to crop to
    int x1 = 0;
    int y1 = 0;
    int x2 = MAXHEIGHT;
    int y2 = MAXWIDTH;
    int width = 0;
    int height = 0;
    if (!args[1].isEmpty()) {
        x1 = ((IntegerValue) args[1].itemAt(0)).getInt();
        if (args[1].hasMany()) {
            y1 = ((IntegerValue) args[1].itemAt(1)).getInt();
            x2 = ((IntegerValue) args[1].itemAt(2)).getInt();
            y2 = ((IntegerValue) args[1].itemAt(3)).getInt();
            width = x2 - x1;
            height = y2 - y1;
        }
    }
    if (width < 1) {
        logger.error("cropping error: x2 value must be greater than x1");
        return Sequence.EMPTY_SEQUENCE;
    }
    if (height < 1) {
        logger.error("cropping error: y2 must be greater than y1");
        return Sequence.EMPTY_SEQUENCE;
    }
    // get the mime-type
    String mimeType = args[2].itemAt(0).getStringValue();
    String formatName = mimeType.substring(mimeType.indexOf("/") + 1);
    // TODO currently ONLY tested for JPEG!!!
    BufferedImage bImage = null;
    try (InputStream inputStream = ((BinaryValue) args[0].itemAt(0)).getInputStream()) {
        // get the image data
        Image image = ImageIO.read(inputStream);
        if (image == null) {
            logger.error("Unable to read image data!");
            return Sequence.EMPTY_SEQUENCE;
        }
        // crop the image
        Image cropImage = Toolkit.getDefaultToolkit().createImage(new FilteredImageSource(image.getSource(), new CropImageFilter(x1, y1, width, height)));
        if (cropImage instanceof BufferedImage) {
            // just in case cropImage is allready an BufferedImage
            bImage = (BufferedImage) cropImage;
        } else {
            bImage = new BufferedImage(cropImage.getWidth(null), cropImage.getHeight(null), BufferedImage.TYPE_INT_RGB);
            // Paint the image onto the buffered image
            Graphics2D g = bImage.createGraphics();
            g.drawImage(cropImage, 0, 0, null);
            g.dispose();
        }
        try (final UnsynchronizedByteArrayOutputStream os = new UnsynchronizedByteArrayOutputStream()) {
            ImageIO.write(bImage, formatName, os);
            // return the new croped image data
            return BinaryValueFromInputStream.getInstance(context, new Base64BinaryValueType(), os.toInputStream());
        }
    } catch (Exception e) {
        throw new XPathException(this, e.getMessage());
    }
}
Also used : XPathException(org.exist.xquery.XPathException) BinaryValueFromInputStream(org.exist.xquery.value.BinaryValueFromInputStream) InputStream(java.io.InputStream) BinaryValue(org.exist.xquery.value.BinaryValue) Base64BinaryValueType(org.exist.xquery.value.Base64BinaryValueType) Image(java.awt.Image) BufferedImage(java.awt.image.BufferedImage) UnsynchronizedByteArrayOutputStream(org.apache.commons.io.output.UnsynchronizedByteArrayOutputStream) BufferedImage(java.awt.image.BufferedImage) XPathException(org.exist.xquery.XPathException) Graphics2D(java.awt.Graphics2D) FilteredImageSource(java.awt.image.FilteredImageSource) CropImageFilter(java.awt.image.CropImageFilter)

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