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

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

Introduction

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

Prototype


public <C extends Closeable> C register(@Nullable C closeable) 

Source Link

Document

Registers the given closeable to be closed when this Closer is #close closed .

Usage

From source file:org.jclouds.vsphere.functions.VirtualMachineToNodeMetadata.java

@Override
public NodeMetadata apply(VirtualMachine vm) {
    Closer closer = Closer.create();
    VSphereServiceInstance instance = serviceInstanceSupplier.get();
    closer.register(instance);
    VirtualMachine freshVm = null;//from   ww  w  . ja  v a2 s.c o  m
    String virtualMachineName = "";
    NodeMetadataBuilder nodeMetadataBuilder = new NodeMetadataBuilder();
    try {
        try {
            String vmMORId = vm.getMOR().get_value();
            ManagedEntity[] vms = new InventoryNavigator(instance.getInstance().getRootFolder())
                    .searchManagedEntities("VirtualMachine");
            for (ManagedEntity machine : vms) {

                if (machine.getMOR().getVal().equals(vmMORId)) {
                    freshVm = (VirtualMachine) machine;
                    break;
                }
            }
            LocationBuilder locationBuilder = new LocationBuilder();
            locationBuilder.description("");
            locationBuilder.id("");
            locationBuilder.scope(LocationScope.HOST);

            virtualMachineName = freshVm.getName();

            VirtualMachinePowerState vmState = freshVm.getRuntime().getPowerState();
            NodeMetadata.Status nodeState = toPortableNodeStatus.get(vmState);
            if (nodeState == null)
                nodeState = Status.UNRECOGNIZED;

            nodeMetadataBuilder.name(virtualMachineName).ids(virtualMachineName)
                    .location(locationBuilder.build()).hostname(virtualMachineName);

            String host = freshVm.getServerConnection().getUrl().getHost();

            try {
                nodeMetadataBuilder.uri(new URI(
                        "https://" + host + ":9443/vsphere-client/vmrc/vmrc.jsp?vm=urn:vmomi:VirtualMachine:"
                                + vmMORId + ":" + freshVm.getSummary().getConfig().getUuid()));
            } catch (URISyntaxException e) {
            }

            Set<String> ipv4Addresses = newHashSet();
            Set<String> ipv6Addresses = newHashSet();

            if (nodeState == Status.RUNNING && !freshVm.getConfig().isTemplate()) {
                Predicates2.retry(new Predicate<VirtualMachine>() {
                    @Override
                    public boolean apply(VirtualMachine vm) {
                        try {
                            return !Strings.isNullOrEmpty(vm.getGuest().getIpAddress());
                        } catch (Exception e) {
                            return false;
                        }
                    }
                }, 60 * 1000 * 10, 10 * 1000, TimeUnit.MILLISECONDS).apply(freshVm);
            }

            if (VSpherePredicate.IsToolsStatusEquals(VirtualMachineToolsStatus.toolsNotInstalled)
                    .apply(freshVm))
                logger.trace("<< No VMware tools installed ( " + virtualMachineName + " )");
            else if (nodeState == Status.RUNNING && not(VSpherePredicate.isTemplatePredicate).apply(freshVm)) {
                GuestNicInfo[] nics = freshVm.getGuest().getNet();
                if (null != nics) {
                    for (GuestNicInfo nic : nics) {
                        String[] addresses = nic.getIpAddress();

                        if (null != addresses) {
                            for (String address : addresses) {
                                if (logger.isTraceEnabled())
                                    logger.trace(
                                            "<< find IP addresses " + address + " for " + virtualMachineName);
                                if (isInet4Address.apply(address)) {
                                    ipv4Addresses.add(address);
                                } else if (isInet6Address.apply(address)) {
                                    ipv6Addresses.add(address);
                                }
                            }
                        }
                    }
                }
                nodeMetadataBuilder.publicAddresses(filter(ipv4Addresses, not(isPrivateAddress)));
                nodeMetadataBuilder.privateAddresses(filter(ipv4Addresses, isPrivateAddress));
            }

            CustomFieldValue[] customFieldValues = freshVm.getCustomValue();
            if (customFieldValues != null) {
                for (CustomFieldValue customFieldValue : customFieldValues) {
                    if (customFieldValue.getKey() == customFields.get().get(VSphereConstants.JCLOUDS_TAGS)
                            .getKey()) {
                        nodeMetadataBuilder.tags(
                                COMMA_SPLITTER.split(((CustomFieldStringValue) customFieldValue).getValue()));
                    } else if (customFieldValue.getKey() == customFields.get()
                            .get(VSphereConstants.JCLOUDS_GROUP).getKey()) {
                        nodeMetadataBuilder.group(((CustomFieldStringValue) customFieldValue).getValue());
                    }
                }
            }
            nodeMetadataBuilder.status(nodeState);
            return nodeMetadataBuilder.build();
        } catch (Throwable t) {
            logger.error("Got an exception for virtual machine name : " + virtualMachineName);
            Throwables.propagate(closer.rethrow(t));
        } finally {
            closer.close();
        }
    } catch (IOException e) {
        return nodeMetadataBuilder.build();
    }
    return nodeMetadataBuilder.build();
}

