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

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

Introduction

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

Prototype

public <X extends Exception> RuntimeException rethrow(Throwable e, Class<X> declaredType)
        throws IOException, X 

Source Link

Document

Stores the given throwable and rethrows it.

Usage

From source file:com.android.builder.files.IncrementalRelativeFileSets.java

/**
 * Reads a zip file and adds all files in the file in a new incremental relative set. The
 * status of each file is set to {@code status}.
 *
 * @param zip the zip file to read, must be a valid, existing zip file
 * @param status the status to set the files to
 * @return the file set//from   w w  w . j  av  a2s  .c  om
 * @throws IOException failed to read the zip file
 */
@NonNull
public static ImmutableMap<RelativeFile, FileStatus> fromZip(@NonNull File zip, FileStatus status)
        throws IOException {
    Preconditions.checkArgument(zip.isFile(), "!zip.isFile()");

    Set<RelativeFile> files = Sets.newHashSet();

    Closer closer = Closer.create();
    try {
        ZFile zipReader = closer.register(new ZFile(zip));
        for (StoredEntry entry : zipReader.entries()) {
            if (entry.getType() == StoredEntryType.FILE) {
                File file = new File(zip,
                        FileUtils.toSystemDependentPath(entry.getCentralDirectoryHeader().getName()));
                files.add(new RelativeFile(zip, file));
            }
        }
    } catch (Throwable t) {
        throw closer.rethrow(t, IOException.class);
    } finally {
        closer.close();
    }

    Map<RelativeFile, FileStatus> map = Maps.asMap(files, Functions.constant(status));
    return ImmutableMap.copyOf(map);
}

From source file:com.android.builder.internal.packaging.zfile.ApkZFileCreator.java

@Override
public void writeFile(@NonNull File inputFile, @NonNull String apkPath) throws IOException {
    Preconditions.checkState(!mClosed, "mClosed == true");

    boolean mayCompress = !mNoCompressPredicate.test(apkPath);

    Closer closer = Closer.create();
    try {//from   ww  w .  j  a  v  a 2s  . c  om
        FileInputStream inputFileStream = closer.register(new FileInputStream(inputFile));
        mZip.add(apkPath, inputFileStream, mayCompress);
    } catch (IOException e) {
        throw closer.rethrow(e, IOException.class);
    } catch (Throwable t) {
        throw closer.rethrow(t);
    } finally {
        closer.close();
    }
}

From source file:com.adobe.epubcheck.opf.OPFPeeker.java

public OPFData peek() throws InvalidVersionException, IOException {
    Closer closer = Closer.create();
    try {//from   ww  w  .j  av  a 2 s .  co  m
        InputStream in = resourceProvider.getInputStream(path);
        if (in == null)
            throw new IOException("Couldn't find resource " + path);
        in = closer.register(resourceProvider.getInputStream(path));
        return peek(in);
    } catch (Throwable e) {
        throw closer.rethrow(e, InvalidVersionException.class);
    } finally {
        closer.close();
    }
}

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

/**
 * Creates a new instance./* w w  w  .ja v  a  2s .co  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:com.android.builder.internal.packaging.OldPackager.java

/**
 * Incrementally updates resources in the packaging. The resources can be added or removed,
 * depending on the changes made to the file. Updating an archive file as modified will update
 * the entries, but will not remove archive entries tht are no longer in the archive.
 *
 * @param file the archive file (zip)/*from ww  w  .ja  v  a  2 s. c  o  m*/
 * @param modificationType the type of file modification
 * @param isIgnored the filter to apply to the contents of the archive; the filter is applied
 * before processing: filtered out files are exactly the same as inexistent files; the filter
 * applies to the path stored in the zip
 * @throws PackagerException failed to update the package
 */
