List of usage examples for java.nio.channels Channels newChannel
public static WritableByteChannel newChannel(OutputStream out)
From source file:org.geowebcache.service.wms.WMSService.java
/** * Handles a getfeatureinfo request/*w ww . j a va 2 s . co m*/ * * @param conv */ private void handleGetFeatureInfo(ConveyorTile tile) throws GeoWebCacheException { TileLayer tl = tld.getTileLayer(tile.getLayerId()); if (tl == null) { throw new GeoWebCacheException(tile.getLayerId() + " is unknown."); } String[] keys = { "x", "y", "srs", "info_format", "bbox", "height", "width" }; Map<String, String> values = ServletUtils.selectedStringsFromMap(tile.servletReq.getParameterMap(), tile.servletReq.getCharacterEncoding(), keys); // TODO Arent we missing some format stuff here? GridSubset gridSubset = tl.getGridSubsetForSRS(SRS.getSRS(values.get("srs"))); BoundingBox bbox = null; try { bbox = new BoundingBox(values.get("bbox")); } catch (NumberFormatException nfe) { log.debug(nfe.getMessage()); } if (bbox == null || !bbox.isSane()) { throw new ServiceException( "The bounding box parameter (" + values.get("srs") + ") is missing or not sane"); } // long[] tileIndex = gridSubset.closestIndex(bbox); MimeType mimeType; try { mimeType = MimeType.createFromFormat(values.get("info_format")); } catch (MimeException me) { throw new GeoWebCacheException( "The info_format parameter (" + values.get("info_format") + ")is missing or not recognized."); } if (mimeType != null && !tl.getInfoMimeTypes().contains(mimeType)) { throw new GeoWebCacheException( "The info_format parameter (" + values.get("info_format") + ") is not supported."); } ConveyorTile gfiConv = new ConveyorTile(sb, tl.getName(), gridSubset.getName(), null, mimeType, tile.getFullParameters(), tile.servletReq, tile.servletResp); gfiConv.setTileLayer(tl); int x, y; try { x = Integer.parseInt(values.get("x")); y = Integer.parseInt(values.get("y")); } catch (NumberFormatException nfe) { throw new GeoWebCacheException("The parameters for x and y must both be positive integers."); } int height, width; try { height = Integer.parseInt(values.get("height")); width = Integer.parseInt(values.get("width")); } catch (NumberFormatException nfe) { throw new GeoWebCacheException("The parameters for height and width must both be positive integers."); } Resource data = tl.getFeatureInfo(gfiConv, bbox, height, width, x, y); try { tile.servletResp.setContentType(mimeType.getMimeType()); ServletOutputStream outputStream = tile.servletResp.getOutputStream(); data.transferTo(Channels.newChannel(outputStream)); outputStream.flush(); } catch (IOException ioe) { tile.servletResp.setStatus(500); log.error(ioe.getMessage()); } }
From source file:org.alfresco.contentstore.ChecksumTest.java
private ByteBuffer copy(InputStream in) throws IOException { File f = TempFileProvider.createTempFile("ContentStoreTest", GUID.generate()); try (OutputStream out = new FileOutputStream(f)) { IOUtils.copy(in, out);//from w w w .j a va2s. c o m } try (ReadableByteChannel c = Channels.newChannel(new FileInputStream(f))) { ByteBuffer bb = ByteBuffer.wrap(java.nio.file.Files.readAllBytes(f.toPath())); return bb; } }
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 2s. c o 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,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.repo.transfer.HttpClientTransmitterImpl.java
public void sendManifest(Transfer transfer, File manifest, OutputStream result) throws TransferException { TransferTarget target = transfer.getTransferTarget(); PostMethod postSnapshotRequest = getPostMethod(); MultipartRequestEntity requestEntity; if (log.isDebugEnabled()) { log.debug("does manifest exist? " + manifest.exists()); log.debug("sendManifest file : " + manifest.getAbsoluteFile()); }//from w w w.j a v a 2 s.co m try { HostConfiguration hostConfig = getHostConfig(target); HttpState httpState = getHttpState(target); try { postSnapshotRequest.setPath(target.getEndpointPath() + "/post-snapshot"); //Put the transferId on the query string postSnapshotRequest.setQueryString( new NameValuePair[] { new NameValuePair("transferId", transfer.getTransferId()) }); //TODO encapsulate the name of the manifest part //And add the manifest file as a "part" Part file = new FilePart(TransferCommons.PART_NAME_MANIFEST, manifest); requestEntity = new MultipartRequestEntity(new Part[] { file }, postSnapshotRequest.getParams()); postSnapshotRequest.setRequestEntity(requestEntity); int responseStatus = httpClient.executeMethod(hostConfig, postSnapshotRequest, httpState); checkResponseStatus("sendManifest", responseStatus, postSnapshotRequest); InputStream is = postSnapshotRequest.getResponseBodyAsStream(); final ReadableByteChannel inputChannel = Channels.newChannel(is); final WritableByteChannel outputChannel = Channels.newChannel(result); try { // copy the channels channelCopy(inputChannel, outputChannel); } finally { inputChannel.close(); outputChannel.close(); } return; } catch (RuntimeException e) { throw e; } catch (Exception e) { String error = "Failed to execute HTTP request to target"; log.debug(error, e); throw new TransferException(MSG_HTTP_REQUEST_FAILED, new Object[] { "sendManifest", target.toString(), e.toString() }, e); } } finally { postSnapshotRequest.releaseConnection(); } }
From source file:schemacrawler.test.utility.TestUtility.java
private static Path writeToTempFile(final InputStream resourceStream) throws IOException, FileNotFoundException { final Path tempFile = createTempFile("resource", "data").normalize().toAbsolutePath(); try (final OutputStream tempFileStream = newOutputStream(tempFile, WRITE, TRUNCATE_EXISTING, CREATE);) { fastChannelCopy(Channels.newChannel(resourceStream), Channels.newChannel(tempFileStream)); }/*w w w. ja v a 2s . c o m*/ return tempFile; }
From source file:jeeves.utils.BinaryFile.java
/** * Copies an input stream (from a file) to an output stream *//*from ww w . j ava2 s . c om*/ public static void copy(InputStream in, OutputStream out, boolean closeInput, boolean closeOutput) throws IOException { try { if (in instanceof FileInputStream) { FileInputStream fin = (FileInputStream) in; WritableByteChannel outChannel; if (out instanceof FileOutputStream) { outChannel = ((FileOutputStream) out).getChannel(); } else { outChannel = Channels.newChannel(out); } fin.getChannel().transferTo(0, Long.MAX_VALUE, outChannel); } else { BufferedInputStream input = new BufferedInputStream(in); byte buffer[] = new byte[BUF_SIZE]; int nRead; while ((nRead = input.read(buffer)) > 0) out.write(buffer, 0, nRead); } } finally { if (closeInput) IOUtils.closeQuietly(in); if (closeOutput) IOUtils.closeQuietly(out); } }
From source file:org.alfresco.contentstore.ChecksumTest.java
@Test public void test0() throws IOException { checksumService.setBlockSize(5);//from w w w . ja v a 2s . c o m UserContext.setUser("user1"); Node node = Node.build().nodeId(GUID.generate()).nodeVersion(1l); try (InputStream in = new ByteArrayInputStream("Hello world".getBytes())) { NodeChecksums checksums = checksumService.getChecksums(node, in); try (InputStream in1 = new ByteArrayInputStream("Hello there world".getBytes()); ReadableByteChannel channel1 = Channels.newChannel(in1)) { PatchDocument patchDocument = new PatchDocumentImpl(); patchService.updatePatchDocument(patchDocument, checksums, channel1); System.out.println("patchDocument = " + patchDocument); } } }
From source file:org.mycore.common.content.util.MCRServletContentHelper.java
/** * Consumes the content and writes it to the ServletOutputStream. *//*from ww w. j a v a2 s . c om*/ private static void copy(final MCRContent content, final ServletOutputStream out, final int inputBufferSize, final int outputBufferSize) throws IOException { final long bytesCopied; long length = content.length(); if (content instanceof MCRSeekableChannelContent) { try (SeekableByteChannel byteChannel = ((MCRSeekableChannelContent) content).getSeekableByteChannel(); WritableByteChannel nout = Channels.newChannel(out)) { endCurrentTransaction(); bytesCopied = copyChannel(byteChannel, nout, outputBufferSize); } } else { try (InputStream contentIS = content.getInputStream(); final InputStream in = isInputStreamBuffered(contentIS, content) ? contentIS : new BufferedInputStream(contentIS, inputBufferSize);) { endCurrentTransaction(); // Copy the inputBufferSize stream to the outputBufferSize stream bytesCopied = IOUtils.copyLarge(in, out, new byte[outputBufferSize]); } } if (length >= 0 && length != bytesCopied) { throw new EOFException("Bytes to send: " + length + " actual: " + bytesCopied); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("Wrote " + bytesCopied + " bytes."); } }
From source file:org.alfresco.contentstore.ChecksumTest.java
@Test public void test1() throws IOException { checksumService.setBlockSize(5);/*ww w . j av a2s . co m*/ UserContext.setUser("user1"); Node node = Node.build().nodeId(GUID.generate()).nodeVersion(1l); NodeChecksums checksums = getChecksumsForString(node, "Hello there world"); try (ReadableByteChannel inChannel = Channels .newChannel(new ByteArrayInputStream("Hello world".getBytes())); ReadableByteChannel inChannel1 = Channels .newChannel(new ByteArrayInputStream("Hello there world".getBytes())); ByteArrayOutputStream bos = new ByteArrayOutputStream(1024); WritableByteChannel patchedChannel = Channels.newChannel(bos)) { PatchDocument patchDocument = new PatchDocumentImpl(); patchService.updatePatchDocument(patchDocument, checksums, inChannel); try (InputStream actual = new ByteArrayInputStream(bos.toByteArray()); InputStream expected = new ByteArrayInputStream("Hello world".getBytes())) { assertEqual(expected, actual); } } }
From source file:org.geowebcache.storage.blobstore.memory.MemoryBlobStore.java
/*** * This method is used for converting a {@link TileObject} {@link Resource} into a {@link ByteArrayResource}. * /*from w ww .j av a2 s . co m*/ * @param obj * @return a TileObject with resource stored in a Byte Array * @throws StorageException */ private TileObject getByteResourceTile(TileObject obj) throws StorageException { // Get TileObject resource Resource blob = obj.getBlob(); final Resource finalBlob; // If it is a ByteArrayResource, the result is simply copied if (obj.getBlob() instanceof ByteArrayResource) { if (LOG.isDebugEnabled()) { LOG.debug("Resource is already a Byte Array, only a copy is needed"); } ByteArrayResource byteArrayResource = (ByteArrayResource) obj.getBlob(); byte[] contents = byteArrayResource.getContents(); byte[] copy = new byte[contents.length]; System.arraycopy(contents, 0, copy, 0, contents.length); finalBlob = new ByteArrayResource(copy); } else { if (LOG.isDebugEnabled()) { LOG.debug("Resource is not a Byte Array, data must be transferred"); } // Else the result is written to a new WritableByteChannel final ByteArrayOutputStream bOut = new ByteArrayOutputStream(); WritableByteChannel wChannel = Channels.newChannel(bOut); try { blob.transferTo(wChannel); } catch (IOException e) { throw new StorageException(e.getLocalizedMessage(), e); } finalBlob = new ByteArrayResource(bOut.toByteArray()); } // Creation of a new Resource TileObject cached = TileObject.createCompleteTileObject(obj.getLayerName(), obj.getXYZ(), obj.getGridSetId(), obj.getBlobFormat(), obj.getParameters(), finalBlob); return cached; }