Search in sources :

Example 1 with PrintStream

use of java.io.PrintStream in project elasticsearch by elastic.

the class MockFSDirectoryService method checkIndex.

public static void checkIndex(Logger logger, Store store, ShardId shardId) {
    if (store.tryIncRef()) {
        logger.info("start check index");
        try {
            Directory dir = store.directory();
            if (!Lucene.indexExists(dir)) {
                return;
            }
            try (CheckIndex checkIndex = new CheckIndex(dir)) {
                BytesStreamOutput os = new BytesStreamOutput();
                PrintStream out = new PrintStream(os, false, StandardCharsets.UTF_8.name());
                checkIndex.setInfoStream(out);
                out.flush();
                CheckIndex.Status status = checkIndex.checkIndex();
                if (!status.clean) {
                    ESTestCase.checkIndexFailed = true;
                    logger.warn("check index [failure] index files={}\n{}", Arrays.toString(dir.listAll()), os.bytes().utf8ToString());
                    throw new IOException("index check failure");
                } else {
                    if (logger.isDebugEnabled()) {
                        logger.debug("check index [success]\n{}", os.bytes().utf8ToString());
                    }
                }
            } catch (LockObtainFailedException e) {
                ESTestCase.checkIndexFailed = true;
                throw new IllegalStateException("IndexWriter is still open on shard " + shardId, e);
            }
        } catch (Exception e) {
            logger.warn("failed to check index", e);
        } finally {
            logger.info("end check index");
            store.decRef();
        }
    }
}
Also used : PrintStream(java.io.PrintStream) LockObtainFailedException(org.apache.lucene.store.LockObtainFailedException) IOException(java.io.IOException) CheckIndex(org.apache.lucene.index.CheckIndex) BytesStreamOutput(org.elasticsearch.common.io.stream.BytesStreamOutput) LockObtainFailedException(org.apache.lucene.store.LockObtainFailedException) IOException(java.io.IOException) Directory(org.apache.lucene.store.Directory)

Example 2 with PrintStream

use of java.io.PrintStream in project buck by facebook.

the class AdbHelper method startActivity.

@SuppressForbidden
public int startActivity(SourcePathResolver pathResolver, HasInstallableApk hasInstallableApk, @Nullable String activity, boolean waitForDebugger) throws IOException, InterruptedException {
    // Might need the package name and activities from the AndroidManifest.
    Path pathToManifest = pathResolver.getAbsolutePath(hasInstallableApk.getApkInfo().getManifestPath());
    AndroidManifestReader reader = DefaultAndroidManifestReader.forPath(hasInstallableApk.getProjectFilesystem().resolve(pathToManifest));
    if (activity == null) {
        // Get list of activities that show up in the launcher.
        List<String> launcherActivities = reader.getLauncherActivities();
        // Sanity check.
        if (launcherActivities.isEmpty()) {
            console.printBuildFailure("No launchable activities found.");
            return 1;
        } else if (launcherActivities.size() > 1) {
            console.printBuildFailure("Default activity is ambiguous.");
            return 1;
        }
        // Construct a component for the '-n' argument of 'adb shell am start'.
        activity = reader.getPackage() + "/" + launcherActivities.get(0);
    } else if (!activity.contains("/")) {
        // If no package name was provided, assume the one in the manifest.
        activity = reader.getPackage() + "/" + activity;
    }
    final String activityToRun = activity;
    PrintStream stdOut = console.getStdOut();
    stdOut.println(String.format("Starting activity %s...", activityToRun));
    StartActivityEvent.Started started = StartActivityEvent.started(hasInstallableApk.getBuildTarget(), activityToRun);
    getBuckEventBus().post(started);
    boolean success = adbCall(new AdbHelper.AdbCallable() {

        @Override
        public boolean call(IDevice device) throws Exception {
            String err = deviceStartActivity(device, activityToRun, waitForDebugger);
            if (err != null) {
                console.printBuildFailure(err);
                return false;
            } else {
                return true;
            }
        }

        @Override
        public String toString() {
            return "start activity";
        }
    }, false);
    getBuckEventBus().post(StartActivityEvent.finished(started, success));
    return success ? 0 : 1;
}
Also used : Path(java.nio.file.Path) PrintStream(java.io.PrintStream) StartActivityEvent(com.facebook.buck.event.StartActivityEvent) IDevice(com.android.ddmlib.IDevice) AdbCommandRejectedException(com.android.ddmlib.AdbCommandRejectedException) InterruptionFailedException(com.facebook.buck.util.InterruptionFailedException) CancellationException(java.util.concurrent.CancellationException) InstallException(com.android.ddmlib.InstallException) TimeoutException(com.android.ddmlib.TimeoutException) IOException(java.io.IOException) HumanReadableException(com.facebook.buck.util.HumanReadableException) ExecutionException(java.util.concurrent.ExecutionException) ShellCommandUnresponsiveException(com.android.ddmlib.ShellCommandUnresponsiveException) SuppressForbidden(com.facebook.buck.annotations.SuppressForbidden)

