/** Creates a jar with a Class-Path entry to workaround the windows classpath limitation. */ private static File toJarWithClasspath(Iterable<File> files) { return Errors.rethrow().get(() -> { File jarFile = File.createTempFile(LONG_CLASSPATH_JAR_PREFIX, ".jar"); try (ZipOutputStream zip = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(jarFile)))) { zip.putNextEntry(new ZipEntry("META-INF/MANIFEST.MF")); try (PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(zip, StandardCharsets.UTF_8)))) { pw.println("Manifest-Version: 1.0"); String classPath = CollectionUtils.join(" ", CollectionUtils.collect(files, File::toURI)); String classPathEntry = "Class-Path: " + classPath; pw.println(CollectionUtils.join("\n ", classPathEntry.split(MATCH_CHUNKS_OF_70_CHARACTERS))); } } return jarFile; }); }
.forEach(Errors.rethrow().wrap(file -> { ZipMisc.read(file, MANIFEST_PATH, input -> addManifest(supported, new Manifest(input), file)); })); files.stream().filter(file -> file.isDirectory()).forEach(Errors.rethrow().wrap(folder -> { File manifestFile = new File(folder, MANIFEST_PATH); if (manifestFile.exists()) {
private void copyVersionsOfPlugin(PluginCatalog catalog, String plugin) { if (!catalog.isSupportedPlatform(plugin)) { return; } Set<Version> versions = catalog.getVersionsFor(plugin); for (Version version : versions) { File source = catalog.getFile(plugin, version); File dest = new File(destination, source.getName()); Errors.rethrow().run(() -> { if (source.isFile()) { FileUtils.copyFile(source, dest); } else { FileUtils.copyDirectory(source, dest); } }); } } }
Errors.rethrow().run(() -> { byte[] manifest = getManifestContent(jarTask, extension).getBytes(StandardCharsets.UTF_8);
Errors.rethrow().run(() -> {
Food thrown = rethrowing.get(() -> cook("spaghetti")); // no default needed
foodOnPlate.forEach(Errors.rethrow().wrap(this::eat));
@Test public void testWiresCrossed() { DurianPlugins.resetForTesting(); Errors.resetForTesting(); DurianPlugins.register(Errors.Plugins.Log.class, new TestHandler("Log")); DurianPlugins.register(Errors.Plugins.Dialog.class, new TestHandler("Dialog")); try { Errors.suppress().run(ErrorsTest::throwException); try { Errors.rethrow().run(ErrorsTest::throwException); } catch (RuntimeException e) { // it should pass the RuntimeException unphased Assert.assertNull(e.getCause()); } try { Errors.log().run(ErrorsTest::throwException); } catch (RuntimeException e) { Assert.assertEquals("Log", e.getMessage()); } try { Errors.dialog().run(ErrorsTest::throwException); } catch (RuntimeException e) { Assert.assertEquals("Dialog", e.getMessage()); } } finally { DurianPlugins.resetForTesting(); Errors.resetForTesting(); } }
/** Adds a manifest to the catalog. */ private void addManifest(List<SwtPlatform> supported, Manifest parsed, File plugin) { // parse out the name (looking out for the ";singleton=true" names String name = parsed.getMainAttributes().getValue(BUNDLE_NAME); int splitIdx = name.indexOf(';'); if (splitIdx > 0) { name = name.substring(0, splitIdx); } // parse out the platform filter (if any) // if it doesn't match an OS that we support, throw it out String platformFilter = parsed.getMainAttributes().getValue(ECLIPSE_PLATFORM_FILTER); if (platformFilter != null) { Filter filter = new Filter(platformFilter.replace(" ", "")); boolean isSupportedOS = supported.stream().anyMatch(Errors.rethrow().wrapPredicate(platform -> filter.matchMap(platform.platformProperties()))); if (!isSupportedOS) { unsupportedPlatform.add(name); return; } } // parse out the version String versionRaw = parsed.getMainAttributes().getValue(BUNDLE_VERSION); Version version = Version.parseVersion(versionRaw); availableVersions.put(name, version); toFile.put(name, version, plugin); }
/** Returns a map from every bundle-id to its corresponding 3-part version (the qualifier is dropped). */ public static Map<String, String> bundleToVersion(EclipseRelease release) { // warn if the user is asking for a too-old version of eclipse, but go ahead and try anyway just in case if (release.version().compareTo(FIRST_ON_CENTRAL.version()) < 0) { System.err.println(FIRST_ON_CENTRAL.version() + " was the first eclipse release that was published on MavenCentral."); } File versionFolder = new File(GoomphCacheLocations.eclipseReleaseMetadata(), release.version().toString()); FileMisc.mkdirs(versionFolder); File artifactsJar = new File(versionFolder, ARTIFACTS_JAR); if (artifactsJar.exists() && artifactsJar.length() > 0) { try { return parseFromFile(artifactsJar); } catch (Exception e) { e.printStackTrace(); System.err.println("Retrying download..."); FileMisc.forceDelete(artifactsJar); } } return Errors.rethrow().get(() -> { byte[] content = Resources.toByteArray(new URL(release.updateSite() + "artifacts.jar")); Files.write(content, artifactsJar); return parseFromFile(artifactsJar); }); }
private void testCharset(Charset charset) { // get the bytes for this string byte[] bytes = TEST_UTF.getBytes(charset); // write the complicated UTF string one byte at a time to an OutputStream String byteByByteOutputStream = StringPrinter.buildString(printer -> { Errors.rethrow().run(() -> { OutputStream output = printer.toOutputStream(charset); for (byte b : bytes) { output.write(b); } }); }); Assert.assertEquals(TEST_UTF, byteByByteOutputStream); // write the complicated UTF string one byte at a time to a PrintStream String byteByBytePrintStream = StringPrinter.buildString(printer -> { Errors.rethrow().run(() -> { OutputStream output = printer.toPrintStream(charset); for (byte b : bytes) { output.write(b); } }); }); Assert.assertEquals(TEST_UTF, byteByBytePrintStream); }
protected String getContents(Predicate<String> subpathsToInclude) throws IOException { TreeDef<File> treeDef = TreeDef.forFile(Errors.rethrow()); List<File> files = TreeStream.depthFirst(treeDef, folder.getRoot()) .filter(file -> file.isFile()) .collect(Collectors.toList()); ListIterator<File> iterator = files.listIterator(files.size()); int rootLength = folder.getRoot().getAbsolutePath().length() + 1; return StringPrinter.buildString(printer -> { Errors.rethrow().run(() -> { while (iterator.hasPrevious()) { File file = iterator.previous(); String subPath = file.getAbsolutePath().substring(rootLength); if (subpathsToInclude.test(subPath)) { printer.println("### " + subPath + " ###"); printer.println(read(subPath)); } } }); }); }
void run() { Set<File> files = new HashSet<>(); File p2asmaven = project.file(destination); groups.forEach((group, action) -> { // populate the def AsMavenGroup def = new AsMavenGroup(group); action.execute(def); // run it AsMavenGroupImpl impl = Errors.rethrow().get(() -> def.run(project, p2asmaven)); // keep track of what is clean files.add(impl.dirP2()); files.add(impl.dirP2Runnable()); files.add(impl.dirMavenGroup()); files.add(impl.tokenFile()); }); // delete the other files deleteStragglers(p2asmaven, files, AsMavenGroupImpl.SUBDIR_P2, AsMavenGroupImpl.SUBDIR_P2_RUNNABLE, AsMavenGroupImpl.SUBDIR_MAVEN); }
@SuppressWarnings("unused") public void wrapping() { // If your functional interface has 0 or 1 outputs, and 0 or 1 inputs, then Errors can wrap it into its standard Java 8 form Throwing.Runnable marathon = () -> { throw new IAmOnFire(); }; java.lang.Runnable marathonSafe = Errors.log().wrap(marathon); Throwing.Consumer<Food> eat = this::eat; java.util.function.Consumer<Food> eatSafe = Errors.log().wrap(eat); Throwing.Supplier<Food> cookSpatula = () -> cook("spatula"); java.util.function.Supplier<Food> cookSpatulaOrGetCereal = Errors.log().wrapWithDefault(cookSpatula, CEREAL); java.util.function.Supplier<Food> cookSpatulaOrBurn = Errors.rethrow().wrap(cookSpatula); Throwing.Function<String, Food> cookAnything = this::cook; java.util.function.Function<String, Food> cookAnythingOrGetCereal = Errors.log().wrapWithDefault(this::cook, CEREAL); java.util.function.Function<String, Food> cookAnythingOrBurn = Errors.rethrow().wrap(this::cook); // If your function has more than 1 input, you can either // A) Make a wrapper function that calls Errors.get() to return a value (recommended) // B) Make a "wrapper wrapper" (see https://github.com/diffplug/durian/blob/master/test/com/diffplug/common/base/ErrorsMultipleInputs.png) // If your function has more than 1 output, see https://github.com/diffplug/durian/blob/master/test/com/diffplug/common/base/ErrorsMultipleOutputs.png }
/** * Reads the given entry from the zip. * * @param input a zip file * @param toRead a path within that zip file * @return the given path within the zip file decoded as a UTF8 string, with only unix newlines. */ public static String read(File input, String toRead) throws IOException { String raw = StringPrinter.buildString(Errors.rethrow().wrap(printer -> { read(input, toRead, inputStream -> { copy(inputStream, printer.toOutputStream(StandardCharsets.UTF_8)); }); })); return FileMisc.toUnixNewline(raw); }
@Override public void finalize() { // If we're taking the "default value" route, Errors has you covered Food logged = Errors.log().getWithDefault(() -> cook("spaghetti"), CEREAL); // log to twitter Food suppressed = Errors.suppress().getWithDefault(() -> cook("spaghetti"), CEREAL); // suppress to insecurity buffer // If we're taking the "rethrow RuntimeException" route, then specifying a // default value would be nonsensical, so we don't do it Food rethrow = Errors.rethrow().get(() -> cook("spaghetti")); // I'm stressed, don't judge me Errors.suppress().run(() -> { eat(logged); eat(suppressed); eat(rethrow); }); }
/** Returns true if the given directory exists, and waits up to 500ms for the directory to exist. */ public static boolean dirExists(File dir) { long start = System.currentTimeMillis(); while (System.currentTimeMillis() - start < MS_RETRY) { File refreshed = Errors.rethrow().get(dir::getCanonicalFile); if (refreshed.exists() && refreshed.isDirectory()) { return true; } else { Errors.rethrow().run(() -> Thread.sleep(1)); } } return false; }
/** Attempts to call {@code supplier} and rethrows any exceptions as unchecked exceptions. */ public <T> T get(Throwing.Supplier<T> supplier) { return wrap(supplier).get(); }
/** Initializes overrides based on project properties named "goomph_override_whatever" */ public static void initFromProject(Project project) { for (Field field : GoomphCacheLocations.class.getFields()) { Object value = project.getProperties().get("goomph_" + field.getName()); if (value != null) { Errors.rethrow().run(() -> field.set(null, value)); } } }