下面列出了com.google.common.io.Files#toString ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Reads credential info from {@link #credentialPath} and returns in a string format.
*
* @return Credential in {@code String} representation.
* @throws IgniteSpiException In case of error.
*/
private String getCredentialFromFile() throws IgniteSpiException {
try {
String fileContents = Files.toString(new File(credentialPath), Charsets.UTF_8);
if (provider.equals("google-compute-engine")) {
Supplier<Credentials> credentialSupplier = new GoogleCredentialsFromJson(fileContents);
return credentialSupplier.get().credential;
}
return fileContents;
}
catch (IOException e) {
throw new IgniteSpiException("Failed to retrieve the private key from the file: " + credentialPath, e);
}
}
@Test
public void testPrivateKeyPlainText() throws Exception {
File privateKeyFile =
new File(currentThread().getContextClassLoader().
getResource("remote-download-source/id_rsa_test").getPath());
String privateKeyPlainText = Files.toString(privateKeyFile, Charset.forName("UTF-8"));
SFTPRemoteConnectorForTest connector = new SFTPRemoteConnectorForTest(getBean(
"sftp://localhost:" + port + "/",
true,
false,
TESTUSER,
null,
null,
"streamsets",
null,
true,
privateKeyPlainText
));
List<Stage.ConfigIssue> issues = initWithNoIssues(connector);
Assert.assertEquals(0, issues.size());
verifyConnection(connector);
connector.close();
}
private static ParseTree parseJavadocFromFile(File file)
throws IOException {
final String content = Files.toString(file, Charsets.UTF_8);
final InputStream in = new ByteArrayInputStream(content.getBytes(Charsets.UTF_8));
final ANTLRInputStream input = new ANTLRInputStream(in);
final JavadocLexer lexer = new JavadocLexer(input);
lexer.removeErrorListeners();
final BaseErrorListener errorListener = new FailOnErrorListener();
lexer.addErrorListener(errorListener);
final CommonTokenStream tokens = new CommonTokenStream(lexer);
final JavadocParser parser = new JavadocParser(tokens);
parser.removeErrorListeners();
parser.addErrorListener(errorListener);
return parser.javadoc();
}
private static void method() throws Exception {
ByteStreams.nullOutputStream();
CharStreams.nullWriter();
Files.toString((File) null, (Charset) null);
Files.write("", (File) null, (Charset) null);
new FileReader((File) null);
new FileReader((String) null);
new FileWriter((File) null);
new FileWriter((File) null, true);
new FileWriter("");
new FileWriter("", true);
}
@RequestMapping(method = RequestMethod.GET)
@ResponseBody
public String get(@RequestParam(name = "path") String path) {
File file = templateService.getFile(path);
if (file != null) {
try {
return Files.toString(file, Charset.forName("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Test
public void doesNotAddValueForInvalidPredicate() throws Exception {
testRdfDescriptionSaver.addValue(BASE_URI, "http://invalid.org/terms/title", "DWC Data", null, BASE_URI);
testRdfDescriptionSaver.commit();
File file = new File(descriptionFileName);
String descriptionFile = Files.toString(file, Charsets.UTF_8);
assertEquals("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<rdf:RDF\n" +
"\txmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n" +
"\n" +
"</rdf:RDF>", descriptionFile);
}
@Test
public void writeCommand() throws Exception {
BzlWriter writer = new BzlWriter(new String[]{"x", "y", "z"}, System.getenv("TEST_TMPDIR"));
writer.write(createRules());
String fileContents = Files.toString(
new File(System.getenv("TEST_TMPDIR") + "/generate_workspace.bzl"),
Charset.defaultCharset());
assertThat(fileContents).contains("# generate_workspace x y z");
}
@Test public void importReplacement() throws Exception {
File basedir = resources.getBasedir("import-replacement");
rule.executeMojo(basedir, "compile");
File fooBarBazTemplate = new File(basedir, "target/generated-sources/twirl/foo/bar/html/baz.template.scala");
assertThat(fooBarBazTemplate).exists();
String fooBarBaz = Files.toString(fooBarBazTemplate, UTF_8);
assertThat(fooBarBaz).contains("import my.other.html.Thing");
}
/**
* Copies the entire contents of a file to a String.
*
* @see com.google.common.io.Files#toString(File, java.nio.charset.Charset)
*/
public static String readFullyString(File sourceFile) {
try {
return Files.toString(sourceFile, Charsets.UTF_8);
} catch (IOException ioe) {
throw Exceptions.propagate(ioe);
}
}
public void localizeDropFiles(Drop drop, int round, String xliffState, boolean introduceSyntaxError) throws BoxSDKServiceException, DropExporterException, IOException {
logger.debug("Localize files in a drop for testing");
FileSystemDropExporter fileSystemDropExporter = (FileSystemDropExporter) dropExporterService.recreateDropExporter(drop);
FileSystemDropExporterConfig fileSystemDropExporterConfig = fileSystemDropExporter.getFileSystemDropExporterConfig();
File[] sourceFiles = Paths.get(fileSystemDropExporterConfig.getDropFolderPath(), DROP_FOLDER_SOURCE_FILES_NAME).toFile().listFiles();
for (File sourceFile : sourceFiles) {
String localizedContent = Files.toString(sourceFile, StandardCharsets.UTF_8);
if (sourceFile.getName().startsWith("ko-KR")) {
logger.debug("For the Korean file, don't translate but add a corrupted text unit (invalid id) at the end");
localizedContent = localizedContent.replaceAll("</body>",
"<trans-unit id=\"badid\" resname=\"TEST2\" xml:space=\"preserve\">\n"
+ "<source xml:lang=\"en\">Content2</source>\n"
+ "<target xml:lang=\"ko-KR\" state=\"new\">Import Drop" + round + " - Content2 ko-KR</target>\n"
+ "</trans-unit>\n"
+ "</body>");
} else {
localizedContent = XliffUtils.localizeTarget(localizedContent, "Import Drop" + round);
}
if (introduceSyntaxError) {
logger.debug("Creating a corrupted xml file to test import errors.");
localizedContent = localizedContent.replaceAll("</body>", "</bod");
}
localizedContent = XliffUtils.replaceTargetState(localizedContent, xliffState);
//TODO(P1) this logic is being duplicated everywhere maybe it should go back into the config or service.
Path localizedFolderPath = Paths.get(fileSystemDropExporterConfig.getDropFolderPath(), DROP_FOLDER_LOCALIZED_FILES_NAME, sourceFile.getName());
Files.write(localizedContent, localizedFolderPath.toFile(), StandardCharsets.UTF_8);
}
}
@Test
public void testSchemaToFile() throws Exception {
command.datasets = Lists.newArrayList("users");
command.outputPath = "target/user.avsc";
int rc = command.run();
Assert.assertEquals("Should return success code", 0, rc);
String fileContent = Files.toString(
new File("target/user.avsc"), BaseCommand.UTF8);
Assert.assertTrue("File should contain pretty printed schema",
TestUtil.matchesSchema(schema).matches(fileContent));
verify(console).trace(contains("repo:hive"));
verifyNoMoreInteractions(console);
}
public void setTemplate(File file) throws FileNotFoundException {
if (!file.isFile()) {
throw new FileNotFoundException(
I18n.get(IExceptionMessage.TEMPLATE_MAKER_1) + ": " + file.getName());
}
String text;
try {
text = Files.toString(file, Charsets.UTF_8);
} catch (IOException e) {
throw new IllegalArgumentException(e);
}
this.setTemplate(text);
}
@Override
public String getString(String name, Charset encoding, JinjavaInterpreter interpreter)
throws IOException {
File file = resolveFileName(name);
if (!file.exists() || !file.isFile()) {
throw new ResourceNotFoundException("Couldn't find resource: " + file);
}
return Files.toString(file, encoding);
}
/**
* Reads file content directly from the filesystem.
*/
public static String getContent(URI fileURI) throws CoreException {
if (fileURI == null) {
return null;
}
String content;
try {
content = Files.toString(toFile(fileURI), Charsets.UTF_8);
} catch (IOException e) {
throw new CoreException(StatusFactory.newErrorStatus("Can not get " + fileURI + " content", e));
}
return content;
}
@Test
public void writeEmpty() throws Exception {
BzlWriter writer = new BzlWriter(new String[]{}, System.getenv("TEST_TMPDIR"));
writer.write(createRules());
String fileContents = Files.toString(
new File(System.getenv("TEST_TMPDIR") + "/generate_workspace.bzl"),
Charset.defaultCharset());
assertThat(fileContents).contains(String.format("def generated_maven_jars():%n pass%n"));
assertThat(fileContents).contains(String.format("def generated_java_libraries():%n pass%n"));
}
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("https://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();
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);
}
public CustomInlineMethodResolver(@Nonnull ClassPath classPath, @Nonnull File inlineTable) throws IOException {
this(classPath, Files.toString(inlineTable, Charset.forName("UTF-8")));
}
public void testNonPrintableChars() throws Exception {
// See https://code.google.com/p/android/issues/detail?id=56205
File file = new File(getTargetDir(), "report");
try {
LintCliClient client = new LintCliClient() {
@Override
String getRevision() {
return "unittest"; // Hardcode version to keep unit test output stable
}
};
//noinspection ResultOfMethodCallIgnored
file.getParentFile().mkdirs();
XmlReporter reporter = new XmlReporter(client, file);
Project project = Project.create(client, new File("/foo/bar/Foo"),
new File("/foo/bar/Foo"));
Warning warning1 = new Warning(TypographyDetector.FRACTIONS,
String.format("Use fraction character %1$c (%2$s) instead of %3$s ?",
'\u00BC', "¼", "1/4"), Severity.WARNING, project);
warning1.line = 592;
warning1.file = new File("/foo/bar/Foo/AndroidManifest.xml");
warning1.errorLine =
" <string name=\"user_registration_name3_3\">Register 3/3</string>\n" +
" ^";
warning1.path = "res/values-en/common_strings.xml";
warning1.location = Location.create(warning1.file,
new DefaultPosition(592, 46, -1), null);
List<Warning> warnings = new ArrayList<Warning>();
warnings.add(warning1);
reporter.write(0, 2, warnings);
String report = Files.toString(file, Charsets.UTF_8);
assertEquals(""
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
+ "<issues format=\"4\" by=\"lint unittest\">\n"
+ "\n"
+ " <issue\n"
+ " id=\"TypographyFractions\"\n"
+ " severity=\"Warning\"\n"
+ " message=\"Use fraction character ¼ (&#188;) instead of 1/4 ?\"\n"
+ " category=\"Usability:Typography\"\n"
+ " priority=\"5\"\n"
+ " summary=\"Fraction string can be replaced with fraction character\"\n"
+ " explanation=\"You can replace certain strings, such as 1/2, and 1/4, with dedicated characters for these, such as ½ (&#189;) and ¼ (&#188;). This can help make the text more readable.\"\n"
+ " url=\"http://en.wikipedia.org/wiki/Number_Forms\"\n"
+ " urls=\"http://en.wikipedia.org/wiki/Number_Forms\">\n"
+ " <location\n"
+ " file=\"AndroidManifest.xml\"\n"
+ " line=\"593\"\n"
+ " column=\"47\"/>\n"
+ " </issue>\n"
+ "\n"
+ "</issues>\n",
report);
// Make sure the XML is valid
Document document = PositionXmlParser.parse(report);
assertNotNull(document);
assertEquals(1, document.getElementsByTagName("issue").getLength());
String explanation = ((Element)document.getElementsByTagName("issue").item(0)).
getAttribute("explanation");
assertEquals(TypographyDetector.FRACTIONS.getExplanation(TextFormat.RAW),
explanation);
} finally {
//noinspection ResultOfMethodCallIgnored
file.delete();
}
}
@Nonnull
private static String readJava(@Nonnull String name) throws Exception {
final File file = new File(JAVA_RESOURCE_DIR, name);
return Files.toString(file, StandardCharsets.UTF_8);
}
/** Patch the device to add an ES256 key for authentication. */
protected static void patchEs256ForAuth(
String deviceId,
String publicKeyFilePath,
String projectId,
String cloudRegion,
String registryName)
throws GeneralSecurityException, IOException {
GoogleCredentials credential =
GoogleCredentials.getApplicationDefault().createScoped(CloudIotScopes.all());
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
HttpRequestInitializer init = new HttpCredentialsAdapter(credential);
final CloudIot service =
new CloudIot.Builder(GoogleNetHttpTransport.newTrustedTransport(), jsonFactory, init)
.setApplicationName(APP_NAME)
.build();
final String devicePath =
String.format(
"projects/%s/locations/%s/registries/%s/devices/%s",
projectId, cloudRegion, registryName, deviceId);
PublicKeyCredential publicKeyCredential = new PublicKeyCredential();
String key = Files.toString(new File(publicKeyFilePath), Charsets.UTF_8);
publicKeyCredential.setKey(key);
publicKeyCredential.setFormat("ES256_PEM");
DeviceCredential devCredential = new DeviceCredential();
devCredential.setPublicKey(publicKeyCredential);
Device device = new Device();
device.setCredentials(Collections.singletonList(devCredential));
Device patchedDevice =
service
.projects()
.locations()
.registries()
.devices()
.patch(devicePath, device)
.setUpdateMask("credentials")
.execute();
System.out.println("Patched device is " + patchedDevice.toPrettyString());
}