Example usage for java.nio.file Files newDirectoryStream

List of usage examples for java.nio.file Files newDirectoryStream

Introduction

In this page you can find the example usage for java.nio.file Files newDirectoryStream.

Prototype

public static DirectoryStream<Path> newDirectoryStream(Path dir, DirectoryStream.Filter<? super Path> filter)
        throws IOException 

Source Link

Document

Opens a directory, returning a DirectoryStream to iterate over the entries in the directory.

Usage

From source file:org.fao.geonet.api.records.MetadataInsertDeleteApi.java

@ApiOperation(value = "Add a record", notes = "Add one or more record from an XML fragment, "
        + "URL or file in a folder on the catalog server. When loading"
        + "from the catalog server folder, it might be faster to use a "
        + "local filesystem harvester.", nickname = "insert")
@RequestMapping(method = { RequestMethod.PUT }, produces = { MediaType.APPLICATION_JSON_VALUE }, consumes = {
        MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE,
        MediaType.APPLICATION_FORM_URLENCODED_VALUE })
@ApiResponses(value = { @ApiResponse(code = 201, message = API_PARAM_REPORT_ABOUT_IMPORTED_RECORDS),
        @ApiResponse(code = 403, message = ApiParams.API_RESPONSE_NOT_ALLOWED_ONLY_EDITOR) })
