Java Code Examples for java.nio.file.Path#toFile()

The following examples show how to use java.nio.file.Path#toFile() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
@BeforeEach
protected void before(TestInfo testInfo) throws Exception {
    init();
    File repoBaseFolder = tempDir.toFile();

    // place repo in a sym-linked folder if requested by the concrete test class
    if (useSymLinkedFolder) {
        Path linkTarget = repoBaseFolder.toPath().resolve("link-target");
        Path link = repoBaseFolder.toPath().resolve("link");
        Files.createDirectory(linkTarget);

        // - creation of most links requires elevated rights on windows, including the ones
        //   created by Files.createSymbolicLink()
        // - creation of junctions should work without elevated rights but can only be created
        //   via mklink.exe /J ...
        if (SystemUtils.IS_OS_WINDOWS) {
            ProcessUtils.startAndWaitForProcess("mklink", "/J", link.toAbsolutePath().toString(), linkTarget.toAbsolutePath().toString());
        } else {
            Files.createSymbolicLink(link, linkTarget);
        }

        repoBaseFolder = link.toFile();
    }
    localRepoMock = new LocalRepoMock(repoBaseFolder, remoteRepoServerType);
    repoPath = localRepoMock.getBaseCanonicalBaseFolder().toPath();
}
 
Example 2
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    String fn = file.getFileName().toString();
    // Skip pyc and pyi files.
    if (fn.endsWith(".pyc") || fn.endsWith(".pyi"))
        return FileVisitResult.CONTINUE;
    
    String entryName = rootEntryName;
    String relativePath = start.relativize(file).toString();
    // If empty, file is the start file.
    if(!relativePath.isEmpty()){                          
        entryName = entryName + "/" + relativePath;
    }
    // Zip uses forward slashes
    entryName = entryName.replace(File.separatorChar, '/');
    
    ZipArchiveEntry entry = new ZipArchiveEntry(file.toFile(), entryName);
    if (Files.isExecutable(file))
        entry.setUnixMode(0100770);
    else
        entry.setUnixMode(0100660);

    zos.putArchiveEntry(entry);
    Files.copy(file, zos);
    zos.closeArchiveEntry();
    return FileVisitResult.CONTINUE;
}
 
Example 3
Source Project: SubServers-2   File: Metrics.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Gets the first bStat Metrics class.
 *
 * @return The first bStats metrics class.
 */
private Class<?> getFirstBStatsClass() {
    Path configPath = new File(plugin.dir, "plugins").toPath().resolve("bStats");
    configPath.toFile().mkdirs();
    File tempFile = new File(configPath.toFile(), "temp.txt");

    try {
        String className = readFile(tempFile);
        if (className != null) {
            try {
                // Let's check if a class with the given name exists.
                return Class.forName(className);
            } catch (ClassNotFoundException ignored) { }
        }
        writeFile(tempFile, getClass().getName());
        return getClass();
    } catch (IOException e) {
        if (logFailedRequests) {
            plugin.getLogger().log(Level.WARNING, "Failed to get first bStats class!", e);
        }
        return null;
    }
}
 
Example 4
Source Project: ache   File: FilesTargetRepository.java    License: Apache License 2.0 6 votes vote down vote up
private synchronized void openNewFile() throws IOException {
    if(currentFile != null) {
        // flush and automatically closes file
        try(OutputStream out = this.currentFile) {
            out.flush();
        }
    }
    long timestamp = System.currentTimeMillis();
    long count = 0;
    Path filePath;
    do {
        String file = String.format("crawl_data-%d-%d.deflate", timestamp, count++);
        filePath = directory.resolve(file);
    } while (Files.exists(filePath));
    OutputStream fileStream = new PrintStream(filePath.toFile());
    this.bytesCounter = new CountingOutputStream(fileStream);
    this.currentFile = new DeflaterOutputStream(this.bytesCounter, true);
}
 
