Java Code Examples for java.nio.file.Paths#get()

The following examples show how to use java.nio.file.Paths#get() . 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 check out the related API usage on the sidebar.
Example 1
Source Project: ofdrw   File: DrawContextTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void fillRect() throws IOException {
    Path outP = Paths.get("target/Canvas-fillRect.ofd");
    try (OFDDoc ofdDoc = new OFDDoc(outP)) {
        VirtualPage vPage = new VirtualPage(ofdDoc.getPageLayout());

        Canvas canvas = new Canvas(200d, 200d);
        canvas.setPosition(Position.Absolute)
                .setX(5d).setY(45d)
                .setBorder(1d);

        canvas.setDrawer(ctx -> {
            ctx.fillRect(20, 20, 150, 100);
        });
        vPage.add(canvas);

        ofdDoc.addVPage(vPage);
    }
    System.out.println("生成文档位置:" + outP.toAbsolutePath().toString());
}
 
Example 2
Source Project: Explvs-AIO   File: ResourceManager.java    License: MIT License 6 votes vote down vote up
private static synchronized boolean saveFileToDataDirectory(final InputStream inputStream, final String relativeFilePath) {
    if (inputStream == null) {
        return false;
    }

    Path outputFilePath = Paths.get(DIRECTORY, relativeFilePath);
    File parentDir = outputFilePath.getParent().toFile();

    if (!parentDir.exists()) {
        if (!parentDir.mkdirs()) {
            System.out.println("Failed to make directory: " + parentDir.toString());
            return false;
        }
    }

    try {
        Files.copy(
                inputStream,
                Paths.get(DIRECTORY, relativeFilePath),
                StandardCopyOption.REPLACE_EXISTING
        );
    } catch (IOException e) {
        e.printStackTrace();
    }
    return true;
}
 
Example 3
private static String getTool(String tool, String property) throws FileNotFoundException {
    String jdkPath = System.getProperty(property);

    if (jdkPath == null) {
        throw new RuntimeException(
                "System property '" + property + "' not set. This property is normally set by jtreg. "
                + "When running test separately, set this property using '-D" + property + "=/path/to/jdk'.");
    }

    Path toolName = Paths.get("bin", tool + (Platform.isWindows() ? ".exe" : ""));

    Path jdkTool = Paths.get(jdkPath, toolName.toString());
    if (!jdkTool.toFile().exists()) {
        throw new FileNotFoundException("Could not find file " + jdkTool.toAbsolutePath());
    }

    return jdkTool.toAbsolutePath().toString();
}
 
Example 4
<T> void writeToFile(final String rootPath, final String fileName, final Persistence<T> persist) throws Exception {
    final Path path = Paths.get(rootPath, fileName);
    try (final FileOutputStream out = new FileOutputStream(path.toFile());
            final BufferedOutputStream bufOutput = new BufferedOutputStream(out)) {
        final byte[] bytes = this.serializer.writeObject(persist);
        final byte[] lenBytes = new byte[4];
        Bits.putInt(lenBytes, 0, bytes.length);
        bufOutput.write(lenBytes);
        bufOutput.write(bytes);
        bufOutput.flush();
        out.getFD().sync();
    }
}
 
Example 5
@Test
public void getsCorrectSize() throws Exception {
  File file = TestUtils.getTestDataFile(PATH);
  SystemFileData systemFileData = new SystemFileData(file, Paths.get("foobar.txt"));

  assertThat(systemFileData.getSize()).isEqualTo(1408431L);
}
 
Example 6
private static String prepareWorkDir() throws IOException {
    Path dir = Paths.get(KRB_WORK_DIR);
    File directory = dir.normalize().toFile();

    FileUtils.deleteQuietly(directory);
    FileUtils.forceMkdir(directory);
    return dir.toString();
}
 
Example 7
@Before
public void setUp() throws Exception {
  final URL rootURL = DatabaseMigrationAcceptanceTest.class.getResource(dataPath);
  hostDataPath = copyDataDir(rootURL);
  final Path databaseArchive =
      Paths.get(
          DatabaseMigrationAcceptanceTest.class
              .getResource(String.format("%s/besu-db-archive.tar.gz", dataPath))
              .toURI());
  extract(databaseArchive, hostDataPath.toAbsolutePath().toString());
  node = besu.createNode(testName, this::configureNode);
  cluster.start(node);
}
 
Example 8
public FileSystemProcessInstances(Process<?> process, Path storage, ProcessInstanceMarshaller marshaller) {
    this.process = process;
    this.storage = Paths.get(storage.toString(), process.id());
    this.marshaller = marshaller;

    try {
        Files.createDirectories(this.storage);
    } catch (IOException e) {
        throw new RuntimeException("Unable to create directories for file based storage of process instances", e);
    }
}
 
