Search in sources :

Example 51 with Files

use of java.nio.file.Files in project component-runtime by Talend.

the class BaseSpark method submitClasspath.

/**
 * Same as {@link BaseSpark#submit(Class, String...)} but automatically
 * set {@code --jars} arguments and bundle on the fly folders into jars.
 *
 * @param main
 * the main to execute.
 * @param args
 * potential arguments to pass to spark submit.
 */
public void submitClasspath(final Class<?> main, final Predicate<File> classpathFilter, final String... args) {
    final Set<File> files;
    try {
        final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
        files = new UrlSet(ClassLoaders.findUrls(contextClassLoader)).excludeJvm().getUrls().stream().map(ClassLoaders::toFile).collect(toSet());
    } catch (final IOException e) {
        throw new IllegalArgumentException(e);
    }
    final String classpath = files.stream().filter(classpathFilter).map(file -> {
        if (file.isDirectory()) {
            // bundle it to let spark submit it
            return config.get().jarCache.computeIfAbsent(file, dir -> {
                final File cache = new File(getRoot(), file.getName() + "_generated_" + System.nanoTime() + ".jar");
                try (final JarOutputStream out = new JarOutputStream(new FileOutputStream(cache))) {
                    zip(file, out, "");
                } catch (final IOException e) {
                    fail(e.getMessage());
                }
                return cache;
            }).getAbsolutePath();
        }
        return file.getAbsolutePath();
    }).collect(joining(File.pathSeparator));
    submit(main, Stream.concat(args == null ? Stream.empty() : Stream.of(args), Stream.of("--jars", classpath)).toArray(String[]::new));
}
Also used : AcceptScopesStrategy(org.jboss.shrinkwrap.resolver.api.maven.strategy.AcceptScopesStrategy) URL(java.net.URL) MavenResolutionStrategy(org.jboss.shrinkwrap.resolver.api.maven.strategy.MavenResolutionStrategy) Optional.of(java.util.Optional.of) LoggerFactory(org.slf4j.LoggerFactory) SparkClusterRule(org.talend.sdk.component.runtime.testing.spark.SparkClusterRule) BooleanSupplier(java.util.function.BooleanSupplier) InetAddress(java.net.InetAddress) ServerSocket(java.net.ServerSocket) Maven(org.jboss.shrinkwrap.resolver.api.maven.Maven) Arrays.asList(java.util.Arrays.asList) Map(java.util.Map) Thread.sleep(java.lang.Thread.sleep) ENGLISH(java.util.Locale.ENGLISH) Path(java.nio.file.Path) ZipEntry(java.util.zip.ZipEntry) Collectors.toSet(java.util.stream.Collectors.toSet) ScopeType(org.jboss.shrinkwrap.resolver.api.maven.ScopeType) Predicate(java.util.function.Predicate) Collection(java.util.Collection) StandardOpenOption(java.nio.file.StandardOpenOption) Set(java.util.Set) Collectors.joining(java.util.stream.Collectors.joining) StandardCharsets(java.nio.charset.StandardCharsets) CountDownLatch(java.util.concurrent.CountDownLatch) List(java.util.List) ClassLoaders(org.apache.ziplock.ClassLoaders) Stream(java.util.stream.Stream) ConfigurableMavenResolverSystem(org.jboss.shrinkwrap.resolver.api.maven.ConfigurableMavenResolverSystem) Optional(java.util.Optional) IntStream(java.util.stream.IntStream) Socket(java.net.Socket) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Getter(lombok.Getter) HashMap(java.util.HashMap) StandardCopyOption(java.nio.file.StandardCopyOption) ArrayList(java.util.ArrayList) UrlSet(org.apache.xbean.finder.UrlSet) JarEntry(java.util.jar.JarEntry) JarOutputStream(java.util.jar.JarOutputStream) OutputStream(java.io.OutputStream) Logger(org.slf4j.Logger) MalformedURLException(java.net.MalformedURLException) Files(java.nio.file.Files) Optional.ofNullable(java.util.Optional.ofNullable) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) Collectors.toList(java.util.stream.Collectors.toList) JarLocation.jarLocation(org.apache.ziplock.JarLocation.jarLocation) AllArgsConstructor(lombok.AllArgsConstructor) InputStream(java.io.InputStream) ClassLoaders(org.apache.ziplock.ClassLoaders) UrlSet(org.apache.xbean.finder.UrlSet) FileOutputStream(java.io.FileOutputStream) JarOutputStream(java.util.jar.JarOutputStream) IOException(java.io.IOException) File(java.io.File)

