List of usage examples for com.google.common.io Files write
public static void write(CharSequence from, File to, Charset charset) throws IOException
From source file:com.google.dart.runner.DartRunner.java
public static void throwingMain(String[] args, PrintStream stdout, PrintStream stderr) throws RunnerError { DartRunnerOptions options = processCommandLineOptions(args); List<LibrarySource> imports = Lists.newArrayList(); if (options.getSourceFiles().isEmpty()) { throw new RunnerError("No script files specified on the command line: " + Joiner.on(" ").join(args)); }/*from w w w .java 2s. c om*/ String script = options.getSourceFiles().get(0); ArrayList<String> scriptArguments = new ArrayList<String>(); LibrarySource app = new UrlLibrarySource(new File(script)); File outFile = options.getOutputFilename(); DefaultDartCompilerListener listener = new DefaultDartCompilerListener(stderr); CompilationResult compiled; compiled = compileApp(app, imports, options, listener); if (listener.getErrorCount() != 0) { throw new RunnerError("Compilation failed."); } if (outFile != null) { File dir = outFile.getParentFile(); if (dir != null) { if (!dir.exists()) { throw new RunnerError("Cannot create: " + outFile.getName() + ". " + dir + " does not exist"); } if (!dir.canWrite()) { throw new RunnerError( "Cannot write " + outFile.getName() + " to " + dir + ": Permission denied."); } } else { dir = new File("."); if (!dir.canWrite()) { throw new RunnerError( "Cannot write " + outFile.getName() + " to " + dir + ": Permission denied."); } } try { Files.write(compiled.js, outFile, Charset.defaultCharset()); } catch (IOException e) { throw new RunnerError(e); } } if (!options.shouldCompileOnly()) { runApp(compiled, app.getName(), options, scriptArguments.toArray(new String[0]), stdout, stderr); } }
From source file:org.apache.aurora.scheduler.http.api.security.Kerberos5ShiroRealmModule.java
@Override protected void configure() { if (!serverKeyTab.isPresent()) { addError("No -" + SERVER_KEYTAB_ARGNAME + " specified."); return;/*from w w w . java 2s. co m*/ } if (!serverPrincipal.isPresent()) { addError("No -" + SERVER_PRINCIPAL_ARGNAME + " specified."); return; } // TODO(ksweeney): Find a better way to configure JAAS in code. String jaasConf = String.format(JAAS_CONF_TEMPLATE, getClass().getName(), serverKeyTab.get().getAbsolutePath(), serverPrincipal.get().getName(), kerberosDebugEnabled); LOG.debug("Generated jaas.conf: " + jaasConf); File jaasConfFile; try { jaasConfFile = File.createTempFile("jaas", "conf"); jaasConfFile.deleteOnExit(); Files.write(jaasConf, jaasConfFile, StandardCharsets.UTF_8); } catch (IOException e) { addError(e); return; } GSSCredential serverCredential; try { LoginContext loginContext = new LoginContext(getClass().getName(), null /* subject (read from jaas config file passed below) */, null /* callbackHandler */, new ConfigFile(jaasConfFile.toURI())); loginContext.login(); serverCredential = Subject.doAs(loginContext.getSubject(), (PrivilegedAction<GSSCredential>) () -> { try { return gssManager.createCredential( null /* Use the service principal name defined in jaas.conf */, GSSCredential.INDEFINITE_LIFETIME, new Oid[] { new Oid(GSS_SPNEGO_MECH_OID), new Oid(GSS_KRB5_MECH_OID) }, GSSCredential.ACCEPT_ONLY); } catch (GSSException e) { throw new RuntimeException(e); } }); } catch (LoginException e) { addError(e); return; } install(new PrivateModule() { @Override protected void configure() { bind(GSSManager.class).toInstance(gssManager); bind(GSSCredential.class).toInstance(serverCredential); bind(Kerberos5Realm.class).in(Singleton.class); expose(Kerberos5Realm.class); } }); ShiroUtils.addRealmBinding(binder()).to(Kerberos5Realm.class); }
From source file:org.apache.flume.client.avro.SpoolingFileLineReader.java
/** * Create a SpoolingFileLineReader to watch the given directory. * * Lines are buffered between when they are read and when they are committed. * The buffer has a fixed size. Its size is determined by (maxLinestoBuffer * * bufferSizePerLine).// w ww . j a v a 2 s . c o m * * @param directory The directory to watch * @param completedSuffix The suffix to append to completed files * @param bufferMaxLines The maximum number of lines to keep in a pre-commit * buffer * @param bufferMaxLineLength The maximum line length for lines in the pre-commit * buffer, in characters */ public SpoolingFileLineReader(File directory, String completedSuffix, int bufferMaxLines, int bufferMaxLineLength) { // Verify directory exists and is readable/writable Preconditions.checkNotNull(directory); Preconditions.checkState(directory.exists(), "Directory does not exist: " + directory.getAbsolutePath()); Preconditions.checkState(directory.isDirectory(), "Path is not a directory: " + directory.getAbsolutePath()); Preconditions.checkState(bufferMaxLines > 0); Preconditions.checkState(bufferMaxLineLength > 0); // Do a canary test to make sure we have access to spooling directory try { File f1 = File.createTempFile("flume", "test", directory); Files.write("testing flume file permissions\n", f1, Charsets.UTF_8); Files.readLines(f1, Charsets.UTF_8); f1.delete(); } catch (IOException e) { throw new FlumeException("Unable to read and modify files" + " in the spooling directory: " + directory, e); } this.directory = directory; this.completedSuffix = completedSuffix; this.bufferMaxLines = bufferMaxLines; this.bufferMaxLineLength = bufferMaxLineLength; }
From source file:net.minecraftforge.gradle.patcher.TaskGenSubprojects.java
private void generateRootBuild(File output) throws IOException { int repoStart, repoEnd; int depStart, depEnd; int jLevelStart, jLevelEnd; {/* w ww . j a va 2s . c o m*/ int startIndex = resource.indexOf("@@"); int endIndex = resource.indexOf("@@", startIndex + 2); //System.out.println("start: "+startIndex + " end: "+endIndex); repoStart = startIndex; repoEnd = endIndex + 3; // account for the ending newline and @@ startIndex = resource.indexOf("@@", endIndex + 2); endIndex = resource.indexOf("@@", startIndex + 2); //System.out.println("start: "+startIndex + " end: "+endIndex); depStart = startIndex; depEnd = endIndex + 3; // account for the ending newline and @@ startIndex = resource.indexOf("@@", endIndex + 2); endIndex = resource.indexOf("@@", startIndex + 2); //System.out.println("start: "+startIndex + " end: "+endIndex); jLevelStart = startIndex; jLevelEnd = endIndex + 2; // keep the line ending this time, only account for @@ } StringBuilder builder = new StringBuilder(); builder.append(resource.subSequence(0, repoStart)); // repositories for (Repo repo : repositories) { lines(builder, 2, "maven {", " name '" + repo.name + "'", " url '" + repo.url + "'", "}"); } builder.append(resource.subSequence(repoEnd, depStart)); // dependencies for (String dep : dependencies) { append(builder, INDENT, INDENT, dep, NEWLINE); } builder.append(resource.subSequence(depEnd, jLevelStart)); builder.append(getJavaLevel()); builder.append(resource.subSequence(jLevelEnd, resource.length())); Files.write(builder.toString(), output, Constants.CHARSET); }
From source file:net.dries007.races.Config.java
public void saveConfig() { if (configFile == null) return;//from w ww.j a v a 2s . co m JsonObject root = new JsonObject(); JsonArray races = new JsonArray(); for (Race race : Race.RACE_MAP.values()) { races.add(Constants.GSON.toJsonTree(race)); } root.add("races", races); root.add("messages", Constants.GSON.toJsonTree(messages)); JsonArray books = new JsonArray(); for (ForDummiesBook dummiesBook : ForDummiesBook.SET) { books.add(Constants.GSON.toJsonTree(dummiesBook)); } root.add("books", books); try { Files.write(Constants.GSON.toJson(root), configFile, Charset.defaultCharset()); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.apache.isis.tool.mavenplugin.IsisMojoSwagger.java
private void writeSwaggerSpec(final SwaggerService swaggerService, final SwaggerService.Visibility visibility, final SwaggerService.Format format, final File swaggerSpecFile) throws MojoFailureException { final String swaggerSpec = swaggerService.generateSwaggerSpec(visibility, format); try {// ww w . ja va 2 s.co m Files.createParentDirs(swaggerSpecFile); } catch (IOException e) { throw new MojoFailureException( String.format("Failed to create dir: '%s'", swaggerSpecFile.getParent())); } try { Files.write(swaggerSpec, swaggerSpecFile, Charsets.UTF_8); } catch (IOException e) { throw new MojoFailureException("Failed to write out " + swaggerSpecFile); } }
From source file:net.kyori.blossom.task.SourceReplacementTask.java
/** * Perform the source replacement task./* w w w . java 2s . c o m*/ * * @throws IOException */ @TaskAction public void run() throws IOException { final PatternSet patternSet = new PatternSet(); patternSet.setIncludes(this.input.getIncludes()); patternSet.setExcludes(this.input.getExcludes()); if (this.output.exists()) { // Remove the output directory if it exists to prevent any possible conflicts deleteDirectory(this.output); } this.output.mkdirs(); this.output = this.output.getCanonicalFile(); // Resolve global and by-file replacements final Map<String, String> globalReplacements = this.resolveReplacementsGlobal(); final Multimap<String, Map<String, String>> fileReplacements = this.resolveReplacementsByFile(); for (final DirectoryTree dirTree : this.input.getSrcDirTrees()) { File dir = dirTree.getDir(); // handle non-existent source directories if (!dir.exists() || !dir.isDirectory()) { continue; } else { dir = dir.getCanonicalFile(); } // this could be written as .matching(source), but it doesn't actually work // because later on gradle casts it directly to PatternSet and crashes final FileTree tree = this.getProject().fileTree(dir).matching(this.input.getFilter()) .matching(patternSet); for (final File file : tree) { final File destination = getDestination(file, dir, this.output); destination.getParentFile().mkdirs(); destination.createNewFile(); boolean wasChanged = false; String text = Files.toString(file, Charsets.UTF_8); if (this.isIncluded(file)) { for (final Map.Entry<String, String> entry : globalReplacements.entrySet()) { text = text.replaceAll(entry.getKey(), entry.getValue()); } wasChanged = true; } final String path = this.getFilePath(file); final Collection<Map<String, String>> collection = fileReplacements.get(path); if (collection != null && !collection.isEmpty()) { for (final Map<String, String> map : collection) { for (final Map.Entry<String, String> entry : map.entrySet()) { text = text.replaceAll(entry.getKey(), entry.getValue()); } } wasChanged = true; } if (wasChanged) { Files.write(text, destination, Charsets.UTF_8); } else { Files.copy(file, destination); } } } }
From source file:org.apache.jackrabbit.oak.plugins.blob.datastore.DataStoreTextWriter.java
@Override public void write(@Nonnull String blobId, @Nonnull String text) throws IOException { checkIfReadOnlyModeEnabled();/* w w w. ja va 2s. co m*/ checkNotNull(blobId, "BlobId cannot be null"); checkNotNull(text, "Text passed for [%s] was null", blobId); File textFile = getFile(stripLength(blobId)); ensureParentExists(textFile); //TODO should we compress Files.write(text, textFile, Charsets.UTF_8); }
From source file:eu.stratosphere.library.clustering.DistributedOnePassKMeans.Util.java
public static String createTempFile(String fileName, String contents) throws IOException { File f = createAndRegisterTempFile(fileName); Files.write(contents, f, Charsets.UTF_8); return "file://" + f.getAbsolutePath(); }
From source file:ninja.miserable.blossom.task.SourceReplacementTask.java
/** * Perform the source replacement task.// ww w . j a v a 2s .c o m * * @throws IOException */ @TaskAction public void run() throws IOException { final PatternSet patternSet = new PatternSet(); patternSet.setIncludes(this.input.getIncludes()); patternSet.setExcludes(this.input.getExcludes()); if (this.output.exists()) { // Remove the output directory if it exists to prevent any possible conflicts FileUtil.deleteDirectory(this.output); } this.output.mkdirs(); this.output = this.output.getCanonicalFile(); // Resolve global and by-file replacements final Map<String, String> globalReplacements = this.resolveReplacementsGlobal(); final Multimap<String, Map<String, String>> fileReplacements = this.resolveReplacementsByFile(); for (final DirectoryTree dirTree : this.input.getSrcDirTrees()) { File dir = dirTree.getDir(); // handle non-existent source directories if (!dir.exists() || !dir.isDirectory()) { continue; } else { dir = dir.getCanonicalFile(); } // this could be written as .matching(source), but it doesn't actually work // because later on gradle casts it directly to PatternSet and crashes final FileTree tree = this.getProject().fileTree(dir).matching(this.input.getFilter()) .matching(patternSet); for (final File file : tree) { final File destination = getDestination(file, dir, this.output); destination.getParentFile().mkdirs(); destination.createNewFile(); boolean wasChanged = false; String text = Files.toString(file, Charsets.UTF_8); if (this.isIncluded(file)) { for (Map.Entry<String, String> entry : globalReplacements.entrySet()) { text = text.replaceAll(entry.getKey(), entry.getValue()); } wasChanged = true; } final String path = this.getFilePath(file); Collection<Map<String, String>> collection = fileReplacements.get(path); if (collection != null && !collection.isEmpty()) { for (Map<String, String> map : collection) { for (Map.Entry<String, String> entry : map.entrySet()) { text = text.replaceAll(entry.getKey(), entry.getValue()); } } wasChanged = true; } if (wasChanged) { Files.write(text, destination, Charsets.UTF_8); } else { Files.copy(file, destination); } } } }