From source file:com.android.repository.io.impl.FileOpImpl.java

@Override
public void saveProperties(@NonNull File file, @NonNull Properties props, @NonNull String comments)
        throws IOException {
    Closer closer = Closer.create();
    try {/*  w  ww.  j av a  2s. c  o m*/
        OutputStream fos = closer.register(newFileOutputStream(file));
        props.store(fos, comments);
    } catch (Throwable e) {
        throw closer.rethrow(e);
    } finally {
        closer.close();
    }
}

From source file:gobblin.runtime.JobLauncherTestHelper.java

public void runTestWithPullLimit(Properties jobProps, long limit) 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 {/*from   w  w w  .j a v a 2 s .com*/
        JobLauncher jobLauncher = closer
                .register(JobLauncherFactory.newJobLauncher(this.launcherProps, jobProps));
        jobLauncher.launchJob(null);
    } finally {
        closer.close();
    }

    List<JobState.DatasetState> datasetStateList = this.datasetStateStore.getAll(jobName, jobId + ".jst");
    DatasetState datasetState = datasetStateList.get(0);

    Assert.assertEquals(datasetState.getState(), JobState.RunningState.COMMITTED);
    Assert.assertEquals(datasetState.getCompletedTasks(), 4);
    Assert.assertEquals(datasetState.getJobFailures(), 0);

    for (TaskState taskState : datasetState.getTaskStates()) {
        Assert.assertEquals(taskState.getWorkingState(), WorkUnitState.WorkingState.COMMITTED);
        Assert.assertEquals(taskState.getPropAsLong(ConfigurationKeys.EXTRACTOR_ROWS_EXTRACTED), limit);
        Assert.assertEquals(taskState.getPropAsLong(ConfigurationKeys.WRITER_ROWS_WRITTEN), limit);
    }
}

From source file:com.android.repository.io.impl.FileOpImpl.java

@Override
@NonNull//ww  w.ja  v  a 2 s.co m
public Properties loadProperties(@NonNull File file) {
    Properties props = new Properties();
    Closer closer = Closer.create();
    try {
        FileInputStream fis = closer.register(new FileInputStream(file));
        props.load(fis);
    } catch (IOException ignore) {
    } finally {
        try {
            closer.close();
        } catch (IOException e) {
        }
    }
    return props;
}

From source file:gobblin.runtime.JobLauncherTestHelper.java

public void runTestWithCommitSuccessfulTasksPolicy(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);
    jobProps.setProperty(ConfigurationKeys.PUBLISH_DATA_AT_JOB_LEVEL, Boolean.FALSE.toString());
    jobProps.setProperty(ConfigurationKeys.JOB_COMMIT_POLICY_KEY, "successful");
    jobProps.setProperty(ConfigurationKeys.SOURCE_CLASS_KEY, TestSourceWithFaultyExtractor.class.getName());
    jobProps.setProperty(ConfigurationKeys.MAX_TASK_RETRIES_KEY, "0");

    Closer closer = Closer.create();
    try {/*from   ww w . j  a  v  a  2 s .c o m*/
        JobLauncher jobLauncher = closer
                .register(JobLauncherFactory.newJobLauncher(this.launcherProps, jobProps));
        jobLauncher.launchJob(null);
    } finally {
        closer.close();
    }

    List<JobState.DatasetState> datasetStateList = this.datasetStateStore.getAll(jobName, jobId + ".jst");
    JobState jobState = datasetStateList.get(0);

    Assert.assertEquals(jobState.getState(), JobState.RunningState.COMMITTED);
    Assert.assertEquals(jobState.getCompletedTasks(), 4);
    for (TaskState taskState : jobState.getTaskStates()) {
        if (taskState.getTaskId().endsWith("0")) {
            Assert.assertEquals(taskState.getWorkingState(), WorkUnitState.WorkingState.FAILED);
        } else {
            Assert.assertEquals(taskState.getWorkingState(), WorkUnitState.WorkingState.COMMITTED);
            Assert.assertEquals(taskState.getPropAsLong(ConfigurationKeys.WRITER_RECORDS_WRITTEN),
                    TestExtractor.TOTAL_RECORDS);
        }
    }
}