Example 52 with Files

use of java.nio.file.Files in project samza by apache.

the class BlobStoreRestoreManager method deleteUnusedStoresFromBlobStore.

/**
 * Deletes blob store contents for stores that were present in the last checkpoint but are either no longer
 * present in job configs (removed by user since last deployment) or are no longer configured to be backed
 * up using blob stores.
 *
 * This method blocks until all the necessary store contents and snapshot index blobs have been marked for deletion.
 */
@VisibleForTesting
static void deleteUnusedStoresFromBlobStore(String jobName, String jobId, String taskName, StorageConfig storageConfig, BlobStoreConfig blobStoreConfig, Map<String, Pair<String, SnapshotIndex>> initialStoreSnapshotIndexes, BlobStoreUtil blobStoreUtil, ExecutorService executor) {
    List<String> storesToBackup = storageConfig.getStoresWithBackupFactory(BlobStoreStateBackendFactory.class.getName());
    List<String> storesToRestore = storageConfig.getStoresWithRestoreFactory(BlobStoreStateBackendFactory.class.getName());
    List<CompletionStage<Void>> storeDeletionFutures = new ArrayList<>();
    initialStoreSnapshotIndexes.forEach((storeName, scmAndSnapshotIndex) -> {
        if (!storesToBackup.contains(storeName) && !storesToRestore.contains(storeName)) {
            LOG.debug("Removing task: {} store: {} from blob store. It is either no longer used, " + "or is no longer configured to be backed up or restored with blob store.", taskName, storeName);
            DirIndex dirIndex = scmAndSnapshotIndex.getRight().getDirIndex();
            Metadata requestMetadata = new Metadata(Metadata.SNAPSHOT_INDEX_PAYLOAD_PATH, Optional.empty(), jobName, jobId, taskName, storeName);
            CompletionStage<Void> storeDeletionFuture = // delete files and sub-dirs previously marked for removal
            blobStoreUtil.cleanUpDir(dirIndex, requestMetadata).thenComposeAsync(v -> blobStoreUtil.deleteDir(dirIndex, requestMetadata), // deleted files and dirs still present
            executor).thenComposeAsync(v -> blobStoreUtil.deleteSnapshotIndexBlob(scmAndSnapshotIndex.getLeft(), requestMetadata), // delete the snapshot index blob
            executor);
            storeDeletionFutures.add(storeDeletionFuture);
        }
    });
    FutureUtil.allOf(storeDeletionFutures).join();
}
Also used : BlobStoreRestoreManagerMetrics(org.apache.samza.storage.blobstore.metrics.BlobStoreRestoreManagerMetrics) DirIndex(org.apache.samza.storage.blobstore.index.DirIndex) LoggerFactory(org.slf4j.LoggerFactory) JobConfig(org.apache.samza.config.JobConfig) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) TaskModel(org.apache.samza.job.model.TaskModel) ArrayList(java.util.ArrayList) FileUtil(org.apache.samza.util.FileUtil) Pair(org.apache.commons.lang3.tuple.Pair) Map(java.util.Map) Path(java.nio.file.Path) ExecutorService(java.util.concurrent.ExecutorService) FutureUtil(org.apache.samza.util.FutureUtil) StorageConfig(org.apache.samza.config.StorageConfig) ImmutableSet(com.google.common.collect.ImmutableSet) TaskName(org.apache.samza.container.TaskName) Logger(org.slf4j.Logger) BlobStoreUtil(org.apache.samza.storage.blobstore.util.BlobStoreUtil) Files(java.nio.file.Files) StorageManagerUtil(org.apache.samza.storage.StorageManagerUtil) Set(java.util.Set) IOException(java.io.IOException) FileUtils(org.apache.commons.io.FileUtils) Checkpoint(org.apache.samza.checkpoint.Checkpoint) File(java.io.File) SamzaException(org.apache.samza.SamzaException) CheckpointId(org.apache.samza.checkpoint.CheckpointId) List(java.util.List) TaskMode(org.apache.samza.job.model.TaskMode) CompletionStage(java.util.concurrent.CompletionStage) TaskRestoreManager(org.apache.samza.storage.TaskRestoreManager) SnapshotIndex(org.apache.samza.storage.blobstore.index.SnapshotIndex) Paths(java.nio.file.Paths) Optional(java.util.Optional) DirDiffUtil(org.apache.samza.storage.blobstore.util.DirDiffUtil) VisibleForTesting(com.google.common.annotations.VisibleForTesting) BlobStoreConfig(org.apache.samza.config.BlobStoreConfig) Config(org.apache.samza.config.Config) ArrayList(java.util.ArrayList) DirIndex(org.apache.samza.storage.blobstore.index.DirIndex) CompletionStage(java.util.concurrent.CompletionStage) VisibleForTesting(com.google.common.annotations.VisibleForTesting)

