List of usage examples for java.nio.channels ReadableByteChannel read
public int read(ByteBuffer dst) throws IOException;
From source file:org.alfresco.contentstore.patch.PatchServiceImpl.java
@Override public void getPatch(PatchDocument patchDocument, NodeChecksums nodeChecksums, ReadableByteChannel inChannel) throws IOException { ByteBuffer buffer = ByteBuffer.allocate(1024 * 100); inChannel.read(buffer); buffer.flip();//from w ww. j a v a2 s .c om updatePatchDocument(patchDocument, nodeChecksums, buffer); }
From source file:com.bennavetta.appsite.file.ResourceService.java
public Resource create(String path, MediaType mime, ReadableByteChannel src) throws IOException { String normalized = PathUtils.normalize(path); log.debug("Creating resource {}", normalized); AppEngineFile file = fs.createNewBlobFile(mime.toString(), normalized); FileWriteChannel channel = fs.openWriteChannel(file, true); MessageDigest digest = null;/*w w w. jav a2s .c o m*/ try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("MD5 not available", e); } ByteBuffer buf = ByteBuffer.allocateDirect(bufferSize.get()); while (src.read(buf) != -1 || buf.position() != 0) { buf.flip(); int read = channel.write(buf); if (read != 0) { int origPos = buf.position(); int origLimit = buf.limit(); buf.position(origPos - read); buf.limit(origPos); digest.update(buf); buf.limit(origLimit); buf.position(origPos); } buf.compact(); } channel.closeFinally(); Resource resource = new Resource(normalized, fs.getBlobKey(file).getKeyString(), digest.digest(), mime); resource.save(); return resource; }
From source file:com.sastix.cms.server.services.content.impl.HashedDirectoryServiceImpl.java
private void replaceFile(final Path file, final URL url) throws IOException { //Create the file SeekableByteChannel sbc = null; try {/* w w w . j a v a 2 s . com*/ //Creates a new Readable Byte channel from URL final ReadableByteChannel rbc = Channels.newChannel(url.openStream()); //Create the file sbc = Files.newByteChannel(file, FILE_REPLACE_OPTIONS); //Clears the buffer buffer.clear(); //Read input Channel while (rbc.read(buffer) != -1) { // prepare the buffer to be drained buffer.flip(); // write to the channel, may block sbc.write(buffer); // If partial transfer, shift remainder down // If buffer is empty, same as doing clear() buffer.compact(); } // EOF will leave buffer in fill state buffer.flip(); // make sure the buffer is fully drained. while (buffer.hasRemaining()) { sbc.write(buffer); } } finally { if (sbc != null) { sbc.close(); } } }
From source file:com.sastix.cms.server.services.content.impl.HashedDirectoryServiceImpl.java
/** * Writes file to disk and copy the contents of the input byte array. * * @param file a Path with file path./*from w ww.ja v a2 s.c o m*/ * @param url a remote/local url to be saved as file * @throws IOException */ private void writeFile(final Path file, final URL url) throws IOException { if (url.toString().startsWith("jar:file:///")) { try { writeZipFile(file, url); } catch (Exception e) { throw new IOException(e); } } else { //Create the file SeekableByteChannel sbc = null; try { //Creates a new Readable Byte channel from URL final ReadableByteChannel rbc = Channels.newChannel(url.openStream()); //Create the file sbc = Files.newByteChannel(file, FILE_OPEN_OPTIONS); //Clears the buffer buffer.clear(); //Read input Channel while (rbc.read(buffer) != -1) { // prepare the buffer to be drained buffer.flip(); // write to the channel, may block sbc.write(buffer); // If partial transfer, shift remainder down // If buffer is empty, same as doing clear() buffer.compact(); } // EOF will leave buffer in fill state buffer.flip(); // make sure the buffer is fully drained. while (buffer.hasRemaining()) { sbc.write(buffer); } } finally { if (sbc != null) { sbc.close(); } } } }
From source file:org.alfresco.provision.ActiveMQService.java
private BrokerStats getBrokerStats() throws IOException { BrokerStats brokerStats = new BrokerStats(); StringBuilder sb = new StringBuilder("http://"); sb.append(activeMQHost);//from w w w .j a va2s. co m sb.append(":"); sb.append(activeMQPort); sb.append("/api/jolokia"); String url = sb.toString(); CloseableHttpResponse httpResponse = null; HttpPost httpPost = new HttpPost(url); Request[] post = new Request[] { new Request("read", "org.apache.activemq:type=Broker,brokerName=localhost", "MemoryPercentUsage"), new Request("read", "org.apache.activemq:type=Broker,brokerName=localhost", "StorePercentUsage"), new Request("read", "org.apache.activemq:type=Broker,brokerName=localhost", "TempPercentUsage") }; String str = mapper.writeValueAsString(post); HttpEntity postEntity = new StringEntity(str); httpPost.setEntity(postEntity); httpResponse = client.execute(httpPost); StatusLine status = httpResponse.getStatusLine(); // Expecting "OK" status if (status.getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = httpResponse.getEntity(); InputStream in = entity.getContent(); try { ByteBuffer bb = ByteBuffer.allocate(1024 * 10); ReadableByteChannel inChannel = Channels.newChannel(in); int read = -1; do { read = inChannel.read(bb); } while (read != -1); bb.flip(); Response[] response = mapper.readValue(bb.array(), Response[].class); for (Response r : response) { if (r.getRequest().getAttribute().equals("MemoryPercentUsage")) { double memoryPercentUsage = r.getValue() != null ? r.getValue() : 0.0; brokerStats.withMemoryPercentUsage(memoryPercentUsage); } else if (r.getRequest().getAttribute().equals("StorePercentUsage")) { double storePercentUsage = r.getValue() != null ? r.getValue() : 0.0; brokerStats.withStorePercentUsage(storePercentUsage); } else if (r.getRequest().getAttribute().equals("TempPercentUsage")) { double tempPercentUsage = r.getValue() != null ? r.getValue() : 0.0; brokerStats.withTempPercentUsage(tempPercentUsage); } } } finally { if (in != null) { in.close(); } } } else { // TODO } return brokerStats; }
From source file:org.alfresco.provision.ActiveMQService.java
private DestinationStats getStats(String destinationType, String destinationName) throws IOException { StringBuilder sb = new StringBuilder("http://"); sb.append(activeMQHost);// w w w . ja v a 2 s. com sb.append(":"); sb.append(activeMQPort); sb.append("/api/jolokia"); String url = sb.toString(); CloseableHttpResponse httpResponse = null; HttpPost httpPost = new HttpPost(url); Request[] post = new Request[] { new Request("read", "org.apache.activemq:type=Broker,brokerName=localhost,destinationType=" + destinationType + ",destinationName=" + destinationName, "AverageEnqueueTime"), new Request("read", "org.apache.activemq:type=Broker,brokerName=localhost,destinationType=" + destinationType + ",destinationName=" + destinationName, "EnqueueCount"), new Request("read", "org.apache.activemq:type=Broker,brokerName=localhost,destinationType=" + destinationType + ",destinationName=" + destinationName, "DequeueCount"), new Request("read", "org.apache.activemq:type=Broker,brokerName=localhost,destinationType=" + destinationType + ",destinationName=" + destinationName, "DispatchCount"), new Request("read", "org.apache.activemq:type=Broker,brokerName=localhost,destinationType=" + destinationType + ",destinationName=" + destinationName, "MemoryPercentUsage"), new Request("read", "org.apache.activemq:type=Broker,brokerName=localhost,destinationType=" + destinationType + ",destinationName=" + destinationName, "AverageBlockedTime"), new Request("read", "org.apache.activemq:type=Broker,brokerName=localhost,destinationType=" + destinationType + ",destinationName=" + destinationName, "QueueSize"), new Request("read", "org.apache.activemq:type=Broker,brokerName=localhost,destinationType=" + destinationType + ",destinationName=" + destinationName, "BlockedSends"), new Request("read", "org.apache.activemq:type=Broker,brokerName=localhost,destinationType=" + destinationType + ",destinationName=" + destinationName, "MaxEnqueueTime") }; String str = mapper.writeValueAsString(post); HttpEntity postEntity = new StringEntity(str); httpPost.setEntity(postEntity); httpResponse = client.execute(httpPost); DestinationStats stats = new DestinationStats(destinationType, destinationName); StatusLine status = httpResponse.getStatusLine(); // Expecting "OK" status if (status.getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = httpResponse.getEntity(); InputStream in = entity.getContent(); try { ByteBuffer bb = ByteBuffer.allocate(1024 * 10); ReadableByteChannel inChannel = Channels.newChannel(in); int read = -1; do { read = inChannel.read(bb); } while (read != -1); bb.flip(); Response[] response = mapper.readValue(bb.array(), Response[].class); for (Response r : response) { if (r.getRequest().getAttribute().equals("AverageEnqueueTime")) { stats.setAverageEnqueueTime(r.getValue() != null ? r.getValue() : 0.0); } else if (r.getRequest().getAttribute().equals("EnqueueCount")) { stats.setEnqueueCount(r.getValue() != null ? r.getValue() : 0.0); } else if (r.getRequest().getAttribute().equals("DequeueCount")) { stats.setDequeueCount(r.getValue() != null ? r.getValue() : 0.0); } else if (r.getRequest().getAttribute().equals("DispatchCount")) { stats.setDispatchCount(r.getValue() != null ? r.getValue() : 0.0); } else if (r.getRequest().getAttribute().equals("MemoryPercentUsage")) { stats.setMemoryPercentUsage(r.getValue() != null ? r.getValue() : 0.0); } else if (r.getRequest().getAttribute().equals("AverageBlockedTime")) { stats.setAverageBlockedTime(r.getValue() != null ? r.getValue() : 0.0); } else if (r.getRequest().getAttribute().equals("QueueSize")) { stats.setQueueSize(r.getValue() != null ? r.getValue() : 0.0); } else if (r.getRequest().getAttribute().equals("MaxEnqueueTime")) { stats.setMaxEnqueueTime(r.getValue() != null ? r.getValue() : 0.0); } else if (r.getRequest().getAttribute().equals("BlockedSends")) { stats.setBlockedSends(r.getValue() != null ? r.getValue() : 0.0); } else if (r.getRequest().getAttribute().equals("DispatchCount")) { stats.setDispatchCount(r.getValue() != null ? r.getValue() : 0.0); } } } finally { if (in != null) { in.close(); } } } else { // TODO } return stats; }
From source file:org.alfresco.cacheserver.TestEdgeServer.java
@Test public void test1() throws Exception { long nodeInternalId = 1l; String nodeId = GUID.generate(); String nodeVersion = "1"; String nodePath = "/1/2/3"; byte[] bytes = "test".getBytes("UTF-8"); String expectedMimeType = "text/plain"; Long expectedSize = new Long(bytes.length); InputStream nodeContent = new ByteArrayInputStream(bytes); ReadableByteChannel channel = null; try {// ww w .jav a2 s . co m contentGetter.addTestContent(nodeInternalId, nodeId, nodeVersion, nodePath, "test", expectedMimeType); edgeServer.repoContentUpdated(Node.build().nodeId(nodeId).versionLabel(nodeVersion).nodePath(nodePath), expectedMimeType, expectedSize, true); UserDetails userDetails = new User("admin", null, null); UserContext.setUser(userDetails); ContentReader content = edgeServer.getByNodeId(nodeId, nodeVersion, true); channel = content.getChannel(); ByteBuffer bb = ByteBuffer.allocate(2048); channel.read(bb); assertNotNull(channel); assertEquals(expectedMimeType, content.getMimeType()); assertEquals(expectedSize, content.getSize()); ByteBuffer expectedNodeContent = ByteBuffer.wrap("test".getBytes("UTF-8")); compare(expectedNodeContent, bb); } finally { if (nodeContent != null) { nodeContent.close(); } if (channel != null) { channel.close(); } UserContext.setUser(null); } }
From source file:org.alfresco.contentstore.ChecksumTest.java
protected int applyPatch(ReadableByteChannel inChannel, WritableByteChannel outChannel, PatchDocument patchDocument) throws IOException { InChannel c = new InChannel(inChannel, patchDocument.getMatchedBlocks(), patchDocument.getBlockSize()); int totalWritten = 0; int blockIndex = c.nextBlock(); if (blockIndex > -1) { for (Patch patch : patchDocument.getPatches()) { int lastMatchingBlockIndex = patch.getLastMatchIndex(); while (blockIndex != -1 && blockIndex <= lastMatchingBlockIndex) { int bytesWritten = outChannel.write(c.currentBlock); totalWritten += bytesWritten; if (bytesWritten != c.blockSize) { throw new RuntimeException("Wrote too few bytes, " + c.blockSize + ", " + bytesWritten); }/*w w w .jav a 2s.com*/ blockIndex = c.nextBlock(); if (blockIndex == -1) { break; } } // apply patch int patchSize = patch.getSize(); ReadableByteChannel patchChannel = Channels.newChannel(patch.getStream()); ByteBuffer patchBB = ByteBuffer.allocate(patchSize); int bytesRead = patchChannel.read(patchBB); patchBB.flip(); int bytesWritten = outChannel.write(patchBB); totalWritten += bytesWritten; if (bytesWritten != bytesRead) { throw new RuntimeException( "Wrote too few bytes, expected " + bytesRead + ", got " + bytesWritten); } } // we're done with all the patches, add the remaining blocks while (blockIndex != -1) { int bytesWritten = outChannel.write(c.currentBlock); totalWritten += bytesWritten; if (bytesWritten != c.bytesRead) { throw new RuntimeException("Wrote too few bytes"); } blockIndex = c.nextBlock(); } } return totalWritten; }