Example 3 with PrintStream

use of java.io.PrintStream in project buck by facebook.

the class AdbHelper method uninstallApkFromDevice.

/**
   * Uninstalls apk from specific device. Reports success or failure to console.
   * It's currently here because it's used both by {@link com.facebook.buck.cli.InstallCommand} and
   * {@link com.facebook.buck.cli.UninstallCommand}.
   */
@SuppressWarnings("PMD.PrematureDeclaration")
@SuppressForbidden
private boolean uninstallApkFromDevice(IDevice device, String packageName, boolean keepData) {
    String name;
    if (device.isEmulator()) {
        name = device.getSerialNumber() + " (" + device.getAvdName() + ")";
    } else {
        name = device.getSerialNumber();
        String model = device.getProperty("ro.product.model");
        if (model != null) {
            name += " (" + model + ")";
        }
    }
    PrintStream stdOut = console.getStdOut();
    stdOut.printf("Removing apk from %s.\n", name);
    try {
        long start = System.currentTimeMillis();
        String reason = deviceUninstallPackage(device, packageName, keepData);
        long end = System.currentTimeMillis();
        if (reason != null) {
            console.printBuildFailure(String.format("Failed to uninstall apk from %s: %s.", name, reason));
            return false;
        }
        long delta = end - start;
        stdOut.printf("Uninstalled apk from %s in %d.%03ds.\n", name, delta / 1000, delta % 1000);
        return true;
    } catch (InstallException ex) {
        console.printBuildFailure(String.format("Failed to uninstall apk from %s.", name));
        ex.printStackTrace(console.getStdErr());
        return false;
    }
}
Also used : PrintStream(java.io.PrintStream) InstallException(com.android.ddmlib.InstallException) SuppressForbidden(com.facebook.buck.annotations.SuppressForbidden)

Example 4 with PrintStream

use of java.io.PrintStream in project elasticsearch by elastic.

the class IndexShard method doCheckIndex.

