Search in sources :

Example 1 with Files

use of java.nio.file.Files in project jetty.project by eclipse.

the class BaseBuilder method build.

/**
     * Build out the Base directory (if needed)
     * 
     * @return true if base directory was changed, false if left unchanged.
     * @throws IOException if unable to build
     */
public boolean build() throws IOException {
    Modules modules = startArgs.getAllModules();
    // Select all the added modules to determine which ones are newly enabled
    Set<String> newly_added = new HashSet<>();
    if (!startArgs.getStartModules().isEmpty()) {
        for (String name : startArgs.getStartModules()) {
            newly_added.addAll(modules.enable(name, "--add-to-start"));
            if (!newly_added.contains(name)) {
                Set<String> sources = modules.get(name).getEnableSources();
                sources.remove("--add-to-start");
                StartLog.info("%s already enabled by %s", name, sources);
            }
        }
    }
    if (StartLog.isDebugEnabled())
        StartLog.debug("added=%s", newly_added);
    // Check the licenses
    if (startArgs.isLicenseCheckRequired()) {
        Licensing licensing = new Licensing();
        for (String name : newly_added) licensing.addModule(modules.get(name));
        if (licensing.hasLicenses()) {
            if (startArgs.isApproveAllLicenses()) {
                StartLog.info("All Licenses Approved via Command Line Option");
            } else if (!licensing.acknowledgeLicenses()) {
                StartLog.warn(EXITING_LICENSE_NOT_ACKNOWLEDGED);
                System.exit(1);
            }
        }
    }
    // generate the files
    List<FileArg> files = new ArrayList<FileArg>();
    AtomicReference<BaseBuilder.Config> builder = new AtomicReference<>();
    AtomicBoolean modified = new AtomicBoolean();
    Path startd = getBaseHome().getBasePath("start.d");
    Path startini = getBaseHome().getBasePath("start.ini");
    if (startArgs.isCreateStartd() && !Files.exists(startd)) {
        if (FS.ensureDirectoryExists(startd)) {
            StartLog.log("MKDIR", baseHome.toShortForm(startd));
            modified.set(true);
        }
        if (Files.exists(startini)) {
            int ini = 0;
            Path startd_startini = startd.resolve("start.ini");
            while (Files.exists(startd_startini)) {
                ini++;
                startd_startini = startd.resolve("start" + ini + ".ini");
            }
            Files.move(startini, startd_startini);
            modified.set(true);
        }
    }
    if (!newly_added.isEmpty()) {
        if (Files.exists(startini) && Files.exists(startd))
            StartLog.warn("Use both %s and %s is deprecated", getBaseHome().toShortForm(startd), getBaseHome().toShortForm(startini));
        boolean useStartD = Files.exists(startd);
        builder.set(useStartD ? new StartDirBuilder(this) : new StartIniBuilder(this));
        newly_added.stream().map(n -> modules.get(n)).forEach(module -> {
            String ini = null;
            try {
                if (module.isSkipFilesValidation()) {
                    StartLog.debug("Skipping [files] validation on %s", module.getName());
                } else {
                    if (startArgs.getStartModules().contains(module.getName())) {
                        ini = builder.get().addModule(module, startArgs.getProperties());
                        if (ini != null)
                            modified.set(true);
                    }
                    for (String file : module.getFiles()) files.add(new FileArg(module, startArgs.getProperties().expand(file)));
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
            if (module.isDynamic()) {
                for (String s : module.getEnableSources()) StartLog.info("%-15s %s", module.getName(), s);
            } else if (module.isTransitive()) {
                if (module.hasIniTemplate())
                    StartLog.info("%-15s transitively enabled, ini template available with --add-to-start=%s", module.getName(), module.getName());
                else
                    StartLog.info("%-15s transitively enabled", module.getName());
            } else
                StartLog.info("%-15s initialized in %s", module.getName(), ini);
        });
    }
    files.addAll(startArgs.getFiles());
    if (!files.isEmpty() && processFileResources(files))
        modified.set(Boolean.TRUE);
    return modified.get();
}
Also used : Path(java.nio.file.Path) Files(java.nio.file.Files) StartIniBuilder(org.eclipse.jetty.start.builders.StartIniBuilder) LocalFileInitializer(org.eclipse.jetty.start.fileinits.LocalFileInitializer) Set(java.util.Set) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) IOException(java.io.IOException) BaseHomeFileInitializer(org.eclipse.jetty.start.fileinits.BaseHomeFileInitializer) TestFileInitializer(org.eclipse.jetty.start.fileinits.TestFileInitializer) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) UriFileInitializer(org.eclipse.jetty.start.fileinits.UriFileInitializer) List(java.util.List) MavenLocalRepoFileInitializer(org.eclipse.jetty.start.fileinits.MavenLocalRepoFileInitializer) URI(java.net.URI) StartDirBuilder(org.eclipse.jetty.start.builders.StartDirBuilder) Path(java.nio.file.Path) Prop(org.eclipse.jetty.start.Props.Prop) CopyOption(java.nio.file.CopyOption) ArrayList(java.util.ArrayList) AtomicReference(java.util.concurrent.atomic.AtomicReference) StartDirBuilder(org.eclipse.jetty.start.builders.StartDirBuilder) StartIniBuilder(org.eclipse.jetty.start.builders.StartIniBuilder) IOException(java.io.IOException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashSet(java.util.HashSet)

Example 2 with Files

use of java.nio.file.Files in project elasticsearch by elastic.

the class SharedClusterSnapshotRestoreIT method testGetSnapshotsRequest.

public void testGetSnapshotsRequest() throws Exception {
    final String repositoryName = "test-repo";
    final String indexName = "test-idx";
    final Client client = client();
    final Path repo = randomRepoPath();
    logger.info("-->  creating repository at {}", repo.toAbsolutePath());
    assertAcked(client.admin().cluster().preparePutRepository(repositoryName).setType("mock").setSettings(Settings.builder().put("location", repo).put("compress", false).put("chunk_size", randomIntBetween(100, 1000), ByteSizeUnit.BYTES).put("wait_after_unblock", 200)));
    logger.info("--> get snapshots on an empty repository");
    expectThrows(SnapshotMissingException.class, () -> client.admin().cluster().prepareGetSnapshots(repositoryName).addSnapshots("non-existent-snapshot").get());
    // with ignore unavailable set to true, should not throw an exception
    GetSnapshotsResponse getSnapshotsResponse = client.admin().cluster().prepareGetSnapshots(repositoryName).setIgnoreUnavailable(true).addSnapshots("non-existent-snapshot").get();
    assertThat(getSnapshotsResponse.getSnapshots().size(), equalTo(0));
    logger.info("--> creating an index and indexing documents");
    // Create index on 2 nodes and make sure each node has a primary by setting no replicas
    assertAcked(prepareCreate(indexName, 1, Settings.builder().put("number_of_replicas", 0)));
    ensureGreen();
    for (int i = 0; i < 10; i++) {
        index(indexName, "doc", Integer.toString(i), "foo", "bar" + i);
    }
    refresh();
    // make sure we return only the in-progress snapshot when taking the first snapshot on a clean repository
    // take initial snapshot with a block, making sure we only get 1 in-progress snapshot returned
    // block a node so the create snapshot operation can remain in progress
    final String initialBlockedNode = blockNodeWithIndex(repositoryName, indexName);
    ListenableActionFuture<CreateSnapshotResponse> responseListener = client.admin().cluster().prepareCreateSnapshot(repositoryName, "snap-on-empty-repo").setWaitForCompletion(false).setIndices(indexName).execute();
    // wait for block to kick in
    waitForBlock(initialBlockedNode, repositoryName, TimeValue.timeValueSeconds(60));
    getSnapshotsResponse = client.admin().cluster().prepareGetSnapshots("test-repo").setSnapshots(randomFrom("_all", "_current", "snap-on-*", "*-on-empty-repo", "snap-on-empty-repo")).get();
    assertEquals(1, getSnapshotsResponse.getSnapshots().size());
    assertEquals("snap-on-empty-repo", getSnapshotsResponse.getSnapshots().get(0).snapshotId().getName());
    // unblock node
    unblockNode(repositoryName, initialBlockedNode);
    // timeout after 10 seconds
    responseListener.actionGet(TimeValue.timeValueMillis(10000L));
    client.admin().cluster().prepareDeleteSnapshot(repositoryName, "snap-on-empty-repo").get();
    final int numSnapshots = randomIntBetween(1, 3) + 1;
    logger.info("--> take {} snapshot(s)", numSnapshots - 1);
    final String[] snapshotNames = new String[numSnapshots];
    for (int i = 0; i < numSnapshots - 1; i++) {
        final String snapshotName = randomAsciiOfLength(8).toLowerCase(Locale.ROOT);
        CreateSnapshotResponse createSnapshotResponse = client.admin().cluster().prepareCreateSnapshot(repositoryName, snapshotName).setWaitForCompletion(true).setIndices(indexName).get();
        assertThat(createSnapshotResponse.getSnapshotInfo().successfulShards(), greaterThan(0));
        snapshotNames[i] = snapshotName;
    }
    logger.info("--> take another snapshot to be in-progress");
    // add documents so there are data files to block on
    for (int i = 10; i < 20; i++) {
        index(indexName, "doc", Integer.toString(i), "foo", "bar" + i);
    }
    refresh();
    final String inProgressSnapshot = randomAsciiOfLength(8).toLowerCase(Locale.ROOT);
    snapshotNames[numSnapshots - 1] = inProgressSnapshot;
    // block a node so the create snapshot operation can remain in progress
    final String blockedNode = blockNodeWithIndex(repositoryName, indexName);
    client.admin().cluster().prepareCreateSnapshot(repositoryName, inProgressSnapshot).setWaitForCompletion(false).setIndices(indexName).get();
    // wait for block to kick in
    waitForBlock(blockedNode, repositoryName, TimeValue.timeValueSeconds(60));
    logger.info("--> get all snapshots with a current in-progress");
    // with ignore unavailable set to true, should not throw an exception
    final List<String> snapshotsToGet = new ArrayList<>();
    if (randomBoolean()) {
        // use _current plus the individual names of the finished snapshots
        snapshotsToGet.add("_current");
        for (int i = 0; i < numSnapshots - 1; i++) {
            snapshotsToGet.add(snapshotNames[i]);
        }
    } else {
        snapshotsToGet.add("_all");
    }
    getSnapshotsResponse = client.admin().cluster().prepareGetSnapshots(repositoryName).setSnapshots(snapshotsToGet.toArray(Strings.EMPTY_ARRAY)).get();
    List<String> sortedNames = Arrays.asList(snapshotNames);
    Collections.sort(sortedNames);
    assertThat(getSnapshotsResponse.getSnapshots().size(), equalTo(numSnapshots));
    assertThat(getSnapshotsResponse.getSnapshots().stream().map(s -> s.snapshotId().getName()).sorted().collect(Collectors.toList()), equalTo(sortedNames));
    getSnapshotsResponse = client.admin().cluster().prepareGetSnapshots(repositoryName).addSnapshots(snapshotNames).get();
    sortedNames = Arrays.asList(snapshotNames);
    Collections.sort(sortedNames);
    assertThat(getSnapshotsResponse.getSnapshots().size(), equalTo(numSnapshots));
    assertThat(getSnapshotsResponse.getSnapshots().stream().map(s -> s.snapshotId().getName()).sorted().collect(Collectors.toList()), equalTo(sortedNames));
    logger.info("--> make sure duplicates are not returned in the response");
    String regexName = snapshotNames[randomIntBetween(0, numSnapshots - 1)];
    final int splitPos = regexName.length() / 2;
    final String firstRegex = regexName.substring(0, splitPos) + "*";
    final String secondRegex = "*" + regexName.substring(splitPos);
    getSnapshotsResponse = client.admin().cluster().prepareGetSnapshots(repositoryName).addSnapshots(snapshotNames).addSnapshots(firstRegex, secondRegex).get();
    assertThat(getSnapshotsResponse.getSnapshots().size(), equalTo(numSnapshots));
    assertThat(getSnapshotsResponse.getSnapshots().stream().map(s -> s.snapshotId().getName()).sorted().collect(Collectors.toList()), equalTo(sortedNames));
    // unblock node
    unblockNode(repositoryName, blockedNode);
    waitForCompletion(repositoryName, inProgressSnapshot, TimeValue.timeValueSeconds(60));
}
Also used : Path(java.nio.file.Path) ShardId(org.elasticsearch.index.shard.ShardId) ByteSizeUnit(org.elasticsearch.common.unit.ByteSizeUnit) Arrays(java.util.Arrays) RestoreSnapshotResponse(org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotResponse) ClusterBlocks(org.elasticsearch.cluster.block.ClusterBlocks) ClusterState(org.elasticsearch.cluster.ClusterState) ClusterStateUpdateTask(org.elasticsearch.cluster.ClusterStateUpdateTask) Matchers.nullValue(org.hamcrest.Matchers.nullValue) Path(java.nio.file.Path) Priority(org.elasticsearch.common.Priority) GetSettingsResponse(org.elasticsearch.action.admin.indices.settings.get.GetSettingsResponse) Matchers.notNullValue(org.hamcrest.Matchers.notNullValue) TestLogging(org.elasticsearch.test.junit.annotations.TestLogging) Matchers.allOf(org.hamcrest.Matchers.allOf) DeletePipelineRequest(org.elasticsearch.action.ingest.DeletePipelineRequest) ElasticsearchAssertions.assertAliasesMissing(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAliasesMissing) Matchers.startsWith(org.hamcrest.Matchers.startsWith) ElasticsearchAssertions.assertBlocked(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertBlocked) CountDownLatch(java.util.concurrent.CountDownLatch) Stream(java.util.stream.Stream) QueryBuilders.matchQuery(org.elasticsearch.index.query.QueryBuilders.matchQuery) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) SnapshotIndexStatus(org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotIndexStatus) InvalidIndexNameException(org.elasticsearch.indices.InvalidIndexNameException) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) Matchers.is(org.hamcrest.Matchers.is) Matchers.containsString(org.hamcrest.Matchers.containsString) ShardSnapshotStatus(org.elasticsearch.cluster.SnapshotsInProgress.ShardSnapshotStatus) XContentFactory(org.elasticsearch.common.xcontent.XContentFactory) ImmutableOpenMap(org.elasticsearch.common.collect.ImmutableOpenMap) GetPipelineResponse(org.elasticsearch.action.ingest.GetPipelineResponse) ClusterService(org.elasticsearch.cluster.service.ClusterService) ArrayList(java.util.ArrayList) BytesArray(org.elasticsearch.common.bytes.BytesArray) SnapshotStatus(org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotStatus) ElasticsearchAssertions.assertIndexTemplateMissing(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertIndexTemplateMissing) Matchers.lessThan(org.hamcrest.Matchers.lessThan) IndicesService(org.elasticsearch.indices.IndicesService) FlushResponse(org.elasticsearch.action.admin.indices.flush.FlushResponse) ElasticsearchAssertions.assertThrows(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertThrows) Files(java.nio.file.Files) SETTING_NUMBER_OF_SHARDS(org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_SHARDS) Client(org.elasticsearch.client.Client) IndexService(org.elasticsearch.index.IndexService) IOUtils(org.apache.lucene.util.IOUtils) RepositoriesService(org.elasticsearch.repositories.RepositoriesService) ExecutionException(java.util.concurrent.ExecutionException) SnapshotIndexShardStage(org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotIndexShardStage) SnapshotsStatusResponse(org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotsStatusResponse) ElasticsearchAssertions.assertAcked(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked) MappingMetaData(org.elasticsearch.cluster.metadata.MappingMetaData) PutRepositoryResponse(org.elasticsearch.action.admin.cluster.repositories.put.PutRepositoryResponse) IngestTestPlugin(org.elasticsearch.ingest.IngestTestPlugin) Settings(org.elasticsearch.common.settings.Settings) Locale(java.util.Locale) SearchResponse(org.elasticsearch.action.search.SearchResponse) XContentFactory.jsonBuilder(org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder) RepositoryException(org.elasticsearch.repositories.RepositoryException) ElasticsearchAssertions.assertIndexTemplateExists(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertIndexTemplateExists) Collection(java.util.Collection) StandardOpenOption(java.nio.file.StandardOpenOption) State(org.elasticsearch.cluster.SnapshotsInProgress.State) ElasticsearchAssertions.assertHitCount(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount) GetStoredScriptResponse(org.elasticsearch.action.admin.cluster.storedscripts.GetStoredScriptResponse) BytesReference(org.elasticsearch.common.bytes.BytesReference) Collectors(java.util.stream.Collectors) ActiveShardCount(org.elasticsearch.action.support.ActiveShardCount) SeekableByteChannel(java.nio.channels.SeekableByteChannel) List(java.util.List) Version(org.elasticsearch.Version) IndexRequestBuilder(org.elasticsearch.action.index.IndexRequestBuilder) IndexRoutingTable(org.elasticsearch.cluster.routing.IndexRoutingTable) MockScriptEngine(org.elasticsearch.script.MockScriptEngine) Matchers.equalTo(org.hamcrest.Matchers.equalTo) ElasticsearchAssertions.assertAliasesExist(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAliasesExist) CreateSnapshotResponse(org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotResponse) RepositoryData(org.elasticsearch.repositories.RepositoryData) XContentType(org.elasticsearch.common.xcontent.XContentType) ListenableActionFuture(org.elasticsearch.action.ListenableActionFuture) IndexId(org.elasticsearch.repositories.IndexId) Entry(org.elasticsearch.cluster.SnapshotsInProgress.Entry) Strings(org.elasticsearch.common.Strings) SETTING_NUMBER_OF_REPLICAS(org.elasticsearch.cluster.metadata.IndexMetaData.SETTING_NUMBER_OF_REPLICAS) SnapshotIndexShardStatus(org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotIndexShardStatus) TimeValue(org.elasticsearch.common.unit.TimeValue) GetSnapshotsResponse(org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsResponse) Plugin(org.elasticsearch.plugins.Plugin) MockRepository(org.elasticsearch.snapshots.mockstore.MockRepository) INDEX_REFRESH_INTERVAL_SETTING(org.elasticsearch.index.IndexSettings.INDEX_REFRESH_INTERVAL_SETTING) ClusterStateResponse(org.elasticsearch.action.admin.cluster.state.ClusterStateResponse) GetIndexTemplatesResponse(org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesResponse) TimeUnit(java.util.concurrent.TimeUnit) ExceptionsHelper(org.elasticsearch.ExceptionsHelper) SnapshotsInProgress(org.elasticsearch.cluster.SnapshotsInProgress) ElasticsearchAssertions.assertAllSuccessful(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAllSuccessful) StoredScriptsIT(org.elasticsearch.script.StoredScriptsIT) Collections(java.util.Collections) MetaDataIndexStateService(org.elasticsearch.cluster.metadata.MetaDataIndexStateService) ElasticsearchAssertions.assertNoFailures(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures) GetSnapshotsResponse(org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsResponse) CreateSnapshotResponse(org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotResponse) ArrayList(java.util.ArrayList) Matchers.containsString(org.hamcrest.Matchers.containsString) Client(org.elasticsearch.client.Client)