Example 9
@Before
public void init() {
  try {
    conf = new OzoneConfiguration();
    conf.set(OZONE_SCM_CLIENT_ADDRESS_KEY, "localhost");

    conf.setInt(OZONE_SCM_CLIENT_PORT_KEY,
        getPort(OZONE_SCM_CLIENT_PORT_DEFAULT, 100));
    conf.setInt(OZONE_SCM_DATANODE_PORT_KEY,
        getPort(OZONE_SCM_DATANODE_PORT_DEFAULT, 100));
    conf.setInt(OZONE_SCM_BLOCK_CLIENT_PORT_KEY,
        getPort(OZONE_SCM_BLOCK_CLIENT_PORT_DEFAULT, 100));
    conf.setInt(OZONE_SCM_SECURITY_SERVICE_PORT_KEY,
        getPort(OZONE_SCM_SECURITY_SERVICE_PORT_DEFAULT, 100));

    DefaultMetricsSystem.setMiniClusterMode(true);
    final String path = folder.newFolder().toString();
    Path metaDirPath = Paths.get(path, "om-meta");
    conf.set(OZONE_METADATA_DIRS, metaDirPath.toString());
    conf.setBoolean(OZONE_SECURITY_ENABLED_KEY, true);
    conf.set(HADOOP_SECURITY_AUTHENTICATION, KERBEROS.name());

    workDir = GenericTestUtils.getTestDir(getClass().getSimpleName());

    startMiniKdc();
    setSecureConfig();
    createCredentialsInKDC();
    generateKeyPair();
    //      OzoneManager.setTestSecureOmFlag(true);
  } catch (Exception e) {
    LOG.error("Failed to initialize TestSecureOzoneCluster", e);
  }
}
 
Example 10
private static boolean fileContainsString(String filename, String text) throws IOException {
    Path p = Paths.get(filename);
    for (String line : Files.readAllLines(p, Charset.defaultCharset())) {
        if (line.contains(text)) {
            return true;
        }
    }
    return false;
}
 
Example 11
public static boolean runScript(String scriptName, String[] scriptArguments, GhidraState scriptState)
		throws Exception {
	
	//set dummy printwriter to satisfy ghidra scripting api
	
	StringWriter sw = new StringWriter();
	PrintWriter writer = new PrintWriter(sw);
	
	TaskMonitor monitor = new DummyCancellableTaskMonitor();
	
	Path p = Paths.get(
			System.getProperty("user.dir"),
			"Ghidra",
			"Extensions",
			"dragondance",
			"ghidra_scripts",
			scriptName
			);
	
	
	//List<ResourceFile> dirs = GhidraScriptUtil.getScriptSourceDirectories();
	
	ResourceFile scriptSource = new ResourceFile(p.toAbsolutePath().toString());
	
	
	if (scriptSource.exists()) {
		GhidraScriptProvider gsp = GhidraScriptUtil.getProvider(scriptSource);

		if (gsp == null) {
			writer.close();
			throw new IOException("Attempting to run subscript '" + scriptName +
				"': unable to run this script type.");
		}
		
		GhidraScript script = gsp.getScriptInstance(scriptSource, writer);
		script.setScriptArgs(scriptArguments);
		
		script.execute(scriptState, monitor, writer);

	}
	else
	{
		return false;
	}
	
	return true;
}
 
Example 12
/**
 * Preprocess the command line arguments passed in by the shell. This method checks, for the first non-option
 * argument, whether the file denoted by it begins with a shebang line. If so, it is assumed that execution in
 * shebang mode is intended. The consequence of this is that the identified script file will be treated as the
 * <em>only</em> script file, and all subsequent arguments will be regarded as arguments to the script.
 * <p>
 * This method canonicalizes the command line arguments to the form {@code <options> <script> -- <arguments>} if a
 * shebang script is identified. On platforms that pass shebang arguments as single strings, the shebang arguments
 * will be broken down into single arguments; whitespace is used as separator.
 * <p>
 * Shebang mode is entered regardless of whether the script is actually run directly from the shell, or indirectly
 * via the {@code jjs} executable. It is the user's / script author's responsibility to ensure that the arguments
 * given on the shebang line do not lead to a malformed argument sequence. In particular, the shebang arguments
 * should not contain any whitespace for purposes other than separating arguments, as the different platforms deal
 * with whitespace in different and incompatible ways.
 * <p>
 * @implNote Example:<ul>
 * <li>Shebang line in {@code script.js}: {@code #!/path/to/jjs --language=es6}</li>
 * <li>Command line: {@code ./script.js arg2}</li>
 * <li>{@code args} array passed to Nashorn: {@code --language=es6,./script.js,arg}</li>
 * <li>Required canonicalized arguments array: {@code --language=es6,./script.js,--,arg2}</li>
 * </ul>
 *
 * @param args the command line arguments as passed into Nashorn.
 * @return the passed and possibly canonicalized argument list
 */
