Example usage for java.nio.file Path getParent

List of usage examples for java.nio.file Path getParent

Introduction

In this page you can find the example usage for java.nio.file Path getParent.

Prototype

Path getParent();

Source Link

Document

Returns the parent path, or null if this path does not have a parent.

Usage

From source file:org.bonitasoft.platform.setup.command.configure.BundleConfigurator.java

void copyDriverFile(Path srcDriverFile, Path targetDriverFile, String dbVendor) throws PlatformException {
    try {/*from w w w  .ja  va  2s  .  co  m*/
        final Path targetDriverFolder = targetDriverFile.getParent();
        targetDriverFolder.toFile().mkdirs();
        Files.copy(srcDriverFile, targetDriverFile);
        LOGGER.info("Copying your " + dbVendor + " driver file '" + getRelativePath(srcDriverFile)
                + "' to tomcat lib folder '" + getRelativePath(targetDriverFolder) + "'");
    } catch (IOException e) {
        throw new PlatformException("Fail to copy driver file lib/" + srcDriverFile.getFileName() + " to "
                + targetDriverFile.toAbsolutePath() + ": " + e.getMessage(), e);
    }
}

From source file:org.codice.ddf.configuration.migration.AbstractMigrationSupport.java

/**
 * Creates a test file at the given path under .
 *
 * <p><i>Note:</i> The file will be created with the filename (no directory) as its content.
 *
 * @param path the path of the test file to create in the specified directory
 * @return a path corresponding to the test file created (relativized from ${ddf.home})
 * @throws IOException if an I/O error occurs while creating the test file
 *///from   w w w. j ava 2  s . com
public Path createFile(Path path) throws IOException {
    return createFile(path.getParent(), path.getFileName().toString());
}

From source file:it.tidalwave.bluemarine2.persistence.impl.DefaultPersistence.java

/*******************************************************************************************************************
 *
 * Exports the repository to the given file.
 *
 * @param   path                    where to export the data to
 * @throws  RDFHandlerException//  www.jav a  2s .c om
 * @throws  IOException
 * @throws  RepositoryException
 *
 ******************************************************************************************************************/
@Override
public void exportToFile(final @Nonnull Path path)
        throws RDFHandlerException, IOException, RepositoryException {
    log.info("exportToFile({})", path);
    Files.createDirectories(path.getParent());

    try (final PrintWriter pw = new PrintWriter(Files.newBufferedWriter(path, UTF_8));
            final RepositoryConnection connection = repository.getConnection()) {
        final RDFHandler writer = new SortingRDFHandler(new N3Writer(pw));

        //            FIXME: use Iterations - and sort
        //            for (final Namespace namespace : connection.getNamespaces().asList())
        //              {
        //                writer.handleNamespace(namespace.getPrefix(), namespace.getName());
        //              }

        writer.handleNamespace("bio", "http://purl.org/vocab/bio/0.1/");
        writer.handleNamespace("bmmo", "http://bluemarine.tidalwave.it/2015/04/mo/");
        writer.handleNamespace("dc", "http://purl.org/dc/elements/1.1/");
        writer.handleNamespace("foaf", "http://xmlns.com/foaf/0.1/");
        writer.handleNamespace("owl", "http://www.w3.org/2002/07/owl#");
        writer.handleNamespace("mo", "http://purl.org/ontology/mo/");
        writer.handleNamespace("rdfs", "http://www.w3.org/2000/01/rdf-schema#");
        writer.handleNamespace("rel", "http://purl.org/vocab/relationship/");
        writer.handleNamespace("vocab", "http://dbtune.org/musicbrainz/resource/vocab/");
        writer.handleNamespace("xs", "http://www.w3.org/2001/XMLSchema#");

        connection.export(writer);
    }
}

From source file:org.ballerinalang.stdlib.system.FileSystemTest.java

