Search in sources :

Example 31 with Closeable

use of java.io.Closeable in project neo4j by neo4j.

the class QueryLoggerKernelExtension method newInstance.

@Override
public Lifecycle newInstance(@SuppressWarnings("unused") KernelContext context, final Dependencies dependencies) throws Throwable {
    final Config config = dependencies.config();
    boolean queryLogEnabled = config.get(GraphDatabaseSettings.log_queries);
    final File queryLogFile = config.get(GraphDatabaseSettings.log_queries_filename);
    final FileSystemAbstraction fileSystem = dependencies.fileSystem();
    final JobScheduler jobScheduler = dependencies.jobScheduler();
    final Monitors monitoring = dependencies.monitoring();
    if (!queryLogEnabled) {
        return createEmptyAdapter();
    }
    return new LifecycleAdapter() {

        Closeable closable;

        @Override
        public void init() throws Throwable {
            Long thresholdMillis = config.get(GraphDatabaseSettings.log_queries_threshold);
            Long rotationThreshold = config.get(GraphDatabaseSettings.log_queries_rotation_threshold);
            int maxArchives = config.get(GraphDatabaseSettings.log_queries_max_archives);
            boolean logQueryParameters = config.get(GraphDatabaseSettings.log_queries_parameter_logging_enabled);
            FormattedLog.Builder logBuilder = FormattedLog.withUTCTimeZone();
            Log log;
            if (rotationThreshold == 0) {
                OutputStream logOutputStream = createOrOpenAsOuputStream(fileSystem, queryLogFile, true);
                log = logBuilder.toOutputStream(logOutputStream);
                closable = logOutputStream;
            } else {
                RotatingFileOutputStreamSupplier rotatingSupplier = new RotatingFileOutputStreamSupplier(fileSystem, queryLogFile, rotationThreshold, 0, maxArchives, jobScheduler.executor(JobScheduler.Groups.queryLogRotation));
                log = logBuilder.toOutputStream(rotatingSupplier);
                closable = rotatingSupplier;
            }
            QueryLogger logger = new QueryLogger(Clocks.systemClock(), log, thresholdMillis, logQueryParameters);
            monitoring.addMonitorListener(logger);
        }

        @Override
        public void shutdown() throws Throwable {
            closable.close();
        }
    };
}
Also used : JobScheduler(org.neo4j.kernel.impl.util.JobScheduler) FormattedLog(org.neo4j.logging.FormattedLog) FileSystemAbstraction(org.neo4j.io.fs.FileSystemAbstraction) Log(org.neo4j.logging.Log) FormattedLog(org.neo4j.logging.FormattedLog) Config(org.neo4j.kernel.configuration.Config) Closeable(java.io.Closeable) OutputStream(java.io.OutputStream) LifecycleAdapter(org.neo4j.kernel.lifecycle.LifecycleAdapter) RotatingFileOutputStreamSupplier(org.neo4j.logging.RotatingFileOutputStreamSupplier) Monitors(org.neo4j.kernel.monitoring.Monitors) File(java.io.File)

Example 32 with Closeable

use of java.io.Closeable in project presto by prestodb.

the class Verifier method run.