From source file:gobblin.runtime.JobLauncherTestHelper.java

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

    JobContext jobContext = null;/*from w w w  .  j a  v a  2  s .c  om*/
    Closer closer = Closer.create();
    try {
        JobLauncher jobLauncher = closer
                .register(JobLauncherFactory.newJobLauncher(this.launcherProps, jobProps));
        jobLauncher.launchJob(null);
        jobContext = ((AbstractJobLauncher) jobLauncher).getJobContext();
    } finally {
        closer.close();
    }

    Assert.assertTrue(jobContext.getJobMetricsOptional().isPresent());
    String jobMetricContextTags = jobContext.getJobMetricsOptional().get().getMetricContext().getTags()
            .toString();
    Assert.assertTrue(jobMetricContextTags.contains(ClusterNameTags.CLUSTER_IDENTIFIER_TAG_NAME),
            ClusterNameTags.CLUSTER_IDENTIFIER_TAG_NAME + " tag missing in job metric context tags.");

    List<JobState.DatasetState> datasetStateList = this.datasetStateStore.getAll(jobName, jobId + ".jst");
    DatasetState datasetState = datasetStateList.get(0);

    Assert.assertEquals(datasetState.getState(), JobState.RunningState.COMMITTED);
    Assert.assertEquals(datasetState.getCompletedTasks(), 4);
    Assert.assertEquals(datasetState.getJobFailures(), 0);

    for (TaskState taskState : datasetState.getTaskStates()) {
        Assert.assertEquals(taskState.getWorkingState(), WorkUnitState.WorkingState.COMMITTED);
        Assert.assertEquals(taskState.getPropAsLong(ConfigurationKeys.WRITER_RECORDS_WRITTEN),
                TestExtractor.TOTAL_RECORDS);
    }
}

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 ww  .ja  v a  2  s . c  o  m
        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:biz.paluch.maven.configurator.AbstractConfigureMojo.java

private void loadPropertySource(Properties properties, Closer closer, String propertySource)
        throws IOException {
    try {//from  ww w  .j  av a  2 s .  co  m
        File file = new File(propertySource);
        InputStream is = null;
        if (file.exists()) {
            getLog().debug("Using File Property Source " + file);
            is = closer.register(new BufferedInputStream(new FileInputStream(file)));

        } else {
            URL url = new URL(propertySource);

            getLog().debug("Using URL Property Source " + url);
            URLConnection connection = url.openConnection();
            is = closer.register(connection.getInputStream());
        }

        properties.load(is);
    } catch (IOException e) {
        throw new IOException("Cannot load property from source " + propertySource, e);
    }
}

From source file:org.pantsbuild.tools.jar.Main.java

private Manifest loadManifest() throws IOException {
    Manifest mf = new Manifest();
    if (options.manifest != null) {
        Closer closer = Closer.create();
        try {//from w  ww  . j  av  a  2  s  .  c  o  m
            FileInputStream input = closer.register(new FileInputStream(options.manifest));
            mf.read(input);
        } catch (IOException e) {
            throw closer.rethrow(new IOException("Failed to load manifest from " + options.manifest, e));
        } finally {
            closer.close();
        }
    }
    return JarBuilder.ensureDefaultManifestEntries(mf);
}

From source file:gobblin.metastore.FsStateStore.java

/**
 * See {@link StateStore#put(String, String, T)}.
 *
 * <p>/*from  w  ww.  j  a v a  2  s .  c o  m*/
 *   This implementation does not support putting the state object into an existing store as
 *   append is to be supported by the Hadoop SequenceFile (HADOOP-7139).
 * </p>
 */
@Override
public void put(String storeName, String tableName, T state) throws IOException {
    String tmpTableName = this.useTmpFileForPut ? TMP_FILE_PREFIX + tableName : tableName;
    Path tmpTablePath = new Path(new Path(this.storeRootDir, storeName), tmpTableName);

    if (!this.fs.exists(tmpTablePath) && !create(storeName, tmpTableName)) {
        throw new IOException("Failed to create a state file for table " + tmpTableName);
    }

    Closer closer = Closer.create();
    try {
        @SuppressWarnings("deprecation")
        SequenceFile.Writer writer = closer.register(SequenceFile.createWriter(this.fs, this.conf, tmpTablePath,
                Text.class, this.stateClass, SequenceFile.CompressionType.BLOCK, new DefaultCodec()));
        writer.append(new Text(Strings.nullToEmpty(state.getId())), state);
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }

    if (this.useTmpFileForPut) {
        Path tablePath = new Path(new Path(this.storeRootDir, storeName), tableName);
        HadoopUtils.renamePath(this.fs, tmpTablePath, tablePath);
    }
}