@Test(description = "Test for creating new file")
public void testCreateDirWithoutParentDir() throws IOException {
    Path filepath = tempDirPath.resolve("temp-dir").resolve("nested-dir");
    FileUtils.deleteDirectory(filepath.getParent().toFile());
    try {/*from  w  w  w  . ja va2 s.c o m*/
        BValue[] args = { new BString(filepath.toString()), new BBoolean(false) };
        BValue[] returns = BRunUtil.invoke(compileResult, "testCreateDir", args);
        assertTrue(returns[0] instanceof BError);
        BError error = (BError) returns[0];
        assertEquals(error.getReason(), "{ballerina/system}FILE_SYSTEM_ERROR");
        log.info("Ballerina error: " + error.getDetails().stringValue());
        assertFalse(Files.exists(filepath));
    } finally {
        FileUtils.deleteDirectory(filepath.getParent().toFile());
    }
}

From source file:org.apache.taverna.robundle.manifest.TestManifestJSON.java

@Test
public void createBundle() throws Exception {
    // Create bundle as in Example 3 of the specification
    // http://wf4ever.github.io/ro/bundle/2013-05-21/
    try (Bundle bundle = Bundles.createBundle()) {
        Calendar createdOnCal = Calendar.getInstance(TimeZone.getTimeZone("Z"), Locale.ENGLISH);
        // "2013-03-05T17:29:03Z"
        // Remember months are 0-based in java.util.Calendar!
        createdOnCal.set(2013, 3 - 1, 5, 17, 29, 03);
        createdOnCal.set(Calendar.MILLISECOND, 0);
        FileTime createdOn = FileTime.fromMillis(createdOnCal.getTimeInMillis());
        Manifest manifest = bundle.getManifest();
        manifest.setCreatedOn(createdOn);
        Agent createdBy = new Agent("Alice W. Land");
        createdBy.setUri(URI.create("http://example.com/foaf#alice"));
        createdBy.setOrcid(URI.create("http://orcid.org/0000-0002-1825-0097"));

        manifest.setCreatedBy(createdBy);

        Path evolutionPath = bundle.getPath(".ro/evolution.ttl");
        Files.createDirectories(evolutionPath.getParent());
        Bundles.setStringValue(evolutionPath, "<manifest.json> < http://purl.org/pav/retrievedFrom> "
                + "<http://wf4ever.github.io/ro/bundle/2013-05-21/example/.ro/manifest.json> .");
        manifest.getHistory().add(evolutionPath);

        Path jpeg = bundle.getPath("folder/soup.jpeg");
        Files.createDirectory(jpeg.getParent());
        Files.createFile(jpeg);//from   www  . j  a  va 2  s  . c om
        // register in manifest first
        bundle.getManifest().getAggregation(jpeg);

        URI blog = URI.create("http://example.com/blog/");
        bundle.getManifest().getAggregation(blog);

        Path readme = bundle.getPath("README.txt");
        Files.createFile(readme);
        PathMetadata readmeMeta = bundle.getManifest().getAggregation(readme);
        readmeMeta.setMediatype("text/plain");
        Agent readmeCreatedby = new Agent("Bob Builder");
        readmeCreatedby.setUri(URI.create("http://example.com/foaf#bob"));
        readmeMeta.setCreatedBy(readmeCreatedby);

        // 2013-02-12T19:37:32.939Z
        createdOnCal.set(2013, 2 - 1, 12, 19, 37, 32);
        createdOnCal.set(Calendar.MILLISECOND, 939);
        createdOn = FileTime.fromMillis(createdOnCal.getTimeInMillis());
        Files.setLastModifiedTime(readme, createdOn);
        readmeMeta.setCreatedOn(createdOn);

        PathMetadata comments = bundle.getManifest()
                .getAggregation(URI.create("http://example.com/comments.txt"));
        comments.getOrCreateBundledAs().setURI(URI.create("urn:uuid:a0cf8616-bee4-4a71-b21e-c60e6499a644"));
        comments.getOrCreateBundledAs().setFolder(bundle.getPath("/folder/"));
        comments.getOrCreateBundledAs().setFilename("external.txt");

        PathAnnotation jpegAnn = new PathAnnotation();
        jpegAnn.setAbout(jpeg);
        Path soupProps = Bundles.getAnnotations(bundle).resolve("soup-properties.ttl");
        Bundles.setStringValue(soupProps, "</folder/soup.jpeg> <http://xmlns.com/foaf/0.1/depicts> "
                + "<http://example.com/menu/tomato-soup> .");
        jpegAnn.setContent(soupProps);
        // jpegAnn.setContent(URI.create("annotations/soup-properties.ttl"));
        jpegAnn.setUri(URI.create("urn:uuid:d67466b4-3aeb-4855-8203-90febe71abdf"));
        manifest.getAnnotations().add(jpegAnn);

        PathAnnotation proxyAnn = new PathAnnotation();
        proxyAnn.setAbout(comments.getBundledAs().getURI());
        proxyAnn.setContent(URI.create("http://example.com/blog/they-aggregated-our-file"));
        manifest.getAnnotations().add(proxyAnn);

        Path metaAnn = Bundles.getAnnotations(bundle).resolve("a-meta-annotation-in-this-ro.txt");
        Bundles.setStringValue(metaAnn, "This bundle contains an annotation about /folder/soup.jpeg");

        PathAnnotation metaAnnotation = new PathAnnotation();
        metaAnnotation.setAbout(bundle.getRoot());
        metaAnnotation.getAboutList().add(URI.create("urn:uuid:d67466b4-3aeb-4855-8203-90febe71abdf"));

        metaAnnotation.setContent(metaAnn);
        manifest.getAnnotations().add(metaAnnotation);

        Path jsonPath = bundle.getManifest().writeAsJsonLD();
        ObjectMapper objectMapper = new ObjectMapper();
        String jsonStr = Bundles.getStringValue(jsonPath);
        //System.out.println(jsonStr);
        JsonNode json = objectMapper.readTree(jsonStr);
        checkManifestJson(json);
    }
}