Example 5
@Test
public void testExtractFileNameWithoutExtension() {
    String name = "TestName";

    Path tempDirectory;
    try {
        tempDirectory = Files.createTempDirectory("extension-test");
    } catch (IOException e) {
        Assume.assumeNoException(e);
        return;
    }
    File file = new File(tempDirectory.toFile(), name);
    String result = FileUtils.extractFileNameNoExtension(file.toPath());

    Assert.assertEquals(name, result);

    Assume.assumeTrue(tempDirectory.toFile().delete());
}
 
Example 6
Source Project: reef   File: REEFScheduler.java    License: Apache License 2.0 5 votes vote down vote up
private String getReefTarUri(final String jobIdentifier) {
  try {
    // Create REEF_TAR
    final FileOutputStream fileOutputStream = new FileOutputStream(REEF_TAR);
    final TarArchiveOutputStream tarArchiveOutputStream =
        new TarArchiveOutputStream(new GZIPOutputStream(fileOutputStream));
    final File globalFolder = new File(this.fileNames.getGlobalFolderPath());
    final DirectoryStream<Path> directoryStream = Files.newDirectoryStream(globalFolder.toPath());

    for (final Path path : directoryStream) {
      tarArchiveOutputStream.putArchiveEntry(new TarArchiveEntry(path.toFile(),
          globalFolder + "/" + path.getFileName()));

      final BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(path.toFile()));
      IOUtils.copy(bufferedInputStream, tarArchiveOutputStream);
      bufferedInputStream.close();

      tarArchiveOutputStream.closeArchiveEntry();
    }
    directoryStream.close();
    tarArchiveOutputStream.close();
    fileOutputStream.close();

    // Upload REEF_TAR to HDFS
    final FileSystem fileSystem = FileSystem.get(new Configuration());
    final org.apache.hadoop.fs.Path src = new org.apache.hadoop.fs.Path(REEF_TAR);
    final String reefTarUriValue = fileSystem.getUri().toString() + this.jobSubmissionDirectoryPrefix + "/" +
        jobIdentifier + "/" + REEF_TAR;
    final org.apache.hadoop.fs.Path dst = new org.apache.hadoop.fs.Path(reefTarUriValue);
    fileSystem.copyFromLocalFile(src, dst);

    return reefTarUriValue;
  } catch (final IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 7
Source Project: synthea   File: ChartRendererTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testRenderFileFromPerson() throws Exception {
  tmpFolder.create();
  
  Path tmpFilePath = Paths.get(tmpFolder.getRoot().getAbsolutePath(), "tmp.png");
  
  Person person = new Person(0L);
  TimeSeriesData data1 = new TimeSeriesData(1.0);
  data1.addValue(3.5);
  data1.addValue(3.9);
  data1.addValue(4.3);
  data1.addValue(4.8);
  person.attributes.put("attr1", data1);
  
  PersonChartConfig chartCfg = new PersonChartConfig();
  chartCfg.setAxisLabelX("Time");
  chartCfg.setAxisAttributeX("time");
  chartCfg.setFilename(tmpFilePath.toString());
  chartCfg.setType("scatter");
  
  PersonSeriesConfig seriesCfg = new PersonSeriesConfig();
  seriesCfg.setAttribute("attr1");
  
  ArrayList<PersonSeriesConfig> seriesList = new ArrayList<PersonSeriesConfig>();
  seriesList.add(seriesCfg);
  
  chartCfg.setSeries(seriesList);
  
  ChartRenderer.drawChartAsFile(person, chartCfg);
  
  // Verify that the image file was created
  File imgFile = tmpFilePath.toFile();
  
  assertTrue("image file created", imgFile.exists());
  assertTrue("image file not empty", imgFile.length() > 0);
}
 
Example 8
public void testGeneratePillarForServerGPGCheckOn() throws Exception {
    MinionServer minion = MinionServerFactoryTest.createTestMinionServer(user);
    Channel channel1 = ChannelTestUtils.createBaseChannel(user);
    minion.addChannel(channel1);
    ServerFactory.save(minion);

    minionPillarManager.generatePillar(minion);

    Path filePath = tmpPillarRoot
            .resolve(PILLAR_DATA_FILE_PREFIX + "_" + minion.getMinionId() + "." + PILLAR_DATA_FILE_EXT);

    assertTrue(Files.exists(filePath));

    Map<String, Object> map;
    try (FileInputStream fi = new FileInputStream(filePath.toFile())) {
        map = new Yaml().loadAs(fi, Map.class);
    }

    Map<String, Object> channels = (Map<String, Object>) map.get("channels");
    assertEquals(1, channels.size());
    assertTrue(channels.containsKey(channel1.getLabel()));

    Map<String, Object> values = (Map<String, Object>) channels.get(channel1.getLabel());

    assertTrue(values.containsKey("pkg_gpgcheck"));
    assertEquals("1", (String) values.get("pkg_gpgcheck"));
}
 
Example 9
@BeforeClass
public static void setUpKerberos() throws Exception {
    servicePrincipal = prepareServiceName();
    LOG.info("Using service principal: " + servicePrincipal);

    Path targetDir = FileSystems.getDefault().getPath("target");
    Path tempDirectory = Files.createTempDirectory(targetDir, "junit.SaslGssApiIntegrationTest.");
    File root = tempDirectory.toFile();

    kdc = new MiniKdc(MiniKdc.createConf(), new File(root, "kdc"));
    kdc.start();

    // hard coded match, default_keytab_name in minikdc-krb5.conf template
    File userKeyTab = new File(KRB5_KEYTAB);
    kdc.createPrincipal(userKeyTab, CLIENT_PRINCIPAL_LOGIN_CONFIG, CLIENT_PRINCIPAL_FACTORY_USERNAME,
            CLIENT_PRINCIPAL_URI_USERNAME, CLIENT_PRINCIPAL_DEFAULT_CONFIG_SCOPE, servicePrincipal);

    if (DEBUG) {
        Keytab kt = Keytab.read(userKeyTab);
        for (KeytabEntry entry : kt.getEntries()) {
            LOG.info("KeyTab Entry: PrincipalName:" + entry.getPrincipalName() + " ; KeyInfo:"+ entry.getKey().getKeyType());
        }

        java.util.logging.Logger logger = java.util.logging.Logger.getLogger("javax.security.sasl");
        logger.setLevel(java.util.logging.Level.FINEST);
        logger.addHandler(new java.util.logging.ConsoleHandler());
        for (java.util.logging.Handler handler : logger.getHandlers()) {
            handler.setLevel(java.util.logging.Level.FINEST);
        }
    }
}
 
Example 10
static FileInputStream create(Path name) {
    try {
        return new FileInputStream(name.toFile());
    } catch (FileNotFoundException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 11
public FileBasedVariableRegistry(final Path[] propertiesPaths) {
    final Map<VariableDescriptor, String> newMap = new HashMap<>(VariableRegistry.ENVIRONMENT_SYSTEM_REGISTRY.getVariableMap());
    final int systemEnvPropCount = newMap.size();
    int totalPropertiesLoaded = systemEnvPropCount;
    LOG.info("Loaded {} properties from system properties and environment variables",systemEnvPropCount);
    try {
        for (final Path path : propertiesPaths) {
            if (Files.exists(path)) {
                final AtomicInteger propsLoaded = new AtomicInteger(0);
                try (final InputStream inStream = new BufferedInputStream(new FileInputStream(path.toFile()))) {
                    Properties properties = new Properties();
                    properties.load(inStream);
                    properties.entrySet().stream().forEach((entry) -> {
                        final VariableDescriptor desc = new VariableDescriptor.Builder(entry.getKey().toString())
                                .description(path.toString())
                                .sensitive(false)
                                .build();
                        newMap.put(desc, entry.getValue().toString());
                        propsLoaded.incrementAndGet();
                    });
                }
                totalPropertiesLoaded += propsLoaded.get();
                if(propsLoaded.get() > 0){
                    LOG.info("Loaded {} properties from '{}'", propsLoaded.get(), path);
                }else{
                    LOG.warn("No properties loaded from '{}'", path);
                }
            } else {
                LOG.warn("Skipping property file {} as it does not appear to exist", path);
            }
        }
    } catch (final IOException ioe) {
        LOG.error("Unable to complete variable registry loading from files due to ", ioe);
    }
    LOG.info("Loaded a total of {} properties.  Including precedence overrides effective accessible registry key size is {}", totalPropertiesLoaded, newMap.size());
    map = newMap;
}
 
Example 12
public static void main(String[] args) throws Exception {
	
	
	Path path = Paths.get("./test-out/nio-test.txt");
	File file = path.toFile();
	file.delete();
	file.createNewFile();
	
	ArrayList<Task> list = new ArrayList<>();
	for (int i = 0; i < taskCount; i++) {
		list.add(new Task(path, i+1));
	}
	
		
	for (Task task : list) {
		task.writeAsync();
	}
	
	//wait end
	synchronized (endObject) {
		try {
			if(endCount != taskCount) endObject.wait();
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	System.out.println("end");
	
}
 
Example 13
private static Path createFactoryFrom(Path srcTemplate,
                                      String factoryFqn,
                                      Path dstFolder) throws IOException {

    String factorySimpleName, packageName;
    int i = factoryFqn.lastIndexOf('.');
    if (i < 0) {
        packageName = "";
        factorySimpleName = factoryFqn;
    } else {
        packageName = factoryFqn.substring(0, i);
        factorySimpleName = factoryFqn.substring(i + 1);
    }

    Path result = dstFolder.resolve(factorySimpleName + ".java");
    File dst = result.toFile();
    File src = srcTemplate.toFile();
    try (BufferedReader r = new BufferedReader(new FileReader(src));
         BufferedWriter w = new BufferedWriter(new FileWriter(dst))) {

        List<String> lines = processTemplate(packageName, factorySimpleName,
                r.lines()).collect(Collectors.toList());

        Iterator<String> it = lines.iterator();
        if (it.hasNext())
            w.write(it.next());
        while (it.hasNext()) {
            w.newLine();
            w.write(it.next());
        }
    }
    return result;
}
 
Example 14
Source Project: dekorate   File: WithKubernetesConfig.java    License: Apache License 2.0 5 votes vote down vote up
default KubernetesConfig getKubernetesConfig(Path path) {
  File f = path.toFile();
  if (f.exists()) {
    try (InputStream is = new FileInputStream(f))  {
      return Serialization.unmarshal(is, KubernetesConfig.class);
    } catch (IOException e) {
      throw DekorateException.launderThrowable(e);
    }
  }

  throw new IllegalStateException("Expected to find kubernetes config at: " + path + "!");
}
 
Example 15
@Override
public void deleteUserStores(String[] domains) throws IdentityUserStoreMgtException {

    int tenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
    Path path;
    if (tenantId == MultitenantConstants.SUPER_TENANT_ID) {
        path = Paths.get(DEPLOYMENT_DIRECTORY);
    } else {
        path = Paths.get(CarbonUtils.getCarbonTenantsDirPath(), String.valueOf(tenantId), USERSTORES);
    }
    File file = path.toFile();
    for (String domainName : domains) {
        if (log.isDebugEnabled()) {
            log.debug("Deleting, .... " + domainName + " domain.");
        }
        try {
            // Run pre user-store name update listeners
            triggerListnersOnUserStorePreDelete(domainName);
            // Delete persisted domain name
            deletePersitedDomain(tenantId, domainName);
        } catch (UserStoreException e) {
            String errorMessage = "Error while deleting user store : " + domainName;
            log.error(errorMessage, e);
            throw new IdentityUserStoreMgtException(errorMessage);
        }
        // Delete file
        deleteFile(file, domainName.replace(".", "_").concat(".xml"));
    }
}
 
Example 16
@Override
protected Void execute() throws Exception {
    for (int i = 0; i<this.productsToProcess.size(); i++) {
        LocalRepositoryProduct repositoryProduct = (LocalRepositoryProduct)this.productsToProcess.get(i);
        try {
            updateProductProgressStatusLater(repositoryProduct, LocalProgressStatus.OPENING);

            // check if the local product exists on the disk
            if (Files.exists(repositoryProduct.getPath())) {
                // the product exists on the local disk

                //TODO Jean temporary method until the Landsat8 product reader will be changed to read the product from a folder
                Path productPath = RemoteProductsRepositoryProvider.prepareProductPathToOpen(repositoryProduct.getPath(), repositoryProduct);
                File productFile = productPath.toFile();

                //TODO Jean old code to get the product path to open
                //File productFile = repositoryProduct.getPath().toFile();

                ProductReader productReader = ProductIO.getProductReaderForInput(productFile);
                if (productReader == null) {
                    // no product reader found in the application
                    updateProductProgressStatusLater(repositoryProduct, LocalProgressStatus.FAIL_OPENED_MISSING_PRODUCT_READER);
                } else {
                    // there is a product reader in the application
                    Product product = productReader.readProductNodes(productFile, null);
                    if (product == null) {
                        // the product has not been read
                        throw new NullPointerException("The product '" + repositoryProduct.getName()+"' has not been read from '" + productFile.getAbsolutePath()+"'.");
                    } else {
                        // open the product in the application
                        Runnable runnable = new PairRunnable<LocalRepositoryProduct, Product>(repositoryProduct, product) {
                            @Override
                            protected void execute(LocalRepositoryProduct localRepositoryProduct, Product productToOpen) {
                                appContext.getProductManager().addProduct(productToOpen); // open the product in the application
                                updateProductProgressStatusLater(localRepositoryProduct, LocalProgressStatus.OPENED);
                            }
                        };
                        SwingUtilities.invokeLater(runnable);
                    }
                }
            } else {
                // the product does not exist into the local repository folder
                updateProductProgressStatusLater(repositoryProduct, LocalProgressStatus.MISSING_PRODUCT_FROM_REPOSITORY);
            }
        } catch (Exception exception) {
            updateProductProgressStatusLater(repositoryProduct, LocalProgressStatus.FAIL_OPENED);
            logger.log(Level.SEVERE, "Failed to open the local product '" + repositoryProduct.getURL() + "'.", exception);
        }
    }
    return null;
}
 
Example 17
Source Project: app-gradle-plugin   File: NullSafeTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testConvert_value() {
  Path testPath = Paths.get("some/path");
  File expectedResult = testPath.toFile();
  Assert.assertEquals(expectedResult, NullSafe.convert(testPath, Path::toFile));
}
 
Example 18
@Transactional(rollbackOn = {Exception.class})
public void export(LunchVoucherMgt lunchVoucherMgt) throws IOException {
  MetaFile metaFile = new MetaFile();
  metaFile.setFileName(
      I18n.get("LunchVoucherCommand")
          + " - "
          + LocalDate.now().format(DateTimeFormatter.ISO_DATE)
          + ".csv");

  Path tempFile = MetaFiles.createTempFile(null, ".csv");
  final OutputStream os = new FileOutputStream(tempFile.toFile());

  try (final Writer writer = new OutputStreamWriter(os)) {

    List<String> header = new ArrayList<>();
    header.add(escapeCsv(I18n.get("Company code")));
    header.add(escapeCsv(I18n.get("Lunch Voucher's number")));
    header.add(escapeCsv(I18n.get("Employee")));
    header.add(escapeCsv(I18n.get("Lunch Voucher format")));

    writer.write(Joiner.on(";").join(header));

    for (LunchVoucherMgtLine lunchVoucherMgtLine : lunchVoucherMgt.getLunchVoucherMgtLineList()) {

      List<String> line = new ArrayList<>();
      line.add(escapeCsv(lunchVoucherMgt.getCompany().getCode()));
      line.add(escapeCsv(lunchVoucherMgtLine.getLunchVoucherNumber().toString()));
      line.add(escapeCsv(lunchVoucherMgtLine.getEmployee().getName()));
      line.add(
          escapeCsv(lunchVoucherMgtLine.getEmployee().getLunchVoucherFormatSelect().toString()));

      writer.write("\n");
      writer.write(Joiner.on(";").join(line));
    }

    Beans.get(MetaFiles.class).upload(tempFile.toFile(), metaFile);

  } catch (Exception e) {
    Throwables.propagate(e);
  } finally {
    Files.deleteIfExists(tempFile);
  }
  /*
   */
  // lunchVoucherMgt.setExported(true);
  lunchVoucherMgt.setCsvFile(metaFile);
  lunchVoucherMgt.setExportDate(Beans.get(AppBaseService.class).getTodayDate());

  lunchVoucherMgtRepository.save(lunchVoucherMgt);
}
 
Example 19
/**
 *
 * @param paths a sorted set of Paths to use for the partitions/journals and
 * the snapshot. The snapshot will always be written to the first path
 * specified.
 * @param partitionCount the number of partitions/journals to use. For best
 * performance, this should be close to the number of threads that are
 * expected to update the repository simultaneously
 * @param serdeFactory the factory for the serializer/deserializer for records
 * @param syncListener the listener
 * @throws IOException if unable to initialize due to IO issue
 */
@SuppressWarnings("unchecked")
public MinimalLockingWriteAheadLog(final SortedSet<Path> paths, final int partitionCount, final SerDeFactory<T> serdeFactory, final SyncListener syncListener) throws IOException {
    this.syncListener = syncListener;

    requireNonNull(paths);
    requireNonNull(serdeFactory);

    if (paths.isEmpty()) {
        throw new IllegalArgumentException("Paths must be non-empty");
    }

    int resolvedPartitionCount = partitionCount;
    int existingPartitions = 0;
    for (final Path path : paths) {
        if (!Files.exists(path)) {
            Files.createDirectories(path);
        }

        final File file = path.toFile();
        if (!file.isDirectory()) {
            throw new IOException("Path given [" + path + "] is not a directory");
        }
        if (!file.canWrite()) {
            throw new IOException("Path given [" + path + "] is not writable");
        }
        if (!file.canRead()) {
            throw new IOException("Path given [" + path + "] is not readable");
        }
        if (!file.canExecute()) {
            throw new IOException("Path given [" + path + "] is not executable");
        }

        final File[] children = file.listFiles();
        if (children != null) {
            for (final File child : children) {
                if (child.isDirectory() && child.getName().startsWith("partition-")) {
                    existingPartitions++;
                }
            }

            if (existingPartitions != 0 && existingPartitions != partitionCount) {
                logger.warn("Constructing MinimalLockingWriteAheadLog with partitionCount={}, but the repository currently has "
                        + "{} partitions; ignoring argument and proceeding with {} partitions",
                        new Object[]{partitionCount, existingPartitions, existingPartitions});
                resolvedPartitionCount = existingPartitions;
            }
        }
    }

    this.basePath = paths.iterator().next();
    this.partialPath = basePath.resolve("snapshot.partial");
    this.snapshotPath = basePath.resolve("snapshot");
    this.serdeFactory = serdeFactory;

    final Path lockPath = basePath.resolve("wali.lock");
    lockChannel = new FileOutputStream(lockPath.toFile()).getChannel();
    lockChannel.lock();

    partitions = new Partition[resolvedPartitionCount];

    Iterator<Path> pathIterator = paths.iterator();
    for (int i = 0; i < resolvedPartitionCount; i++) {
        // If we're out of paths, create a new iterator to start over.
        if (!pathIterator.hasNext()) {
            pathIterator = paths.iterator();
        }

        final Path partitionBasePath = pathIterator.next();

        partitions[i] = new Partition<>(partitionBasePath.resolve("partition-" + i), serdeFactory, i, getVersion());
    }
}
 
Example 20
private Future<File> createCodeArchive(File toolkitRoot, JsonObject submission, String mainCompositeKind) throws IOException, URISyntaxException {
    
    String tkName = toolkitRoot != null ? toolkitRoot.getName() : null;
            
    Path zipOutPath = pack(toolkitRoot, submission, tkName, mainCompositeKind);
    
    if (keepBuildArchive || keepArtifacts(submission)) {
    	final JsonObject submissionResult = GsonUtilities.objectCreate(submission, RemoteContext.SUBMISSION_RESULTS);
    	submissionResult.addProperty(SubmissionResultsKeys.ARCHIVE_PATH, zipOutPath.toString());
    }
            
    return new CompletedFuture<File>(zipOutPath.toFile());
}