Example 53 with Files

use of java.nio.file.Files in project samza by apache.

the class TestBlobStoreUtil method testRestoreDirRestoresMultiPartFilesCorrectly.

@Test
public void testRestoreDirRestoresMultiPartFilesCorrectly() throws IOException {
    Path restoreDirBasePath = Files.createTempDirectory(BlobStoreTestUtil.TEMP_DIR_PREFIX);
    // remote file == 26 blobs, blob ids from a to z, blob contents from a to z, offsets 0 to 25.
    DirIndex mockDirIndex = mock(DirIndex.class);
    when(mockDirIndex.getDirName()).thenReturn(DirIndex.ROOT_DIR_NAME);
    FileIndex mockFileIndex = mock(FileIndex.class);
    when(mockFileIndex.getFileName()).thenReturn("1.sst");
    // setup mock file attributes. create a temp file to get current user/group/permissions so that they
    // match with restored files.
    File tmpFile = Paths.get(restoreDirBasePath.toString(), "tempfile-" + new Random().nextInt()).toFile();
    tmpFile.createNewFile();
    PosixFileAttributes attrs = Files.readAttributes(tmpFile.toPath(), PosixFileAttributes.class);
    FileMetadata fileMetadata = new // ctime mtime does not matter. size == 26
    FileMetadata(// ctime mtime does not matter. size == 26
    1234L, // ctime mtime does not matter. size == 26
    1243L, // ctime mtime does not matter. size == 26
    26, attrs.owner().getName(), attrs.group().getName(), PosixFilePermissions.toString(attrs.permissions()));
    when(mockFileIndex.getFileMetadata()).thenReturn(fileMetadata);
    // delete so that it doesn't show up in restored dir contents.
    Files.delete(tmpFile.toPath());
    List<FileBlob> mockFileBlobs = new ArrayList<>();
    StringBuilder fileContents = new StringBuilder();
    for (int i = 0; i < 26; i++) {
        FileBlob mockFileBlob = mock(FileBlob.class);
        char c = (char) ('a' + i);
        // blob contents == blobId
        fileContents.append(c);
        when(mockFileBlob.getBlobId()).thenReturn(String.valueOf(c));
        when(mockFileBlob.getOffset()).thenReturn(i);
        mockFileBlobs.add(mockFileBlob);
    }
    when(mockFileIndex.getBlobs()).thenReturn(mockFileBlobs);
    CRC32 checksum = new CRC32();
    checksum.update(fileContents.toString().getBytes());
    when(mockFileIndex.getChecksum()).thenReturn(checksum.getValue());
    when(mockDirIndex.getFilesPresent()).thenReturn(ImmutableList.of(mockFileIndex));
    BlobStoreManager mockBlobStoreManager = mock(BlobStoreManager.class);
    when(mockBlobStoreManager.get(anyString(), any(OutputStream.class), any(Metadata.class))).thenAnswer((Answer<CompletionStage<Void>>) invocationOnMock -> {
        String blobId = invocationOnMock.getArgumentAt(0, String.class);
        OutputStream outputStream = invocationOnMock.getArgumentAt(1, OutputStream.class);
        outputStream.write(blobId.getBytes());
        ((FileOutputStream) outputStream).getFD().sync();
        return CompletableFuture.completedFuture(null);
    });
    BlobStoreUtil blobStoreUtil = new BlobStoreUtil(mockBlobStoreManager, EXECUTOR, null, null);
    blobStoreUtil.restoreDir(restoreDirBasePath.toFile(), mockDirIndex, metadata).join();
    assertTrue(new DirDiffUtil().areSameDir(Collections.emptySet(), false).test(restoreDirBasePath.toFile(), mockDirIndex));
}
Also used : Path(java.nio.file.Path) SortedSet(java.util.SortedSet) FileMetadata(org.apache.samza.storage.blobstore.index.FileMetadata) FileTime(java.nio.file.attribute.FileTime) TimeoutException(java.util.concurrent.TimeoutException) Random(java.util.Random) RetriableException(org.apache.samza.storage.blobstore.exceptions.RetriableException) FileUtil(org.apache.samza.util.FileUtil) Pair(org.apache.commons.lang3.tuple.Pair) Map(java.util.Map) Path(java.nio.file.Path) FutureUtil(org.apache.samza.util.FutureUtil) ImmutableSet(com.google.common.collect.ImmutableSet) PosixFileAttributes(java.nio.file.attribute.PosixFileAttributes) ImmutableMap(com.google.common.collect.ImmutableMap) Set(java.util.Set) CompletionException(java.util.concurrent.CompletionException) Checkpoint(org.apache.samza.checkpoint.Checkpoint) DirDiff(org.apache.samza.storage.blobstore.diff.DirDiff) CheckpointId(org.apache.samza.checkpoint.CheckpointId) IOUtils(org.apache.commons.io.IOUtils) List(java.util.List) CompletionStage(java.util.concurrent.CompletionStage) SnapshotIndex(org.apache.samza.storage.blobstore.index.SnapshotIndex) Optional(java.util.Optional) RandomStringUtils(org.apache.commons.lang3.RandomStringUtils) SnapshotMetadata(org.apache.samza.storage.blobstore.index.SnapshotMetadata) MoreExecutors(com.google.common.util.concurrent.MoreExecutors) DirIndex(org.apache.samza.storage.blobstore.index.DirIndex) FileBlob(org.apache.samza.storage.blobstore.index.FileBlob) Matchers(org.mockito.Matchers) CheckpointV2(org.apache.samza.checkpoint.CheckpointV2) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Answer(org.mockito.stubbing.Answer) PosixFilePermissions(java.nio.file.attribute.PosixFilePermissions) ArgumentCaptor(org.mockito.ArgumentCaptor) ImmutableList(com.google.common.collect.ImmutableList) BlobStoreManager(org.apache.samza.storage.blobstore.BlobStoreManager) BlobStoreStateBackendFactory(org.apache.samza.storage.blobstore.BlobStoreStateBackendFactory) ExecutorService(java.util.concurrent.ExecutorService) OutputStream(java.io.OutputStream) FileIndex(org.apache.samza.storage.blobstore.index.FileIndex) Files(java.nio.file.Files) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) FileUtils(org.apache.commons.io.FileUtils) Test(org.junit.Test) Metadata(org.apache.samza.storage.blobstore.Metadata) File(java.io.File) SamzaException(org.apache.samza.SamzaException) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Mockito(org.mockito.Mockito) Ignore(org.junit.Ignore) Paths(java.nio.file.Paths) NullOutputStream(org.apache.commons.io.output.NullOutputStream) CRC32(java.util.zip.CRC32) Assert(org.junit.Assert) Collections(java.util.Collections) InputStream(java.io.InputStream) DeletedException(org.apache.samza.storage.blobstore.exceptions.DeletedException) FileBlob(org.apache.samza.storage.blobstore.index.FileBlob) CRC32(java.util.zip.CRC32) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) NullOutputStream(org.apache.commons.io.output.NullOutputStream) FileMetadata(org.apache.samza.storage.blobstore.index.FileMetadata) ArrayList(java.util.ArrayList) FileMetadata(org.apache.samza.storage.blobstore.index.FileMetadata) SnapshotMetadata(org.apache.samza.storage.blobstore.index.SnapshotMetadata) Metadata(org.apache.samza.storage.blobstore.Metadata) BlobStoreManager(org.apache.samza.storage.blobstore.BlobStoreManager) Checkpoint(org.apache.samza.checkpoint.Checkpoint) FileIndex(org.apache.samza.storage.blobstore.index.FileIndex) Random(java.util.Random) FileOutputStream(java.io.FileOutputStream) DirIndex(org.apache.samza.storage.blobstore.index.DirIndex) PosixFileAttributes(java.nio.file.attribute.PosixFileAttributes) File(java.io.File) CompletionStage(java.util.concurrent.CompletionStage) Test(org.junit.Test)