public void updateResourceArchive(@NonNull File file, @NonNull FileModificationType modificationType,
        @NonNull final Predicate<String> isIgnored) throws PackagerException {
    Preconditions.checkNotNull(mApkCreator, "mApkCreator == null");

    if (modificationType == FileModificationType.NEW || modificationType == FileModificationType.CHANGED) {
        try {
            Closer closer = Closer.create();
            try {
                /*
                 * Note that ZipAbortException has to be masked because it is not allowed in
                 * the Predicate interface.
                 */
                Predicate<String> newIsIgnored = input -> {
                    try {
                        if (!mNoJavaClassZipFilter.checkEntry(input)) {
                            return true;
                        }
                    } catch (ZipAbortException e) {
                        throw new RuntimeException(e);
                    }

                    return isIgnored.apply(input);
                };

                mApkCreator.writeZip(file, null, newIsIgnored::apply);
            } catch (Throwable t) {
                throw closer.rethrow(t, ZipAbortException.class);
            } finally {
                closer.close();
            }
        } catch (IOException e) {
            throw new PackagerException(e);
        }
    }
}

From source file:com.android.builder.files.IncrementalRelativeFileSets.java

/**
 * Computes the incremental file set that results from comparing a zip file with a possibly
 * existing cached file. If the cached file does not exist, then the whole zip is reported
 * as {@link FileStatus#NEW}./*from w w  w.j  av a  2 s  .  c o m*/
 *
 * @param zip the zip file to read, must be a valid, existing zip file
 * @return the file set
 * @throws IOException failed to read the zip file
 */
@NonNull
public static ImmutableMap<RelativeFile, FileStatus> fromZip(@NonNull File zip, @NonNull FileCacheByPath cache)
        throws IOException {
    Preconditions.checkArgument(zip.isFile(), "!zip.isFile()");

    File oldFile = cache.get(zip);
    if (oldFile == null) {
        return fromZip(zip, FileStatus.NEW);
    }

    Map<RelativeFile, FileStatus> result = Maps.newHashMap();

    Closer closer = Closer.create();
    try {
        ZFile newZipReader = closer.register(new ZFile(zip));
        ZFile oldZipReader = closer.register(new ZFile(oldFile));

        /*
         * Search for new and modified files.
         */
        for (StoredEntry entry : newZipReader.entries()) {
            String path = entry.getCentralDirectoryHeader().getName();
            if (entry.getType() == StoredEntryType.FILE) {
                File file = new File(zip, FileUtils.toSystemDependentPath(path));
                RelativeFile newRelative = new RelativeFile(zip, file);

                StoredEntry oldEntry = oldZipReader.get(path);
                if (oldEntry == null || oldEntry.getType() != StoredEntryType.FILE) {
                    result.put(newRelative, FileStatus.NEW);
                    continue;
                }

                if (oldEntry.getCentralDirectoryHeader().getCrc32() != entry.getCentralDirectoryHeader()
                        .getCrc32()
                        || oldEntry.getCentralDirectoryHeader().getUncompressedSize() != entry
                                .getCentralDirectoryHeader().getUncompressedSize()) {
                    result.put(newRelative, FileStatus.CHANGED);
                }

                /*
                 * If we get here, then the file exists in both unmodified.
                 */
            }
        }

        for (StoredEntry entry : oldZipReader.entries()) {
            String path = entry.getCentralDirectoryHeader().getName();
            File file = new File(zip, FileUtils.toSystemDependentPath(path));
            RelativeFile oldRelative = new RelativeFile(zip, file);

            StoredEntry newEntry = newZipReader.get(path);
            if (newEntry == null || newEntry.getType() != StoredEntryType.FILE) {
                /*
                 * File does not exist in new. It has been deleted.
                 */
                result.put(oldRelative, FileStatus.REMOVED);
            }

        }
    } catch (Throwable t) {
        throw closer.rethrow(t, IOException.class);
    } finally {
        closer.close();
    }

    return ImmutableMap.copyOf(result);
}

From source file:com.adobe.epubcheck.xml.XMLParser.java