From source file:com.yqboots.fss.web.controller.FileItemController.java

@PreAuthorize(FileItemPermissions.WRITE)
@RequestMapping(value = WebKeys.MAPPING_ROOT, method = RequestMethod.POST)
public String update(@Valid @ModelAttribute(WebKeys.MODEL) final FileUploadForm form,
        @PageableDefault final Pageable pageable, final BindingResult bindingResult, final ModelMap model)
        throws IOException {
    new FileUploadFormValidator().validate(form, bindingResult);
    if (bindingResult.hasErrors()) {
        model.addAttribute(WebKeys.PAGE, fileItemManager.findByPath(StringUtils.EMPTY, pageable));
        return VIEW_HOME;
    }/*  w w  w . j a v a  2s . c  om*/

    final MultipartFile file = form.getFile();
    final String path = form.getPath();
    final boolean overrideExisting = form.isOverrideExisting();

    final Path destination = Paths
            .get(fileItemManager.getFullPath(path) + File.separator + file.getOriginalFilename());
    if (Files.exists(destination) && overrideExisting) {
        file.transferTo(destination.toFile());
    } else {
        Files.createDirectories(destination.getParent());
        Files.createFile(destination);
        file.transferTo(destination.toFile());
    }

    model.clear();
    return REDIRECT_VIEW_PATH;
}

From source file:org.dia.kafka.isatools.producer.DirWatcher.java

/**
 * Process all events for keys queued to the watcher
 * @param isatProd/*w w w  .j av a 2 s.  com*/
 */
void processEvents(ISAToolsKafkaProducer isatProd) {
    for (;;) {

        // wait for key to be signalled
        WatchKey key;
        try {
            key = watcher.take();
        } catch (InterruptedException x) {
            return;
        }

        Path dir = keys.get(key);
        if (dir == null) {
            System.err.println("WatchKey not recognized!!");
            continue;
        }

        List<JSONObject> jsonParsedResults = new ArrayList<JSONObject>();

        for (WatchEvent<?> event : key.pollEvents()) {
            WatchEvent.Kind kind = event.kind();

            // TBD - provide example of how OVERFLOW event is handled
            if (kind == OVERFLOW) {
                continue;
            }

            // Context for directory entry event is the file name of entry
            WatchEvent<Path> ev = cast(event);
            Path name = ev.context();
            Path child = dir.resolve(name);

            // If an inner file has been modify then, recreate the entry
            if (kind == ENTRY_MODIFY || kind == ENTRY_CREATE) {
                File fileCheck = child.getParent().toFile();
                if (child.toFile().isDirectory()) {
                    fileCheck = child.toFile();
                }

                System.out.format("[%s] %s : %s\n", this.getClass().getSimpleName(), kind.toString(),
                        fileCheck.getAbsolutePath());
                List<String> folderFiles = ISAToolsKafkaProducer.getFolderFiles(fileCheck);
                List<JSONObject> jsonObjects = ISAToolsKafkaProducer.doTikaRequest(folderFiles);
                if (!jsonObjects.isEmpty()) {
                    //                        jsonParsedResults.addAll(jsonObjects);
                    isatProd.sendISAToolsUpdates(jsonObjects);
                }
            }

            // TODO this event has still to be specified for documents
            if (kind == ENTRY_DELETE) {
                System.err.println(String.format("Delete event not supported %s", child.toAbsolutePath()));
            }

            // if directory is created, and watching recursively, then
            // register it and its sub-directories
            if (kind == ENTRY_CREATE) {
                try {
                    if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
                        registerAll(child);
                    }
                } catch (IOException x) {
                    // ignore to keep sample readbale
                    System.err.format("IOException when creating %s \n", child.toAbsolutePath());
                }
            }
        }

        // reset key and remove from set if directory no longer accessible
        boolean valid = key.reset();
        if (!valid) {
            keys.remove(key);

            // all directories are inaccessible
            if (keys.isEmpty()) {
                break;
            }
        }
    }
}

