List of usage examples for com.google.common.io Closer register
public <C extends Closeable> C register(@Nullable C closeable)
From source file:com.android.builder.internal.packaging.OldPackager.java
/** * Creates a new instance./* w w w . j av a 2s .c om*/ * * <p>This creates a new builder that will create the specified output file. * * @param creationData APK creation data * @param resLocation location of the zip with the resources, if any * @param logger the logger * @throws PackagerException failed to create the initial APK * @throws IOException failed to create the APK */ public OldPackager(@NonNull ApkCreatorFactory.CreationData creationData, @Nullable String resLocation, @NonNull ILogger logger) throws PackagerException, IOException { checkOutputFile(creationData.getApkPath()); Closer closer = Closer.create(); try { checkOutputFile(creationData.getApkPath()); File resFile = null; if (resLocation != null) { resFile = new File(resLocation); checkInputFile(resFile); } mLogger = logger; ApkCreatorFactory factory = new SignedJarApkCreatorFactory(); mApkCreator = factory.make(creationData); mLogger.verbose("Packaging %s", creationData.getApkPath().getName()); // add the resources if (resFile != null) { addZipFile(resFile); } } catch (Throwable e) { closer.register(mApkCreator); mApkCreator = null; throw closer.rethrow(e, PackagerException.class); } finally { closer.close(); } }
From source file:io.macgyver.core.script.ScriptExecutor.java
public Object run(Resource f, Map<String, Object> vars, boolean failIfNotFound) { Closer closer = Closer.create(); Object rval = null;//from w ww .j a va2 s . c om try { logger.debug("script {}", f); if (!f.exists() && !failIfNotFound) { logger.info("init script not found: {}", f); return null; } ScriptEngine engine = null; if (!scriptEngineManagerCachingEnabled) { ScriptEngineManager factory = new ScriptEngineManager(); engine = factory.getEngineByExtension(getExtension(f)); } else { engine = getEngineByExtensionFromCache(getExtension(f)); } if (engine == null) { throw new ScriptExecutionException( "could not create ScriptEngine for extension: " + getExtension(f)); } Reader fr = new InputStreamReader(f.openInputStream()); closer.register(fr); if (vars != null) { bindings.putAll(vars); } collectBindings(bindings, Optional.fromNullable(engine.getFactory().getLanguageName())); rval = engine.eval(fr, bindings); fr.close(); } catch (ScriptExecutionException e) { throw e; } catch (ScriptException e) { throw new ScriptExecutionException(e); } catch (IOException e) { throw new ScriptExecutionException(e); } catch (RuntimeException e) { throw new ScriptExecutionException(e); } finally { try { closer.close(); } catch (IOException e) { logger.warn("problem closing reader", e); } } return rval; }
From source file:com.tinspx.util.io.ByteUtils.java
/** * Copies at most {@code limit} bytes from {@code from} into {@code to}, * returning the total number of bytes copied. {@code to} is not closed. * // www. j ava 2 s . c om * @param from the source to read bytes from * @param to the destination to copy bytes read from {@code from} into * @param limit the maximum number of bytes to copy * @return the total number of bytes copied from {@code from} to {@code to} * @throws IOException if an IOException occurs * @throws NullPointerException if either {@code from} or {@code to} is null * @throws IllegalArgumentException if {@code limit} is negative */ @ThreadLocalArray(8192) public static long copy(@NonNull ByteSource from, @NonNull @WillNotClose WritableByteChannel to, long limit) throws IOException { checkLimit(limit); final Closer closer = Closer.create(); try { if (from instanceof ChannelSource) { return copy(closer.register(((ChannelSource) from).openChannel()), to, limit); } else { return copy(closer.register(from.openStream()), to, limit); } } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } }
From source file:com.tinspx.util.io.ByteUtils.java
/** * Copies at most {@code limit} bytes from {@code from} into {@code to}, * returning the total number of bytes copied. {@code from} is not closed. * /*from ww w .j a v a 2s . c o m*/ * @param from the source to read bytes from * @param to the destination to copy bytes read from {@code from} into * @param limit the maximum number of bytes to copy * @return the total number of bytes copied from {@code from} to {@code to} * @throws IOException if an IOException occurs * @throws NullPointerException if either {@code from} or {@code to} is null * @throws IllegalArgumentException if {@code limit} is negative */ @ThreadLocalArray(8192) public static long copy(@NonNull @WillNotClose ReadableByteChannel from, @NonNull ByteSink to, long limit) throws IOException { checkLimit(limit); final Closer closer = Closer.create(); try { if (to instanceof ChannelSink) { return copy(from, closer.register(((ChannelSink) to).openChannel()), limit); } else { OutputStream out = closer.register(to.openStream()); long total = copy(from, out, limit); out.flush(); return total; } } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } }
From source file:org.jclouds.vsphere.compute.config.VSphereComputeServiceAdapter.java
@Override public NodeAndInitialCredentials<VirtualMachine> createNodeWithGroupEncodedIntoName(String tag, String name, Template template) {// w w w .j a v a 2 s. c om try { Closer closer = Closer.create(); VSphereServiceInstance instance = null; try { instance = this.serviceInstance.get(); VSphereHost sphereHost = vSphereHost.get(); closer.register(instance); closer.register(sphereHost); Folder rootFolder = instance.getInstance().getRootFolder(); ComputerNameValidator.INSTANCE.validate(name); VirtualMachine master = getVMwareTemplate(template.getImage().getId(), rootFolder); ResourcePool resourcePool = checkNotNull( tryFindResourcePool(rootFolder, sphereHost.getHost().getName()), "resourcePool"); VirtualMachineCloneSpec cloneSpec = new MasterToVirtualMachineCloneSpec(resourcePool, sphereHost.getDatastore(), VSphereApiMetadata.defaultProperties().getProperty(CLONING)) .apply(master); VSphereTemplateOptions vOptions = VSphereTemplateOptions.class.cast(template.getOptions()); Set<String> networks = vOptions.getNetworks(); VirtualMachineConfigSpec virtualMachineConfigSpec = new VirtualMachineConfigSpec(); virtualMachineConfigSpec.setMemoryMB((long) template.getHardware().getRam()); if (template.getHardware().getProcessors().size() > 0) virtualMachineConfigSpec .setNumCPUs((int) template.getHardware().getProcessors().get(0).getCores()); else virtualMachineConfigSpec.setNumCPUs(1); Set<NetworkConfig> networkConfigs = Sets.newHashSet(); for (String network : networks) { NetworkConfig config = networkConfigurationForNetworkAndOptions.apply(network, vOptions); networkConfigs.add(config); } List<VirtualDeviceConfigSpec> updates = Lists.newArrayList(); long currentDiskSize = 0; int numberOfHardDrives = 0; int diskKey = 0; for (VirtualDevice device : master.getConfig().getHardware().getDevice()) { if (device instanceof VirtualDisk) { VirtualDisk vd = (VirtualDisk) device; diskKey = vd.getKey(); currentDiskSize += vd.getCapacityInKB(); numberOfHardDrives++; } } for (VirtualDevice device : master.getConfig().getHardware().getDevice()) { if (device instanceof VirtualEthernetCard) { VirtualDeviceConfigSpec nicSpec = new VirtualDeviceConfigSpec(); nicSpec.setOperation(VirtualDeviceConfigSpecOperation.remove); nicSpec.setDevice(device); updates.add(nicSpec); } else if (device instanceof VirtualCdrom) { if (vOptions.isoFileName() != null) { VirtualCdrom vCdrom = (VirtualCdrom) device; VirtualDeviceConfigSpec cdSpec = new VirtualDeviceConfigSpec(); cdSpec.setOperation(VirtualDeviceConfigSpecOperation.edit); VirtualCdromIsoBackingInfo iso = new VirtualCdromIsoBackingInfo(); Datastore datastore = vSphereHost.get().getDatastore(); VirtualDeviceConnectInfo cInfo = new VirtualDeviceConnectInfo(); cInfo.setStartConnected(true); cInfo.setConnected(true); iso.setDatastore(datastore.getMOR()); iso.setFileName("[" + datastore.getName() + "] " + vOptions.isoFileName()); vCdrom.setConnectable(cInfo); vCdrom.setBacking(iso); cdSpec.setDevice(vCdrom); updates.add(cdSpec); } } else if (device instanceof VirtualFloppy) { if (vOptions.flpFileName() != null) { VirtualFloppy vFloppy = (VirtualFloppy) device; VirtualDeviceConfigSpec floppySpec = new VirtualDeviceConfigSpec(); floppySpec.setOperation(VirtualDeviceConfigSpecOperation.edit); VirtualFloppyImageBackingInfo image = new VirtualFloppyImageBackingInfo(); Datastore datastore = vSphereHost.get().getDatastore(); VirtualDeviceConnectInfo cInfo = new VirtualDeviceConnectInfo(); cInfo.setStartConnected(true); cInfo.setConnected(true); image.setDatastore(datastore.getMOR()); image.setFileName("[" + datastore.getName() + "] " + vOptions.flpFileName()); vFloppy.setConnectable(cInfo); vFloppy.setBacking(image); floppySpec.setDevice(vFloppy); updates.add(floppySpec); } } else if (device instanceof VirtualLsiLogicController) { //int unitNumber = master.getConfig().getHardware().getDevice().length; int unitNumber = numberOfHardDrives; List<? extends Volume> volumes = template.getHardware().getVolumes(); VirtualLsiLogicController lsiLogicController = (VirtualLsiLogicController) device; String dsName = vSphereHost.get().getDatastore().getName(); for (Volume volume : volumes) { long currentVolumeSize = 1024 * 1024 * volume.getSize().longValue(); VirtualDeviceConfigSpec diskSpec = new VirtualDeviceConfigSpec(); VirtualDisk disk = new VirtualDisk(); VirtualDiskFlatVer2BackingInfo diskFileBacking = new VirtualDiskFlatVer2BackingInfo(); int ckey = lsiLogicController.getKey(); unitNumber++; String fileName = "[" + dsName + "] " + name + "/" + name + unitNumber + ".vmdk"; diskFileBacking.setFileName(fileName); diskFileBacking.setDiskMode("persistent"); disk.setControllerKey(ckey); disk.setUnitNumber(unitNumber); disk.setBacking(diskFileBacking); long size = currentVolumeSize; disk.setCapacityInKB(size); disk.setKey(-1); diskSpec.setOperation(VirtualDeviceConfigSpecOperation.add); diskSpec.setFileOperation(VirtualDeviceConfigSpecFileOperation.create); diskSpec.setDevice(disk); updates.add(diskSpec); } } } updates.addAll(createNicSpec(networkConfigs)); virtualMachineConfigSpec .setDeviceChange(updates.toArray(new VirtualDeviceConfigSpec[updates.size()])); // VirtualMachineBootOptions bootOptions = new VirtualMachineBootOptions(); // List<VirtualMachineBootOptionsBootableDevice> bootOrder = Lists.newArrayList(); // // VirtualMachineBootOptionsBootableDiskDevice diskBootDevice = new VirtualMachineBootOptionsBootableDiskDevice(); // diskBootDevice.setDeviceKey(diskKey); // bootOrder.add(diskBootDevice); // bootOrder.add(new VirtualMachineBootOptionsBootableCdromDevice()); // bootOptions.setBootOrder(bootOrder.toArray(new VirtualMachineBootOptionsBootableDevice[0])); // // virtualMachineConfigSpec.setBootOptions(bootOptions); cloneSpec.setConfig(virtualMachineConfigSpec); vOptions.getPublicKey(); VirtualMachine cloned = null; try { cloned = cloneMaster(master, tag, name, cloneSpec); Set<String> tagsFromOption = vOptions.getTags(); if (tagsFromOption.size() > 0) { StringBuilder tags = new StringBuilder(); for (String vmTag : vOptions.getTags()) { tags.append(vmTag).append(","); } tags.deleteCharAt(tags.length() - 1); cloned.getServerConnection().getServiceInstance().getCustomFieldsManager().setField(cloned, customFields.get().get(VSphereConstants.JCLOUDS_TAGS).getKey(), tags.toString()); cloned.getServerConnection().getServiceInstance().getCustomFieldsManager().setField(cloned, customFields.get().get(VSphereConstants.JCLOUDS_GROUP).getKey(), tag); if (vOptions.postConfiguration()) postConfiguration(cloned, name, tag, networkConfigs); else { VSpherePredicate.WAIT_FOR_VMTOOLS(1000 * 60 * 60 * 2, TimeUnit.MILLISECONDS) .apply(cloned); } } } catch (Exception e) { logger.error("Can't clone vm " + master.getName(), e); propagate(e); } if (vOptions.waitOnPort() != null) { } NodeAndInitialCredentials<VirtualMachine> nodeAndInitialCredentials = new NodeAndInitialCredentials<VirtualMachine>( cloned, cloned.getName(), LoginCredentials.builder().user("root").password(vmInitPassword).build()); return nodeAndInitialCredentials; } catch (Throwable e) { // must catch Throwable throw closer.rethrow(e); } finally { closer.close(); } } catch (Throwable t) { Throwables.propagateIfPossible(t); } return null; }
From source file:com.tinspx.util.io.ByteUtils.java
/** * Provides an alternative to {@link ByteSource#read()}. *//*from w w w . j a va 2s. co m*/ @ThreadLocalArray(8192) public static byte[] toByteArray(ByteSource source) throws IOException { final Closer closer = Closer.create(); try { if (source instanceof ChannelSource && ((ChannelSource) source).hasKnownSize()) { return toByteArray(closer.register(source.openStream()), checkByteSourceSize(source)); } else { return toByteArray(closer.register(source.openStream())); } } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } }
From source file:tachyon.shell.TfsShell.java
private void copyPath(File src, TachyonFileSystem tachyonClient, TachyonURI dstPath) throws IOException { try {//www .j ava 2 s . com if (!src.isDirectory()) { // If the dstPath is a directory, then it should be updated to be the path of the file where // src will be copied to TachyonFile fd = tachyonClient.openIfExists(dstPath); if (fd != null) { FileInfo tFile = tachyonClient.getInfo(fd); if (tFile.isFolder) { dstPath = dstPath.join(src.getName()); } } Closer closer = Closer.create(); FileOutStream os = null; try { os = closer.register(tachyonClient.getOutStream(dstPath, OutStreamOptions.defaults())); FileInputStream in = closer.register(new FileInputStream(src)); FileChannel channel = closer.register(in.getChannel()); ByteBuffer buf = ByteBuffer.allocate(8 * Constants.MB); while (channel.read(buf) != -1) { buf.flip(); os.write(buf.array(), 0, buf.limit()); } } catch (IOException e) { // Close the out stream and delete the file, so we don't have an incomplete file lying // around if (os != null) { os.cancel(); fd = tachyonClient.openIfExists(dstPath); if (fd != null) { tachyonClient.delete(fd); } } throw e; } finally { closer.close(); } } else { tachyonClient.mkdir(dstPath); List<String> errorMessages = new ArrayList<String>(); String[] fileList = src.list(); for (String file : fileList) { TachyonURI newPath = new TachyonURI(dstPath, new TachyonURI(file)); File srcFile = new File(src, file); try { copyPath(srcFile, tachyonClient, newPath); } catch (IOException e) { errorMessages.add(e.getMessage()); } } if (errorMessages.size() != 0) { if (errorMessages.size() == fileList.length) { // If no files were created, then delete the directory TachyonFile f = tachyonClient.openIfExists(dstPath); if (f != null) { tachyonClient.delete(f); } } throw new IOException(Joiner.on('\n').join(errorMessages)); } } } catch (TachyonException e) { throw new IOException(e.getMessage()); } }
From source file:io.macgyver.plugin.ci.jenkins.JenkinsApiProxy.java
protected void proxyResponse(Response southResponse, HttpServletRequest northRequest, HttpServletResponse northResponse) throws IOException { int statusCode = southResponse.code(); northResponse.setStatus(statusCode); Closer closer = Closer.create(); try {/*from w w w . ja v a 2 s . c o m*/ Headers h = southResponse.headers(); for (String name : h.names()) { if (name.toLowerCase().equals("content-encoding")) { // do nothing } else if (name.toLowerCase().equals("content-length")) { // do nothing } else { logger.info("Add header: {}:{}", name, h.get(name)); northResponse.addHeader(name, h.get(name)); } } ResponseBody body = southResponse.body(); logger.info("jenkins response: {}", northResponse.getStatus()); String contentType = southResponse.header("content-type"); if (contentType.contains("json")) { String val = rewriteResponseBody(body.string(), northRequest); logger.info("body: {}", val); JsonNode n = mapper.readTree(val); PrintWriter pw = northResponse.getWriter(); closer.register(pw); pw.print(n.toString()); } else if (contentType.contains("xml")) { PrintWriter pw = northResponse.getWriter(); closer.register(pw); String val = rewriteResponseBody(body.string(), northRequest); pw.print(val); } else { OutputStream os = northResponse.getOutputStream(); closer.register(os); InputStream is = body.byteStream(); closer.register(is); ByteStreams.copy(is, os); } } finally { closer.close(); } }
From source file:tachyon.shell.TfsShell.java
/** * Copies a file specified by argv from the filesystem to the local filesystem. This is the * utility function./*from w w w .j ava 2s. c o m*/ * * @param srcPath The source TachyonURI (has to be a file) * @param dstFile The destination file in the local filesystem * @throws IOException */ public void copyFileToLocal(TachyonURI srcPath, File dstFile) throws IOException { try { TachyonFile srcFd = mTfs.open(srcPath); File tmpDst = File.createTempFile("copyToLocal", null); tmpDst.deleteOnExit(); Closer closer = Closer.create(); try { InStreamOptions op = new InStreamOptions.Builder(mTachyonConf) .setTachyonStorageType(TachyonStorageType.NO_STORE).build(); FileInStream is = closer.register(mTfs.getInStream(srcFd, op)); FileOutputStream out = closer.register(new FileOutputStream(tmpDst)); byte[] buf = new byte[64 * Constants.MB]; int t = is.read(buf); while (t != -1) { out.write(buf, 0, t); t = is.read(buf); } if (!tmpDst.renameTo(dstFile)) { throw new IOException( "Failed to rename " + tmpDst.getPath() + " to destination " + dstFile.getPath()); } System.out.println("Copied " + srcPath + " to " + dstFile.getPath()); } finally { closer.close(); } } catch (TachyonException e) { throw new IOException(e.getMessage()); } }
From source file:org.pantsbuild.tools.jar.JarBuilder.java
/** * As an optimization, use {@link JarEntryCopier} to copy one jar file to * another without decompressing and recompressing. * * @param writer target to copy JAR file entries to. * @param entries entries that came from a jar file *//*from w ww. j a va 2 s . co m*/ private void copyJarFiles(JarWriter writer, Iterable<ReadableJarEntry> entries) throws IOException { // Walk the entries to bucketize by input jar file names Multimap<JarSource, ReadableJarEntry> jarEntries = HashMultimap.create(); for (ReadableJarEntry entry : entries) { Preconditions.checkState(entry.getSource() instanceof JarSource); jarEntries.put((JarSource) entry.getSource(), entry); } // Copy the data from each jar input file to the output for (JarSource source : jarEntries.keySet()) { Closer jarFileCloser = Closer.create(); try { final InputSupplier<JarFile> jarSupplier = jarFileCloser .register(new JarSupplier(new File(source.name()))); JarFile jarFile = jarSupplier.getInput(); for (ReadableJarEntry readableJarEntry : jarEntries.get(source)) { JarEntry jarEntry = readableJarEntry.getJarEntry(); String resource = jarEntry.getName(); writer.copy(resource, jarFile, jarEntry); } } catch (IOException ex) { throw jarFileCloser.rethrow(ex); } finally { jarFileCloser.close(); } } }