private void doCheckIndex() throws IOException {
    long timeNS = System.nanoTime();
    if (!Lucene.indexExists(store.directory())) {
        return;
    }
    BytesStreamOutput os = new BytesStreamOutput();
    PrintStream out = new PrintStream(os, false, StandardCharsets.UTF_8.name());
    if ("checksum".equals(checkIndexOnStartup)) {
        // physical verification only: verify all checksums for the latest commit
        IOException corrupt = null;
        MetadataSnapshot metadata = snapshotStoreMetadata();
        for (Map.Entry<String, StoreFileMetaData> entry : metadata.asMap().entrySet()) {
            try {
                Store.checkIntegrity(entry.getValue(), store.directory());
                out.println("checksum passed: " + entry.getKey());
            } catch (IOException exc) {
                out.println("checksum failed: " + entry.getKey());
                exc.printStackTrace(out);
                corrupt = exc;
            }
        }
        out.flush();
        if (corrupt != null) {
            logger.warn("check index [failure]\n{}", os.bytes().utf8ToString());
            throw corrupt;
        }
    } else {
        // full checkindex
        try (CheckIndex checkIndex = new CheckIndex(store.directory())) {
            checkIndex.setInfoStream(out);
            CheckIndex.Status status = checkIndex.checkIndex();
            out.flush();
            if (!status.clean) {
                if (state == IndexShardState.CLOSED) {
                    // ignore if closed....
                    return;
                }
                logger.warn("check index [failure]\n{}", os.bytes().utf8ToString());
                if ("fix".equals(checkIndexOnStartup)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("fixing index, writing new segments file ...");
                    }
                    checkIndex.exorciseIndex(status);
                    if (logger.isDebugEnabled()) {
                        logger.debug("index fixed, wrote new segments file \"{}\"", status.segmentsFileName);
                    }
                } else {
                    // only throw a failure if we are not going to fix the index
                    throw new IllegalStateException("index check failure but can't fix it");
                }
            }
        }
    }
    if (logger.isDebugEnabled()) {
        logger.debug("check index [success]\n{}", os.bytes().utf8ToString());
    }
    recoveryState.getVerifyIndex().checkIndexTime(Math.max(0, TimeValue.nsecToMSec(System.nanoTime() - timeNS)));
}
Also used : PrintStream(java.io.PrintStream) StoreFileMetaData(org.elasticsearch.index.store.StoreFileMetaData) IOException(java.io.IOException) Map(java.util.Map) BytesStreamOutput(org.elasticsearch.common.io.stream.BytesStreamOutput) CheckIndex(org.apache.lucene.index.CheckIndex) MetadataSnapshot(org.elasticsearch.index.store.Store.MetadataSnapshot)

Example 5 with PrintStream

use of java.io.PrintStream in project buck by facebook.

the class ConcatStepTest method testConcatFiles.

@Test
public void testConcatFiles() throws IOException {
    // Create three files containing "foo", "bar", and "baz"
    // and see if they are correctly concatenated.
    File dest = temp.newFile();
    ImmutableList.Builder<Path> inputsBuilder = ImmutableList.builder();
    String[] fileContents = { "foo", "bar", "baz" };
    for (int i = 0; i < fileContents.length; i++) {
        File src = temp.newFile();
        PrintStream out = new PrintStream(src);
        out.print(fileContents[i]);
        inputsBuilder.add(src.toPath());
        out.close();
    }
    ProjectFilesystem filesystem = new ProjectFilesystem(temp.getRoot().toPath());
    ExecutionContext context = TestExecutionContext.newInstance();
    ConcatStep step = new ConcatStep(filesystem, inputsBuilder.build(), dest.toPath());
    step.execute(context);
    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(dest)));
    assertEquals(reader.readLine(), "foobarbaz");
    reader.close();
}
Also used : Path(java.nio.file.Path) PrintStream(java.io.PrintStream) InputStreamReader(java.io.InputStreamReader) ImmutableList(com.google.common.collect.ImmutableList) FileInputStream(java.io.FileInputStream) ExecutionContext(com.facebook.buck.step.ExecutionContext) TestExecutionContext(com.facebook.buck.step.TestExecutionContext) BufferedReader(java.io.BufferedReader) ProjectFilesystem(com.facebook.buck.io.ProjectFilesystem) File(java.io.File) Test(org.junit.Test)

Aggregations

PrintStream (java.io.PrintStream)3915 ByteArrayOutputStream (java.io.ByteArrayOutputStream)1549 Test (org.junit.Test)1011 File (java.io.File)711 IOException (java.io.IOException)650 FileOutputStream (java.io.FileOutputStream)455 ArrayList (java.util.ArrayList)228 OutputStream (java.io.OutputStream)211 FileNotFoundException (java.io.FileNotFoundException)184 Test (org.junit.jupiter.api.Test)168 Before (org.junit.Before)165 StringWriter (java.io.StringWriter)154 InputStream (java.io.InputStream)152 WriterOutputStream (org.apache.commons.io.output.WriterOutputStream)141 BufferedReader (java.io.BufferedReader)128 Map (java.util.Map)109 InputStreamReader (java.io.InputStreamReader)104 BufferedOutputStream (java.io.BufferedOutputStream)103 Date (java.util.Date)101 HashMap (java.util.HashMap)91