Example usage for com.google.common.io Closer create

List of usage examples for com.google.common.io Closer create

Introduction

In this page you can find the example usage for com.google.common.io Closer create.

Prototype

public static Closer create() 

Source Link

Document

Creates a new Closer .

Usage

From source file:gobblin.runtime.JobLauncherTestHelper.java

public void runTestWithCancellation(final Properties jobProps) throws Exception {
    String jobName = jobProps.getProperty(ConfigurationKeys.JOB_NAME_KEY);
    String jobId = JobLauncherUtils.newJobId(jobName).toString();
    jobProps.setProperty(ConfigurationKeys.JOB_ID_KEY, jobId);

    Closer closer = Closer.create();
    try {/*  w  w w .j a va  2  s  .  com*/
        final JobLauncher jobLauncher = closer
                .register(JobLauncherFactory.newJobLauncher(this.launcherProps, jobProps));

        final AtomicBoolean isCancelled = new AtomicBoolean(false);
        // This thread will cancel the job after some time
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(500);
                    jobLauncher.cancelJob(null);
                    isCancelled.set(true);
                } catch (Exception je) {
                    // Ignored
                }
            }
        });
        thread.start();

        jobLauncher.launchJob(null);
        Assert.assertTrue(isCancelled.get());
    } finally {
        closer.close();
    }

    List<JobState.DatasetState> datasetStateList = this.datasetStateStore.getAll(jobName, jobId + ".jst");
    Assert.assertTrue(datasetStateList.isEmpty());
}

From source file:org.grouplens.lenskit.eval.data.subsample.SubsampleTask.java

/**
 * Run the Subsample command./*from w  w w  .  j a  v  a 2 s  . co m*/
 *
 * @return DataSource The subsample DataSource file
 * @throws org.grouplens.lenskit.eval.TaskExecutionException
 *
 */
@SuppressWarnings("PMD.AvoidCatchingThrowable")
@Override
public DataSource perform() throws TaskExecutionException {
    UpToDateChecker check = new UpToDateChecker();
    check.addInput(source.lastModified());
    File subsampleFile = getOutput();
    check.addOutput(subsampleFile);
    if (check.isUpToDate()) {
        logger.info("subsample {} up to date", getName());
        return makeDataSource();
    }
    try {
        logger.info("sampling {} of {}", subsampleFraction, source.getName());
        Closer closer = Closer.create();
        RatingWriter subsampleWriter = closer.register(RatingWriters.csv(subsampleFile));
        try {
            mode.doSample(source, subsampleWriter, subsampleFraction, getProject().getRandom());
        } catch (Throwable th) {
            throw closer.rethrow(th);
        } finally {
            closer.close();
        }
    } catch (IOException e) {
        throw new TaskExecutionException("Error writing output file", e);
    }
    return makeDataSource();
}

From source file:se.sics.datamodel.util.DMKeyFactory.java