private static String[] preprocessArgs(final String[] args) {
    if (args.length == 0) {
        return args;
    }

    final List<String> processedArgs = new ArrayList<>();
    processedArgs.addAll(Arrays.asList(args));

    // Nashorn supports passing multiple shebang arguments. On platforms that pass anything following the
    // shebang interpreter notice as one argument, the first element of the argument array needs to be special-cased
    // as it might actually contain several arguments. Mac OS X splits shebang arguments, other platforms don't.
    // This special handling is also only necessary if the first argument actually starts with an option.
    if (args[0].startsWith("-") && !System.getProperty("os.name", "generic").startsWith("Mac OS X")) {
        processedArgs.addAll(0, ScriptingFunctions.tokenizeString(processedArgs.remove(0)));
    }

    int shebangFilePos = -1; // -1 signifies "none found"
    // identify a shebang file and its position in the arguments array (if any)
    for (int i = 0; i < processedArgs.size(); ++i) {
        final String a = processedArgs.get(i);
        if (!a.startsWith("-")) {
            final Path p = Paths.get(a);
            String l = "";
            try (final BufferedReader r = Files.newBufferedReader(p)) {
                l = r.readLine();
            } catch (IOException ioe) {
                // ignore
            }
            if (l.startsWith("#!")) {
                shebangFilePos = i;
            }
            // We're only checking the first non-option argument. If it's not a shebang file, we're in normal
            // execution mode.
            break;
        }
    }
    if (shebangFilePos != -1) {
        // Insert the argument separator after the shebang script file.
        processedArgs.add(shebangFilePos + 1, "--");
    }
    return processedArgs.toArray(new String[0]);
}
 
Example 13
/**
 * Update Grib Collection if needed
 *
 * @return true if the collection was updated
 */
public static boolean updateGribCollection(FeatureCollectionConfig config, CollectionUpdateType updateType,
    Logger logger) throws IOException {
  if (logger == null)
    logger = classLogger;

  long start = System.currentTimeMillis();

  Formatter errlog = new Formatter();
  CollectionSpecParser specp = config.getCollectionSpecParser(errlog);
  Path rootPath = Paths.get(specp.getRootDir());
  boolean isGrib1 = config.type == FeatureCollectionType.GRIB1;

  boolean changed;

  if (config.ptype == FeatureCollectionConfig.PartitionType.none
      || config.ptype == FeatureCollectionConfig.PartitionType.all) {

    try (CollectionAbstract dcm = new CollectionPathMatcher(config, specp, logger)) {
      changed =
          updateGribCollection(isGrib1, dcm, updateType, FeatureCollectionConfig.PartitionType.none, logger, errlog);
    }

  } else if (config.ptype == FeatureCollectionConfig.PartitionType.timePeriod) {

    try (TimePartition tp = new TimePartition(config, specp, logger)) {
      changed = updateTimePartition(isGrib1, tp, updateType, logger);
    }

  } else {

    // LOOK assume wantSubdirs makes it into a Partition. Isnt there something better ??
    if (specp.wantSubdirs()) { // its a partition

      try (DirectoryPartition dpart =
          new DirectoryPartition(config, rootPath, true, new GribCdmIndex(logger), NCX_SUFFIX, logger)) {
        dpart.putAuxInfo(FeatureCollectionConfig.AUX_CONFIG, config);
        changed = updateDirectoryCollectionRecurse(isGrib1, dpart, config, updateType, logger);
      }

    } else { // otherwise its a leaf directory
      changed = updateLeafCollection(isGrib1, config, updateType, true, logger, rootPath);
    }
  }

  long took = System.currentTimeMillis() - start;
  logger.info("updateGribCollection {} changed {} took {} msecs", config.collectionName, changed, took);
  return changed;
}
 
