static public BytesHandle BytesToHandle(byte[] value) { return (value == null) ? null : new BytesHandle(value); } static public Stream<BytesHandle> BytesToHandle(Stream<? extends byte[]> values) {
/** * 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; } }; }
/** * 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; } }; }
@Override public <C> ContentHandle<C> newHandle(Class<C> type) { @SuppressWarnings("unchecked") ContentHandle<C> handle = isHandled(type) ? (ContentHandle<C>) new BytesHandle() : null; return handle; } };
@Override public <C> ContentHandle<C> newHandle(Class<C> type) { @SuppressWarnings("unchecked") ContentHandle<C> handle = isHandled(type) ? (ContentHandle<C>) new BytesHandle() : null; return handle; } };
@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); } } }
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); }
/** * @param moduleName appended to the baseUri to determine the model definition URI * @param modelDefinition JSON or XML * @return */ public String loadModel(String moduleName, String modelDefinition) { GenericDocumentManager mgr = client.newDocumentManager(); DocumentMetadataHandle dmh = new DocumentMetadataHandle(); dmh.getCollections().add(modelCollection); String modelUri = baseUri + moduleName; mgr.write(modelUri, dmh, new BytesHandle(modelDefinition.getBytes())); return modelUri; }
private Object readDocContent(String docId) { Object docContent = null; if (docContentType == byte[].class){ docContent = ((BytesHandle)docManager.read(docId, new BytesHandle())).get(); } else if (docContentType == File.class) { try { docContent = new SAXReader().read((File) docManager.readAs(docId, docContentType)); } catch (DocumentException e) { throw new MarkLogicException(new MarkLogicErrorCode("Can't read document"), e); } } else { docContent = docManager.readAs(docId, docContentType); } return docContent; }
private Object readDocContent(String docId) { Object docContent = null; if (docContentType == byte[].class){ docContent = ((BytesHandle)docManager.read(docId, new BytesHandle())).get(); } else if (docContentType == File.class) { try { docContent = new SAXReader().read((File) docManager.readAs(docId, docContentType)); } catch (DocumentException e) { throw new MarkLogicException(new MarkLogicErrorCode("Can't read document"), e); } } else { docContent = docManager.readAs(docId, docContentType); } return docContent; }
/** * Read document using BytesHandle * * @param client * @param uri * @param type * @throws IOException */ public BytesHandle readDocumentUsingBytesHandle(DatabaseClient client, String uri, String type) throws IOException, NullPointerException { // create doc manager DocumentManager docMgr = null; docMgr = documentManagerSelector(client, docMgr, type); // create handle BytesHandle contentHandle = new BytesHandle(); // create doc id String readDocId = uri; System.out.println("Read " + readDocId + " from database"); docMgr.read(readDocId, contentHandle); return contentHandle; }
@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")); }
private AbstractWriteHandle prepareWriteHandle(Object docContent) { AbstractWriteHandle genericHandle = null; if (MarkLogicOutputProperties.DocType.BINARY == properties.docType.getValue()) { if (docContent instanceof byte[]) { genericHandle = new BytesHandle((byte[]) docContent); } else if (docContent instanceof File) { genericHandle = new FileHandle((File) docContent); } else if (docContent instanceof String) { genericHandle = new StringHandle((String) docContent); } else { throw new MarkLogicException(new MarkLogicErrorCode("Unsupported Content Represent in " + docContent.getClass())); } } else { if (docContent instanceof String) { genericHandle = new StringHandle((String) docContent); } } return genericHandle; }
private AbstractWriteHandle prepareWriteHandle(Object docContent) { AbstractWriteHandle genericHandle = null; if (MarkLogicOutputProperties.DocType.BINARY == properties.docType.getValue()) { if (docContent instanceof byte[]) { genericHandle = new BytesHandle((byte[]) docContent); } else if (docContent instanceof File) { genericHandle = new FileHandle((File) docContent); } else if (docContent instanceof String) { genericHandle = new StringHandle((String) docContent); } else { throw new MarkLogicException(new MarkLogicErrorCode("Unsupported Content Represent in " + docContent.getClass())); } } else { if (docContent instanceof String) { genericHandle = new StringHandle((String) docContent); } } return genericHandle; }
@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(); }
@Test public void testXMLRuleDefinitionsWithStructuredQuery() throws SAXException, IOException, ForbiddenUserException, FailedRequestException, ResourceNotFoundException { RuleDefinition defWithImport = new RuleDefinition(); defWithImport.setName("javatestrule2"); File ruleFile = new File("src/test/resources/structured-query.xml"); FileHandle queryHandle = new FileHandle(ruleFile); defWithImport.importQueryDefinition(queryHandle); ruleManager.writeRule(defWithImport); assertTrue(ruleManager.exists("javatestrule2")); RuleDefinition def = ruleManager.readRule("javatestrule2", new RuleDefinition()); assertEquals("javatestrule2", def.getName()); assertXMLEqual( "Search element round-tripped - structured query and options", "<search:search xmlns:search=\"http://marklogic.com/appservices/search\">" + "<search:query>" + "<search:term-query><search:text>foo</search:text></search:term-query>" + "</search:query>" + "</search:search>", new String( def.exportQueryDefinition(new BytesHandle()).get())); ruleManager.delete("javatestrule"); }
sourceNode.equals(readNode)); BytesHandle bytesHandle = new BytesHandle(); docMgr.read(docId, bytesHandle); readNode = mapper.readTree(bytesHandle.get());
@Test public void testReadWrite() throws IOException { String docId = "/test/testWrite1.txt"; String text = "A simple text document"; TextDocumentManager docMgr = Common.client.newTextDocumentManager(); docMgr.write(docId, new StringHandle().with(text)); assertEquals("Text document write difference",text,docMgr.read(docId, new StringHandle()).get()); BytesHandle bytesHandle = new BytesHandle(); docMgr.read(docId, bytesHandle); assertEquals("Text document mismatch reading bytes", bytesHandle.get().length,text.length()); InputStreamHandle inputStreamHandle = new InputStreamHandle(); docMgr.read(docId, inputStreamHandle); byte[] b = Common.streamToBytes(inputStreamHandle.get()); assertEquals("Text document mismatch reading input stream",new String(b),text); Reader reader = docMgr.read(docId, new ReaderHandle()).get(); String s = Common.readerToString(reader); assertEquals("Text document mismatch with reader",s,text); File file = docMgr.read(docId, new FileHandle()).get(); assertEquals("Text document mismatch with file",text.length(),file.length()); }
@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 getNullTests() throws DatatypeConfigurationException, JsonProcessingException, IOException { String javascript = "var myNull; myNull"; ServerEvaluationCall call = Common.evalClient.newServerEval().javascript(javascript) .addVariable("myNull", (String) null); try (EvalResultIterator results = call.eval()) { assertEquals("myNull looks wrong", null, results.next().getString()); } try (EvalResultIterator results = call.eval()) { assertEquals("myNull looks wrong", null, results.next().get(new StringHandle()).get()); } try (EvalResultIterator results = call.eval()) { assertEquals("myNull looks wrong", null, results.next().get(new BytesHandle()).get()); } try (EvalResultIterator results = call.eval()) { NullNode jsonNullNode = new ObjectMapper().createObjectNode().nullNode(); assertEquals("myNull looks wrong", jsonNullNode, results.next().get(new JacksonHandle()).get()); } try (EvalResultIterator results = call.eval()) { ReaderHandle valueReader = results.next().get(new ReaderHandle()); String value = HandleAccessor.contentAsString(valueReader); assertEquals("myNull looks wrong", "null", value); } }