@PreAuthorize("hasRole('Editor')")
@ResponseStatus(HttpStatus.CREATED)/*from  w w w. j  a  va 2  s.  c o m*/
public @ResponseBody SimpleMetadataProcessingReport insert(
        @ApiParam(value = API_PARAM_RECORD_TYPE, required = false, defaultValue = "METADATA") @RequestParam(required = false, defaultValue = "METADATA") final MetadataType metadataType,
        @ApiParam(value = "XML fragment.", required = false) @RequestBody(required = false) String xml,
        @ApiParam(value = "URL of a file to download and insert.", required = false) @RequestParam(required = false) String[] url,
        @ApiParam(value = "Server folder where to look for files.", required = false) @RequestParam(required = false) String serverFolder,
        @ApiParam(value = "(Server folder import only) Recursive search in folder.", required = false) @RequestParam(required = false, defaultValue = "false") final boolean recursiveSearch,
        @ApiParam(value = "(MEF file only) Assign to current catalog.", required = false) @RequestParam(required = false, defaultValue = "false") final boolean assignToCatalog,
        @ApiParam(value = API_PARAM_RECORD_UUID_PROCESSING, required = false, defaultValue = "NOTHING") @RequestParam(required = false, defaultValue = "NOTHING") final MEFLib.UuidAction uuidProcessing,
        @ApiParam(value = API_PARAP_RECORD_GROUP, required = false) @RequestParam(required = false) final String group,
        @ApiParam(value = API_PARAM_RECORD_TAGS, required = false) @RequestParam(required = false) final String[] category,
        @ApiParam(value = API_PARAM_RECORD_VALIDATE, required = false) @RequestParam(required = false, defaultValue = "false") final boolean rejectIfInvalid,
        @ApiParam(value = API_PARAM_RECORD_XSL, required = false, defaultValue = "_none_") @RequestParam(required = false, defaultValue = "_none_") final String transformWith,
        @ApiParam(value = API_PARAM_FORCE_SCHEMA, required = false) @RequestParam(required = false) String schema,
        @ApiParam(value = "(experimental) Add extra information to the record.", required = false) @RequestParam(required = false) final String extra,
        HttpServletRequest request) throws Exception {
    if (url == null && xml == null && serverFolder == null) {
        throw new IllegalArgumentException(
                String.format("XML fragment or a URL or a server folder MUST be provided."));
    }
    SimpleMetadataProcessingReport report = new SimpleMetadataProcessingReport();
    ApplicationContext applicationContext = ApplicationContextHolder.get();

    if (xml != null) {
        Element element = null;
        try {
            element = Xml.loadString(xml, false);
        } catch (JDOMParseException ex) {
            throw new IllegalArgumentException(
                    String.format("XML fragment is invalid. Error is %s", ex.getMessage()));
        }
        Pair<Integer, String> pair = loadRecord(metadataType, Xml.loadString(xml, false), uuidProcessing, group,
                category, rejectIfInvalid, false, transformWith, schema, extra, request);
        report.addMetadataInfos(pair.one(),
                String.format("Metadata imported from XML with UUID '%s'", pair.two()));

        triggerImportEvent(request, pair.two());

        report.incrementProcessedRecords();
    }
    if (url != null) {
        for (String u : url) {
            Element xmlContent = null;
            try {
                xmlContent = Xml.loadFile(ApiUtils.downloadUrlInTemp(u));
            } catch (Exception e) {
                report.addError(e);
            }
            if (xmlContent != null) {
                Pair<Integer, String> pair = loadRecord(metadataType, xmlContent, uuidProcessing, group,
                        category, rejectIfInvalid, false, transformWith, schema, extra, request);
                report.addMetadataInfos(pair.one(),
                        String.format("Metadata imported from URL with UUID '%s'", pair.two()));

                triggerImportEvent(request, pair.two());

            }

            report.incrementProcessedRecords();
        }
    }
    if (serverFolder != null) {
        Path serverFolderPath = IO.toPath(serverFolder);

        final List<Path> files = Lists.newArrayList();
        final MEFLib.MefOrXmlFileFilter predicate = new MEFLib.MefOrXmlFileFilter();
        if (recursiveSearch) {
            Files.walkFileTree(serverFolderPath, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (predicate.accept(file)) {
                        files.add(file);
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        } else {
            try (DirectoryStream<Path> paths = Files.newDirectoryStream(serverFolderPath, predicate)) {
                for (Path file : paths) {
                    files.add(file);
                }
            }
        }

        if (files.size() == 0) {
            throw new Exception(
                    String.format("No XML or MEF or ZIP file found in server folder '%s'.", serverFolder));
        }
        SettingManager settingManager = ApplicationContextHolder.get().getBean(SettingManager.class);
        ServiceContext context = ApiUtils.createServiceContext(request);
        for (Path f : files) {
            if (MEFLib.isValidArchiveExtensionForMEF(f.getFileName().toString())) {
                try {
                    MEFLib.Version version = MEFLib.getMEFVersion(f);
                    List<String> ids = MEFLib.doImport(version == MEFLib.Version.V1 ? "mef" : "mef2",
                            uuidProcessing, transformWith, settingManager.getSiteId(), metadataType, category,
                            group, rejectIfInvalid, assignToCatalog, context, f);
                    for (String id : ids) {
                        report.addMetadataInfos(Integer.parseInt(id),
                                String.format("Metadata imported from MEF with id '%s'", id));
                        triggerCreationEvent(request, id);

                        report.incrementProcessedRecords();
                    }
                } catch (Exception e) {
                    report.addError(e);
                    report.addInfos(String.format("Failed to import MEF file '%s'. Check error for details.",
                            f.getFileName().toString()));
                }
            } else {
                try {
                    Pair<Integer, String> pair = loadRecord(metadataType, Xml.loadFile(f), uuidProcessing,
                            group, category, rejectIfInvalid, false, transformWith, schema, extra, request);
                    report.addMetadataInfos(pair.one(),
                            String.format("Metadata imported from server folder with UUID '%s'", pair.two()));

                    triggerCreationEvent(request, pair.two());

                } catch (Exception e) {
                    report.addError(e);
                }
                report.incrementProcessedRecords();
            }

        }
    }
    report.close();
    return report;
}

From source file:org.eclipse.winery.repository.backend.filebased.FilebasedRepository.java

@Override
public <T extends TOSCAElementId> SortedSet<T> getNestedIds(GenericId ref, Class<T> idClass) {
    Path dir = this.id2AbsolutePath(ref);
    SortedSet<T> res = new TreeSet<T>();
    if (!Files.exists(dir)) {
        // the id has been generated by the exporter without existance test.
        // This test is done here.
        return res;
    }/*w w  w .  jav  a 2  s .co  m*/
    assert (Files.isDirectory(dir));
    // list all directories contained in this directory
    try (DirectoryStream<Path> ds = Files.newDirectoryStream(dir, new OnlyNonHiddenDirectories())) {
        for (Path p : ds) {
            XMLId xmlId = new XMLId(p.getFileName().toString(), true);
            @SuppressWarnings("unchecked")
            Constructor<T>[] constructors = (Constructor<T>[]) idClass.getConstructors();
            assert (constructors.length == 1);
            Constructor<T> constructor = constructors[0];
            assert (constructor.getParameterTypes().length == 2);
            T id;
            try {
                id = constructor.newInstance(ref, xmlId);
            } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                    | InvocationTargetException e) {
                FilebasedRepository.logger.debug("Internal error at invocation of id constructor", e);
                // abort everything, return invalid result
                return res;
            }
            res.add(id);
        }
    } catch (IOException e) {
        FilebasedRepository.logger.debug("Cannot close ds", e);
    }
    return res;
}

From source file:de.phillme.PhotoSorter.java

private List<PhotoFile> listSourceFiles() throws IOException, ImageProcessingException {
    List<PhotoFile> result = new ArrayList<>();
    Date date;/* w w w.  ja  va  2 s . c o  m*/

    try (DirectoryStream<Path> stream = Files.newDirectoryStream(this.photosPath, "*.*")) {
        for (Path entry : stream) {
            date = null;
            PhotoFile photoFile;

            String fileType = detectMimeType(entry);
            //String fileExt = getFileExt(entry.getFileName().toString());

            if (fileType != null && fileType.contains("image")) {

                date = getDateFromExif(entry);
            }
            if (date != null) {
                photoFile = new PhotoFile(entry, date);

                result.add(photoFile);
            } else {
                LOGGER.info("Date of " + entry.getFileName()
                        + " could not be determined. Skipping for image processing...");
            }
        }
    } catch (DirectoryIteratorException ex) {
        // I/O error encounted during the iteration, the cause is an IOException
        throw ex.getCause();
    }
    return result;
}

From source file:org.codice.ddf.configuration.admin.ConfigurationAdminMigrationTest.java

@Test(expected = IOException.class)
public void testInitStillProcessesFilesWhenTheyCannotBeMovedToProcessedDirectory() throws Exception {

    PowerMockito.doThrow(new IOException()).when(Files.class);
    Files.newDirectoryStream(any(Path.class), any(String.class));

    setUpTwoConfigFileIterator(configurationDirectoryStream);
    setUpConfigurationFileFactoryForTwoFiles();

    when(Files.newDirectoryStream(any(Path.class), any(String.class))).thenReturn(failedDirectoryStream);

    ConfigurationAdminMigration configurationAdminMigration = new ConfigurationAdminMigration(
            configurationDirectoryStream, PROCESSED_DIRECTORY_PATH, FAILED_DIRECTORY_PATH,
            configurationFileFactory, configurationFilePoller, configurationAdmin,
            CONFIGURATION_FILE_EXTENSION);

    configurationAdminMigration.init();//from   w w w  .ja  va2s . co  m

    verifyStatic();
    Files.move(any(Path.class), any(Path.class));
    Files.newDirectoryStream(any(Path.class), any(String.class));

    verify(configurationDirectoryStream).iterator();
    verify(configurationFileFactory).createConfigurationFile(CONFIG_PATH1);
    verify(configFile1).createConfig();
    verify(configurationFileFactory).createConfigurationFile(CONFIG_PATH2);
    verify(configFile2).createConfig();
    verify(configurationDirectoryStream).close();
}

From source file:frameworks.Masken.java

public boolean maskenInstall(JTable table, JTextArea jTLog, EDPSession session, String LinuxUser,
        String LinuxPass, String Host) {
    try {//from  w w w . jav a  2s.co  m
        ByteArrayOutputStream error = new ByteArrayOutputStream();
        StringBuilder fromServer = new StringBuilder();
        StringBuilder screenls = new StringBuilder();
        StringBuilder screenlsstring = new StringBuilder();
        String maskennummer;
        String fromServerString = "";
        String[] fromServerArray;
        String resourcesServerString = "";
        String[] resourcesServerArray;
        ArrayList datei = new ArrayList();
        String prio = "";
        String xmlziel = "";
        String resourcesziel = "";
        int masksearch = 0;
        int sshexitstatus = 0;
        File file = null;
        int zielzeile = 0;
        String tabellekopf = "";
        boolean failure = false;
        int firstcell = 0;
        int lastcell = 0;
        boolean newpanenotebook = true;

        //SSh Verbindung zum Mandanten ffnen
        SshClient sshclient = new SshClient();
        sshclient.connect(LinuxUser, LinuxPass, Host, 22);

        jTLog.append("----------Maskenimport----------\n");

        jTLog.append("Vorhandene Masken aus Mandanten ermittelt\n");
        jTLog.paint(jTLog.getGraphics());
        //Dateinamen erzeugen
        for (int i = 0; i < table.getRowCount(); i++) {
            //Fehlerflag auf true setzen
            failure = true;
            xmlziel = table.getValueAt(i, 2).toString().replace(table.getValueAt(i, 0).toString(),
                    table.getValueAt(i, 1).toString());
            xmlziel = table.getValueAt(i, 2).toString();
            resourcesziel = table.getValueAt(i, 3).toString().replace(table.getValueAt(i, 0).toString(),
                    table.getValueAt(i, 1).toString());
            maskennummer = table.getValueAt(i, 1).toString();

            // hab ich eine ZD und ein Masken TGZ?      
            if (table.getValueAt(i, 3).equals("TGZ")) {
                xmlziel = table.getValueAt(i, 2).toString();
                prio = xmlziel.substring(xmlziel.indexOf(".") + 1, xmlziel.lastIndexOf("."));
                prio = prio.substring(prio.indexOf(".") + 1, prio.length());
                // Dann kann ich die Maske einfach auf den Serverv kopieren
                file = new File(GlobalVars.dir + "\\Masken\\" + table.getValueAt(i, 2).toString());
                sshexitstatus = sshclient.sendfile(file.toString(), xmlziel);
                jTLog.append("Neue Maske " + maskennummer + prio + " wird hochgeladen\n");
                jTLog.paint(jTLog.getGraphics());
                // und importieren
                jTLog.append("Neue Maske " + maskennummer + prio + " wird im Mandanten importiert\n");
                jTLog.paint(jTLog.getGraphics());
                sshexitstatus = sshclient.sendcommand(
                        "eval `sh denv.sh`;screen_import.sh -n " + maskennummer + " -p " + prio + " " + xmlziel,
                        error, fromServer);

                // und generieren
                jTLog.append("Neue Maske " + maskennummer + prio + " wird generiert\n");
                jTLog.paint(jTLog.getGraphics());
                // Maske generieren
                maskegenerieren(session, maskennummer, prio);

                jTLog.append(error.toString());
                jTLog.paint(jTLog.getGraphics());
                // Kein ZD und kein TGZ File, also muss die Maske integriert werden
            } else {
                datei.clear();
                prio = xmlziel.substring(xmlziel.indexOf(".") + 1, xmlziel.lastIndexOf("."));
                prio = prio.substring(prio.indexOf(".") + 1, prio.indexOf("-"));
                //Tabelle oder Kopf
                tabellekopf = xmlziel.substring(xmlziel.lastIndexOf(".") - 1, xmlziel.lastIndexOf("."));
                if (tabellekopf.equals("Z")) {
                    tabellekopf = "_T.xml";
                } else {
                    tabellekopf = "_M.xml";
                }
                // Maske individualisieren falls notwendig
                individuelleMaskePruefen(session, maskennummer, prio, jTLog);
                // Maske sichern mit screen_export
                jTLog.append(
                        "Maske " + maskennummer + " " + prio + " wird gesichert und kann mit screen_import -n "
                                + maskennummer + " -p " + prio + " screen_restauriert werden\n");
                jTLog.paint(jTLog.getGraphics());
                sshexitstatus = sshclient.sendcommand(
                        "eval `sh denv.sh`;screen_export.sh -n " + maskennummer + " -p " + prio, error,
                        fromServer);

                //Tmp leeren
                File tmpdir = new File("tmp");
                if (tmpdir.exists() && (tmpdir.isDirectory())) {
                    deleteDir(tmpdir);

                }
                new File("tmp").mkdir();

                // Masken.tgz abholen
                jTLog.append("Maske " + maskennummer + " " + prio + " wird geladen\n");
                jTLog.paint(jTLog.getGraphics());
                String servermaske = "./screen." + maskennummer + "." + prio + ".tgz";

                sshexitstatus = sshclient.getfile(servermaske, "tmp\\");
                if (sshexitstatus == -1) {// Maske wurde erfolgreich geladen

                    //Maske einlesen
                    jTLog.append("Maske " + maskennummer + " " + prio + " wird ausgepackt\n");
                    jTLog.paint(jTLog.getGraphics());
                    //tgz lokal auspacken
                    uncompressTarGZ(new File("tmp\\screen." + maskennummer + "." + prio + ".tgz"),
                            new File("tmp\\"));
                    // tgz lschen
                    new File("tmp\\screen." + maskennummer + "." + prio + ".tgz").delete();
                    String changemaske = "screen_" + maskennummer + "_" + prio + tabellekopf;
                    //Maske einlesen
                    jTLog.append("Maske " + maskennummer + " " + prio + " wird erweitert\n");
                    jTLog.paint(jTLog.getGraphics());
                    BufferedReader inservermaske = null;
                    inservermaske = new BufferedReader(new FileReader("tmp\\screens\\screen_" + maskennummer
                            + "\\" + prio + "\\screen_" + maskennummer + "_" + prio + tabellekopf));
                    BufferedReader inmaske = null;
                    inmaske = new BufferedReader(
                            new FileReader(GlobalVars.dir + "\\Masken\\" + table.getValueAt(i, 2).toString()));
                    PrintWriter outservermaske = new PrintWriter(
                            new BufferedWriter(new FileWriter("tmp\\screens\\screen_" + maskennummer + "\\"
                                    + prio + "\\Xscreen_" + maskennummer + "_" + prio + tabellekopf)));
                    int lineNr = 0;
                    zielzeile = 0;
                    firstcell = 0;
                    lastcell = 0;
                    String line = inservermaske.readLine();
                    while (line != null) {

                        datei.add(line);
                        if (line.contains("<cell") && (firstcell == 0))
                            firstcell = lineNr;
                        if (line.contains("</layout.grid") && (firstcell != 0))
                            lastcell = lineNr;
                        if (line.contains("</pane.notebook>")) {
                            zielzeile = lineNr;
                            newpanenotebook = false;
                        }
                        lineNr++;

                        line = inservermaske.readLine();
                    }
                    inservermaske.close();

                    // Raus schreiben der Datei
                    for (int izeilen = 0; izeilen < lineNr - 1; izeilen++) {
                        outservermaske.print(datei.get(izeilen) + "\n");
                        if ((zielzeile == 0) && (firstcell == izeilen)) {
                            outservermaske.print(
                                    "<layout.notebook>\n<pane.notebook msgId=\"b825893d-f00a-4500-ae24-c2fe5364ae0e\">\n <layout.grid>\n"
                                            + "      <cell gridX=\"0\" gridY=\"0\">\n");
                        }
                        if ((zielzeile == 0) && (lastcell == izeilen)) {
                            outservermaske.print("</pane.notebook>\n");
                            zielzeile = izeilen;
                        }

                        if ((izeilen == zielzeile) && (zielzeile != 0)) {
                            line = inmaske.readLine();
                            while (line != null) {
                                // Zuerst die Datei einlesen und jede Zeile raus schreiben
                                outservermaske.print(line + "\n");
                                line = inmaske.readLine();

                            }
                            if (newpanenotebook)
                                outservermaske.print("</layout.notebook>\n </cell>\n </layout.grid> \n");
                        }
                    }
                    outservermaske.close();

                    // Neue Datei nun auf die alte kopieren
                    Files.move(
                            Paths.get("tmp\\screens\\screen_" + maskennummer + "\\" + prio + "\\Xscreen_"
                                    + maskennummer + "_" + prio + tabellekopf),
                            Paths.get("tmp\\screens\\screen_" + maskennummer + "\\" + prio + "\\screen_"
                                    + maskennummer + "_" + prio + tabellekopf),
                            REPLACE_EXISTING);

                    // Resources Dateien anschauen
                    // Append an die Resources.language
                    // sshexitstatus = sshclient.sendcommand("cat  ./screens/screen_" + maskennummer + "/" + prio + "/ResourcesFW  >> ./screens/screen_" + maskennummer + "/" + prio + "/Resources.language", error, fromServer);
                    String resourcesstring = FileUtils.readFileToString(
                            new File(GlobalVars.dir + "\\Masken\\" + table.getValueAt(i, 3).toString()),
                            "utf-8");
                    FileWriter fw = new FileWriter(new File(
                            "tmp\\screens\\screen_" + maskennummer + "\\" + prio + "\\Resources.language"),
                            true);
                    fw.write(resourcesstring);//appends the string to the file
                    if (newpanenotebook)
                        fw.write("b825893d-f00a-4500-ae24-c2fe5364ae0e=Allgemein\n");
                    fw.close();
                    //An Resources_*  den String auch noch anhngen
                    // dazu erst mal die Dateien suchen
                    Path dir = Paths.get("tmp\\screens\\screen_" + maskennummer + "\\" + prio);
                    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "Resources_*")) {
                        for (Path resourcesfile : stream) {
                            fw = new FileWriter(resourcesfile.toFile(), true);
                            fw.write(resourcesstring);//appends the string to the file
                            if (newpanenotebook)
                                fw.write("b825893d-f00a-4500-ae24-c2fe5364ae0e=Allgemein\n");
                            fw.close();
                        }
                    }

                    // Tgz wieder erzeugen
                    createTarGzip("tmp\\", "tmp\\screen." + maskennummer + "." + prio + ".tgz");
                    // Maske wieder auf Server schieben

                    sshexitstatus = sshclient.sendfile("\\tmp\\screen." + maskennummer + "." + prio + ".tgz",
                            "screen." + maskennummer + "." + prio + ".tgz");
                    jTLog.append("Neue Maske " + maskennummer + prio + " wird hochgeladen\n");
                    jTLog.paint(jTLog.getGraphics());
                    // und importieren
                    jTLog.append("Neue Maske " + maskennummer + prio + " wird im Mandanten importiert\n");
                    jTLog.paint(jTLog.getGraphics());
                    sshexitstatus = sshclient
                            .sendcommand(
                                    "eval `sh denv.sh`;screen_import.sh -n " + maskennummer + " -p " + prio
                                            + " " + "screen." + maskennummer + "." + prio + ".tgz",
                                    error, fromServer);

                    // und generieren
                    jTLog.append("Neue Maske " + maskennummer + prio + " wird generiert\n");
                    jTLog.paint(jTLog.getGraphics());
                    // Maske generieren
                    maskegenerieren(session, maskennummer, prio);

                    jTLog.append(error.toString());
                    jTLog.paint(jTLog.getGraphics());

                }
                /*
                //Alter Weg
                // Maske abholen
                jTLog.append("Maske " + maskennummer + " " + prio + " wird geladen\n");
                jTLog.paint(jTLog.getGraphics());
                //String servermaske = "./screens/screen_" + maskennummer + "/" + prio + "/screen_" + maskennummer + "_" + prio + "_M.xml";
                servermaske = "./screens/screen_" + maskennummer + "/" + prio + "/screen_" + maskennummer + "_" + prio + tabellekopf;
                        
                sshexitstatus = sshclient.getfile(servermaske, "tmp\\" + maskennummer + prio + ".xml");
                if (sshexitstatus == -1) {// Maske wurde erfolgreich geladen
                //Maske einlesen
                jTLog.append("Maske " + maskennummer + " " + prio + " wird erweitert\n");
                jTLog.paint(jTLog.getGraphics());
                        
                BufferedReader inservermaske = null;
                inservermaske = new BufferedReader(new FileReader("tmp\\" + maskennummer + prio + ".xml"));
                BufferedReader inmaske = null;
                inmaske = new BufferedReader(new FileReader(GlobalVars.dir + "\\Masken\\" + table.getValueAt(i, 2).toString()));
                PrintWriter outservermaske = new PrintWriter(new BufferedWriter(new FileWriter("tmp\\" + maskennummer + prio + "X.xml")));
                int lineNr = 0;
                String line = inservermaske.readLine();
                while (line != null) {
                        
                    datei.add(line);
                        
                    if (line.contains("</pane.notebook>")) {
                        zielzeile = lineNr;
                    }
                    lineNr++;
                        
                    line = inservermaske.readLine();
                }
                inservermaske.close();
                        
                // Raus schreiben der Datei
                for (int izeilen = 0; izeilen < lineNr - 1; izeilen++) {
                    outservermaske.print(datei.get(izeilen) + "\n");
                    if (izeilen == zielzeile) {
                        line = inmaske.readLine();
                        while (line != null) {
                            // Zuerst die Datei einlesen und jede Zeile raus schreiben
                            outservermaske.print(line + "\n");
                            line = inmaske.readLine();
                        
                        }
                    }
                }
                outservermaske.close();
                        
                //Datei zurck zum server schicken
                jTLog.append("Maske " + maskennummer + " " + prio + " wird gesendet\n");
                jTLog.paint(jTLog.getGraphics());
                sshexitstatus = sshclient.sendfile("tmp\\" + maskennummer + prio + "X.xml", servermaske);
                if (sshexitstatus == -1) {// Maske wurde auf Server bertragen
                    // Jetzt noch die Resources Datei an die Resources auf dem server anhngen
                    sshexitstatus = sshclient.sendfile(GlobalVars.dir + "\\Masken\\" + table.getValueAt(i, 3).toString(), "./screens/screen_" + maskennummer + "/" + prio + "/ResourcesFW");
                    if (sshexitstatus == -1) {
                        sshexitstatus = sshclient.sendcommand("cat  ./screens/screen_" + maskennummer + "/" + prio + "/ResourcesFW  >> ./screens/screen_" + maskennummer + "/" + prio + "/Resources.language", error, fromServer);
                        //Resources wurde auf Server bertragen  
                         jTLog.append(error.toString());
                        jTLog.paint(jTLog.getGraphics());
                        if (sshexitstatus==0)
                        {
                           sshexitstatus = sshclient.sendcommand("ls screens/screen_" + maskennummer + "/" + prio + "/Resources_* -l", error, fromServer);
                           jTLog.append(error.toString());
                            jTLog.paint(jTLog.getGraphics());
                        if (sshexitstatus == 0) {
                                    
                            resourcesServerString = fromServer.toString();
                            resourcesServerArray = resourcesServerString.split("\n");
                            ///Bisher alles gut gelaufen, deswegen failure auf false setzen
                            failure = false;
                            for (int iresources = 0; iresources < resourcesServerArray.length; iresources++) {
                                if (resourcesServerArray[iresources].toString().contains("Resources")) {
                                    sshexitstatus = sshclient.sendcommand("cat  ./screens/screen_" + maskennummer + "/" + prio + "/ResourcesFW  >>" + resourcesServerArray[iresources].toString().substring(resourcesServerArray[iresources].lastIndexOf(" "), resourcesServerArray[iresources].length()), error, fromServer);
                                    if (sshexitstatus != 0) {
                                        failure = true;
                                    }
                                    jTLog.append(error.toString());
                                    jTLog.paint(jTLog.getGraphics());
                                }
                        
                            }
                        
                            jTLog.append("Maske " + maskennummer + " " + prio + " wird generiert\n");
                        
                            // Maske nun noch generieren
                            maskegenerieren(session, maskennummer, prio); 
                        }
                               
                                
                        }
                        
                    }
                        
                }
                        
                }*/
                if (failure) {

                    //Alte Maske wieder importieren 
                    //  jTLog.append(error.toString());
                    //  jTLog.append("Gesicherte Maske wird wieder installiert !!! manuelle Nacharbeit notwendig!!!\n");
                    //  jTLog.paint(jTLog.getGraphics());
                    //  sshexitstatus = sshclient.sendcommand("eval `sh denv.sh`;screen_import.sh -n " + maskennummer + " -p " + prio+" screen."+maskennummer+"."+prio+".tgz", error, fromServer);
                }

            }

        }

    } catch (JSchException ex) {
        Logger.getLogger(Masken.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Masken.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InterruptedException ex) {
        Logger.getLogger(Masken.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SftpException ex) {
        Logger.getLogger(Masken.class.getName()).log(Level.SEVERE, null, ex);
    }
    return true;
}

From source file:org.eclipse.winery.repository.backend.filebased.FilebasedRepository.java

@Override
// below, toscaComponents is an array, which is used in an iterator
// As Java does not allow generic arrays, we have to suppress the warning when fetching an
// element out of the list
@SuppressWarnings("unchecked")
public Collection<Namespace> getUsedNamespaces() {
    // @formatter:off
    @SuppressWarnings("rawtypes")
    Class[] toscaComponentIds = { ArtifactTemplateId.class, ArtifactTypeId.class, CapabilityTypeId.class,
            NodeTypeId.class, NodeTypeImplementationId.class, PolicyTemplateId.class, PolicyTypeId.class,
            RelationshipTypeId.class, RelationshipTypeImplementationId.class, RequirementTypeId.class,
            ServiceTemplateId.class };
    // @formatter:on

    // we use a HashSet to avoid reporting duplicate namespaces
    Collection<Namespace> res = new HashSet<Namespace>();

    for (Class<? extends TOSCAComponentId> id : toscaComponentIds) {
        String rootPathFragment = Util.getRootPathFragment(id);
        Path dir = this.repositoryRoot.resolve(rootPathFragment);
        if (!Files.exists(dir)) {
            continue;
        }//from  w  w  w  .  j a  v  a 2s  .c  om
        assert (Files.isDirectory(dir));

        final OnlyNonHiddenDirectories onhdf = new OnlyNonHiddenDirectories();

        // list all directories contained in this directory
        try (DirectoryStream<Path> ds = Files.newDirectoryStream(dir, onhdf)) {
            for (Path nsP : ds) {
                // the current path is the namespace
                Namespace ns = new Namespace(nsP.getFileName().toString(), true);
                res.add(ns);
            }
        } catch (IOException e) {
            FilebasedRepository.logger.debug("Cannot close ds", e);
        }
    }
    return res;
}

From source file:org.roda.core.storage.fs.FileStorageService.java

@Override
public CloseableIterable<BinaryVersion> listBinaryVersions(StoragePath storagePath)
        throws GenericException, RequestNotValidException, NotFoundException, AuthorizationDeniedException {
    Path fauxPath = FSUtils.getEntityPath(historyDataPath, storagePath);
    Path parent = fauxPath.getParent();
    final String baseName = fauxPath.getFileName().toString();

    CloseableIterable<BinaryVersion> iterable;

    if (!FSUtils.exists(parent)) {
        return new EmptyClosableIterable<>();
    }/*  w w w  .  j  av  a2  s  .com*/

    try {
        final DirectoryStream<Path> directoryStream = Files.newDirectoryStream(parent,
                new DirectoryStream.Filter<Path>() {

                    @Override
                    public boolean accept(Path entry) throws IOException {
                        return entry.getFileName().toString().startsWith(baseName);
                    }
                });

        final Iterator<Path> pathIterator = directoryStream.iterator();
        iterable = new CloseableIterable<BinaryVersion>() {

            @Override
            public Iterator<BinaryVersion> iterator() {
                return new Iterator<BinaryVersion>() {

                    @Override
                    public boolean hasNext() {
                        return pathIterator.hasNext();
                    }

                    @Override
                    public BinaryVersion next() {
                        Path next = pathIterator.next();
                        BinaryVersion ret;
                        try {
                            ret = FSUtils.convertPathToBinaryVersion(historyDataPath, historyMetadataPath,
                                    next);
                        } catch (GenericException | NotFoundException | RequestNotValidException e) {
                            LOGGER.error(
                                    "Error while list path " + basePath + " while parsing resource " + next, e);
                            ret = null;
                        }

                        return ret;
                    }

                };
            }

            @Override
            public void close() throws IOException {
                directoryStream.close();
            }
        };

    } catch (NoSuchFileException e) {
        throw new NotFoundException("Could not find versions of " + storagePath, e);
    } catch (IOException e) {
        throw new GenericException("Error finding version of " + storagePath, e);
    }

    return iterable;
}

From source file:org.eclipse.winery.repository.backend.filebased.FilebasedRepository.java

/**
 * Removes all files and dirs except the .git directory
 *//*from   www  . ja v  a 2  s .com*/
@Override
public void doClear() {
    try {
        DirectoryStream.Filter<Path> noGitDirFilter = new DirectoryStream.Filter<Path>() {

            @Override
            public boolean accept(Path entry) throws IOException {
                return !(entry.getFileName().toString().equals(".git"));
            }
        };

        DirectoryStream<Path> ds = Files.newDirectoryStream(this.repositoryRoot, noGitDirFilter);
        for (Path p : ds) {
            FileUtils.forceDelete(p);
        }
    } catch (IOException e) {
        FilebasedRepository.logger.error(e.getMessage());
        e.printStackTrace();
    }
}

From source file:org.eclipse.swt.snippets.SnippetExplorer.java

/**
 * Load all available Snippets from the preconfigured source path and from the
 * current classppath.//from   w w  w . j  a v  a 2 s .c om
 *
 * @return all found Snippets (never <code>null</code>)
 */
private static List<Snippet> loadSnippets() {
    // Similar to SnippetLauncher this explorer tries to load Snippet0 to Snippet500
    // even if no sources are available. This array is used to track which snippets
    // are already loaded from source.
    final boolean[] loadedSnippets = new boolean[501];
    final List<Snippet> snippets = new ArrayList<>();

    // load snippets from source directory
    final Path sourceDir = SnippetsConfig.SNIPPETS_SOURCE_DIR.toPath();
    if (Files.exists(sourceDir)) {
        try (DirectoryStream<Path> files = Files.newDirectoryStream(sourceDir, "*.java")) {
            for (Path file : files) {
                try {
                    final Snippet snippet = snippetFromSource(file);
                    if (snippet == null) {
                        continue;
                    }
                    snippets.add(snippet);
                    if (snippet.snippetNum >= 0) {
                        loadedSnippets[snippet.snippetNum] = true;
                    }
                } catch (ClassNotFoundException | IOException ex) {
                    System.err.println("Failed to load snippet from " + file + ". Error: " + ex);
                }
            }
        } catch (IOException ex) {
            System.err.println("Failed to access source directory " + sourceDir + ". Error: " + ex);
        }
    }

    // load snippets from classpath
    for (int i = 0; i < loadedSnippets.length; i++) {
        if (!loadedSnippets[i]) {
            final int snippetNum = i;
            final String snippetName = "Snippet" + snippetNum;
            final Class<?> snippetClass;
            try {
                snippetClass = Class.forName(SnippetsConfig.SNIPPETS_PACKAGE + "." + snippetName, false,
                        SnippetExplorer.class.getClassLoader());
            } catch (ClassNotFoundException e) {
                continue;
            }
            final String[] arguments = SnippetsConfig.getSnippetArguments(snippetNum);
            snippets.add(new Snippet(snippetNum, snippetName, snippetClass, null, null, arguments));
        }
    }

    return snippets;
}

From source file:com.cloudbees.clickstack.util.Files2.java

/**
 * @param srcDir/*from  www  .  j a  v  a2 s  .  c  om*/
 * @param pattern
 * @return
 * @throws RuntimeIOException
 * @throws IllegalStateException More or less than 1 child dir found
 */
@Nonnull
public static Path findUniqueDirectoryBeginningWith(@Nonnull Path srcDir, @Nonnull final String pattern)
        throws RuntimeIOException, IllegalStateException {
    Preconditions.checkArgument(Files.isDirectory(srcDir), "Source %s is not a directory",
            srcDir.toAbsolutePath());

    DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
        @Override
        public boolean accept(Path entry) throws IOException {
            String fileName = entry.getFileName().toString();
            if (pattern == null) {
                return true;
            } else if (fileName.startsWith(pattern)) {
                return true;
            } else {
                return false;
            }
        }
    };

    try (DirectoryStream<Path> paths = Files.newDirectoryStream(srcDir, filter)) {
        try {
            return Iterables.getOnlyElement(paths);
        } catch (NoSuchElementException e) {
            throw new IllegalStateException("Directory beginning with '" + pattern + "' not found in path: "
                    + srcDir + ", absolutePath: " + srcDir.toAbsolutePath());
        } catch (IllegalArgumentException e) {
            throw new IllegalStateException(
                    "More than 1 directory beginning with '" + pattern + "' found in path: " + srcDir
                            + ", absolutePath: " + srcDir.toAbsolutePath() + " -> " + paths);
        }
    } catch (IOException e) {
        throw new RuntimeIOException(
                "Exception finding unique child directory beginning with " + filter + "in " + srcDir);
    }
}