public static DMKeyComponents getKeyComponents(Key key) throws IOException {
    Closer closer = Closer.create();
    try {//from ww w. jav  a 2  s  .c  o m
        ByteArrayInputStream bais = closer.register(new ByteArrayInputStream(key.getArray()));
        DataInputStream r = closer.register(new DataInputStream(bais));

        ByteId dbId = deserializeByteId(r);
        byte keyType = r.readByte();
        ByteId typeId = deserializeByteId(r);

        if (keyType == DMKeyFactory.typeKF) {
            return new TypeKeyComp(dbId, typeId);
            //            } else if (keyType == DMKeyFactory.tmFieldKF) {
            //                readTMFieldKey(r, dbId, typeId);
        } else if (keyType == DMKeyFactory.dataKF) {
            return readDataKey(r, dbId, typeId);
        } else if (keyType == DMKeyFactory.indexKF) {
            return readIndexKey(r, dbId, typeId);
        } else {
            throw new IOException("getKeyComponents - unknown type of key");
        }
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:com.android.builder.internal.packaging.OldPackager.java

/**
 * Creates a new instance.//ww w.  j  a va  2 s .  c  o  m
 *
 * <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:org.ow2.proactive_grid_cloud_portal.dataspace.util.VFSZipper.java

private static void copyFileContents(FileObject fo, ZipOutputStream zos) throws IOException {
    Closer closer = Closer.create();
    try {//from   w  w  w  .j  a va  2  s  .  c o  m
        InputStream inputStream = fo.getContent().getInputStream();
        closer.register(inputStream);
        ByteStreams.copy(inputStream, zos);
    } catch (IOException ioe) {
        throw closer.rethrow(ioe);
    } finally {
        closer.close();
    }
}

From source file:org.ow2.proactive_grid_cloud_portal.dataspace.FileSystem.java

public static void copy(InputStream is, FileObject outFile) throws IOException {
    outFile.refresh();//from   www  . j  a v  a  2  s .co  m
    Closer closer = Closer.create();
    closer.register(is);
    try {
        OutputStream os = outFile.getContent().getOutputStream();
        closer.register(os);
        ByteStreams.copy(is, os);
    } catch (IOException ioe) {
        throw closer.rethrow(ioe);
    } finally {
        closer.close();
    }
}

From source file:io.prestosql.elasticsearch.ElasticsearchClient.java

@PreDestroy
public void tearDown() {
    // Closer closes the resources in reverse order.
    // Therefore, we first clear the clients map, then close each client.
    try (Closer closer = Closer.create()) {
        closer.register(clients::clear);
        for (Entry<String, TransportClient> entry : clients.entrySet()) {
            closer.register(entry.getValue());
        }/*from  ww  w.  j  av  a  2 s  .  com*/
        closer.register(executor::shutdown);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}

From source file:alluxio.client.block.stream.BlockInStream.java

/**
 * Creates an instance of {@link BlockInStream}.
 *
 * This method keeps polling the block worker until the block is cached to Alluxio or
 * it successfully acquires a UFS read token with a timeout.
 * (1) If the block is cached to Alluxio after polling, it returns {@link BlockInStream}
 *     to read the block from Alluxio storage.
 * (2) If a UFS read token is acquired after polling, it returns {@link BlockInStream}
 *     to read the block from an Alluxio worker that reads the block from UFS.
 * (3) If the polling times out, an {@link IOException} with cause
 *     {@link alluxio.exception.UfsBlockAccessTokenUnavailableException} is thrown.
 *
 * @param context the file system context
 * @param ufsPath the UFS path//w  w w.ja  v a  2  s . c  o  m
 * @param blockId the block ID
 * @param blockSize the block size
 * @param blockStart the position at which the block starts in the file
 * @param workerNetAddress the worker network address
 * @param options the options
 * @throws IOException if it fails to create an instance
 * @return the {@link BlockInStream} created
 */
// TODO(peis): Use options idiom (ALLUXIO-2579).
public static BlockInStream createUfsBlockInStream(FileSystemContext context, String ufsPath, long blockId,
        long blockSize, long blockStart, WorkerNetAddress workerNetAddress, InStreamOptions options)
        throws IOException {
    Closer closer = Closer.create();
    try {
        BlockWorkerClient blockWorkerClient = closer
                .register(context.createBlockWorkerClient(workerNetAddress));
        LockBlockOptions lockBlockOptions = LockBlockOptions.defaults().setUfsPath(ufsPath)
                .setOffset(blockStart).setBlockSize(blockSize)
                .setMaxUfsReadConcurrency(options.getMaxUfsReadConcurrency());

        LockBlockResult lockBlockResult = closer
                .register(blockWorkerClient.lockUfsBlock(blockId, lockBlockOptions)).getResult();
        PacketInStream inStream;
        if (lockBlockResult.getLockBlockStatus().blockInAlluxio()) {
            boolean local = blockWorkerClient.getDataServerAddress().getHostName()
                    .equals(NetworkAddressUtils.getClientHostName());
            if (local && Configuration.getBoolean(PropertyKey.USER_SHORT_CIRCUIT_ENABLED)) {
                inStream = closer.register(PacketInStream
                        .createLocalPacketInStream(lockBlockResult.getBlockPath(), blockId, blockSize));
            } else {
                inStream = closer.register(PacketInStream.createNettyPacketInStream(context,
                        blockWorkerClient.getDataServerAddress(), blockId, lockBlockResult.getLockId(),
                        blockWorkerClient.getSessionId(), blockSize, false,
                        Protocol.RequestType.ALLUXIO_BLOCK));
            }
            blockWorkerClient.accessBlock(blockId);
        } else {
            Preconditions.checkState(lockBlockResult.getLockBlockStatus().ufsTokenAcquired());
            inStream = closer.register(
                    PacketInStream.createNettyPacketInStream(context, blockWorkerClient.getDataServerAddress(),
                            blockId, lockBlockResult.getLockId(), blockWorkerClient.getSessionId(), blockSize,
                            !options.getAlluxioStorageType().isStore(), Protocol.RequestType.UFS_BLOCK));
        }
        return new BlockInStream(inStream, blockWorkerClient, closer, options);
    } catch (AlluxioException | IOException e) {
        CommonUtils.closeQuietly(closer);
        throw CommonUtils.castToIOException(e);
    }
}

From source file:com.facebook.buck.parser.ParallelPerBuildState.java

public ParallelPerBuildState(DaemonicParserState permState, ConstructorArgMarshaller marshaller,
        BuckEventBus eventBus, Cell rootCell, boolean enableProfiling) {
    this.permState = permState;
    this.marshaller = marshaller;
    this.eventBus = eventBus;
    this.enableProfiling = enableProfiling;
    this.cells = new ConcurrentHashMap<>();
    this.cellSymlinkAllowability = new ConcurrentHashMap<>();
    this.parsers = new ThreadLocal<Map<Cell, ProjectBuildFileParser>>() {
        @Override//  w  ww .ja  va 2s .com
        protected Map<Cell, ProjectBuildFileParser> initialValue() {
            return new HashMap<>();
        }
    };
    this.buildInputPathsUnderSymlink = Sets.newHashSet();
    this.symlinkExistenceCache = new ConcurrentHashMap<>();

    this.stdout = new PrintStream(ByteStreams.nullOutputStream());
    this.stderr = new PrintStream(ByteStreams.nullOutputStream());
    this.console = new Console(Verbosity.STANDARD_INFORMATION, stdout, stderr, Ansi.withoutTty());

    this.symlinkCheckers = new TargetNodeListener() {
        @Override
        public void onCreate(Path buildFile, TargetNode<?> node) throws IOException {
            registerInputsUnderSymlinks(buildFile, node);
        }
    };

    this.closer = Closer.create();

    this.pendingWorkQueueCount = new AtomicInteger(0);
    this.pendingBuildTargets = new LinkedBlockingQueue<>();
    this.pendingBuildFiles = new LinkedBlockingQueue<>();
    this.completionNotifier = new CountDownLatch(1);

    register(rootCell);
}

From source file:com.comphenix.protocol.CommandProtocol.java

private void dump(CommandSender sender) {
    Closer closer = Closer.create();

    if (FILE_FORMAT == null)
        FILE_FORMAT = new SimpleDateFormat("yyyy-MM-dd_HH.mm.ss");
    if (TIMESTAMP_FORMAT == null)
        TIMESTAMP_FORMAT = new SimpleDateFormat("MM/dd/yy HH:mm:ss");

    try {/*  w  w w .  ja  v a 2 s. c o  m*/
        Date date = new Date();
        File file = new File(plugin.getDataFolder(), "dump-" + FILE_FORMAT.format(date) + ".txt");
        if (file.exists()) {
            file.delete();
        }

        file.createNewFile();

        FileWriter fw = closer.register(new FileWriter(file));
        PrintWriter pw = closer.register(new PrintWriter(fw));

        pw.println("ProtocolLib Dump");
        pw.println("Timestamp: " + TIMESTAMP_FORMAT.format(date));
        pw.println();

        pw.println("ProtocolLib Version: " + plugin.toString());
        pw.println("Bukkit Version: " + plugin.getServer().getBukkitVersion());
        pw.println("Server Version: " + plugin.getServer().getVersion());
        pw.println("Java Version: " + System.getProperty("java.version"));
        pw.println();

        ProtocolManager manager = ProtocolLibrary.getProtocolManager();
        pw.println("ProtocolLib: " + DetailedErrorReporter.getStringDescription(plugin));
        pw.println("Manager: " + DetailedErrorReporter.getStringDescription(manager));
        pw.println();

        Set<PacketListener> listeners = manager.getPacketListeners();
        if (listeners.size() > 0) {
            pw.println("Listeners:");

            for (PacketListener listener : listeners) {
                pw.println(DetailedErrorReporter.getStringDescription(listener));
            }
        } else {
            pw.println("No listeners");
        }

        sender.sendMessage("Data dump written to " + file.getAbsolutePath());
    } catch (IOException ex) {
        ProtocolLibrary.getStaticLogger().log(Level.SEVERE, "Failed to create dump:", ex);
        sender.sendMessage(ChatColor.RED + "Failed to create dump! Check console!");
    } finally {
        try {
            closer.close();
        } catch (IOException ex1) {
        }
    }
}