Example 3 with Files

use of java.nio.file.Files in project buck by facebook.

the class ClassesImpl method createJar.

@Override
public void createJar(Path jarPath) throws IOException {
    try (JarOutputStream jar = new JarOutputStream(Files.newOutputStream(jarPath))) {
        List<Path> files = Files.walk(root.getRoot().toPath()).filter(path -> path.toFile().isFile()).collect(Collectors.toList());
        for (Path file : files) {
            ZipEntry entry = new ZipEntry(MorePaths.pathWithUnixSeparators(root.getRoot().toPath().relativize(file)));
            jar.putNextEntry(entry);
            ByteStreams.copy(Files.newInputStream(file), jar);
            jar.closeEntry();
        }
    }
}
Also used : Files(java.nio.file.Files) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) File(java.io.File) MorePaths(com.facebook.buck.io.MorePaths) List(java.util.List) ClassReader(org.objectweb.asm.ClassReader) ByteStreams(com.google.common.io.ByteStreams) ClassVisitor(org.objectweb.asm.ClassVisitor) Path(java.nio.file.Path) JarOutputStream(java.util.jar.JarOutputStream) ZipEntry(java.util.zip.ZipEntry) TemporaryFolder(org.junit.rules.TemporaryFolder) InputStream(java.io.InputStream) Path(java.nio.file.Path) ZipEntry(java.util.zip.ZipEntry) JarOutputStream(java.util.jar.JarOutputStream)

