List of usage examples for java.nio.channels Channels newChannel
public static WritableByteChannel newChannel(OutputStream out)
From source file:org.wikidata.wdtk.util.DirectoryManagerImpl.java
@Override public long createFile(String fileName, InputStream inputStream) throws IOException { long fileSize; Path filePath = this.directory.resolve(fileName); try (ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream); FileChannel fc = FileChannel.open(filePath, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW)) { fileSize = fc.transferFrom(readableByteChannel, 0, Long.MAX_VALUE); }/* w ww. j a v a 2s . co m*/ return fileSize; }
From source file:com.atilika.kuromoji.trie.DoubleArrayTrie.java
/** * Load Stored data/* www . jav a 2s .com*/ * * @param input input stream to read the double array trie from * @return double array trie, not null * @throws IOException if an IO error occured during reading the double array trie */ public static DoubleArrayTrie read(InputStream input) throws IOException { DoubleArrayTrie trie = new DoubleArrayTrie(); DataInputStream dis = new DataInputStream(new BufferedInputStream(input)); trie.compact = dis.readBoolean(); int baseCheckSize = dis.readInt(); // Read size of baseArr and checkArr int tailSize = dis.readInt(); // Read size of tailArr ReadableByteChannel channel = Channels.newChannel(dis); ByteBuffer tmpBaseBuffer = ByteBuffer.allocate(baseCheckSize * 4); channel.read(tmpBaseBuffer); tmpBaseBuffer.rewind(); trie.baseBuffer = tmpBaseBuffer.asIntBuffer(); ByteBuffer tmpCheckBuffer = ByteBuffer.allocate(baseCheckSize * 4); channel.read(tmpCheckBuffer); tmpCheckBuffer.rewind(); trie.checkBuffer = tmpCheckBuffer.asIntBuffer(); ByteBuffer tmpTailBuffer = ByteBuffer.allocate(tailSize * 2); channel.read(tmpTailBuffer); tmpTailBuffer.rewind(); trie.tailBuffer = tmpTailBuffer.asCharBuffer(); input.close(); return trie; }
From source file:io.pravega.segmentstore.storage.impl.extendeds3.S3FileSystemImpl.java
@Synchronized @Override//from w w w .j a v a 2 s. c o m public void putObject(String bucketName, String key, Range range, Object content) { Path path = Paths.get(this.baseDir, bucketName, key); try (FileChannel channel = FileChannel.open(path, StandardOpenOption.WRITE)) { long startOffset = range.getFirst(); long length = range.getLast() + 1 - range.getFirst(); do { long bytesTransferred = channel.transferFrom(Channels.newChannel((InputStream) content), range.getFirst(), range.getLast() + 1 - range.getFirst()); length -= bytesTransferred; startOffset += bytesTransferred; } while (length > 0); AclSize aclKey = aclMap.get(key); aclMap.put(key, aclKey.withSize(range.getLast() + 1)); } catch (IOException e) { throw new S3Exception("NoObject", 404, "NoSuchKey", key); } }
From source file:pl.allegro.tech.hermes.consumers.consumer.sender.http.ByteBufferEntity.java
@Override public void writeTo(OutputStream outstream) throws IOException { Args.notNull(outstream, "Output stream"); WritableByteChannel channel = Channels.newChannel(outstream); channel.write(buffer);/* www .j av a 2 s . c o m*/ outstream.flush(); }
From source file:org.eclipse.jgit.lfs.server.fs.ObjectDownloadListener.java
/** * @param repository/*from ww w. j a v a 2s .c o m*/ * the repository storing large objects * @param context * the servlet asynchronous context * @param response * the servlet response * @param id * id of the object to be downloaded * @throws IOException */ public ObjectDownloadListener(FileLfsRepository repository, AsyncContext context, HttpServletResponse response, AnyLongObjectId id) throws IOException { this.context = context; this.response = response; this.in = repository.getReadChannel(id); this.out = response.getOutputStream(); this.outChannel = Channels.newChannel(out); response.addHeader(HttpSupport.HDR_CONTENT_LENGTH, String.valueOf(repository.getSize(id))); response.setContentType(Constants.HDR_APPLICATION_OCTET_STREAM); }
From source file:org.cryptomator.frontend.webdav.servlet.DavFolder.java
private void addMemberFile(DavFile memberFile, InputStream inputStream) { try (ReadableByteChannel src = Channels.newChannel(inputStream); // WritableByteChannel dst = Files.newByteChannel(memberFile.path, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) { ByteStreams.copy(src, dst);//from ww w .java 2 s. c om } catch (IOException e) { throw new UncheckedIOException(e); } }
From source file:net.technicpack.launchercore.mirror.download.Download.java
@Override @SuppressWarnings("unused") public void run() { ReadableByteChannel rbc = null; FileOutputStream fos = null;// w w w. j a v a 2 s .c o m try { HttpURLConnection conn = Utils.openHttpConnection(url); int response = conn.getResponseCode(); int responseFamily = response / 100; if (responseFamily == 3) { String redirUrlText = conn.getHeaderField("Location"); if (redirUrlText != null && !redirUrlText.isEmpty()) { URL redirectUrl = null; try { redirectUrl = new URL(redirUrlText); } catch (MalformedURLException ex) { throw new DownloadException("Invalid Redirect URL: " + url, ex); } conn = Utils.openHttpConnection(redirectUrl); response = conn.getResponseCode(); responseFamily = response / 100; } } if (responseFamily != 2) { throw new DownloadException("The server issued a " + response + " response code."); } InputStream in = getConnectionInputStream(conn); size = conn.getContentLength(); outFile = new File(outPath); outFile.delete(); rbc = Channels.newChannel(in); fos = new FileOutputStream(outFile); stateChanged(); Thread progress = new MonitorThread(Thread.currentThread(), rbc); progress.start(); fos.getChannel().transferFrom(rbc, 0, size > 0 ? size : Integer.MAX_VALUE); in.close(); rbc.close(); progress.interrupt(); synchronized (timeoutLock) { if (isTimedOut) { return; } } if (size > 0) { if (size == outFile.length()) { result = Result.SUCCESS; } } else { result = Result.SUCCESS; } } catch (ClosedByInterruptException ex) { result = Result.FAILURE; return; } catch (PermissionDeniedException e) { exception = e; result = Result.PERMISSION_DENIED; } catch (DownloadException e) { exception = e; result = Result.FAILURE; } catch (Exception e) { exception = e; e.printStackTrace(); } finally { IOUtils.closeQuietly(fos); IOUtils.closeQuietly(rbc); } }
From source file:org.onebusaway.webapp.actions.admin.bundles.SyncBundleAction.java
public String syncBundle() { String syncStatus = "Syncing in progress"; String apiHost = "http://admin.staging.obast.org:9999/api/bundle/latest"; JsonObject latestBundle = null;// w w w . ja v a 2 s.c o m try { latestBundle = getJsonData(apiHost).getAsJsonObject(); } catch (Exception e) { _log.error("Failed to retrieve name of the latest deployed bundle"); } String datasetName = latestBundle.get("dataset").getAsString(); String buildName = latestBundle.get("name").getAsString(); String bundleId = latestBundle.get("id").getAsString(); String bundleFileName = buildName + ".tar.gz"; String tmpDir = new NYCFileUtils().createTmpDirectory(); String bundleDir = "/var/lib/oba/bundles"; String deployDir = "/var/lib/oba/bundles/active"; String bundleBuildDir = "/var/lib/oba/bundles/builder"; try { String bundleSourceString = "http://admin.staging.obast.org:9999/api/bundle/archive/get-by-name/" + datasetName + "/" + buildName + "/" + bundleFileName; URL bundleSource = new URL(bundleSourceString); ReadableByteChannel rbc = Channels.newChannel(bundleSource.openStream()); FileOutputStream fos = new FileOutputStream(tmpDir + File.separator + bundleFileName); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { unzipBundle(tmpDir, bundleFileName); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Copy to extracted files /var/lib/oba/bundles/active try { //FileUtils.copyDirectory(new File(tmpDir + File.separator + "untarredBundle" + File.separator + buildName), new File(deployDir)); FileUtils.copyDirectory(new File(tmpDir + File.separator + "untarredBundle"), new File(deployDir)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Copy downloaded .tar.gz bundle to bundle builds dir String buildDest = bundleBuildDir + File.separator + datasetName + File.separator + "builds" + File.separator + buildName + File.separator + bundleFileName; try { FileUtils.copyFile(new File(tmpDir + File.separator + bundleFileName), new File(buildDest)); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Copy inputs and outputs dirs File srcInputDir = new File(tmpDir + File.separator + "untarredBundle" + File.separator + buildName + File.separator + "inputs"); File srcOutputDir = new File(tmpDir + File.separator + "untarredBundle" + File.separator + buildName + File.separator + "outputs"); String destBuildsDir = bundleBuildDir + File.separator + datasetName + File.separator + "builds" + File.separator + buildName; try { FileUtils.copyDirectory(srcInputDir, new File(destBuildsDir + File.separator + "inputs")); FileUtils.copyDirectory(srcOutputDir, new File(destBuildsDir + File.separator + "outputs")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } // Copy gtfs and aux files to aux_latest and gtfs_latest String gtfsFileDest = bundleBuildDir + File.separator + datasetName + File.separator + "gtfs_latest"; String auxFileDest = bundleBuildDir + File.separator + datasetName + File.separator + "aux_latest"; File[] inputFiles = srcInputDir.listFiles(); for (File inputFile : inputFiles) { try { String fileName = inputFile.getName(); int idx = fileName.indexOf("_"); if (idx > 0) { // Skip over config dir String agencyNum = fileName.substring(0, idx); String zipFileName = fileName.substring(idx + 1); if (agencyNum.equals("29")) { // For CT aux files String fileDest = auxFileDest + File.separator + agencyNum + File.separator + zipFileName; FileUtils.copyFile(inputFile, new File(fileDest)); } else { String fileDest = gtfsFileDest + File.separator + agencyNum + File.separator + zipFileName; FileUtils.copyFile(inputFile, new File(fileDest)); } } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } syncStatus = "Complete"; return "syncStatus"; }
From source file:com.github.neoio.net.message.staging.memory.MemoryMessageStaging.java
@Override public int writeTempReadBytes(ByteBuffer buffer) throws NetIOException { return NIOUtils.writeToChannel(Channels.newChannel(readTempStageCount), buffer); }
From source file:com.nike.cerberus.operation.gateway.PublishLambdaOperation.java
private File downloadArtifact(final URL artifactUrl) { final File tempDir = Files.createTempDir(); final String filePath = tempDir.getPath() + File.pathSeparator + "lambda.artifact"; logger.debug("Downloading artifact to {}", tempDir.getAbsolutePath()); try {/*from ww w . j a va2s . c om*/ ReadableByteChannel rbc = Channels.newChannel(artifactUrl.openStream()); FileOutputStream fos = new FileOutputStream(filePath); fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE); } catch (IOException e) { logger.error("Failed to download the lambda artifact!", e); throw new IllegalStateException("Failed to download the lambda artifact.", e); } return new File(filePath); }