下面列出了com.google.common.io.Files#readFirstLine ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static boolean isSupportPerf() {
File paranoidFile = new File("/proc/sys/kernel/perf_event_paranoid");
if (!paranoidFile.exists()) {
return false;
}
try {
String value = Files.readFirstLine(paranoidFile, Charsets.UTF_8);
int paranoid = Integer.parseInt(value);
if (paranoid >= 2) {
return false;
}
} catch (Exception e) {
throw new RuntimeException("read /proc/sys/kernel/perf_event_paranoid error.", e);
}
return true;
}
private static boolean isPrivateKeyFile(File file) {
if (!file.isFile() ||
(!LintUtils.endsWith(file.getPath(), "pem") && //NON-NLS-1$
!LintUtils.endsWith(file.getPath(), "key"))) { //NON-NLS-1$
return false;
}
try {
String firstLine = Files.readFirstLine(file, Charsets.US_ASCII);
return firstLine != null &&
firstLine.startsWith("---") && //NON-NLS-1$
firstLine.contains("PRIVATE KEY"); //NON-NLS-1$
} catch (IOException ex) {
// Don't care
}
return false;
}
/**
* Checks whether this license has previously been accepted.
* @param sdkRoot The root directory of the Android SDK
* @return true if this license has already been accepted
*/
public boolean checkAccepted(@Nullable File sdkRoot) {
if (sdkRoot == null) {
return false;
}
File licenseDir = new File(sdkRoot, LICENSE_DIR);
File licenseFile = new File(licenseDir, mLicenseRef == null ? mLicenseHash : mLicenseRef);
if (!licenseFile.exists()) {
return false;
}
try {
String hash = Files.readFirstLine(licenseFile, Charsets.UTF_8);
return hash.equals(mLicenseHash);
} catch (IOException e) {
return false;
}
}
@Nullable
protected String readMetadata(@Nonnull Metadata metadata) throws MojoExecutionException {
final File metadataFile = ensureMetadataFile(metadata);
if (!metadataFile.exists()) {
return null;
}
try {
return Files.readFirstLine(metadataFile, Charsets.UTF_8);
} catch (IOException e) {
final String message =
MessageFormat.format("Could not read {0} file at {1}", metadata.getFileName(),
metadataFile);
throw new MojoExecutionException(message, e);
}
}
private Secret createKeyVaultSecret(String servicePrincipal, String identityPrincipal) throws Exception {
String vaultName = SdkContext.randomResourceName("vlt", 10);
String secretName = SdkContext.randomResourceName("srt", 10);
String secretValue = Files.readFirstLine(new File(getClass().getClassLoader().getResource("test.certificate").getFile()), Charset.defaultCharset());
Vault vault = keyVaultManager.vaults()
.define(vaultName)
.withRegion(Region.US_EAST)
.withExistingResourceGroup(RG_NAME)
.defineAccessPolicy()
.forServicePrincipal(servicePrincipal)
.allowSecretAllPermissions()
.attach()
.defineAccessPolicy()
.forObjectId(identityPrincipal)
.allowSecretAllPermissions()
.attach()
.withAccessFromAzureServices()
.withDeploymentEnabled()
// Important!! Only soft delete enabled key vault can be assigned to application gateway
// See also: https://github.com/MicrosoftDocs/azure-docs/issues/34382
.withSoftDeleteEnabled()
.create();
return vault.secrets()
.define(secretName)
.withValue(secretValue)
.create();
}
private GenericContainer createFrontend(final Network network) {
final String image;
try {
image = Files.readFirstLine(new File("target/docker/image-name"), Charsets.UTF_8);
} catch (IOException e) {
throw new RuntimeException(e);
}
return new GenericContainer(image)
.withExposedPorts(1338)
.withCommand("http://backend:" + BACKEND_PORT)
.withNetwork(network)
.withNetworkAliases("frontend");
}
@Test
public void testExecute() throws Exception {
for (int i = 0; i < 1000; i++) {
loadProcessor.execute();
}
String loadAvg = Files.readFirstLine(new File(ROOT_PATH, "/proc/must_contains_2_running_tasks_to_paas_unit_test22222222222222222/loadavg"), Charset.defaultCharset());
Assert.assertTrue(loadAvg.startsWith("2.00"));
loadAvg = Files.readFirstLine(new File(ROOT_PATH, "/proc/must_contains_5_running_tasks_to_paas_unit_test55555555555555555/loadavg"), Charset.defaultCharset());
Assert.assertTrue(loadAvg.startsWith("5.00"));
}
@Test
public void testFileExistsToError() throws Exception {
FileRefTestUtil.writePredefinedTextToFile(testFolder.getRoot());
Record record = createRecord();
final String OTHER_TEXT = "some other text";
File targetFile = testFolder.newFile("target.txt");
Files.write(OTHER_TEXT.getBytes(Charset.forName("UTF-8")), targetFile);
Assert.assertEquals(OTHER_TEXT, Files.readFirstLine(targetFile, Charset.forName("UTF-8")));
path = testFolder.getRoot().getAbsolutePath();
setupServer(path, true);
RemoteUploadTarget target = new RemoteUploadTarget(getBean(
scheme.name() + "://localhost:" + port + "/",
true,
DataFormat.WHOLE_FILE,
targetFile.getName(),
WholeFileExistsAction.TO_ERROR
));
TargetRunner runner = new TargetRunner.Builder(RemoteUploadDTarget.class, target).build();
runner.runInit();
runner.runWrite(Collections.singletonList(record));
List<Record> errorRecords = runner.getErrorRecords();
Assert.assertEquals(1, errorRecords.size());
Assert.assertEquals(Errors.REMOTE_UPLOAD_02.getCode(), errorRecords.get(0).getHeader().getErrorCode());
Assert.assertEquals(record.get().getValueAsMap(), errorRecords.get(0).get().getValueAsMap());
Assert.assertEquals(0, runner.getEventRecords().size());
String line = Files.readFirstLine(targetFile, Charset.forName("UTF-8"));
Assert.assertEquals(OTHER_TEXT, line);
destroyAndValidate(runner);
}
private void testPhase(MapConfigKey<String> filePhase, MapConfigKey<String> templatePhase,
AttributeSensor<String> directory) throws IOException {
File file1 = new File(sourceFileDir, "file1");
Files.write(TEST_CONTENT_FILE, file1, Charset.defaultCharset());
File template1 = new File(sourceTemplateDir, "template1");
Files.write(TEST_CONTENT_TEMPLATE, template1, Charset.defaultCharset());
final EmptySoftwareProcess testEntity =
app.createAndManageChild(EntitySpec.create(EmptySoftwareProcess.class)
.configure(VanillaSoftwareProcess.LAUNCH_COMMAND, "true")
.configure(filePhase.getName(),
ImmutableMap.of(file1.getAbsolutePath(), "file1"))
.configure(templatePhase.getName(),
ImmutableMap.of(template1.getAbsolutePath(), "template1")));
app.start(ImmutableList.of(location));
final String installDirName = testEntity.sensors().get(directory);
assertNotNull(installDirName);
final File installDir = new File(installDirName);
final File file1Installed = new File(installDir, "file1");
final String firstLine = Files.readFirstLine(file1Installed, Charset.defaultCharset());
assertEquals(TEST_CONTENT_FILE, firstLine);
final File template1Installed = new File(installDir, "template1");
Properties props = new Properties();
final FileInputStream templateStream = new FileInputStream(template1Installed);
props.load(templateStream);
assertEquals(props.getProperty("id"), testEntity.getId());
}
@Test
public void resources() throws Exception {
File basedir = resources.getBasedir("resources/project-with-resources");
mojos.executeMojo(basedir, "process-resources");
File resource = new File(basedir, "target/classes/resource.txt");
Assert.assertTrue(resource.exists());
String line = Files.readFirstLine(resource, Charset.defaultCharset());
Assert.assertTrue(line.contains("resource.txt"));
}
@Test
public void resourcesWithTargetPath() throws Exception {
File basedir = resources.getBasedir("resources/project-with-resources-with-target-path");
mojos.executeMojo(basedir, "process-resources");
File resource = new File(basedir, "target/classes/resources/targetPath/resource.txt");
Assert.assertTrue(resource.exists());
String line = Files.readFirstLine(resource, Charset.defaultCharset());
Assert.assertTrue(line.contains("resource.txt"));
}
@Test
public void testResources() throws Exception {
File basedir = resources.getBasedir("resources/project-with-test-resources");
mojos.executeMojo(basedir, "process-test-resources");
File resource = new File(basedir, "target/test-classes/resource.txt");
Assert.assertTrue(resource.exists());
String line = Files.readFirstLine(resource, Charset.defaultCharset());
Assert.assertTrue(line.contains("resource.txt"));
}
@Test
public void testResourcesWithTargetPath() throws Exception {
File basedir = resources.getBasedir("resources/project-with-test-resources-with-target-path");
mojos.executeMojo(basedir, "process-test-resources");
File resource = new File(basedir, "target/test-classes/resources/targetPath/resource.txt");
Assert.assertTrue(resource.exists());
String line = Files.readFirstLine(resource, Charset.defaultCharset());
Assert.assertTrue(line.contains("resource.txt"));
}
public static String getPort() throws IOException {
return Files.readFirstLine(new File(portPath), Charsets.UTF_8);
}
@Test
public void testSlowQueryLog() throws Exception {
File logFile = File.createTempFile("slow-query", ".log");
try {
ObjectMapper objectMapper = Jackson.newObjectMapper();
SlowQueryLogConfiguration config = objectMapper.readValue(
"{" +
"\"tooManyDeltasThreshold\": 20," +
"\"file\": {" +
"\"type\": \"file\"," +
"\"currentLogFilename\": \"" + logFile.getAbsolutePath() + "\"," +
"\"archive\": false" +
"}" +
"}",
SlowQueryLogConfiguration.class);
SlowQueryLog log = new LogbackSlowQueryLogProvider(config, new MetricRegistry()).get();
Expanded expanded = mock(Expanded.class);
when(expanded.getNumPersistentDeltas()).thenReturn(100);
when(expanded.getNumDeletedDeltas()).thenReturn(2L);
log.log("test:table", "test-key", expanded);
// Logging is asynchronous; allow up to 10 seconds for the message to be logged
Stopwatch stopwatch = Stopwatch.createStarted();
while (logFile.length() == 0 && stopwatch.elapsed(TimeUnit.SECONDS) < 10) {
Thread.sleep(100);
}
String line = Files.readFirstLine(logFile, Charsets.UTF_8);
assertNotNull(line);
assertTrue(line.endsWith("Too many deltas: 100 2 test:table test-key"));
} finally {
//noinspection ResultOfMethodCallIgnored
logFile.delete();
// Reset everything so future tests that use slow query logging don't log to the file
new LogbackSlowQueryLogProvider(new SlowQueryLogConfiguration(), new MetricRegistry()).get();
}
}
private void verifyTargetFile(File targetFile) throws IOException {
String line = Files.readFirstLine(targetFile, Charset.forName("UTF-8"));
Assert.assertEquals(FileRefTestUtil.TEXT, line);
}
public static void main(String[] args) {
try {
try {
httpTransport = GoogleNetHttpTransport.newTrustedTransport();
// Check for valid setup.
Preconditions.checkArgument(!SERVICE_ACCOUNT_EMAIL.startsWith("[["),
"Please enter your service account e-mail from the Google APIs "
+ "Console to the SERVICE_ACCOUNT_EMAIL constant in %s",
StorageServiceAccountSample.class.getName());
Preconditions.checkArgument(!BUCKET_NAME.startsWith("[["),
"Please enter your desired Google Cloud Storage bucket name "
+ "to the BUCKET_NAME constant in %s", StorageServiceAccountSample.class.getName());
String p12Content = Files.readFirstLine(new File("key.p12"), Charset.defaultCharset());
Preconditions.checkArgument(!p12Content.startsWith("Please"), p12Content);
//[START snippet]
// Build a service account credential.
GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
.setJsonFactory(JSON_FACTORY)
.setServiceAccountId(SERVICE_ACCOUNT_EMAIL)
.setServiceAccountScopes(Collections.singleton(STORAGE_SCOPE))
.setServiceAccountPrivateKeyFromP12File(new File("key.p12"))
.build();
// Set up and execute a Google Cloud Storage request.
String URI = "https://storage.googleapis.com/" + BUCKET_NAME;
HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
GenericUrl url = new GenericUrl(URI);
HttpRequest request = requestFactory.buildGetRequest(url);
HttpResponse response = request.execute();
String content = response.parseAsString();
//[END snippet]
// Instantiate transformer input.
Source xmlInput = new StreamSource(new StringReader(content));
StreamResult xmlOutput = new StreamResult(new StringWriter());
// Configure transformer.
Transformer transformer = TransformerFactory.newInstance().newTransformer(); // An identity
// transformer
transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "testing.dtd");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
transformer.transform(xmlInput, xmlOutput);
// Pretty print the output XML.
System.out.println("\nBucket listing for " + BUCKET_NAME + ":\n");
System.out.println(xmlOutput.getWriter().toString());
System.exit(0);
} catch (IOException e) {
System.err.println(e.getMessage());
}
} catch (Throwable t) {
t.printStackTrace();
}
System.exit(1);
}