Example 4 with Files

use of java.nio.file.Files in project opennms by OpenNMS.

the class NewtsConverter method processStringsProperties.

private void processStringsProperties(final Path path) {
    try {
        // Find an process all 'strings.properties' files
        Files.walk(path).filter(p -> p.endsWith("strings.properties")).forEach(p -> {
            final Properties properties = new Properties();
            try (final BufferedReader r = Files.newBufferedReader(p)) {
                properties.load(r);
            } catch (final IOException e) {
                throw Throwables.propagate(e);
            }
            final ResourcePath resourcePath = buildResourcePath(p.getParent());
            if (resourcePath == null) {
                return;
            }
            this.injectStringPropertiesToNewts(resourcePath, Maps.fromProperties(properties));
        });
    } catch (Exception e) {
        LOG.error("Error while reading string.properties", e);
        return;
    }
}
Also used : Connection(java.sql.Connection) LoggerFactory(org.slf4j.LoggerFactory) NewtsUtils(org.opennms.netmgt.newts.support.NewtsUtils) SampleRepository(org.opennms.newts.api.SampleRepository) BigDecimal(java.math.BigDecimal) Optional(com.google.common.base.Optional) Counter(org.opennms.newts.api.Counter) ResultSet(java.sql.ResultSet) Map(java.util.Map) Path(java.nio.file.Path) Resource(org.opennms.newts.api.Resource) ValueType(org.opennms.newts.api.ValueType) AbstractDS(org.opennms.netmgt.rrd.model.AbstractDS) Sets(com.google.common.collect.Sets) Indexer(org.opennms.newts.api.search.Indexer) List(java.util.List) PeriodFormatterBuilder(org.joda.time.format.PeriodFormatterBuilder) ParseException(org.apache.commons.cli.ParseException) ResourcePath(org.opennms.netmgt.model.ResourcePath) RrdConvertUtils(org.opennms.netmgt.rrd.model.RrdConvertUtils) FilenameUtils(org.apache.commons.io.FilenameUtils) SortedMap(java.util.SortedMap) Iterables(com.google.common.collect.Iterables) UnsignedLong(com.google.common.primitives.UnsignedLong) Options(org.apache.commons.cli.Options) HelpFormatter(org.apache.commons.cli.HelpFormatter) PeriodFormatter(org.joda.time.format.PeriodFormatter) MetricType(org.opennms.newts.api.MetricType) AbstractRRD(org.opennms.netmgt.rrd.model.AbstractRRD) ArrayList(java.util.ArrayList) Interval(org.joda.time.Interval) Lists(com.google.common.collect.Lists) CommandLine(org.apache.commons.cli.CommandLine) ClassPathXmlApplicationContext(org.springframework.context.support.ClassPathXmlApplicationContext) Sample(org.opennms.newts.api.Sample) PosixParser(org.apache.commons.cli.PosixParser) Option(org.apache.commons.cli.Option) ExecutorService(java.util.concurrent.ExecutorService) Period(org.joda.time.Period) Logger(org.slf4j.Logger) Properties(java.util.Properties) CommandLineParser(org.apache.commons.cli.CommandLineParser) Files(java.nio.file.Files) Throwables(com.google.common.base.Throwables) IOException(java.io.IOException) Maps(com.google.common.collect.Maps) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) Paths(java.nio.file.Paths) ForkJoinPool(java.util.concurrent.ForkJoinPool) Timestamp(org.opennms.newts.api.Timestamp) Statement(java.sql.Statement) DataSourceFactory(org.opennms.core.db.DataSourceFactory) BufferedReader(java.io.BufferedReader) Gauge(org.opennms.newts.api.Gauge) ResourcePath(org.opennms.netmgt.model.ResourcePath) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException) Properties(java.util.Properties) ParseException(org.apache.commons.cli.ParseException) IOException(java.io.IOException)