public void process() {
    try {/*from w ww .ja  v  a  2  s.  co m*/
        Closer closer = Closer.create();
        try {
            InputStream in = closer.register(context.resourceProvider.getInputStream(path));
            // System.err.println("DEBUG XMLParser#process on" + resource);
            if (!in.markSupported()) {
                in = new BufferedInputStream(in);
            }

            String encoding = sniffEncoding(in);
            if (encoding != null && !encoding.equals("UTF-8") && !encoding.equals("UTF-16")) {
                report.message(MessageId.CSS_003, EPUBLocation.create(path, ""), encoding);
            }

            InputSource ins = new InputSource(in);
            ins.setSystemId(zipRoot + path);
            parser.parse(ins, this);

        } catch (Throwable e) {
            // ensure that any checked exception types other than IOException that
            // could be thrown are
            // provided here, e.g. throw closer.rethrow(e,
            // CheckedException.class);
            // throw closer.rethrow(e);
            throw closer.rethrow(e, SAXException.class);
        } finally {
            closer.close();
        }
    } catch (FileNotFoundException e) {
        String message = e.getMessage();
        message = new File(message).getName();
        int p = message.indexOf("(");
        if (p > 0) {
            message = message.substring(0, message.indexOf("("));
        }
        message = message.trim();
        report.message(MessageId.RSC_001, EPUBLocation.create(path), message);
    } catch (IOException e) {
        report.message(MessageId.PKG_008, EPUBLocation.create(path), path);
    } catch (IllegalArgumentException e) {
        report.message(MessageId.RSC_005, EPUBLocation.create(path), e.getMessage());
    } catch (SAXException e) {
        report.message(MessageId.RSC_005, EPUBLocation.create(path), e.getMessage());
    }
}

From source file:org.grouplens.lenskit.eval.traintest.TrainTestEvalJob.java

@SuppressWarnings("PMD.AvoidCatchingThrowable")
private void runEvaluation() throws IOException, RecommenderBuildException {
    Closer closer = Closer.create();
    try {//ww  w .  j ava  2 s  .c  o m
        TableWriter userTable = userOutputSupplier.get();
        if (userTable != null) {
            closer.register(userTable);
        }
        TableWriter predictTable = predictOutputSupplier.get();
        if (predictTable != null) {
            closer.register(predictTable);
        }

        List<Object> outputRow = Lists.newArrayList();

        ExecutionInfo execInfo = buildExecInfo();

        logger.info("Building {}", algorithm.getName());
        StopWatch buildTimer = new StopWatch();
        buildTimer.start();
        RecommenderInstance rec = algorithm.makeTestableRecommender(data, snapshot, execInfo);
        buildTimer.stop();
        logger.info("Built {} in {}", algorithm.getName(), buildTimer);

        logger.info("Measuring {}", algorithm.getName());
        for (ModelMetric metric : modelMetrics) {
            outputRow.addAll(metric.measureAlgorithm(algorithm, data, rec.getRecommender()));
        }

        logger.info("Testing {}", algorithm.getName());
        StopWatch testTimer = new StopWatch();
        testTimer.start();
        List<TestUserMetricAccumulator> evalAccums = new ArrayList<TestUserMetricAccumulator>(
                evaluators.size());

        List<Object> userRow = new ArrayList<Object>();

        UserEventDAO testUsers = data.getTestData().getUserEventDAO();
        for (TestUserMetric eval : evaluators) {
            TestUserMetricAccumulator accum = eval.makeAccumulator(algorithm, data);
            evalAccums.add(accum);
        }

        Cursor<UserHistory<Event>> userProfiles = closer.register(testUsers.streamEventsByUser());
        for (UserHistory<Event> p : userProfiles) {
            assert userRow.isEmpty();
            userRow.add(p.getUserId());

            long uid = p.getUserId();
            LongSet testItems = p.itemSet();

            Supplier<SparseVector> preds = new PredictionSupplier(rec, uid, testItems);
            Supplier<List<ScoredId>> recs = new RecommendationSupplier(rec, uid, testItems);
            Supplier<UserHistory<Event>> hist = new HistorySupplier(rec.getUserEventDAO(), uid);
            Supplier<UserHistory<Event>> testHist = Suppliers.ofInstance(p);

            TestUser test = new TestUser(uid, hist, testHist, preds, recs);

            for (TestUserMetricAccumulator accum : evalAccums) {
                Object[] ures = accum.evaluate(test);
                if (ures != null) {
                    userRow.addAll(Arrays.asList(ures));
                }
            }
            if (userTable != null) {
                try {
                    userTable.writeRow(userRow);
                } catch (IOException e) {
                    throw new RuntimeException("error writing user row", e);
                }
            }
            userRow.clear();

            if (predictTable != null) {
                writePredictions(predictTable, uid, RatingVectorUserHistorySummarizer.makeRatingVector(p),
                        test.getPredictions());
            }
        }
        testTimer.stop();
        logger.info("Tested {} in {}", algorithm.getName(), testTimer);

        writeOutput(buildTimer, testTimer, outputRow, evalAccums);
    } catch (Throwable th) {
        throw closer.rethrow(th, RecommenderBuildException.class);
    } finally {
        closer.close();
    }
}

