List of usage examples for java.nio.file Path resolve
default Path resolve(String other)
From source file:net.daboross.bukkitdev.skywars.world.WorldUnzipper.java
public void doWorldUnzip(Logger logger) throws StartupFailedException { Validate.notNull(logger, "Logger cannot be null"); Path outputDir = Bukkit.getWorldContainer().toPath().resolve(Statics.BASE_WORLD_NAME); if (Files.exists(outputDir)) { return;/*ww w . j av a2 s . c o m*/ } try { Files.createDirectories(outputDir); } catch (IOException e) { throw new StartupFailedException("Couldn't create directory " + outputDir.toAbsolutePath() + "."); } InputStream fis = WorldUnzipper.class.getResourceAsStream(Statics.ZIP_FILE_PATH); if (fis == null) { throw new StartupFailedException("Couldn't get resource.\nError creating world. Please delete " + Statics.BASE_WORLD_NAME + " and restart server."); } try { try (ZipInputStream zis = new ZipInputStream(fis)) { ZipEntry ze = zis.getNextEntry(); while (ze != null) { String fileName = ze.getName(); Path newFile = outputDir.resolve(fileName); Path parent = newFile.getParent(); if (parent != null) { Files.createDirectories(parent); } if (ze.isDirectory()) { logger.log(Level.FINER, "Making dir {0}", newFile); Files.createDirectories(newFile); } else if (Files.exists(newFile)) { logger.log(Level.FINER, "Already exists {0}", newFile); } else { logger.log(Level.FINER, "Copying {0}", newFile); try (FileOutputStream fos = new FileOutputStream(newFile.toFile())) { try { int next; while ((next = zis.read()) != -1) { fos.write(next); } fos.flush(); } catch (IOException ex) { logger.log(Level.WARNING, "Error copying file from zip", ex); throw new StartupFailedException("Error creating world. Please delete " + Statics.BASE_WORLD_NAME + " and restart server."); } fos.close(); } } try { ze = zis.getNextEntry(); } catch (IOException ex) { throw new StartupFailedException( "Error getting next zip entry\nError creating world. Please delete " + Statics.BASE_WORLD_NAME + " and restart server.", ex); } } } } catch (IOException | RuntimeException ex) { throw new StartupFailedException( "\nError unzipping world. Please delete " + Statics.BASE_WORLD_NAME + " and restart server.", ex); } }
From source file:com.oxiane.maven.xqueryMerger.Merger.java
@Override public void execute() throws MojoExecutionException { Path sourceRootPath = inputSources.toPath(); Path destinationRootPath = outputDirectory.toPath(); IOFileFilter filter = buildFilter(); Iterator<File> it = FileUtils.iterateFiles(inputSources, filter, FileFilterUtils.directoryFileFilter()); if (!it.hasNext()) { getLog().warn("No file found matching " + filter.toString() + " in " + inputSources.getAbsolutePath()); }/*w w w.j a v a 2 s.c o m*/ while (it.hasNext()) { File sourceFile = it.next(); Path fileSourcePath = sourceFile.toPath(); Path relativePath = sourceRootPath.relativize(fileSourcePath); getLog().debug("[Merger] found source: " + fileSourcePath.toString()); getLog().debug("[Merger] relative path is " + relativePath.toString()); StreamSource source = new StreamSource(sourceFile); XQueryMerger merger = new XQueryMerger(source); merger.setMainQuery(); File destinationFile = destinationRootPath.resolve(relativePath).toFile(); getLog().debug("[Merger] destination will be " + destinationFile.getAbsolutePath()); try { String result = merger.merge(); destinationFile.getParentFile().mkdirs(); OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(destinationFile), merger.getEncoding()); osw.write(result); osw.flush(); osw.close(); getLog().debug("[Merger] " + relativePath.toString() + " merged into " + destinationFile.getAbsolutePath()); } catch (ParsingException ex) { getLog().error(ex.getMessage()); throw new MojoExecutionException("Merge of " + sourceFile.getAbsolutePath() + " fails", ex); } catch (FileNotFoundException ex) { getLog().error(ex.getMessage()); throw new MojoExecutionException( "Unable to create destination " + destinationFile.getAbsolutePath(), ex); } catch (IOException ex) { getLog().error(ex.getMessage()); throw new MojoExecutionException("While writing " + destinationFile.getAbsolutePath(), ex); } } }
From source file:eu.itesla_project.sampling.tools.DataComparatorTool.java
@Override public void run(CommandLine line) throws Exception { try (ComputationManager computationManager = new LocalComputationManager()) { SamplerWp41Config config = SamplerWp41Config.load(); //String dataDir = line.getOptionValue(DataComparatorCommand.DATA_DIR); String dataDir = config.getValidationDir().toFile().getAbsolutePath(); if (!Files.exists(config.getValidationDir())) { throw new RuntimeException("validation data directory not found: " + config.getValidationDir()); }//from w w w . j a v a 2 s . c o m String oFilePrefix = line.getOptionValue("ofile"); String set1 = line.hasOption("set1") ? line.getOptionValue("set1") : ""; String set2 = line.hasOption("set2") ? line.getOptionValue("set2") : ""; if ((!"".equals(set1 + set2)) && (("".equals(set1)) || ("".equals(set2)))) { throw new RuntimeException("either specify both set1 and set2 parameters, or none of them"); } try (CommandExecutor executor = computationManager.newCommandExecutor(createEnv(config), WORKING_DIR_PREFIX, config.isDebug())) { Path workingDir = executor.getWorkingDir(); eu.itesla_project.computation.Command cmd = createConcatMatFilesCmd(config.getValidationDir(), MOD3FILES_PATTERN, config.getValidationDir().resolve(CONCATSAMPLESFILENAME), config); int priority = 1; ExecutionReport report = executor.start(new CommandExecution(cmd, 1, priority)); report.log(); if (report.getErrors().isEmpty()) { report = executor.start(new CommandExecution(createDataComparatorCmd( config.getValidationDir().resolve(M1INPUTFILENAME).toFile().getAbsolutePath(), config.getValidationDir().resolve(CONCATSAMPLESFILENAME).toFile().getAbsolutePath(), set1, set2, config), 1, priority)); report.log(); Files.copy(workingDir.resolve(DATA_COMPARATOR_OUT_FIG), Paths.get(oFilePrefix + ".fig"), REPLACE_EXISTING); Files.copy(workingDir.resolve(DATA_COMPARATOR_OUT_PNG), Paths.get(oFilePrefix + ".png"), REPLACE_EXISTING); } } } }
From source file:com.facebook.buck.zip.UnzipTest.java
@Test public void testExtractZipFile() throws IOException { try (Zip zip = new Zip(zipFile, true)) { zip.add("1.bin", DUMMY_FILE_CONTENTS); zip.add("subdir/2.bin", DUMMY_FILE_CONTENTS); zip.addDir("emptydir"); }/*from w w w . j a v a 2 s . c o m*/ Path extractFolder = tmpFolder.newFolder(); ImmutableList<Path> result = Unzip.extractZipFile(zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(), Unzip.ExistingFileMode.OVERWRITE); assertTrue(Files.exists(extractFolder.toAbsolutePath().resolve("1.bin"))); Path bin2 = extractFolder.toAbsolutePath().resolve("subdir/2.bin"); assertTrue(Files.exists(bin2)); assertTrue(Files.isDirectory(extractFolder.toAbsolutePath().resolve("emptydir"))); try (InputStream input = Files.newInputStream(bin2)) { byte[] buffer = new byte[DUMMY_FILE_CONTENTS.length]; int bytesRead = input.read(buffer, 0, DUMMY_FILE_CONTENTS.length); assertEquals(DUMMY_FILE_CONTENTS.length, bytesRead); for (int i = 0; i < DUMMY_FILE_CONTENTS.length; i++) { assertEquals(DUMMY_FILE_CONTENTS[i], buffer[i]); } } assertEquals(ImmutableList.of(extractFolder.resolve("1.bin"), extractFolder.resolve("subdir/2.bin")), result); }
From source file:com.hortonworks.streamline.streams.actions.storm.topology.StormTopologyActionsImpl.java
private Path addArtifactsToJar(Path artifactsLocation) throws Exception { Path jarFile = Paths.get(stormJarLocation); if (artifactsLocation.toFile().isDirectory()) { File[] artifacts = artifactsLocation.toFile().listFiles(); if (artifacts != null && artifacts.length > 0) { Path newJar = Files.copy(jarFile, artifactsLocation.resolve(jarFile.getFileName())); List<String> artifactFileNames = Arrays.stream(artifacts).filter(File::isFile).map(File::getName) .collect(toList());//from w w w . ja v a2s .co m List<String> commands = new ArrayList<>(); commands.add(javaJarCommand); commands.add("uf"); commands.add(newJar.toString()); artifactFileNames.stream().forEachOrdered(name -> { commands.add("-C"); commands.add(artifactsLocation.toString()); commands.add(name); }); ShellProcessResult shellProcessResult = executeShellProcess(commands); if (shellProcessResult.exitValue != 0) { LOG.error("Adding artifacts to jar command failed - exit code: {} / output: {}", shellProcessResult.exitValue, shellProcessResult.stdout); throw new RuntimeException( "Topology could not be deployed " + "successfully: fail to add artifacts to jar"); } LOG.debug("Added files {} to jar {}", artifactFileNames, jarFile); return newJar; } } else { LOG.debug("Artifacts directory {} does not exist, not adding any artifacts to jar", artifactsLocation); } return jarFile; }
From source file:SecurityWatch.java
public void watchVideoCamera(Path path) throws IOException, InterruptedException { watchService = FileSystems.getDefault().newWatchService(); register(path, StandardWatchEventKinds.ENTRY_CREATE); OUTERMOST: while (true) { final WatchKey key = watchService.poll(); if (key == null) { System.out.println("The video camera is jammed - security watch system is canceled!"); break; } else {/* w w w .j a v a 2 s. c o m*/ for (WatchEvent<?> watchEvent : key.pollEvents()) { final Kind<?> kind = watchEvent.kind(); if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } if (kind == StandardWatchEventKinds.ENTRY_CREATE) { //get the filename for the event final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent; final Path filename = watchEventPath.context(); final Path child = path.resolve(filename); if (Files.probeContentType(child).equals("image/jpeg")) { //print it out the video capture time SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); System.out.println("Video capture successfully at: " + dateFormat.format(new Date())); } else { System.out.println("The video camera capture format failed! This could be a virus!"); break OUTERMOST; } } } boolean valid = key.reset(); if (!valid) { break; } } } watchService.close(); }
From source file:org.apache.taverna.databundle.TestDataBundles.java
@Test public void clear() throws Exception { Path inputs = DataBundles.getInputs(dataBundle); Path file1 = inputs.resolve("file1"); Path file1Txt = inputs.resolve("file1.txt"); Path file1Png = inputs.resolve("file1.png"); Path file1Else = inputs.resolve("file1somethingelse.txt"); Files.createFile(file1);/*from w w w . j av a 2s. co m*/ Files.createFile(file1Txt); Files.createFile(file1Png); Files.createFile(file1Else); DataBundles.deleteAllExtensions(file1); assertFalse(Files.exists(file1)); assertFalse(Files.exists(file1Txt)); assertFalse(Files.exists(file1Png)); assertTrue(Files.exists(file1Else)); }
From source file:com.google.cloud.dataflow.sdk.io.TextIOTest.java
License:asdf
private <T> void runTestWrite(T[] elems, String header, String footer, Coder<T> coder, int numShards) throws Exception { String outputName = "file.txt"; Path baseDir = Files.createTempDirectory(tempFolder, "testwrite"); String baseFilename = baseDir.resolve(outputName).toString(); Pipeline p = TestPipeline.create();//from www. j a v a2s . c o m PCollection<T> input = p.apply(Create.of(Arrays.asList(elems)).withCoder(coder)); TextIO.Write.Bound<T> write; if (coder.equals(StringUtf8Coder.of())) { TextIO.Write.Bound<String> writeStrings = TextIO.Write.to(baseFilename); // T==String write = (TextIO.Write.Bound<T>) writeStrings; } else { write = TextIO.Write.to(baseFilename).withCoder(coder); } if (numShards == 1) { write = write.withoutSharding(); } else { write = write.withNumShards(numShards).withShardNameTemplate(ShardNameTemplate.INDEX_OF_MAX); } write = write.withHeader(header).withFooter(footer); input.apply(write); p.run(); assertOutputFiles(elems, header, footer, coder, numShards, baseDir, outputName, write.getShardNameTemplate()); }
From source file:io.github.dsheirer.gui.SDRTrunk.java
/** * Initialize the contents of the frame. *//* w w w . j a va 2s . c o m*/ private void initGUI() { mMainGui.setLayout(new MigLayout("insets 0 0 0 0 ", "[grow,fill]", "[grow,fill]")); /** * Setup main JFrame window */ mTitle = SystemProperties.getInstance().getApplicationName(); mMainGui.setTitle(mTitle); mMainGui.setBounds(100, 100, 1280, 800); mMainGui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //Set preferred sizes to influence the split mSpectralPanel.setPreferredSize(new Dimension(1280, 300)); mControllerPanel.setPreferredSize(new Dimension(1280, 500)); mSplitPane = new JideSplitPane(JideSplitPane.VERTICAL_SPLIT); mSplitPane.setDividerSize(5); mSplitPane.add(mSpectralPanel); mSplitPane.add(mControllerPanel); mBroadcastStatusVisible = SystemProperties.getInstance().get(PROPERTY_BROADCAST_STATUS_VISIBLE, false); //Show broadcast status panel when user requests - disabled by default if (mBroadcastStatusVisible) { mSplitPane.add(getBroadcastStatusPanel()); } mMainGui.add(mSplitPane, "cell 0 0,span,grow"); /** * Menu items */ JMenuBar menuBar = new JMenuBar(); mMainGui.setJMenuBar(menuBar); JMenu fileMenu = new JMenu("File"); menuBar.add(fileMenu); JMenuItem logFilesMenu = new JMenuItem("Logs & Recordings"); logFilesMenu.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { try { Desktop.getDesktop().open(getHomePath().toFile()); } catch (Exception e) { mLog.error("Couldn't open file explorer"); JOptionPane.showMessageDialog(mMainGui, "Can't launch file explorer - files are located at: " + getHomePath().toString(), "Can't launch file explorer", JOptionPane.ERROR_MESSAGE); } } }); fileMenu.add(logFilesMenu); JMenuItem settingsMenu = new JMenuItem("Icon Manager"); settingsMenu.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { mIconManager.showEditor(mMainGui); } }); fileMenu.add(settingsMenu); fileMenu.add(new JSeparator()); JMenuItem exitMenu = new JMenuItem("Exit"); exitMenu.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { System.exit(0); } }); fileMenu.add(exitMenu); JMenu viewMenu = new JMenu("View"); viewMenu.add(new BroadcastStatusVisibleMenuItem(mControllerPanel)); menuBar.add(viewMenu); JMenuItem screenCaptureItem = new JMenuItem("Screen Capture"); screenCaptureItem.setMnemonic(KeyEvent.VK_C); screenCaptureItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, ActionEvent.ALT_MASK)); screenCaptureItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { try { Robot robot = new Robot(); final BufferedImage image = robot.createScreenCapture(mMainGui.getBounds()); SystemProperties props = SystemProperties.getInstance(); Path capturePath = props.getApplicationFolder("screen_captures"); if (!Files.exists(capturePath)) { try { Files.createDirectory(capturePath); } catch (IOException e) { mLog.error("Couldn't create 'screen_captures' " + "subdirectory in the " + "SDRTrunk application directory", e); } } String filename = TimeStamp.getTimeStamp("_") + "_screen_capture.png"; final Path captureFile = capturePath.resolve(filename); EventQueue.invokeLater(new Runnable() { @Override public void run() { try { ImageIO.write(image, "png", captureFile.toFile()); } catch (IOException e) { mLog.error("Couldn't write screen capture to " + "file [" + captureFile.toString() + "]", e); } } }); } catch (AWTException e) { mLog.error("Exception while taking screen capture", e); } } }); menuBar.add(screenCaptureItem); }
From source file:org.apache.taverna.databundle.TestDataBundles.java
@Test public void clearRecursive() throws Exception { Path inputs = DataBundles.getInputs(dataBundle); Path file1 = inputs.resolve("file1"); Path file1Dir = inputs.resolve("file1.dir"); Files.createDirectory(file1); Files.createDirectory(file1Dir); Path nested = file1Dir.resolve("nested"); Files.createDirectory(nested); Path filePng = file1Dir.resolve("file.png"); Path fileTxt = nested.resolve("file1somethingelse.txt"); Files.createFile(filePng);/*from w w w . j ava2s . co m*/ Files.createFile(fileTxt); DataBundles.deleteAllExtensions(file1); assertFalse(Files.exists(file1)); assertFalse(Files.exists(nested)); assertFalse(Files.exists(file1Dir)); assertFalse(Files.exists(filePng)); assertFalse(Files.exists(fileTxt)); }