@Deprecated @Override public DefaultManifest writeTo(Writer writer) { SingleMessageLogger.nagUserOfDeprecated("Manifest.writeTo(Writer)", "Please use Manifest.writeTo(Object) instead"); try { Manifest javaManifest = generateJavaManifest(getEffectiveManifest()); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); javaManifest.write(buffer); String manifestContent = buffer.toString(DEFAULT_CONTENT_CHARSET); if (!DEFAULT_CONTENT_CHARSET.equals(contentCharset)) { // Convert the UTF-8 manifest bytes to the requested content charset manifestContent = new String(manifestContent.getBytes(contentCharset), contentCharset); } writer.write(manifestContent); writer.flush(); } catch (IOException e) { throw new UncheckedIOException(e); } return this; }
static void writeTo(org.gradle.api.java.archives.Manifest manifest, OutputStream outputStream, String contentCharset) { try { Manifest javaManifest = generateJavaManifest(manifest.getEffectiveManifest()); ByteArrayOutputStream buffer = new ByteArrayOutputStream(); javaManifest.write(buffer); byte[] manifestBytes; if (DEFAULT_CONTENT_CHARSET.equals(contentCharset)) { manifestBytes = buffer.toByteArray(); } else { // Convert the UTF-8 manifest bytes to the requested content charset manifestBytes = buffer.toString(DEFAULT_CONTENT_CHARSET).getBytes(contentCharset); } outputStream.write(manifestBytes); } catch (IOException e) { throw new UncheckedIOException(e); } }
@Override public org.gradle.api.java.archives.Manifest writeTo(Object path) { File manifestFile = fileResolver.resolve(path); try { File parentFile = manifestFile.getParentFile(); if (parentFile != null) { FileUtils.forceMkdir(parentFile); } IoActions.withResource(new FileOutputStream(manifestFile), new Action<FileOutputStream>() { @Override public void execute(FileOutputStream fileOutputStream) { writeTo(fileOutputStream); } }); return this; } catch (IOException e) { throw new UncheckedIOException(e); } }
private void read(Object manifestPath) { File manifestFile = fileResolver.resolve(manifestPath); try { byte[] manifestBytes = FileUtils.readFileToByteArray(manifestFile); manifestBytes = prepareManifestBytesForInteroperability(manifestBytes); // Eventually convert manifest content to UTF-8 before handing it to java.util.jar.Manifest if (!DEFAULT_CONTENT_CHARSET.equals(contentCharset)) { manifestBytes = new String(manifestBytes, contentCharset).getBytes(DEFAULT_CONTENT_CHARSET); } // Effectively read the manifest Manifest javaManifest = new Manifest(new ByteArrayInputStream(manifestBytes)); addJavaManifestToAttributes(javaManifest); addJavaManifestToSections(javaManifest); } catch (IOException e) { throw new UncheckedIOException(e); } }
@TaskAction void exec() { getProject().exec(new Action<ExecSpec>() { @Override public void execute(ExecSpec execSpec) { try { if (dexMergerExecutable == null) { dexMergerExecutable = Utils.dexMergerExecutable(); } execSpec.setExecutable(dexMergerExecutable); execSpec.args(destination.getCanonicalPath()); execSpec.args(source.getFiles()); } catch (IOException e) { throw new UncheckedIOException(e); } } }); }
public static HashValue createHash(InputStream instr, String algorithm) { MessageDigest messageDigest; try { messageDigest = createMessageDigest(algorithm); byte[] buffer = new byte[4096]; try { while (true) { int nread = instr.read(buffer); if (nread < 0) { break; } messageDigest.update(buffer, 0, nread); } } finally { instr.close(); } } catch (IOException e) { throw new UncheckedIOException(e); } return new HashValue(messageDigest.digest()); }
public void execute(Action<? super BufferedWriter> action) { try { File parentFile = file.getParentFile(); if (parentFile != null) { if (!parentFile.mkdirs() && !parentFile.isDirectory()) { throw new IOException(String.format("Unable to create directory '%s'", parentFile)); } } BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), encoding)); try { action.execute(writer); } finally { writer.close(); } } catch (Exception e) { throw new UncheckedIOException(String.format("Could not write to file '%s'.", file), e); } }
/** * Returns an args transformer that replaces the provided args with a generated args file containing the args. Uses platform text encoding. */ public static Transformer<List<String>, List<String>> argsFileGenerator(final File argsFile, final Transformer<ArgWriter, PrintWriter> argWriterFactory) { return new Transformer<List<String>, List<String>>() { @Override public List<String> transform(List<String> args) { if (args.isEmpty()) { return args; } argsFile.getParentFile().mkdirs(); try { PrintWriter writer = new PrintWriter(argsFile); try { ArgWriter argWriter = argWriterFactory.transform(writer); argWriter.args(args); } finally { writer.close(); } } catch (IOException e) { throw new UncheckedIOException(String.format("Could not write options file '%s'.", argsFile.getAbsolutePath()), e); } return Collections.singletonList("@" + argsFile.getAbsolutePath()); } }; }
public Properties create() { URL resource = classLoader.getResource(resourceName); if (resource == null) { throw new RuntimeException( "Unable to find the released versions information.\n" + "The resource '" + resourceName + "' was not found.\n" + "Most likely, you haven't run the 'prepareVersionsInfo' task.\n" + "If you have trouble running tests from your IDE, please run gradlew idea|eclipse first." ); } try { Properties properties = new Properties(); InputStream stream = resource.openStream(); try { properties.load(stream); } finally { stream.close(); } return properties; } catch (IOException e) { throw new UncheckedIOException(e); } }
@Override public boolean readFrom(Object path) { if (fileResolver == null) { return false; } File descriptorFile = fileResolver.resolve(path); if (descriptorFile == null || !descriptorFile.exists()) { return false; } try { FileReader reader = new FileReader(descriptorFile); readFrom(reader); return true; } catch (IOException e) { throw new UncheckedIOException(e); } }
public void printDaemonStarted(PrintStream target, Long pid, String uid, Address address, File daemonLog) { target.print(daemonGreeting()); // Encode as ascii try { OutputStream outputStream = new EncodedStream.EncodedOutput(target); FlushableEncoder encoder = new OutputStreamBackedEncoder(outputStream); encoder.writeNullableString(pid == null ? null : pid.toString()); encoder.writeString(uid); MultiChoiceAddress multiChoiceAddress = (MultiChoiceAddress) address; new MultiChoiceAddressSerializer().write(encoder, multiChoiceAddress); encoder.writeString(daemonLog.getPath()); encoder.flush(); } catch (IOException e) { throw new UncheckedIOException(e); } target.println(); //ibm vm 1.6 + windows XP gotchas: //we need to print something else to the stream after we print the daemon greeting. //without it, the parent hangs without receiving the message above (flushing does not help). LOGGER.debug("Completed writing the daemon greeting. Closing streams..."); //btw. the ibm vm+winXP also has some issues detecting closed streams by the child but we handle this problem differently. }
public DaemonStartupInfo readDiagnostics(String message) { //Assuming the message has correct format. Not bullet proof, but seems to work ok for now. if (!message.startsWith(daemonGreeting())) { throw new IllegalArgumentException(String.format("Unexpected daemon startup message: %s", message)); } try { String encoded = message.substring(daemonGreeting().length()).trim(); InputStream inputStream = new EncodedStream.EncodedInput(new ByteArrayInputStream(encoded.getBytes())); Decoder decoder = new InputStreamBackedDecoder(inputStream); String pidString = decoder.readNullableString(); String uid = decoder.readString(); Long pid = pidString == null ? null : Long.valueOf(pidString); Address address = new MultiChoiceAddressSerializer().read(decoder); File daemonLog = new File(decoder.readString()); return new DaemonStartupInfo(uid, address, new DaemonDiagnostics(daemonLog, pid)); } catch (IOException e) { throw new UncheckedIOException(e); } }
private void maybeConfigureFrom(File propertiesFile, Map<String, String> result) { if (!propertiesFile.isFile()) { return; } Properties properties = new Properties(); try { FileInputStream inputStream = new FileInputStream(propertiesFile); try { properties.load(inputStream); } finally { inputStream.close(); } } catch (IOException e) { throw new UncheckedIOException(e); } for (Object key : properties.keySet()) { if (GradleProperties.ALL.contains(key.toString())) { result.put(key.toString(), properties.get(key).toString()); } } }
public static Scriptable parse(File source, String encoding, Action<Context> contextConfig) { Context context = Context.enter(); if (contextConfig != null) { contextConfig.execute(context); } Scriptable scope = context.initStandardObjects(); try { Reader reader = new InputStreamReader(new FileInputStream(source), encoding); try { context.evaluateReader(scope, reader, source.getName(), 0, null); } finally { reader.close(); } } catch (IOException e) { throw new UncheckedIOException(e); } finally { Context.exit(); } return scope; }
private JavaVersion parseJavaVersionCommandOutput(String javaExecutable, BufferedReader reader) { try { String versionStr = reader.readLine(); while (versionStr != null) { Matcher matcher = Pattern.compile("(?:java|openjdk) version \"(.+?)\"").matcher(versionStr); if (matcher.matches()) { return JavaVersion.toVersion(matcher.group(1)); } versionStr = reader.readLine(); } } catch (IOException e) { throw new UncheckedIOException(e); } throw new GradleException(String.format("Could not determine Java version using executable %s.", javaExecutable)); }
/** * Saves the settings of the file chooser; and by settings I mean the 'last visited directory'. * * @param saveCurrentDirectoryVsSelectedFilesParent this should be true if you're selecting only directories, false if you're selecting only files. I don't know what if you allow both. */ public static void saveSettings(SettingsNode settingsNode, JFileChooser fileChooser, String id, Class fileChooserClass, boolean saveCurrentDirectoryVsSelectedFilesParent) { SettingsNode childNode = settingsNode.addChildIfNotPresent(getPrefix(fileChooserClass, id)); String save; try { if (saveCurrentDirectoryVsSelectedFilesParent) { save = fileChooser.getCurrentDirectory().getCanonicalPath(); } else { save = fileChooser.getSelectedFile().getCanonicalPath(); } } catch (IOException e) { throw new UncheckedIOException(e); } if (save != null) { childNode.setValueOfChild(DIRECTORY_NAME, save); } }
/** * If you do have an init script that's a resource, this will extract it based on the name and write it to a temporary file and delete it on exit. * * @param resourceClass the class associated with the resource * @param resourceName the name (minus extension or '.') of the resource */ protected File extractInitScriptFile(Class resourceClass, String resourceName) { File file = null; try { file = temporaryFileProvider.createTemporaryFile(resourceName, INIT_SCRIPT_EXTENSION); } catch (UncheckedIOException e) { logger.error("Creating init script file temp file", e); return null; } file.deleteOnExit(); if (extractResourceAsFile(resourceClass, resourceName + INIT_SCRIPT_EXTENSION, file)) { return file; } logger.error("Internal error! Failed to extract init script for executing commands!"); return null; }
private void processDirectory(File file, final Trie.Builder builder) { new DirectoryFileTree(file).visit(new FileVisitor() { @Override public void visitDir(FileVisitDetails dirDetails) { } @Override public void visitFile(FileVisitDetails fileDetails) { try { ZipEntry zipEntry = new ZipEntry(fileDetails.getPath()); InputStream inputStream = fileDetails.open(); try { processEntry(zipEntry, builder); } finally { inputStream.close(); } } catch (IOException e) { throw new UncheckedIOException(e); } } }); }
@Override public void write(IvyModulePublishMetadata module, File output) { try { output.getParentFile().mkdirs(); OutputStream outputStream = new FileOutputStream(output); try { SimpleXmlWriter xmlWriter = new SimpleXmlWriter(outputStream, " "); writeTo(module, xmlWriter); xmlWriter.flush(); } finally { outputStream.close(); } } catch (IOException e) { throw new UncheckedIOException(e); } }
public void publish(List<ModuleVersionPublisher> publishResolvers, IvyModulePublishMetadata publishMetaData) { try { // Make a copy of the publication and filter missing artifacts DefaultIvyModulePublishMetadata publication = new DefaultIvyModulePublishMetadata(publishMetaData.getId(), publishMetaData.getModuleDescriptor()); for (IvyModuleArtifactPublishMetadata artifact: publishMetaData.getArtifacts()) { addPublishedArtifact(artifact, publication); } for (ModuleVersionPublisher publisher : publishResolvers) { LOGGER.info("Publishing to {}", publisher); publisher.publish(publication); } } catch (IOException e) { throw new UncheckedIOException(e); } }
private File findExecutable(OperatingSystem operatingSystem, String name) { List<File> path = pathEntries.isEmpty() ? operatingSystem.getPath() : pathEntries; String exeName = operatingSystem.getExecutableName(name); try { if (name.contains(File.separator)) { return maybeResolveFile(operatingSystem, new File(name), new File(exeName)); } for (File pathEntry : path) { File resolved = maybeResolveFile(operatingSystem, new File(pathEntry, name), new File(pathEntry, exeName)); if (resolved != null) { return resolved; } } } catch (IOException e) { throw new UncheckedIOException(e); } return null; }
public void generateReport(Set<Project> projects) { try { ReportRenderer renderer = getRenderer(); renderer.setClientMetaData(getClientMetaData()); File outputFile = getOutputFile(); if (outputFile != null) { renderer.setOutputFile(outputFile); } else { renderer.setOutput(getTextOutputFactory().create(getClass())); } for (Project project : projects) { renderer.startProject(project); projectReportGenerator.generateReport(project); renderer.completeProject(project); } renderer.complete(); } catch (IOException e) { throw new UncheckedIOException(e); } }
public void write(Collection<TestClassResult> results) { try { OutputStream outputStream = new FileOutputStream(resultsFile); try { if (!results.isEmpty()) { // only write if we have results, otherwise truncate FlushableEncoder encoder = new KryoBackedEncoder(outputStream); encoder.writeSmallInt(RESULT_VERSION); write(results, encoder); encoder.flush(); } } finally { outputStream.close(); } } catch (IOException e) { throw new UncheckedIOException(e); } }
public void publish(IvyNormalizedPublication publication, PublicationAwareRepository repository) { ModuleVersionPublisher publisher = repository.createPublisher(); IvyPublicationIdentity projectIdentity = publication.getProjectIdentity(); ModuleComponentIdentifier moduleVersionIdentifier = DefaultModuleComponentIdentifier.newId(projectIdentity.getOrganisation(), projectIdentity.getModule(), projectIdentity.getRevision()); // This indicates the IvyPublishMetaData should probably not be responsible for creating a ModuleDescriptor... BuildableIvyModulePublishMetadata publishMetaData = new DefaultIvyModulePublishMetadata(moduleVersionIdentifier, ""); try { for (IvyArtifact publishArtifact : publication.getArtifacts()) { publishMetaData.addArtifact(createIvyArtifact(publishArtifact), publishArtifact.getFile()); } IvyArtifactName artifact = new DefaultIvyArtifactName("ivy", "ivy", "xml"); publishMetaData.addArtifact(artifact, publication.getDescriptorFile()); publisher.publish(publishMetaData); } catch (IOException e) { throw new UncheckedIOException(e); } }
private List<Include> parseFile(File file) { List<Include> includes = Lists.newArrayList(); try { BufferedReader bf = new BufferedReader(new PreprocessingReader(new BufferedReader(new FileReader(file)))); try { String line; while ((line = bf.readLine()) != null) { Matcher m = includePattern.matcher(line.trim()); if (m.matches()) { boolean isImport = "import".equals(m.group(1)); String value = m.group(2); includes.add(DefaultInclude.parse(value, isImport)); } } } finally { IOUtils.closeQuietly(bf); } } catch (IOException e) { throw new UncheckedIOException(e); } return includes; }
/** * Renders a multi-page HTML report from the given model, into the given directory. */ public <T> void render(T model, ReportRenderer<T, HtmlReportBuilder> renderer, File outputDirectory) { try { outputDirectory.mkdirs(); DefaultHtmlReportContext context = new DefaultHtmlReportContext(outputDirectory); renderer.render(model, context); for (Resource resource : context.resources.values()) { File destFile = new File(outputDirectory, resource.path); if (!destFile.exists()) { GFileUtils.copyURLToFile(resource.source, destFile); } } } catch (IOException e) { throw new UncheckedIOException(e); } }
@Override public void pack(final TaskOutputsInternal taskOutputs, OutputStream output, final TaskOutputOriginWriter writeOrigin) { IoActions.withResource(new TarOutputStream(output, "utf-8"), new Action<TarOutputStream>() { @Override public void execute(TarOutputStream outputStream) { outputStream.setLongFileMode(TarOutputStream.LONGFILE_POSIX); outputStream.setBigNumberMode(TarOutputStream.BIGNUMBER_POSIX); outputStream.setAddPaxHeadersForNonAsciiNames(true); try { packMetadata(writeOrigin, outputStream); pack(taskOutputs, outputStream); } catch (IOException e) { throw new UncheckedIOException(e); } } }); }
@Override public boolean load(final BuildCacheKey key, final BuildCacheEntryReader reader) throws BuildCacheException { return persistentCache.useCache("load build cache entry", new Factory<Boolean>() { @Override public Boolean create() { File file = getFile(key.getHashCode()); if (file.isFile()) { try { Closer closer = Closer.create(); FileInputStream stream = closer.register(new FileInputStream(file)); try { reader.readFrom(stream); return true; } finally { closer.close(); } } catch (IOException ex) { throw new UncheckedIOException(ex); } } return false; } }); }
public void expand(final Map<String, ?> properties) { transformers.add(new Transformer<Reader, Reader>() { public Reader transform(Reader original) { try { Template template; try { SimpleTemplateEngine engine = new SimpleTemplateEngine(); template = engine.createTemplate(original); } finally { original.close(); } StringWriter writer = new StringWriter(); template.make(properties).writeTo(writer); return new StringReader(writer.toString()); } catch (IOException e) { throw new UncheckedIOException(e); } } }); }
private Properties loadModuleProperties(String name, File jarFile) { try { ZipFile zipFile = new ZipFile(jarFile); try { final String entryName = name + "-classpath.properties"; ZipEntry entry = zipFile.getEntry(entryName); if (entry == null) { throw new IllegalStateException("Did not find " + entryName + " in " + jarFile.getAbsolutePath()); } return GUtil.loadProperties(zipFile.getInputStream(entry)); } finally { zipFile.close(); } } catch (IOException e) { throw new UncheckedIOException(e); } }
private static List<File> findAvailableClasspathFiles(ClassLoader classLoader) { List<URL> rawClasspath = ClasspathUtil.getClasspath(classLoader).getAsURLs(); List<File> classpathFiles = new ArrayList<File>(); for (URL url : rawClasspath) { if (url.getProtocol().equals("file")) { try { File classpathFile = new File(url.toURI()); addClasspathFile(classpathFile, classpathFiles); } catch (URISyntaxException e) { throw new UncheckedIOException(e); } } } // The file names passed to -cp are canonicalised by the JVM when it creates the system classloader, and so the file names are // lost if they happen to refer to links, for example, into the Gradle artifact cache. Try to reconstitute the file names // from the system classpath if (classLoader == ClassLoader.getSystemClassLoader()) { for (String value : System.getProperty("java.class.path").split(File.pathSeparator)) { addClasspathFile(new File(value), classpathFiles); } } return classpathFiles; }
public DefaultClassPath create() { File markerFile = new File(cache.getBaseDir(), "built.bin"); final boolean rebuild = !markerFile.exists(); BuildSrcBuildListenerFactory.Listener listener = listenerFactory.create(rebuild); gradleLauncher.addListener(listener); gradleLauncher.run(); Collection<File> classpath = listener.getRuntimeClasspath(); LOGGER.debug("Gradle source classpath is: {}", classpath); try { markerFile.createNewFile(); } catch (IOException e) { throw new UncheckedIOException(e); } return new DefaultClassPath(classpath); }
public void open(Runnable runnable, Factory factory) { this.factory = factory; try { cacheFile.getParentFile().mkdirs(); file = new RandomAccessFile(cacheFile, "rw"); output = new ByteOutput(file); input = new ByteInput(file); currentFileSize = file.length(); nextBlock = currentFileSize; if (currentFileSize == 0) { runnable.run(); } } catch (IOException e) { throw new UncheckedIOException(e); } }
@Override public void describeTo(Appendable appendable) { parent.describeTo(appendable); try { appendable.append(" > "); } catch (IOException e) { throw new UncheckedIOException(e); } child.describeTo(appendable); }
@Override public void describeTo(Appendable appendable) { try { appendable.append(getDescription()); } catch (IOException e) { throw new UncheckedIOException(e); } }
public DefaultMavenPom writeTo(final Writer pomWriter) { try { getEffectivePom().writeNonEffectivePom(pomWriter); } catch (IOException e) { throw new UncheckedIOException(e); } return this; }
public MavenPomFileGenerator writeTo(File file) { xmlTransformer.transform(file, POM_FILE_ENCODING, new Action<Writer>() { public void execute(Writer writer) { try { new MavenXpp3Writer().write(writer, model); } catch (IOException e) { throw new UncheckedIOException(e); } } }); return this; }
private Model parsePomFileIntoMavenModel(MavenNormalizedPublication publication) { File pomFile = publication.getPomFile(); try { Model model = readModelFromPom(pomFile); model.setPomFile(pomFile); return model; } catch (XmlPullParserException parseException) { throw new InvalidMavenPublicationException(publication.getName(), "POM file is invalid. Check any modifications you have made to the POM file.", parseException); } catch (IOException ex) { throw new UncheckedIOException(ex); } }
/** * Note: always throws the failure in some form. The return value is to keep the compiler happy. */ public static RuntimeException throwAsUncheckedException(Throwable t) { if (t instanceof RuntimeException) { throw (RuntimeException) t; } if (t instanceof Error) { throw (Error) t; } if (t instanceof IOException) { throw new UncheckedIOException(t); } throw new UncheckedException(t); }
public static void moveFile(File source, File destination) { try { FileUtils.moveFile(source, destination); } catch (IOException e) { throw new UncheckedIOException(e); } }