Example 14
Source Project: besu   File: BlocksSubCommand.java    License: Apache License 2.0 4 votes vote down vote up
private void checkCommand(
    final ExportSubCommand exportSubCommand, final Long startBlock, final Long endBlock) {
  checkNotNull(exportSubCommand.parentCommand);

  final Optional<Long> maybeStartBlock = getStartBlock();
  final Optional<Long> maybeEndBlock = getEndBlock();

  maybeStartBlock
      .filter(blockNum -> blockNum < 0)
      .ifPresent(
          (blockNum) -> {
            throw new CommandLine.ParameterException(
                spec.commandLine(),
                "Parameter --start-block ("
                    + blockNum
                    + ") must be greater than or equal to zero.");
          });

  maybeEndBlock
      .filter(blockNum -> blockNum < 0)
      .ifPresent(
          (blockNum) -> {
            throw new CommandLine.ParameterException(
                spec.commandLine(),
                "Parameter --end-block ("
                    + blockNum
                    + ") must be greater than or equal to zero.");
          });

  if (maybeStartBlock.isPresent() && maybeEndBlock.isPresent()) {
    if (endBlock <= startBlock) {
      throw new CommandLine.ParameterException(
          spec.commandLine(),
          "Parameter --end-block ("
              + endBlock
              + ") must be greater start block ("
              + startBlock
              + ").");
    }
  }

  // Error if data directory is empty
  final Path databasePath =
      Paths.get(
          parentCommand.parentCommand.dataDir().toAbsolutePath().toString(),
          BesuController.DATABASE_PATH);
  final File databaseDirectory = new File(databasePath.toString());
  if (!databaseDirectory.isDirectory() || databaseDirectory.list().length == 0) {
    // Empty data directory, nothing to export
    throw new CommandLine.ParameterException(
        spec.commandLine(),
        "Chain is empty.  Unable to export blocks from specified data directory: "
            + databaseDirectory.toString());
  }
}
 
Example 15
Source Project: hadoop-ozone   File: GenesisUtil.java    License: Apache License 2.0 4 votes vote down vote up
public static Path getTempPath() {
  return Paths.get(System.getProperty(TMP_DIR));
}
 
Example 16
@Override
public void start(final Stage primaryStage) {
    final String userHome = System.getProperty("user.home");

    final XYChart chart1 = new XYChart(new DefaultNumericAxis(), new DefaultNumericAxis());
    final XYChart chart2 = new XYChart();

    now = System.currentTimeMillis();
    dataSet1 = getDemoDataSet(now, true);
    dataSet2 = getDemoDataSet(now, false);
    dataSet2.getMetaInfo().put("magNr", Integer.toString(5));
    chart1.getDatasets().setAll(dataSet1, dataSet2); // two data sets

    final Scene scene = new Scene(chart1, 800, 600);
    primaryStage.setTitle(this.getClass().getSimpleName() + " - original");
    primaryStage.setScene(scene);
    primaryStage.setOnCloseRequest(evt -> Platform.exit());

    final Stage secondaryStage = new Stage();

    secondaryStage.setTitle(this.getClass().getSimpleName() + " - recovered");
    secondaryStage.setScene(new Scene(chart2, 800, 600));
    secondaryStage.setOnCloseRequest(evt -> Platform.exit());
    primaryStage.show();
    secondaryStage.show();

    LOGGER.atInfo().log("userHome = " + userHome);
    final Path path = Paths.get(userHome + "/ChartSamples");
    final String fileName = PNG_FILE_NAME;

    final boolean addDateTimeToFileName = true;

    // write DataSet to File and recover
    DataSetUtils.writeDataSetToFile(dataSet1, path, CSV_FILE_NAME_1, false);
    DataSetUtils.writeDataSetToFile(dataSet2, path, CSV_FILE_NAME_2, true);
    DataSetUtils.writeDataSetToFile(dataSet2, path, CSV_FILE_NAME_SYSTEMTIME, false);

    // start periodic screen capture
    final PeriodicScreenCapture screenCapture = new PeriodicScreenCapture(path, fileName, scene, DEFAULT_DELAY,
            DEFAULT_PERIOD, addDateTimeToFileName);

    screenCapture.addListener(obs -> {
        final long userTimeStampMillis = System.currentTimeMillis();

        // add some important meta data to dataSet1 (e.g. acquisition time
        // stamp)
        dataSet1.getMetaInfo().put("acqTimeStamp", Long.toString(userTimeStampMillis));
        dataSet2.getMetaInfo().put("acqTimeStamp", Long.toString(userTimeStampMillis));

        final String actualFileName1 = DataSetUtils.writeDataSetToFile(dataSet1, path, CSV_FILE_NAME_1_TIMESTAMED,
                false);
        final String actualFileName2 = DataSetUtils.writeDataSetToFile(dataSet2, path, CSV_FILE_NAME_2_TIMESTAMED,
                true);

        // to suppress serialising the meta-data, default: true
        // DataSetSerialiser.setMetaDataSerialised(false); // uncomment
        // to suppress serialising data labels and styles, default: true
        // DataSetSerialiser.setDataLablesSerialised(false); // uncomment
        boolean asFloat = true;
        fastByteBuffer.reset(); // '0' writing at start of buffer
        DataSetSerialiser.writeDataSetToByteArray(dataSet2, fastByteBuffer, asFloat);
        LOGGER.atInfo().log("written bytes to byte buffer = " + fastByteBuffer.position());
        fastByteBuffer.reset(); // return read position to '0'

        LOGGER.atInfo().log("write data time-stamped to directory = " + path);
        LOGGER.atInfo().log("actualFileName1 = " + actualFileName1);
        LOGGER.atInfo().log("actualFileName2 = " + actualFileName2);

        // recover written data sets
        final DataSet recoveredDataSet1 = DataSetUtils.readDataSetFromFile(actualFileName1);
        final DataSet recoveredDataSet2 = DataSetUtils.readDataSetFromFile(actualFileName2);
        final DataSet recoveredDataSet3 = DataSetSerialiser.readDataSetFromByteArray(fastByteBuffer);

        chart2.getDatasets().clear();
        if (recoveredDataSet1 != null) {
            chart2.getDatasets().add(recoveredDataSet1);
        }

        if (recoveredDataSet2 != null) {
            chart2.getDatasets().add(recoveredDataSet2);
        }

        if (recoveredDataSet3 != null) {
            chart2.getDatasets().add(recoveredDataSet3);
        }

        // generate new data sets
        now = System.currentTimeMillis();
        dataSet1 = getDemoDataSet(now, true);
        dataSet2 = getDemoDataSet(now, false);
        chart1.getDatasets().setAll(dataSet1, dataSet2); // two data sets
    });

    screenCapture.start();

    // screenCapture.stop();
}
 
