@Override public void accept(DocumentRecord documentRecord) { String uri = documentRecord.getUri(); ZipEntry zipEntry = buildZipEntry(documentRecord); synchronized (this.zipOutputStream) { try { zipOutputStream.putNextEntry(zipEntry); if (logger.isDebugEnabled()) { logger.debug("Writing zip entry, name: " + zipEntry.getName()); } zipOutputStream.write(documentRecord.getContent(new BytesHandle()).get()); zipOutputStream.closeEntry(); } catch (IOException e) { throw new RuntimeException("Unable to write zip entry for URI: " + uri + "; cause: " + e.getMessage(), e); } } }
/** * Initializes the handle with a byte array for the content. * @param content the byte array */ public BytesHandle(byte[] content) { this(); set(content); }
/** * Specifies the format of the content and returns the handle * as a fluent convenience. * @param format the format of the content * @return this handle */ public BytesHandle withFormat(Format format) { setFormat(format); return this; } /**
@Test public void testWrite_ttl_FileHandle() throws Exception { File file = new File(datasource + "relative3.ttl"); FileInputStream fileinputstream = new FileInputStream(file); ByteArrayOutputStream byteoutputstream = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; // Get triples into bytes from file for (int readNum; (readNum = fileinputstream.read(buf)) != -1;) { byteoutputstream.write(buf, 0, readNum); } byte[] bytes = byteoutputstream.toByteArray(); fileinputstream.close(); byteoutputstream.close(); BytesHandle contentHandle = new BytesHandle(); contentHandle.set(bytes); // write triples in bytes to DB gmWriter.write("http://test.turtle.com/byteHandle", contentHandle.withMimetype(RDFMimeTypes.TURTLE)); BytesHandle byteHandle = gmWriter.read("http://test.turtle.com/byteHandle", new BytesHandle().withMimetype(RDFMimeTypes.TURTLE)); byte[] readInBytes = byteHandle.get(); String readInString = new String(readInBytes); assertTrue("Did not insert document or inserted empty doc", readInString.contains("#relativeIRI")); }
static public BytesHandle BytesToHandle(byte[] value) { return (value == null) ? null : new BytesHandle(value); } static public Stream<BytesHandle> BytesToHandle(Stream<? extends byte[]> values) {
void receiveElement(Element ruleElement) { Element nameElement = getChildByName(ruleElement, RequestConstants.RESTAPI_NS, "name"); this.setName(nameElement.getTextContent()); Element descElement = getChildByName(ruleElement, RequestConstants.RESTAPI_NS, "description"); this.setDescription(descElement.getTextContent()); Element searchElement = getChildByName(ruleElement, RequestConstants.SEARCH_NS, "search"); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.VERSION, "1.0"); trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); trans.setOutputProperty(OutputKeys.INDENT, "no"); trans.transform(new DOMSource(searchElement), new StreamResult(baos)); importQueryDefinition(new BytesHandle(baos.toByteArray()) .withFormat(Format.XML)); } catch (TransformerConfigurationException e) { throw new MarkLogicIOException( "Could not get query from rule payload"); } catch (TransformerException e) { throw new MarkLogicIOException( "Could not get query from rule payload"); } receiveRuleMetadataImpl(ruleElement); }
BytesHandle bh = new BytesHandle(ba); bh.setFormat(Format.TEXT);
@Test public void testReadWrite() throws IOException, XpathException { String docId = "/test/binary-sample.png"; String mimetype = "image/png"; BinaryDocumentManager docMgr = Common.client.newBinaryDocumentManager(); docMgr.setMetadataExtraction(MetadataExtraction.PROPERTIES); docMgr.write(docId, new BytesHandle().with(BYTES_BINARY).withMimetype(mimetype)); DocumentDescriptor desc = docMgr.exists(docId); assertTrue("Binary exists did not get number of bytes", desc.getByteLength() != DocumentDescriptor.UNKNOWN_LENGTH); assertEquals("Binary exists got wrong number of bytes", BYTES_BINARY.length, desc.getByteLength()); byte[] buf = docMgr.read(docId, new BytesHandle()).get(); assertEquals("Binary document read wrong number of bytes", BYTES_BINARY.length, buf.length); buf = Common.streamToBytes(docMgr.read(docId, new InputStreamHandle()).get()); assertTrue("Binary document read binary empty input stream",buf.length > 0); BytesHandle handle = new BytesHandle(); buf = docMgr.read(docId, handle, 9, 10).get(); assertEquals("Binary range read wrong number of bytes", 10, buf.length); assertEquals("Binary range did not set length in handle", 10, handle.getByteLength()); docMgr.setMetadataCategories(Metadata.PROPERTIES); Document metadataDocument = docMgr.readMetadata(docId, new DOMHandle()).get(); assertXpathEvaluatesTo("image/png","string(/*[local-name()='metadata']/*[local-name()='properties']/*[local-name()='content-type'])", metadataDocument); assertXpathEvaluatesTo("text HD-HTML","string(/*[local-name()='metadata']/*[local-name()='properties']/*[local-name()='filter-capabilities'])", metadataDocument); assertXpathEvaluatesTo("815","string(/*[local-name()='metadata']/*[local-name()='properties']/*[local-name()='size'])", metadataDocument); }
@Test public void testJSONRuleDefinitions() throws SAXException, IOException, ForbiddenUserException, FailedRequestException, ResourceNotFoundException { File ruleFile = new File("src/test/resources/rule1.json"); FileHandle ruleHandle = new FileHandle(ruleFile); ruleHandle.setFormat(Format.JSON); ruleManager.writeRule("javatestrule", ruleHandle); assertTrue(ruleManager.exists("javatestrule")); RuleDefinition def = ruleManager.readRule("javatestrule", new RuleDefinition()); assertEquals("javatestrule", def.getName()); assertXMLEqual( "Search element round-tripped - structured query and options", "<search:search xmlns:search=\"http://marklogic.com/appservices/search\">" + "<search:qtext>favorited:true</search:qtext>" + "<search:options xmlns:search=\"http://marklogic.com/appservices/search\">" + "<search:constraint name=\"favorited\">" + "<search:value>" + "<search:element ns=\"\" name=\"favorited\" />" + "</search:value>" + "</search:constraint>" + "</search:options>" + "</search:search>", new String( def.exportQueryDefinition(new BytesHandle()).get())); BytesHandle bHandle = ruleManager.readRule("javatestrule", new BytesHandle().withFormat(Format.JSON)); assertEquals( "{\"rule\":{\"name\":\"javatestrule\", \"description\":\"rule to demonstrate REST alerting\", \"search\":{\"qtext\":[\"favorited:true\"], \"options\":{\"constraint\":[{\"name\":\"favorited\", \"value\":{\"element\":{\"ns\":\"\", \"name\":\"favorited\"}}}]}}, \"rule-metadata\":null}}", new String(bHandle.get())); ruleManager.delete("javatestrule"); }
BytesHandle contentHandle = new BytesHandle(); contentHandle.set(bytes);
@Test public void testWrite_n3_BytesHandle() throws Exception { File file = new File(datasource + "relative7.n3"); FileInputStream fileinputstream = new FileInputStream(file); ByteArrayOutputStream byteoutputstream = new ByteArrayOutputStream(); byte[] buf = new byte[1024]; // Get triples into bytes from file for (int readNum; (readNum = fileinputstream.read(buf)) != -1;) { byteoutputstream.write(buf, 0, readNum); } byte[] bytes = byteoutputstream.toByteArray(); fileinputstream.close(); byteoutputstream.close(); BytesHandle contentHandle = new BytesHandle(); contentHandle.set(bytes); // write triples in bytes to DB gmWriter.write("http://test.n3.com/byte", contentHandle.withMimetype(RDFMimeTypes.N3)); InputStreamHandle read = gmWriter.read("http://test.n3.com/byte", new InputStreamHandle().withMimetype(RDFMimeTypes.N3)); InputStream fileRead = read.get(); String readContent = convertInputStreamToString(fileRead); assertTrue("Did not find expected content after inserting the triples:: Found: " + readContent, readContent.contains("/publications/journals/Journal1/1940")); read.close(); }
moveMgr.stopJob(ticket); BytesHandle readContents = client.newDocumentManager().read("/doc/string", new BytesHandle()); System.out.println("Read doc, and format=[" + readContents.getFormat() + "]"); assertEquals("contents from db should match", docContents, new String(readContents.get()));
@Override public Content adapt(DocumentWriteOperation operation) { String uri = operation.getUri(); ContentCreateOptions options = adaptMetadata(operation.getMetadata()); AbstractWriteHandle handle = operation.getContent(); if (handle instanceof StringHandle) { return ContentFactory.newContent(uri, ((StringHandle) handle).get(), options); } else if (handle instanceof FileHandle) { return ContentFactory.newContent(uri, ((FileHandle) handle).get(), options); } else if (handle instanceof BytesHandle) { return ContentFactory.newContent(uri, ((BytesHandle) handle).get(), options); } else if (handle instanceof InputStreamHandle) { try { return ContentFactory.newContent(uri, ((InputStreamHandle) handle).get(), options); } catch (IOException e) { throw new RuntimeException("Unable to read content input stream: " + e.getMessage(), e); } } else if (handle instanceof DOMHandle) { return ContentFactory.newContent(uri, ((DOMHandle) handle).get(), options); } else throw new IllegalArgumentException("No support yet for content class: " + handle.getClass().getName()); }
beforeStr = new String(before); BytesHandle bytesH = new BytesHandle(); bytesH.fromBuffer(before); after = bytesH.toBuffer(); assertNotNull("Bytes after",after); assertXMLEqual("Bytes buffering",beforeStr,new String(after));
/** * Zero-argument constructor. */ public BytesHandle() { super(); setResendable(true); } /**
/** * Specifies the mime type of the content and returns the handle * as a fluent convenience. * @param mimetype the mime type of the content * @return this handle */ public BytesHandle withMimetype(String mimetype) { setMimetype(mimetype); return this; }
public static HandleFactoryRegistry registerDefaults(HandleFactoryRegistry registry) { registry.register(BytesHandle.newFactory()); registry.register(DOMHandle.newFactory()); registry.register(FileHandle.newFactory()); registry.register(InputSourceHandle.newFactory()); registry.register(InputStreamHandle.newFactory()); registry.register(ReaderHandle.newFactory()); registry.register(SourceHandle.newFactory()); registry.register(StringHandle.newFactory()); registry.register(XMLEventReaderHandle.newFactory()); registry.register(XMLStreamReaderHandle.newFactory()); return registry; }
/** * Creates a factory to create a BytesHandle instance for a byte[] array. * @return the factory */ static public ContentHandleFactory newFactory() { return new ContentHandleFactory() { @Override public Class<?>[] getHandledClasses() { return new Class<?>[]{ byte[].class }; } @Override public boolean isHandled(Class<?> type) { return byte[].class.isAssignableFrom(type); } @Override public <C> ContentHandle<C> newHandle(Class<C> type) { @SuppressWarnings("unchecked") ContentHandle<C> handle = isHandled(type) ? (ContentHandle<C>) new BytesHandle() : null; return handle; } }; }
void receiveElement(Element ruleElement) { Element nameElement = getChildByName(ruleElement, RequestConstants.RESTAPI_NS, "name"); this.setName(nameElement.getTextContent()); Element descElement = getChildByName(ruleElement, RequestConstants.RESTAPI_NS, "description"); this.setDescription(descElement.getTextContent()); Element searchElement = getChildByName(ruleElement, RequestConstants.SEARCH_NS, "search"); try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.VERSION, "1.0"); trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); trans.setOutputProperty(OutputKeys.INDENT, "no"); trans.transform(new DOMSource(searchElement), new StreamResult(baos)); importQueryDefinition(new BytesHandle(baos.toByteArray()) .withFormat(Format.XML)); } catch (TransformerConfigurationException e) { throw new MarkLogicIOException( "Could not get query from rule payload"); } catch (TransformerException e) { throw new MarkLogicIOException( "Could not get query from rule payload"); } receiveRuleMetadataImpl(ruleElement); }
BytesHandle bh = new BytesHandle(ba); bh.setFormat(Format.TEXT);