From source file:com.ejisto.event.listener.SessionRecorderManager.java

private File selectOutputDirectory(Component parent, String directoryPath, boolean saveLastSelectionPath,
        SettingsRepository settingsRepository) {
    String targetPath = null;// w  ww.j  a va2  s  . c o  m
    Path savedPath = null;
    if (StringUtils.isNotBlank(directoryPath)) {
        savedPath = Paths.get(directoryPath);
        Path selectionPath = savedPath.getParent();
        if (selectionPath != null) {
            targetPath = selectionPath.toString();
        }
    }
    JFileChooser fileChooser = new JFileChooser(targetPath);
    fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    fileChooser.setDialogType(JFileChooser.SAVE_DIALOG);
    fileChooser.setSelectedFile(savedPath != null ? savedPath.toFile() : null);
    fileChooser.setDialogTitle(getMessage("session.record.save.target"));

    return GuiUtils.openFileSelectionDialog(parent, saveLastSelectionPath, fileChooser, LAST_OUTPUT_PATH,
            settingsRepository);
}

From source file:org.codice.ddf.configuration.migration.AbstractMigrationSupport.java

/**
 * Creates a test softlink at the given path.
 *
 * @param path the path of the test softlink to create in the specified directory
 * @param dest the destination path for the softlink
 * @return a path corresponding to the test softlink created (relativized from ${ddf.home})
 * @throws IOException if an I/O error occurs while creating the test softlink
 * @throws UnsupportedOperationException if the implementation does not support symbolic links
 *///from w  ww .  j  a v  a2  s .  c om
public Path createSoftLink(Path path, Path dest) throws IOException {
    return createSoftLink(path.getParent(), path.getFileName().toString(), dest);
}

From source file:org.cirdles.squid.web.SquidReportingService.java