Example 54 with Files

use of java.nio.file.Files in project FXyzLib by Birdasaur.

the class CSVScatter3DTest method start.

@Override
public void start(Stage primaryStage) throws Exception {
    Group sceneRoot = new Group();
    Scene scene = new Scene(sceneRoot, sceneWidth, sceneHeight, true, SceneAntialiasing.BALANCED);
    scene.setFill(Color.BLACK);
    camera = new PerspectiveCamera(true);
    // setup camera transform for rotational support
    cameraTransform.setTranslate(0, 0, 0);
    cameraTransform.getChildren().add(camera);
    camera.setNearClip(0.1);
    camera.setFarClip(10000.0);
    camera.setTranslateX(0);
    camera.setTranslateZ(-1000);
    cameraTransform.ry.setAngle(-25.0);
    cameraTransform.rx.setAngle(-10.0);
    // add a Point Light for better viewing of the grid coordinate system
    PointLight light = new PointLight(Color.WHITE);
    cameraTransform.getChildren().add(new AmbientLight());
    light.setTranslateX(camera.getTranslateX());
    light.setTranslateY(camera.getTranslateY());
    light.setTranslateZ(camera.getTranslateZ());
    scene.setCamera(camera);
    long time = System.currentTimeMillis();
    Group group = new Group(cameraTransform);
    List<Point3D> data = new ArrayList<>();
    // // create some data
    // IntStream.range(0,100000)
    // .forEach(i->data.add(new Point3D((float)(30*Math.sin(50*i)),
    // (float)(Math.sin(i)*(100+30*Math.cos(100*i))),
    // (float)(Math.cos(i)*(100+30*Math.cos(200*i))),
    // i))); // <-- f
    // // and write to csv file
    // Path out = Paths.get("output.txt");
    // Files.write(out,data.stream().map(p3d->p3d.toCSV()).collect(Collectors.toList()),Charset.defaultCharset());
    // read from csv file
    Path out = getCSVFile(0);
    if (out != null) {
        Files.lines(out).map(s -> s.split(";")).forEach(s -> data.add(new Point3D(Float.parseFloat(s[0]), Float.parseFloat(s[1]), Float.parseFloat(s[2]), Float.parseFloat(s[3]))));
    }
    ScatterMesh scatter = new ScatterMesh(data, true, 1, 0);
    // DENSITY
    // texture is given by p.f value, don't change this!
    scatter.setTextureModeVertices3D(1530, p -> p.f);
    group.getChildren().add(scatter);
    sceneRoot.getChildren().addAll(group);
    // First person shooter keyboard movement
    scene.setOnKeyPressed(event -> {
        double change = 10.0;
        // Add shift modifier to simulate "Running Speed"
        if (event.isShiftDown()) {
            change = 50.0;
        }
        // What key did the user press?
        KeyCode keycode = event.getCode();
        // Step 2c: Add Zoom controls
        if (keycode == KeyCode.W) {
            camera.setTranslateZ(camera.getTranslateZ() + change);
        }
        if (keycode == KeyCode.S) {
            camera.setTranslateZ(camera.getTranslateZ() - change);
        }
        // Step 2d:  Add Strafe controls
        if (keycode == KeyCode.A) {
            camera.setTranslateX(camera.getTranslateX() - change);
        }
        if (keycode == KeyCode.D) {
            camera.setTranslateX(camera.getTranslateX() + change);
        }
    });
    scene.setOnMousePressed((MouseEvent me) -> {
        mousePosX = me.getSceneX();
        mousePosY = me.getSceneY();
        mouseOldX = me.getSceneX();
        mouseOldY = me.getSceneY();
    });
    scene.setOnMouseDragged((MouseEvent me) -> {
        mouseOldX = mousePosX;
        mouseOldY = mousePosY;
        mousePosX = me.getSceneX();
        mousePosY = me.getSceneY();
        mouseDeltaX = (mousePosX - mouseOldX);
        mouseDeltaY = (mousePosY - mouseOldY);
        double modifier = 10.0;
        double modifierFactor = 0.1;
        if (me.isControlDown()) {
            modifier = 0.1;
        }
        if (me.isShiftDown()) {
            modifier = 50.0;
        }
        if (me.isPrimaryButtonDown()) {
            // +
            cameraTransform.ry.setAngle(((cameraTransform.ry.getAngle() + mouseDeltaX * modifierFactor * modifier * 2.0) % 360 + 540) % 360 - 180);
            // -
            cameraTransform.rx.setAngle(((cameraTransform.rx.getAngle() - mouseDeltaY * modifierFactor * modifier * 2.0) % 360 + 540) % 360 - 180);
        } else if (me.isSecondaryButtonDown()) {
            double z = camera.getTranslateZ();
            double newZ = z + mouseDeltaX * modifierFactor * modifier;
            camera.setTranslateZ(newZ);
        } else if (me.isMiddleButtonDown()) {
            // -
            cameraTransform.t.setX(cameraTransform.t.getX() + mouseDeltaX * modifierFactor * modifier * 0.3);
            // -
            cameraTransform.t.setY(cameraTransform.t.getY() + mouseDeltaY * modifierFactor * modifier * 0.3);
        }
    });
    primaryStage.setTitle("F(X)yz - ScatterMesh Test");
    primaryStage.setScene(scene);
    primaryStage.show();
    final boolean constantVertices = true;
    lastEffect = System.nanoTime();
    AtomicInteger count = new AtomicInteger(0);
    List<List<Number>> fullData = new ArrayList<>();
    if (constantVertices) {
        // if possible we can cache all the data
        Stream.of(0, 1, 2, 3, 4, 3, 2, 1).forEach(i -> {
            Path out2 = getCSVFile(i);
            if (out2 != null) {
                try {
                    List<Number> data2 = new ArrayList<>();
                    Files.lines(out2).map(s -> s.split(";")).forEach(s -> {
                        float f = Float.parseFloat(s[3]);
                        // 4 vertices tetrahedra
                        data2.add(f);
                        data2.add(f);
                        data2.add(f);
                        data2.add(f);
                    });
                    fullData.add(data2);
                } catch (IOException ex) {
                }
            }
        });
    }
    AnimationTimer timerEffect = new AnimationTimer() {

        @Override
        public void handle(long now) {
            if (now > lastEffect + 50_000_000l) {
                try {
                    // long t=System.currentTimeMillis();
                    if (constantVertices && fullData != null) {
                        // Vertices coordinates are always the same: mesh is tha same, we only
                        // need to update F on each element
                        scatter.setFunctionData(fullData.get(count.get() % 8));
                    // System.out.println("t "+(System.currentTimeMillis()-t));
                    } else {
                        // vertices coordinates may change in time, we need to create them all over again reading the files:
                        Path out2 = getCSVFile((int) (Stream.of(0, 1, 2, 3, 4, 3, 2, 1).toArray()[count.get() % 8]));
                        if (out2 != null) {
                            List<Point3D> data2 = new ArrayList<>();
                            Files.lines(out2).map(s -> s.split(";")).forEach(s -> data2.add(new Point3D(Float.parseFloat(s[0]), Float.parseFloat(s[1]), Float.parseFloat(s[2]), Float.parseFloat(s[3]))));
                            scatter.setScatterData(data2);
                            scatter.setTextureModeVertices1D(1530, p -> p);
                        }
                    // System.out.println("t "+(System.currentTimeMillis()-t));
                    }
                } catch (IOException ex) {
                }
                count.getAndIncrement();
                lastEffect = now;
            }
        }
    };
    timerEffect.start();
}
Also used : Path(java.nio.file.Path) Scene(javafx.scene.Scene) ScatterMesh(org.fxyz.shapes.primitives.ScatterMesh) Palette(org.fxyz.utils.Palette) URISyntaxException(java.net.URISyntaxException) MouseEvent(javafx.scene.input.MouseEvent) PointLight(javafx.scene.PointLight) ArrayList(java.util.ArrayList) Application(javafx.application.Application) PerspectiveCamera(javafx.scene.PerspectiveCamera) CameraTransformer(org.fxyz.cameras.CameraTransformer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Path(java.nio.file.Path) KeyCode(javafx.scene.input.KeyCode) Color(javafx.scene.paint.Color) Files(java.nio.file.Files) IOException(java.io.IOException) Group(javafx.scene.Group) AnimationTimer(javafx.animation.AnimationTimer) List(java.util.List) Stream(java.util.stream.Stream) Stage(javafx.stage.Stage) Paths(java.nio.file.Paths) SceneAntialiasing(javafx.scene.SceneAntialiasing) Point3D(org.fxyz.geometry.Point3D) AmbientLight(javafx.scene.AmbientLight) Group(javafx.scene.Group) MouseEvent(javafx.scene.input.MouseEvent) AnimationTimer(javafx.animation.AnimationTimer) ArrayList(java.util.ArrayList) PerspectiveCamera(javafx.scene.PerspectiveCamera) IOException(java.io.IOException) Scene(javafx.scene.Scene) ScatterMesh(org.fxyz.shapes.primitives.ScatterMesh) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Point3D(org.fxyz.geometry.Point3D) KeyCode(javafx.scene.input.KeyCode) ArrayList(java.util.ArrayList) List(java.util.List) PointLight(javafx.scene.PointLight) AmbientLight(javafx.scene.AmbientLight)

Example 55 with Files

use of java.nio.file.Files in project cassandra by apache.

the class CassandraDaemon method migrateSystemDataIfNeeded.

/**
 * Checks if the data of the local system keyspaces need to be migrated to a different location.
 *
 * @throws IOException
 */
public void migrateSystemDataIfNeeded() throws IOException {
    // anything. If it is not the case we want to try to migrate the data.
    if (!DatabaseDescriptor.useSpecificLocationForLocalSystemData() && DatabaseDescriptor.getNonLocalSystemKeyspacesDataFileLocations().length <= 1)
        return;
    // We can face several cases:
    // 1) The system data are spread accross the data file locations and need to be moved to
    // the first data location (upgrade to 4.0)
    // 2) The system data are spread accross the data file locations and need to be moved to
    // the system keyspace location configured by the user (upgrade to 4.0)
    // 3) The system data are stored in the first data location and need to be moved to
    // the system keyspace location configured by the user (system_data_file_directory has been configured)
    Path target = Paths.get(DatabaseDescriptor.getLocalSystemKeyspacesDataFileLocations()[0]);
    String[] nonLocalSystemKeyspacesFileLocations = DatabaseDescriptor.getNonLocalSystemKeyspacesDataFileLocations();
    String[] sources = DatabaseDescriptor.useSpecificLocationForLocalSystemData() ? nonLocalSystemKeyspacesFileLocations : Arrays.copyOfRange(nonLocalSystemKeyspacesFileLocations, 1, nonLocalSystemKeyspacesFileLocations.length);
    for (String source : sources) {
        Path dataFileLocation = Paths.get(source);
        if (!Files.exists(dataFileLocation))
            continue;
        try (Stream<Path> locationChildren = Files.list(dataFileLocation)) {
            Path[] keyspaceDirectories = locationChildren.filter(p -> SchemaConstants.isLocalSystemKeyspace(p.getFileName().toString())).toArray(Path[]::new);
            for (Path keyspaceDirectory : keyspaceDirectories) {
                try (Stream<Path> keyspaceChildren = Files.list(keyspaceDirectory)) {
                    Path[] tableDirectories = keyspaceChildren.filter(Files::isDirectory).filter(p -> !SystemKeyspace.TABLES_SPLIT_ACROSS_MULTIPLE_DISKS.contains(p.getFileName().toString())).toArray(Path[]::new);
                    for (Path tableDirectory : tableDirectories) {
                        FileUtils.moveRecursively(tableDirectory, target.resolve(dataFileLocation.relativize(tableDirectory)));
                    }
                    if (!SchemaConstants.SYSTEM_KEYSPACE_NAME.equals(keyspaceDirectory.getFileName().toString())) {
                        FileUtils.deleteDirectoryIfEmpty(keyspaceDirectory);
                    }
                }
            }
        }
    }
}
Also used : Path(java.nio.file.Path) Arrays(java.util.Arrays) ScheduledExecutors(org.apache.cassandra.concurrent.ScheduledExecutors) SSTableHeaderFix(org.apache.cassandra.io.sstable.SSTableHeaderFix) URL(java.net.URL) Mx4jTool(org.apache.cassandra.utils.Mx4jTool) File(org.apache.cassandra.io.util.File) LoggerFactory(org.slf4j.LoggerFactory) CommitLog(org.apache.cassandra.db.commitlog.CommitLog) CASSANDRA_PID_FILE(org.apache.cassandra.config.CassandraRelevantProperties.CASSANDRA_PID_FILE) MetricRegistryListener(com.codahale.metrics.MetricRegistryListener) DefaultNameFactory(org.apache.cassandra.metrics.DefaultNameFactory) JMXServerUtils(org.apache.cassandra.utils.JMXServerUtils) CASSANDRA_FOREGROUND(org.apache.cassandra.config.CassandraRelevantProperties.CASSANDRA_FOREGROUND) SystemViewsKeyspace(org.apache.cassandra.db.virtual.SystemViewsKeyspace) Gossiper(org.apache.cassandra.gms.Gossiper) InetAddress(java.net.InetAddress) BufferPoolMetricSet(com.codahale.metrics.jvm.BufferPoolMetricSet) CASSANDRA_JMX_REMOTE_PORT(org.apache.cassandra.config.CassandraRelevantProperties.CASSANDRA_JMX_REMOTE_PORT) MemoryUsageGaugeSet(com.codahale.metrics.jvm.MemoryUsageGaugeSet) Path(java.nio.file.Path) JMXConnectorServer(javax.management.remote.JMXConnectorServer) DatabaseDescriptor(org.apache.cassandra.config.DatabaseDescriptor) Keyspace(org.apache.cassandra.db.Keyspace) FBUtilities(org.apache.cassandra.utils.FBUtilities) SharedMetricRegistries(com.codahale.metrics.SharedMetricRegistries) ObjectName(javax.management.ObjectName) List(java.util.List) AuthCacheService(org.apache.cassandra.auth.AuthCacheService) Stream(java.util.stream.Stream) JAVA_VERSION(org.apache.cassandra.config.CassandraRelevantProperties.JAVA_VERSION) ColumnFamilyStore(org.apache.cassandra.db.ColumnFamilyStore) FileUtils(org.apache.cassandra.io.util.FileUtils) Future(org.apache.cassandra.utils.concurrent.Future) TableMetadata(org.apache.cassandra.schema.TableMetadata) SizeEstimatesRecorder(org.apache.cassandra.db.SizeEstimatesRecorder) VirtualKeyspaceRegistry(org.apache.cassandra.db.virtual.VirtualKeyspaceRegistry) NativeLibrary(org.apache.cassandra.utils.NativeLibrary) SchemaConstants(org.apache.cassandra.schema.SchemaConstants) StandardMBean(javax.management.StandardMBean) InetAddressAndPort(org.apache.cassandra.locator.InetAddressAndPort) NANOSECONDS(java.util.concurrent.TimeUnit.NANOSECONDS) JAVA_CLASS_PATH(org.apache.cassandra.config.CassandraRelevantProperties.JAVA_CLASS_PATH) QueryProcessor(org.apache.cassandra.cql3.QueryProcessor) JAVA_VM_NAME(org.apache.cassandra.config.CassandraRelevantProperties.JAVA_VM_NAME) SystemKeyspace(org.apache.cassandra.db.SystemKeyspace) Schema(org.apache.cassandra.schema.Schema) Meter(com.codahale.metrics.Meter) StartupClusterConnectivityChecker(org.apache.cassandra.net.StartupClusterConnectivityChecker) MemoryPoolMXBean(java.lang.management.MemoryPoolMXBean) ImmutableList(com.google.common.collect.ImmutableList) ConfigurationException(org.apache.cassandra.exceptions.ConfigurationException) CassandraMetricsRegistry(org.apache.cassandra.metrics.CassandraMetricsRegistry) ReporterConfig(com.addthis.metrics3.reporter.config.ReporterConfig) COM_SUN_MANAGEMENT_JMXREMOTE_PORT(org.apache.cassandra.config.CassandraRelevantProperties.COM_SUN_MANAGEMENT_JMXREMOTE_PORT) ManagementFactory(java.lang.management.ManagementFactory) JVMStabilityInspector(org.apache.cassandra.utils.JVMStabilityInspector) FileDescriptorRatioGauge(com.codahale.metrics.jvm.FileDescriptorRatioGauge) FutureCombiner(org.apache.cassandra.utils.concurrent.FutureCombiner) Logger(org.slf4j.Logger) Files(java.nio.file.Files) IOException(java.io.IOException) ThreadAwareSecurityManager(org.apache.cassandra.security.ThreadAwareSecurityManager) SystemKeyspaceMigrator40(org.apache.cassandra.db.SystemKeyspaceMigrator40) VirtualSchemaKeyspace(org.apache.cassandra.db.virtual.VirtualSchemaKeyspace) UnknownHostException(java.net.UnknownHostException) TimeUnit(java.util.concurrent.TimeUnit) Paths(java.nio.file.Paths) MBeanWrapper(org.apache.cassandra.utils.MBeanWrapper) VisibleForTesting(com.google.common.annotations.VisibleForTesting) GarbageCollectorMetricSet(com.codahale.metrics.jvm.GarbageCollectorMetricSet) AuditLogManager(org.apache.cassandra.audit.AuditLogManager) StartupException(org.apache.cassandra.exceptions.StartupException) Files(java.nio.file.Files)

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