Example 17
private static void testDumpEndBegin() throws Exception {
    Path testEndBegin = Paths.get("testEndBegin.jfr");
    OutputAnalyzer output = JcmdHelper.jcmd("JFR.dump", "filename=" + testEndBegin.toFile().getAbsolutePath(), "begin=" + Instant.now(), "end=" + Instant.now().minusSeconds(200));
    output.shouldContain("Dump failed, begin must preceed end.");
    assertMissingFile(testEndBegin);
}
 
Example 18
public DirectoryReportDelivery(String directoryPath) {
    super("File-based report delivery");
    this.dir = Paths.get(directoryPath);
}
 
Example 19
Source Project: size-analyzer   File: ProjectAnalyzer.java    License: Apache License 2.0 4 votes vote down vote up
private static ImmutableList<Suggestion> analyzeDirectory(
    File rootDirectory,
    Project project,
    File directory,
    ImmutableList<ProjectSuggester> projectSuggesters,
    ImmutableList<ProjectTreeSuggester> suggesters) {
  ImmutableList.Builder<Suggestion> resultBuilder = ImmutableList.<Suggestion>builder();
  File[] files = directory.listFiles();
  for (File file : files) {
    String name = file.getName();
    if (name.equals(".gradle") || name.equals(".idea") || name.equals("build")) {
      continue;
    }
    if (file.isDirectory()) {
      File buildFile = new File(file, Project.BUILD_GRADLE);
      if (buildFile.exists()) {
        Project subProject = Project.create(file, project);
        resultBuilder.addAll(
            analyzeProject(rootDirectory, subProject, file, projectSuggesters, suggesters));
      } else {
        // recurse, through directory under the same directory.
        resultBuilder.addAll(
            analyzeDirectory(rootDirectory, project, file, projectSuggesters, suggesters));
      }
    } else {
      GradleContext context =
          project != null ? project.getContext() : GradleContext.create(1, false);
      Path pathWithinModule =
          project != null
              ? Paths.get(project.getProjectDirectory().getPath())
                  .relativize(Paths.get(file.getPath()))
              : Paths.get(file.getName());
      Path pathWithinRoot =
          Paths.get(rootDirectory.getPath()).relativize(Paths.get(file.getPath()));
      for (ProjectTreeSuggester suggester : suggesters) {
        SystemFileData systemFileData =
            new SystemFileData(file, pathWithinRoot, pathWithinModule);
        resultBuilder.addAll(suggester.processProjectEntry(context, systemFileData));
      }
    }
  }

  return resultBuilder.build();
}
 
Example 20
Source Project: Java-Coding-Problems   File: Main.java    License: MIT License 3 votes vote down vote up
public static void main(String[] args) throws IOException, InterruptedException {

        final Path path = Paths.get("D:/captures");
        VideoCaptureWatcher watcher = new VideoCaptureWatcher();

        watcher.watchVideoCaptureSystem(path);
    }