From source file:org.grouplens.lenskit.eval.traintest.TrainTestJob.java

@SuppressWarnings("PMD.AvoidCatchingThrowable")
private void runEvaluation() throws IOException, RecommenderBuildException {
    EventBus bus = task.getProject().getEventBus();
    bus.post(JobEvents.started(this));
    Closer closer = Closer.create();
    try {//from  w w w  . ja  va2s.c o m
        outputs = task.getOutputs().getPrefixed(algorithmInfo, dataSet);
        TableWriter userResults = outputs.getUserWriter();
        List<Object> outputRow = Lists.newArrayList();

        logger.info("Building {} on {}", algorithmInfo, dataSet);
        StopWatch buildTimer = new StopWatch();
        buildTimer.start();
        buildRecommender();
        buildTimer.stop();
        logger.info("Built {} in {}", algorithmInfo.getName(), buildTimer);

        logger.info("Measuring {} on {}", algorithmInfo.getName(), dataSet.getName());

        StopWatch testTimer = new StopWatch();
        testTimer.start();
        List<Object> userRow = Lists.newArrayList();

        List<MetricWithAccumulator<?>> accumulators = Lists.newArrayList();

        for (Metric<?> eval : outputs.getMetrics()) {
            accumulators.add(makeMetricAccumulator(eval));
        }

        LongSet testUsers = dataSet.getTestData().getUserDAO().getUserIds();
        final NumberFormat pctFormat = NumberFormat.getPercentInstance();
        pctFormat.setMaximumFractionDigits(2);
        pctFormat.setMinimumFractionDigits(2);
        final int nusers = testUsers.size();
        logger.info("Testing {} on {} ({} users)", algorithmInfo, dataSet, nusers);
        int ndone = 0;
        for (LongIterator iter = testUsers.iterator(); iter.hasNext();) {
            if (Thread.interrupted()) {
                throw new InterruptedException("eval job interrupted");
            }
            long uid = iter.nextLong();
            userRow.add(uid);
            userRow.add(null); // placeholder for the per-user time
            assert userRow.size() == 2;

            Stopwatch userTimer = Stopwatch.createStarted();
            TestUser test = getUserResults(uid);

            userRow.add(test.getTrainHistory().size());
            userRow.add(test.getTestHistory().size());

            for (MetricWithAccumulator<?> accum : accumulators) {
                List<Object> ures = accum.measureUser(test);
                if (ures != null) {
                    userRow.addAll(ures);
                }
            }
            userTimer.stop();
            userRow.set(1, userTimer.elapsed(TimeUnit.MILLISECONDS) * 0.001);
            if (userResults != null) {
                try {
                    userResults.writeRow(userRow);
                } catch (IOException e) {
                    throw new RuntimeException("error writing user row", e);
                }
            }
            userRow.clear();

            ndone += 1;
            if (ndone % 100 == 0) {
                testTimer.split();
                double time = testTimer.getSplitTime();
                double tpu = time / ndone;
                double tleft = (nusers - ndone) * tpu;
                logger.info("tested {} of {} users ({}), ETA {}", ndone, nusers,
                        pctFormat.format(((double) ndone) / nusers),
                        DurationFormatUtils.formatDurationHMS((long) tleft));
            }
        }
        testTimer.stop();
        logger.info("Tested {} in {}", algorithmInfo.getName(), testTimer);

        writeMetricValues(buildTimer, testTimer, outputRow, accumulators);
        bus.post(JobEvents.finished(this));
    } catch (Throwable th) {
        bus.post(JobEvents.failed(this, th));
        throw closer.rethrow(th, RecommenderBuildException.class);
    } finally {
        try {
            cleanup();
        } finally {
            outputs = null;
            closer.close();
        }
    }
}