List of usage examples for com.google.common.io Files toString
public static String toString(File file, Charset charset) throws IOException
From source file:org.glowroot.agent.plugin.cassandra.CassandraWrapper.java
private static void downloadAndExtract(File baseDir) throws IOException { // using System.out to make sure user sees why there is a big delay here System.out.print("Downloading Cassandra " + CASSANDRA_VERSION + "..."); URL url = new URL("http://www-us.apache.org/dist/cassandra/" + CASSANDRA_VERSION + "/apache-cassandra-" + CASSANDRA_VERSION + "-bin.tar.gz"); InputStream in = url.openStream(); File archiveFile = File.createTempFile("cassandra-" + CASSANDRA_VERSION + "-", ".tar.gz"); Files.asByteSink(archiveFile).writeFrom(in); in.close();// www.j a va 2 s. c o m Archiver archiver = ArchiverFactory.createArchiver(ArchiveFormat.TAR, CompressionType.GZIP); archiver.extract(archiveFile, baseDir); archiveFile.delete(); System.out.println(" OK"); File cassandraDir = new File(baseDir, "apache-cassandra-" + CASSANDRA_VERSION); File confDir = new File(cassandraDir, "conf"); // reduce logging to stdout File logbackXmlFile = new File(confDir, "logback.xml"); String xml = Files.toString(logbackXmlFile, UTF_8); xml = xml.replace("<root level=\"INFO\">", "<root level=\"ERROR\">"); xml = xml.replace("<logger name=\"org.apache.cassandra\" level=\"DEBUG\"/>", ""); Files.asCharSink(logbackXmlFile, UTF_8).write(xml); // long timeouts needed on slow travis ci machines File yamlFile = new File(confDir, "cassandra.yaml"); String yaml = Files.toString(yamlFile, UTF_8); yaml = yaml.replaceAll("(?m)^read_request_timeout_in_ms: .*$", "read_request_timeout_in_ms: 30000"); yaml = yaml.replaceAll("(?m)^write_request_timeout_in_ms: .*$", "write_request_timeout_in_ms: 30000"); Files.asCharSink(yamlFile, UTF_8).write(yaml); }
From source file:org.apache.flume.source.jms.JMSSource.java
@Override protected void doConfigure(Context context) throws FlumeException { sourceCounter = new SourceCounter(getName()); initialContextFactoryName = context.getString(JMSSourceConfiguration.INITIAL_CONTEXT_FACTORY, "").trim(); providerUrl = context.getString(JMSSourceConfiguration.PROVIDER_URL, "").trim(); destinationName = context.getString(JMSSourceConfiguration.DESTINATION_NAME, "").trim(); String destinationTypeName = context.getString(JMSSourceConfiguration.DESTINATION_TYPE, "").trim() .toUpperCase();/*from ww w . j a v a2 s . c o m*/ messageSelector = context.getString(JMSSourceConfiguration.MESSAGE_SELECTOR, "").trim(); batchSize = context.getInteger(JMSSourceConfiguration.BATCH_SIZE, JMSSourceConfiguration.BATCH_SIZE_DEFAULT); errorThreshold = context.getInteger(JMSSourceConfiguration.ERROR_THRESHOLD, JMSSourceConfiguration.ERROR_THRESHOLD_DEFAULT); userName = Optional.fromNullable(context.getString(JMSSourceConfiguration.USERNAME)); pollTimeout = context.getLong(JMSSourceConfiguration.POLL_TIMEOUT, JMSSourceConfiguration.POLL_TIMEOUT_DEFAULT); String passwordFile = context.getString(JMSSourceConfiguration.PASSWORD_FILE, "").trim(); if (passwordFile.isEmpty()) { password = Optional.of(""); } else { try { password = Optional.of(Files.toString(new File(passwordFile), Charsets.UTF_8).trim()); } catch (IOException e) { throw new FlumeException(String.format("Could not read password file %s", passwordFile), e); } } String converterClassName = context .getString(JMSSourceConfiguration.CONVERTER_TYPE, JMSSourceConfiguration.CONVERTER_TYPE_DEFAULT) .trim(); if (JMSSourceConfiguration.CONVERTER_TYPE_DEFAULT.equalsIgnoreCase(converterClassName)) { converterClassName = DefaultJMSMessageConverter.Builder.class.getName(); } Context converterContext = new Context(context.getSubProperties(JMSSourceConfiguration.CONVERTER + ".")); try { @SuppressWarnings("rawtypes") Class clazz = Class.forName(converterClassName); boolean isBuilder = JMSMessageConverter.Builder.class.isAssignableFrom(clazz); if (isBuilder) { JMSMessageConverter.Builder builder = (JMSMessageConverter.Builder) clazz.newInstance(); converter = builder.build(converterContext); } else { Preconditions.checkState(JMSMessageConverter.class.isAssignableFrom(clazz), String.format("Class %s is not a subclass of JMSMessageConverter", clazz.getName())); converter = (JMSMessageConverter) clazz.newInstance(); boolean configured = Configurables.configure(converter, converterContext); if (logger.isDebugEnabled()) { logger.debug(String.format("Attempted configuration of %s, result = %s", converterClassName, String.valueOf(configured))); } } } catch (Exception e) { throw new FlumeException(String.format("Unable to create instance of converter %s", converterClassName), e); } String connectionFactoryName = context.getString(JMSSourceConfiguration.CONNECTION_FACTORY, JMSSourceConfiguration.CONNECTION_FACTORY_DEFAULT).trim(); assertNotEmpty(initialContextFactoryName, String.format("Initial Context Factory is empty. This is specified by %s", JMSSourceConfiguration.INITIAL_CONTEXT_FACTORY)); assertNotEmpty(providerUrl, String.format("Provider URL is empty. This is specified by %s", JMSSourceConfiguration.PROVIDER_URL)); assertNotEmpty(destinationName, String.format("Destination Name is empty. This is specified by %s", JMSSourceConfiguration.DESTINATION_NAME)); assertNotEmpty(destinationTypeName, String.format("Destination Type is empty. This is specified by %s", JMSSourceConfiguration.DESTINATION_TYPE)); try { destinationType = JMSDestinationType.valueOf(destinationTypeName); } catch (IllegalArgumentException e) { throw new FlumeException(String.format("Destination type '%s' is " + "invalid.", destinationTypeName), e); } Preconditions.checkArgument(batchSize > 0, "Batch size must be greater " + "than 0"); InitialContext initalContext; try { Properties contextProperties = new Properties(); contextProperties.setProperty(javax.naming.Context.INITIAL_CONTEXT_FACTORY, initialContextFactoryName); contextProperties.setProperty(javax.naming.Context.PROVIDER_URL, providerUrl); initalContext = initialContextFactory.create(contextProperties); } catch (NamingException e) { throw new FlumeException(String.format("Could not create initial context %s provider %s", initialContextFactoryName, providerUrl), e); } try { connectionFactory = (ConnectionFactory) initalContext.lookup(connectionFactoryName); } catch (NamingException e) { throw new FlumeException("Could not lookup ConnectionFactory", e); } }
From source file:org.cordovastudio.editors.designer.rendering.DeviceArtDescriptor.java
public static List<DeviceArtDescriptor> getDescriptors(@Nullable File[] folders) { List<File> files = getDescriptorFiles(folders); List<DeviceArtDescriptor> result = Lists.newArrayList(); for (File file : files) try {//from w w w .j a v a 2 s.c o m String xml = Files.toString(file, Charsets.UTF_8); Document document = XmlUtils.parseDocumentSilently(xml, false); if (document != null) { File baseFolder = file.getParentFile(); addDescriptors(result, document, baseFolder); } else { Logger.getInstance(DeviceArtDescriptor.class).error("Couldn't parse " + file); } } catch (IOException e) { Logger.getInstance(DeviceArtDescriptor.class).error(e); } return result; }
From source file:org.gradle.api.internal.tasks.AntGroovydoc.java
private String getGroovyVersion(List<File> combinedClasspath) { File temp;/*from w w w.j a v a 2 s.c om*/ final String tempPath; try { temp = File.createTempFile("temp", ""); String p = temp.getCanonicalPath(); tempPath = File.separatorChar == '/' ? p : p.replace(File.separatorChar, '/'); temp.deleteOnExit(); } catch (IOException e) { throw new GradleException("Unable to create temp file needed for Groovydoc", e); } ant.withClasspath(combinedClasspath).execute(new Closure<Object>(this, this) { @SuppressWarnings("UnusedDeclaration") public Object doCall(Object it) { final GroovyObjectSupport antBuilder = (GroovyObjectSupport) it; antBuilder.invokeMethod("taskdef", ImmutableMap.of("name", "groovy", "classname", "org.codehaus.groovy.ant.Groovy")); antBuilder.invokeMethod("groovy", new Object[] { "new File('" + tempPath + "').text = GroovySystem.version" }); return null; } }); try { return Files.toString(temp, Charset.defaultCharset()).trim(); } catch (IOException e) { throw new GradleException("Unable to find Groovy version needed for Groovydoc", e); } }
From source file:com.samskivert.depot.tools.GenRecord.java
/** Processes a resolved persistent record class instance. */ protected void processRecord(File source, Class<?> rclass) { // make sure we extend persistent record if (!_prclass.isAssignableFrom(rclass)) { logInfo("Skipping non-record '" + rclass.getName() + "'"); return;//from www . j a va2 s.c o m } // determine our primary key fields for getKey() generation (if we're not an abstract) List<Field> kflist = Lists.newArrayList(); if (!Modifier.isAbstract(rclass.getModifiers())) { // determine which fields make up our primary key; we'd just use Class.getFields() but // that returns things in a random order whereas ours returns fields in declaration // order starting from the top-most class and going down the line for (Field field : getFields(rclass)) { if (hasAnnotation(field, Id.class)) kflist.add(field); else if (hasAnnotation(field, GeneratedValue.class)) { logWarn("Skipping " + rclass.getName() + ". Field '" + field.getName() + "' has @GeneratedValue, which may only used on primary keys with @Id.", null); return; } } } // determine which fields we need to generate constants for List<Field> flist = Lists.newArrayList(); for (Field field : rclass.getFields()) { if (isPersistentField(field)) { flist.add(field); } } Set<Field> declared = Sets.newHashSet(); for (Field field : rclass.getDeclaredFields()) { if (isPersistentField(field)) { declared.add(field); } } // read the source file and break it into lines Charset charset = Charset.defaultCharset(); // TODO? String sourceText; String[] lines = null; try { sourceText = Files.toString(source, charset); lines = Files.readLines(source, charset).toArray(new String[0]); } catch (IOException ioe) { logWarn("Error reading '" + source + "'", ioe); return; } // now determine where to insert our static field declarations int bstart = -1, bend = -1; int nstart = -1, nend = -1; int mstart = -1, mend = -1; for (int ii = 0; ii < lines.length; ii++) { String line = lines[ii].trim(); // look for the start of the class body if (NAME_PATTERN.matcher(line).find()) { if (line.endsWith("{")) { bstart = ii + 1; } else { // search down a few lines for the open brace for (int oo = 1; oo < 10; oo++) { if (get(lines, ii + oo).trim().endsWith("{")) { bstart = ii + oo + 1; break; } } } // track the last } on a line by itself and we'll call that the end of the class body } else if (line.equals("}")) { bend = ii; // look for our field and method markers } else if (line.equals(FIELDS_START)) { nstart = ii; } else if (line.equals(FIELDS_END)) { nend = ii + 1; } else if (line.equals(METHODS_START)) { mstart = ii; } else if (line.equals(METHODS_END)) { mend = ii + 1; } } // sanity check the markers if (check(source, "fields start", nstart, "fields end", nend) || check(source, "fields end", nend, "fields start", nstart) || check(source, "methods start", mstart, "methods end", mend) || check(source, "methods end", mend, "methods start", mstart)) { return; } // we have no previous markers then stuff the fields at the top of the class body and the // methods at the bottom if (nstart == -1) { nstart = bstart; nend = bstart; } if (mstart == -1) { mstart = bend; mend = bend; } // get the unqualified class name String rname = DepotUtil.justClassName(rclass); // generate our fields section StringBuilder fsection = new StringBuilder(); // add our prototype declaration Map<String, String> subs = Maps.newHashMap(); // We could add the @Generated annotation, but // - we'd need to add the import for javax.annotation.Generated // - it adds a lot of boilerplate to the source file // - we can't annotate the static initializer that registers the key fields // So it was decided to omit it and the few benefits: // - marked as Generated in javadoc // - timestamp of last generation // - a reference back to this class // subs.put("generated", "@Generated(value={\"" + GenRecordTask.class.getName() + "\"}, " + // "date=\"" + // ISO 8601 date // new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").format(new Date()) + "\")"); subs.put("record", rname); fsection.append(mergeTemplate(PROTO_TMPL, subs)); // add our ColumnExp constants for (int ii = 0; ii < flist.size(); ii++) { Field f = flist.get(ii); String fname = f.getName(); // create our substitution mappings Map<String, String> fsubs = Maps.newHashMap(subs); fsubs.put("type", getTypeName(f.getGenericType())); fsubs.put("field", fname); fsubs.put("capfield", unStudlyName(fname).toUpperCase()); // now generate our bits fsection.append(mergeTemplate(COL_TMPL, fsubs)); } // generate our methods section StringBuilder msection = new StringBuilder(); // add a getKey() method, if applicable if (kflist.size() > 0) { StringBuilder argList = new StringBuilder(); StringBuilder argNameList = new StringBuilder(); StringBuilder fieldNameList = new StringBuilder(); for (Field keyField : kflist) { if (argList.length() > 0) { argList.append(", "); argNameList.append(", "); fieldNameList.append(", "); } String name = keyField.getName(); argList.append(simpleName(keyField.getGenericType())).append(" ").append(name); argNameList.append(name); fieldNameList.append(unStudlyName(name)); } subs.put("argList", argList.toString()); subs.put("argNameList", argNameList.toString()); subs.put("fieldNameList", fieldNameList.toString()); // generate our bits and append them as appropriate to the string buffers msection.append(mergeTemplate(KEY_TMPL, subs)); } // now bolt everything back together into a class declaration StringWriter out = new StringWriter(); PrintWriter pout = new PrintWriter(out); for (int ii = 0; ii < nstart; ii++) { pout.println(lines[ii]); } if (fsection.length() > 0) { String prev = get(lines, nstart - 1); if (!isBlank(prev) && !prev.equals("{")) pout.println(); pout.println(" " + FIELDS_START); pout.write(fsection.toString()); pout.println(" " + FIELDS_END); if (!isBlank(get(lines, nend))) pout.println(); } for (int ii = nend; ii < mstart; ii++) { pout.println(lines[ii]); } if (msection.length() > 0) { if (!isBlank(get(lines, mstart - 1))) pout.println(); pout.println(" " + METHODS_START); pout.write(msection.toString()); pout.println(" " + METHODS_END); String next = get(lines, mend); if (!isBlank(next) && !next.equals("}")) pout.println(); } for (int ii = mend; ii < lines.length; ii++) { pout.println(lines[ii]); } String newSourceText = out.toString(); if (!sourceText.equals(newSourceText)) { try { Files.write(newSourceText, source, charset); logInfo("Regenerated '" + source + "'"); } catch (IOException ioe) { logWarn("Error writing to '" + source + "'", ioe); } } }
From source file:org.apache.provisionr.commands.CreateCommand.java
@VisibleForTesting AdminAccess collectCurrentUserCredentialsForAdminAccess() { try {//from w w w . j a v a 2s . c om String publicKey = Files.toString(new File(publicKeyPath), Charsets.UTF_8); String privateKey = Files.toString(new File(privateKeyPath), Charsets.UTF_8); return AdminAccess.builder().username(System.getProperty("user.name")).publicKey(publicKey) .privateKey(privateKey).createAdminAccess(); } catch (Exception e) { throw Throwables.propagate(e); } }
From source file:org.apache.gobblin.service.modules.orchestration.FSDagStateStore.java
/** * Return a {@link Dag} given a file name. * @param dagFile/* w w w. j a va2 s. co m*/ * @return the {@link Dag} associated with the dagFiel. */ @VisibleForTesting public Dag<JobExecutionPlan> getDag(File dagFile) throws IOException { String serializedDag = Files.toString(dagFile, Charsets.UTF_8); return deserializeDag(serializedDag); }
From source file:com.google.api.codegen.DiscoveryGeneratorTestBase.java
private String displayValue(Object value) throws IOException { if (value instanceof Doc) { return ((Doc) value).prettyPrint(100); } else if (value instanceof File) { return Files.toString((File) value, StandardCharsets.UTF_8); } else if (value instanceof MessageOrBuilder) { // Convert proto to text format, considering any instances. return formatter.printToString((MessageOrBuilder) value); } else {/*from w w w. j a va 2s . com*/ return value.toString(); } }
From source file:com.google.javascript.jscomp.fuzzing.Driver.java
private JSONObject getConfig() { if (config == null) { File file = new File(configFileName); try {/*ww w .j a v a2 s. c o m*/ config = new JSONObject(Files.toString(file, StandardCharsets.UTF_8)); } catch (JSONException | IOException e) { e.printStackTrace(); } } return config; }
From source file:com.android.idegen.IntellijProject.java
private void createVcsFile(File ideaDir, Iterable<Module> modules) throws IOException { String vcsTemplate = Files.toString( new File(DirectorySearch.findTemplateDir(), "idea" + File.separator + VCS_TEMPLATE_FILE_NAME), CHARSET);/*from www . ja v a 2 s . c o m*/ Set<String> gitRoots = new HashSet<>(); for (Module mod : modules) { File dir = mod.getDir(); // Look for git root in the module directory and its parents. while (dir != null) { File gitRoot = new File(dir, ".git"); if (gitRoot.exists()) { gitRoots.add(dir.getCanonicalPath()); break; } else { dir = dir.getParentFile(); } } } StringBuilder sb = new StringBuilder(); for (String root : gitRoots) { sb.append(" <mapping directory=\"").append(root).append("\" vcs=\"Git\" />\n"); } vcsTemplate = vcsTemplate.replace("@VCS@", sb.toString()); Files.write(vcsTemplate, new File(ideaDir, "vcs.xml"), CHARSET); }