Example 5 with Files

use of java.nio.file.Files in project jdk8u_jdk by JetBrains.

the class Compiler method compileOne.

private File compileOne(Type type) {
    if (this.flags.contains(Flags.USECACHE)) {
        File dir = cache.get(type.getName());
        if (dir != null) {
            return dir;
        }
    }
    List<JavaFileObject> files = new ArrayList<>();
    SourceProcessor accum = (name, src) -> files.add(new SourceFile(name, src));
    for (Type dep : type.typeDependencies()) {
        dep.generateAsDependency(accum, type.methodDependencies());
    }
    type.generate(accum);
    JavacTask ct = (JavacTask) this.systemJavaCompiler.getTask(null, this.fm, null, null, null, files);
    File destDir = null;
    do {
        int value = counter.incrementAndGet();
        destDir = new File(root, Integer.toString(value));
    } while (destDir.exists());
    if (this.flags.contains(Flags.VERBOSE)) {
        System.out.println("Compilation unit for " + type.getName() + " : compiled into " + destDir);
        for (JavaFileObject jfo : files) {
            System.out.println(jfo.toString());
        }
    }
    try {
        destDir.mkdirs();
        this.fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(destDir));
    } catch (IOException e) {
        throw new RuntimeException("IOException encountered during compilation");
    }
    Boolean result = ct.call();
    if (result == Boolean.FALSE) {
        throw new RuntimeException("Compilation failure in " + type.getName() + " unit");
    }
    if (this.flags.contains(Flags.USECACHE)) {
        File existing = cache.putIfAbsent(type.getName(), destDir);
        if (existing != null) {
            deleteDir(destDir);
            return existing;
        }
    } else {
        this.tempDirs.add(destDir);
    }
    return destDir;
}
Also used : java.util(java.util) Type(separate.SourceModel.Type) JavacTask(com.sun.source.util.JavacTask) Files(java.nio.file.Files) javax.tools(javax.tools) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Class(separate.SourceModel.Class) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) FileVisitResult(java.nio.file.FileVisitResult) java.io(java.io) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SourceProcessor(separate.SourceModel.SourceProcessor) URI(java.net.URI) Path(java.nio.file.Path) Extends(separate.SourceModel.Extends) SimpleFileVisitor(java.nio.file.SimpleFileVisitor) SourceProcessor(separate.SourceModel.SourceProcessor) Type(separate.SourceModel.Type) JavacTask(com.sun.source.util.JavacTask)

Aggregations

Files (java.nio.file.Files)243 IOException (java.io.IOException)210 Path (java.nio.file.Path)196 List (java.util.List)176 Collectors (java.util.stream.Collectors)154 Paths (java.nio.file.Paths)133 File (java.io.File)127 ArrayList (java.util.ArrayList)117 Map (java.util.Map)109 Set (java.util.Set)96 Collections (java.util.Collections)89 Arrays (java.util.Arrays)81 Stream (java.util.stream.Stream)77 HashMap (java.util.HashMap)74 HashSet (java.util.HashSet)58 InputStream (java.io.InputStream)55 Collection (java.util.Collection)55 Logger (org.slf4j.Logger)54 Pattern (java.util.regex.Pattern)53 Optional (java.util.Optional)51