public Path generateReports(String myFileName, InputStream prawnFile, InputStream taskFile, boolean useSBM,
        boolean userLinFits, String refMatFilter, String concRefMatFilter, String preferredIndexIsotopeName)
        throws IOException, JAXBException, SAXException {

    IndexIsoptopesEnum preferredIndexIsotope = IndexIsoptopesEnum.valueOf(preferredIndexIsotopeName);

    // Posix attributes added to support web service on Linux - ignoring windows for now
    Set<PosixFilePermission> perms = EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE, GROUP_READ);

    // detect if prawnfile is zipped
    boolean prawnIsZip = false;
    String fileName = "";
    if (myFileName == null) {
        fileName = DEFAULT_PRAWNFILE_NAME;
    } else if (myFileName.toLowerCase().endsWith(".zip")) {
        fileName = FilenameUtils.removeExtension(myFileName);
        prawnIsZip = true;/*ww  w.  ja v  a  2  s. com*/
    } else {
        fileName = myFileName;
    }

    SquidProject squidProject = new SquidProject();
    prawnFileHandler = squidProject.getPrawnFileHandler();

    CalamariFileUtilities.initSampleParametersModels();

    Path reportsZip = null;
    Path reportsFolder = null;
    try {
        Path uploadDirectory = Files.createTempDirectory("upload");
        Path uploadDirectory2 = Files.createTempDirectory("upload2");

        Path prawnFilePath;
        Path taskFilePath;
        if (prawnIsZip) {
            Path prawnFilePathZip = uploadDirectory.resolve("prawn-file.zip");
            Files.copy(prawnFile, prawnFilePathZip);
            prawnFilePath = extractZippedFile(prawnFilePathZip.toFile(), uploadDirectory.toFile());
        } else {
            prawnFilePath = uploadDirectory.resolve("prawn-file.xml");
            Files.copy(prawnFile, prawnFilePath);
        }

        taskFilePath = uploadDirectory2.resolve("task-file.xls");
        Files.copy(taskFile, taskFilePath);

        ShrimpDataFileInterface prawnFileData = prawnFileHandler
                .unmarshallPrawnFileXML(prawnFilePath.toString(), true);
        squidProject.setPrawnFile(prawnFileData);

        // hard-wired for now
        squidProject.getTask().setCommonPbModel(CommonPbModel.getDefaultModel("GA Common Lead 2018", "1.0"));
        squidProject.getTask().setPhysicalConstantsModel(
                PhysicalConstantsModel.getDefaultModel(SQUID2_DEFAULT_PHYSICAL_CONSTANTS_MODEL_V1, "1.0"));
        File squidTaskFile = taskFilePath.toFile();

        squidProject.createTaskFromImportedSquid25Task(squidTaskFile);

        squidProject.setDelimiterForUnknownNames("-");

        TaskInterface task = squidProject.getTask();
        task.setFilterForRefMatSpotNames(refMatFilter);
        task.setFilterForConcRefMatSpotNames(concRefMatFilter);
        task.setUseSBM(useSBM);
        task.setUserLinFits(userLinFits);
        task.setSelectedIndexIsotope(preferredIndexIsotope);

        // process task           
        task.applyTaskIsotopeLabelsToMassStations();

        Path calamariReportsFolderAliasParent = Files.createTempDirectory("reports-destination");
        Path calamariReportsFolderAlias = calamariReportsFolderAliasParent
                .resolve(DEFAULT_SQUID3_REPORTS_FOLDER.getName() + "-from Web Service");
        File reportsDestinationFile = calamariReportsFolderAlias.toFile();

        reportsEngine = prawnFileHandler.getReportsEngine();
        prawnFileHandler.initReportsEngineWithCurrentPrawnFileName(fileName);
        reportsEngine.setFolderToWriteCalamariReports(reportsDestinationFile);

        reportsEngine.produceReports(task.getShrimpFractions(), (ShrimpFraction) task.getUnknownSpots().get(0),
                task.getReferenceMaterialSpots().size() > 0
                        ? (ShrimpFraction) task.getReferenceMaterialSpots().get(0)
                        : (ShrimpFraction) task.getUnknownSpots().get(0),
                true, false);

        squidProject.produceTaskAudit();

        squidProject.produceUnknownsCSV(true);
        squidProject.produceReferenceMaterialCSV(true);
        // next line report will show only super sample for now
        squidProject.produceUnknownsBySampleForETReduxCSV(true);

        Files.delete(prawnFilePath);

        reportsFolder = Paths.get(reportsEngine.getFolderToWriteCalamariReports().getParentFile().getPath());

    } catch (IOException | JAXBException | SAXException | SquidException iOException) {

        Path config = Files.createTempFile("SquidWebServiceMessage", "txt",
                PosixFilePermissions.asFileAttribute(perms));
        try (BufferedWriter writer = Files.newBufferedWriter(config, StandardCharsets.UTF_8)) {
            writer.write("Squid Reporting web service was not able to process supplied files.");
            writer.newLine();
            writer.write(iOException.getMessage());
            writer.newLine();
        }
        File message = config.toFile();

        Path messageDirectory = Files.createTempDirectory("message");
        Path messageFilePath = messageDirectory.resolve("Squid Web Service Message.txt");
        Files.copy(message.toPath(), messageFilePath);

        reportsFolder = messageFilePath.getParent();
    }

    reportsZip = ZipUtility.recursivelyZip(reportsFolder);
    FileUtilities.recursiveDelete(reportsFolder);

    return reportsZip;
}