// Returns number of failed queries
public int run(List<QueryPair> queries) throws InterruptedException {
    ExecutorService executor = newFixedThreadPool(threadCount);
    CompletionService<Validator> completionService = new ExecutorCompletionService<>(executor);
    int totalQueries = queries.size() * config.getSuiteRepetitions();
    log.info("Total Queries:     %d", totalQueries);
    log.info("Whitelisted Queries: %s", Joiner.on(',').join(whitelist));
    int queriesSubmitted = 0;
    for (int i = 0; i < config.getSuiteRepetitions(); i++) {
        for (QueryPair query : queries) {
            for (int j = 0; j < config.getQueryRepetitions(); j++) {
                // If a whitelist exists, only run the tests on the whitelist
                if (!whitelist.isEmpty() && !whitelist.contains(query.getName())) {
                    log.debug("Query %s is not whitelisted", query.getName());
                    continue;
                }
                if (blacklist.contains(query.getName())) {
                    log.debug("Query %s is blacklisted", query.getName());
                    continue;
                }
                Validator validator = new Validator(config.getControlGateway(), config.getTestGateway(), config.getControlTimeout(), config.getTestTimeout(), config.getMaxRowCount(), config.isExplainOnly(), config.getDoublePrecision(), isCheckCorrectness(query), true, config.isVerboseResultsComparison(), config.getControlTeardownRetries(), config.getTestTeardownRetries(), query);
                completionService.submit(validator::valid, validator);
                queriesSubmitted++;
            }
        }
    }
    log.info("Allowed Queries:     %d", queriesSubmitted);
    log.info("Skipped Queries:     %d", (totalQueries - queriesSubmitted));
    log.info("---------------------");
    executor.shutdown();
    int total = 0;
    int valid = 0;
    int failed = 0;
    int skipped = 0;
    double lastProgress = 0;
    while (total < queriesSubmitted) {
        total++;
        Validator validator = takeUnchecked(completionService);
        if (validator.isSkipped()) {
            if (!config.isQuiet()) {
                log.warn("%s", validator.getSkippedMessage());
            }
            skipped++;
            continue;
        }
        if (validator.valid()) {
            valid++;
        } else {
            failed++;
        }
        for (EventClient eventClient : eventClients) {
            eventClient.post(buildEvent(validator));
        }
        double progress = (((double) total) / totalQueries) * 100;
        if (!config.isQuiet() || (progress - lastProgress) > 1) {
            log.info("Progress: %s valid, %s failed, %s skipped, %.2f%% done", valid, failed, skipped, progress);
            lastProgress = progress;
        }
    }
    log.info("Results: %s / %s (%s skipped)", valid, failed, skipped);
    log.info("");
    for (EventClient eventClient : eventClients) {
        if (eventClient instanceof Closeable) {
            try {
                ((Closeable) eventClient).close();
            } catch (IOException ignored) {
            }
            log.info("");
        }
    }
    return failed;
}
Also used : Closeable(java.io.Closeable) ExecutorService(java.util.concurrent.ExecutorService) ExecutorCompletionService(java.util.concurrent.ExecutorCompletionService) IOException(java.io.IOException) EventClient(io.airlift.event.client.EventClient)

Example 33 with Closeable

use of java.io.Closeable in project requery by requery.

the class SqlCipherMetaData method queryMemory.

@Override
protected <R> R queryMemory(Function<Cursor, R> function, String query) throws SQLException {
    try {
        final SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(":memory:", "", null);
        Cursor cursor = database.rawQuery(query, null);
        return function.apply(closeWithCursor(new Closeable() {

            @Override
            public void close() throws IOException {
                database.close();
            }
        }, cursor));
    } catch (SQLiteException e) {
        throw new SQLException(e);
    }
}
Also used : SQLiteDatabase(net.sqlcipher.database.SQLiteDatabase) SQLException(java.sql.SQLException) Closeable(java.io.Closeable) Cursor(android.database.Cursor) SQLiteException(net.sqlcipher.database.SQLiteException)

Example 34 with Closeable

use of java.io.Closeable in project byte-buddy by raphw.

the class ClassFileLocatorForJarFileTest method testJarFileClosable.

@Test
public void testJarFileClosable() throws Exception {
    JarFile jarFile = mock(JarFile.class);
    Closeable classFileLocator = new ClassFileLocator.ForJarFile(jarFile);
    classFileLocator.close();
    verify(jarFile).close();
}
Also used : Closeable(java.io.Closeable) JarFile(java.util.jar.JarFile) Test(org.junit.Test)

Example 35 with Closeable

use of java.io.Closeable in project spring-boot by spring-projects.

the class SampleBitronixApplication method main.

public static void main(String[] args) throws Exception {
    ApplicationContext context = SpringApplication.run(SampleBitronixApplication.class, args);
    AccountService service = context.getBean(AccountService.class);
    AccountRepository repository = context.getBean(AccountRepository.class);
    service.createAccountAndNotify("josh");
    System.out.println("Count is " + repository.count());
    try {
        service.createAccountAndNotify("error");
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
    System.out.println("Count is " + repository.count());
    Thread.sleep(100);
    ((Closeable) context).close();
}
Also used : ApplicationContext(org.springframework.context.ApplicationContext) Closeable(java.io.Closeable)

Aggregations

Closeable (java.io.Closeable)216 IOException (java.io.IOException)88 Test (org.junit.Test)56 ArrayList (java.util.ArrayList)29 File (java.io.File)26 HashMap (java.util.HashMap)12 VirtualFile (org.jboss.vfs.VirtualFile)12 URL (java.net.URL)9 Path (java.nio.file.Path)9 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)8 Map (java.util.Map)7 ISE (io.druid.java.util.common.ISE)6 InputStream (java.io.InputStream)6 MountHandle (org.jboss.as.server.deployment.module.MountHandle)6 ResourceRoot (org.jboss.as.server.deployment.module.ResourceRoot)6 ProgramController (co.cask.cdap.app.runtime.ProgramController)5 ProgramType (co.cask.cdap.proto.ProgramType)4 ProgramId (co.cask.cdap.proto.id.ProgramId)4 Pair (io.druid.java.util.common.Pair)4 FileOutputStream (java.io.FileOutputStream)4