List of usage examples for java.nio.file Path toAbsolutePath
Path toAbsolutePath();
From source file:de.dal33t.powerfolder.clientserver.ServerClient.java
private byte[] prepareKerberosLogin() { try {//www.ja v a 2s.c o m Path outputFile = Controller.getTempFilesLocation().resolve("login.conf"); if (Files.notExists(outputFile)) { InputStream configFile = Thread.currentThread().getContextClassLoader() .getResourceAsStream("kerberos/login.conf"); PathUtils.copyFromStreamToFile(configFile, outputFile); } System.setProperty("java.security.auth.login.config", outputFile.toAbsolutePath().toString()); System.setProperty("java.security.krb5.realm", ConfigurationEntry.KERBEROS_SSO_REALM.getValue(getController())); String kdc = ConfigurationEntry.KERBEROS_SSO_KDC.getValue(getController()); System.setProperty("java.security.krb5.kdc", kdc); LoginContext lc = new LoginContext("SignedOnUserLoginContext", new TextCallbackHandler()); lc.login(); Subject clientSubject = lc.getSubject(); username = clientSubject.getPrincipals().iterator().next().getName(); return Subject.doAs(clientSubject, new ServiceTicketGenerator()); } catch (Exception e) { logWarning("Unable to login: " + e); return null; } finally { loggingIn.set(false); } }
From source file:org.tinymediamanager.core.movie.tasks.MovieUpdateDatasourceTask2.java
/** * for SingleMovie or DiscFolders/*w w w. j ava2 s. co m*/ * * @param dataSource * the data source * @param movieDir * the movie folder * @param isDiscFolder * is the movie in a disc folder? */ private void createSingleMovieFromDir(Path dataSource, Path movieDir, boolean isDiscFolder) { LOGGER.info( "Parsing single movie directory: " + movieDir + " (are we a disc folder? " + isDiscFolder + ")"); Path relative = dataSource.relativize(movieDir); // STACKED FOLDERS - go up ONE level (only when the stacked folder == // stacking marker) // movie/CD1/ & /movie/CD2 -> go up // movie CD1/ & /movie CD2 -> NO - there could be other files/folders there // if (!Utils.getFolderStackingMarker(relative.toString()).isEmpty() && // level > 1) { if (!Utils.getFolderStackingMarker(relative.toString()).isEmpty() && Utils.getFolderStackingMarker(relative.toString()).equals(movieDir.getFileName().toString())) { movieDir = movieDir.getParent(); } Movie movie = movieList.getMovieByPath(movieDir); HashSet<Path> allFiles = getAllFilesRecursive(movieDir, 3); // need 3 (was // 2) because // extracted BD filesFound.add(movieDir.toAbsolutePath()); // our global cache filesFound.addAll(allFiles); // our global cache // convert to MFs (we need it anyways at the end) ArrayList<MediaFile> mfs = new ArrayList<>(); for (Path file : allFiles) { mfs.add(new MediaFile(file)); } allFiles.clear(); if (movie == null) { LOGGER.debug("| movie not found; looking for NFOs"); movie = new Movie(); String bdinfoTitle = ""; // title parsed out of BDInfo String videoName = ""; // title from file // *************************************************************** // first round - try to parse NFO(s) first // *************************************************************** // TODO: add movie.addMissingMetaData(otherMovie) to get merged movie from // multiple NFOs ;) for (MediaFile mf : mfs) { if (mf.getType().equals(MediaFileType.NFO)) { // PathMatcher matcher = // FileSystems.getDefault().getPathMatcher("glob:*.[nN][fF][oO]"); LOGGER.info("| parsing NFO " + mf.getFileAsPath()); Movie nfo = null; switch (MovieModuleManager.MOVIE_SETTINGS.getMovieConnector()) { case XBMC: nfo = MovieToXbmcNfoConnector.getData(mf.getFileAsPath()); if (nfo == null) { // try the other nfo = MovieToKodiNfoConnector.getData(mf.getFileAsPath()); } if (nfo == null) { // try the other nfo = MovieToMpNfoConnector.getData(mf.getFileAsPath()); } break; case KODI: nfo = MovieToKodiNfoConnector.getData(mf.getFileAsPath()); // not needed at the moment since kodi is downwards compatible // if (nfo == null) { // // try the other // nfo = MovieToXbmcNfoConnector.getData(mf.getFileAsPath()); // } if (nfo == null) { // try the other nfo = MovieToMpNfoConnector.getData(mf.getFileAsPath()); } break; case MP: nfo = MovieToMpNfoConnector.getData(mf.getFileAsPath()); if (nfo == null) { // try the other nfo = MovieToKodiNfoConnector.getData(mf.getFileAsPath()); } // not needed at the moment since kodi is downwards compatible // if (nfo == null) { // // try the other // nfo = MovieToXbmcNfoConnector.getData(mf.getFileAsPath()); // } break; } if (nfo != null) { movie = nfo; } // was NFO, but parsing exception. try to find at least imdb id within if (movie.getImdbId().isEmpty()) { try { String imdb = Utils.readFileToString(mf.getFileAsPath()); imdb = ParserUtils.detectImdbId(imdb); if (!imdb.isEmpty()) { LOGGER.debug("| Found IMDB id: " + imdb); movie.setImdbId(imdb); } } catch (IOException e) { LOGGER.warn("| couldn't read NFO " + mf); } } } // end NFO else if (mf.getType().equals(MediaFileType.TEXT)) { try { String txtFile = Utils.readFileToString(mf.getFileAsPath()); String bdinfo = StrgUtils.substr(txtFile, ".*Disc Title:\\s+(.*?)[\\n\\r]"); if (!bdinfo.isEmpty()) { LOGGER.debug("| Found Disc Title in BDInfo.txt: " + bdinfo); bdinfoTitle = WordUtils.capitalizeFully(bdinfo); } String imdb = ParserUtils.detectImdbId(txtFile); if (!imdb.isEmpty()) { LOGGER.debug("| Found IMDB id: " + imdb); movie.setImdbId(imdb); } } catch (Exception e) { LOGGER.warn("| couldn't read TXT " + mf.getFilename()); } } else if (mf.getType().equals(MediaFileType.VIDEO)) { videoName = mf.getBasename(); } } // end NFO MF loop movie.setNewlyAdded(true); movie.setDateAdded(new Date()); } // end first round - we might have a filled movie if (movie.getTitle().isEmpty()) { // get the "cleaner" name/year combo // ParserUtils.ParserInfo video = ParserUtils.getCleanerString(new // String[] { videoName, movieDir.getName(), bdinfoTitle }); // does not work reliable yet - user folder name String[] video = ParserUtils.detectCleanMovienameAndYear(movieDir.getFileName().toString()); movie.setTitle(video[0]); if (!video[1].isEmpty()) { movie.setYear(video[1]); } } // if the String 3D is in the movie dir, assume it is a 3D movie Matcher matcher = video3DPattern.matcher(movieDir.getFileName().toString()); if (matcher.find()) { movie.setVideoIn3D(true); } // get edition from name movie.setEdition(MovieEdition.getMovieEditionFromString(movieDir.getFileName().toString())); movie.setPath(movieDir.toAbsolutePath().toString()); movie.setDataSource(dataSource.toString()); // movie.findActorImages(); // TODO: find as MediaFiles LOGGER.debug("| store movie into DB as: " + movie.getTitle()); movieList.addMovie(movie); if (movie.getMovieSet() != null) { LOGGER.debug("| movie is part of a movieset"); // movie.getMovieSet().addMovie(movie); movie.getMovieSet().insertMovie(movie); movieList.sortMoviesInMovieSet(movie.getMovieSet()); movie.getMovieSet().saveToDb(); } // *************************************************************** // second round - now add all the other known files // *************************************************************** addMediafilesToMovie(movie, mfs); // *************************************************************** // third round - try to match unknown graphics like title.ext or // filename.ext as poster // *************************************************************** if (movie.getArtworkFilename(MediaFileType.POSTER).isEmpty()) { for (MediaFile mf : mfs) { if (mf.getType().equals(MediaFileType.GRAPHIC)) { LOGGER.debug("| parsing unknown graphic " + mf.getFilename()); List<MediaFile> vid = movie.getMediaFiles(MediaFileType.VIDEO); if (vid != null && !vid.isEmpty()) { String vfilename = vid.get(0).getFilename(); if (FilenameUtils.getBaseName(vfilename).equals(FilenameUtils.getBaseName(mf.getFilename())) // basename // match || FilenameUtils.getBaseName(Utils.cleanStackingMarkers(vfilename)).trim() .equals(FilenameUtils.getBaseName(mf.getFilename())) // basename // w/o // stacking || movie.getTitle().equals(FilenameUtils.getBaseName(mf.getFilename()))) { // title // match mf.setType(MediaFileType.POSTER); movie.addToMediaFiles(mf); } } } } } // *************************************************************** // check if that movie is an offline movie // *************************************************************** boolean isOffline = false; for (MediaFile mf : movie.getMediaFiles(MediaFileType.VIDEO)) { if ("disc".equalsIgnoreCase(mf.getExtension())) { isOffline = true; } } movie.setOffline(isOffline); movie.reEvaluateStacking(); movie.saveToDb(); }
From source file:org.apache.nifi.authorization.FlowParser.java
/** * Extracts the root group id from the flow configuration file provided in nifi.properties, and extracts * the root group input ports and output ports, and their access controls. * *//* ww w . ja va 2 s . c o m*/ public FlowInfo parse(final File flowConfigurationFile) { if (flowConfigurationFile == null) { logger.debug("Flow Configuration file was null"); return null; } // if the flow doesn't exist or is 0 bytes, then return null final Path flowPath = flowConfigurationFile.toPath(); try { if (!Files.exists(flowPath) || Files.size(flowPath) == 0) { logger.warn("Flow Configuration does not exist or was empty"); return null; } } catch (IOException e) { logger.error("An error occurred determining the size of the Flow Configuration file"); return null; } // otherwise create the appropriate input streams to read the file try (final InputStream in = Files.newInputStream(flowPath, StandardOpenOption.READ); final InputStream gzipIn = new GZIPInputStream(in)) { final byte[] flowBytes = IOUtils.toByteArray(gzipIn); if (flowBytes == null || flowBytes.length == 0) { logger.warn("Could not extract root group id because Flow Configuration File was empty"); return null; } // create validating document builder final DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setNamespaceAware(true); docFactory.setSchema(flowSchema); // parse the flow final DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); final Document document = docBuilder.parse(new ByteArrayInputStream(flowBytes)); // extract the root group id final Element rootElement = document.getDocumentElement(); final Element rootGroupElement = (Element) rootElement.getElementsByTagName("rootGroup").item(0); if (rootGroupElement == null) { logger.warn("rootGroup element not found in Flow Configuration file"); return null; } final Element rootGroupIdElement = (Element) rootGroupElement.getElementsByTagName("id").item(0); if (rootGroupIdElement == null) { logger.warn("id element not found under rootGroup in Flow Configuration file"); return null; } final String rootGroupId = rootGroupIdElement.getTextContent(); final List<PortDTO> ports = new ArrayList<>(); ports.addAll(getPorts(rootGroupElement, "inputPort")); ports.addAll(getPorts(rootGroupElement, "outputPort")); return new FlowInfo(rootGroupId, ports); } catch (final SAXException | ParserConfigurationException | IOException ex) { logger.error("Unable to parse flow {} due to {}", new Object[] { flowPath.toAbsolutePath(), ex }); return null; } }
From source file:com.bytelightning.opensource.pokerface.PokerFace.java
/** * If requested by the user, this method walks the script directory discovering, loading, compiling, and initialing an .js javascript files it finds in the specified directory or it's children. * @param baseScriptDirectory The contents of this directory should be structured in the same layout as the url's we wish to interfere with. * @param watchScriptDirectory If true, a watch will be placed on <code>baseScriptDirectory</code> and any javascript file modifications (cud) will be dynamically rebuilt and reflected in the running server. * @return True if all scripts were successfully loaded. *///from w w w.jav a 2 s. c o m protected boolean configureScripts(final List<Path> jsLibs, final HierarchicalConfiguration scriptConfig, final Path baseScriptDirectory, boolean watchScriptDirectory) { // Our unit test has verified that CompiledScripts can produce objects (endpoints) that can be executed from ANY thread (and even concurrently execute immutable methods). // However we have not validated that Nashorn can compile *and* recompile scripts from multiple threads. //TODO: Write unit test to see if we can use all available processors to compile discovered javascript files. ScriptCompilationExecutor = Executors.newSingleThreadScheduledExecutor(); // This is done to make sure the engine is allocated in the same thread that will be doing the compiling. Callable<Boolean> compileScriptsTask = new Callable<Boolean>() { @Override public Boolean call() { Nashorn = new ScriptEngineManager().getEngineByName("nashorn"); if (jsLibs != null) for (Path lib : jsLibs) if (!loadScriptLibrary(lib)) return false; // Recursively discover javascript files, compile, load, and setup any that are found. EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS); try { Files.walkFileTree(baseScriptDirectory, opts, Integer.MAX_VALUE, new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (Files.isDirectory(dir) && dir.getFileName().toString().startsWith("#")) return FileVisitResult.SKIP_SUBTREE; return super.preVisitDirectory(dir, attrs); } @Override public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException { if (Files.isRegularFile(path)) { if (path.toString().toLowerCase().endsWith(".js")) { MakeJavaScriptEndPointDescriptor(baseScriptDirectory, path, scriptConfig, new NewEndpointSetupCallback()); } } return FileVisitResult.CONTINUE; } }); } catch (IOException e) { Logger.error("Unable recursively load scripts", e); return false; } return true; } }; // Walk the root directory recursively compiling all discovered javascript files (does not return until all endpoint files have been setup). try { if (!ScriptCompilationExecutor.submit(compileScriptsTask).get()) return false; } catch (Throwable e) { Logger.error("Unable to compile scripts", e); return false; } if (watchScriptDirectory) { try { // Establish a watch on the root ScriptDirectoryWatcher.establishWatch(baseScriptDirectory, new DirectoryWatchEventListener() { // Internal Callable task to load, compile, and initialize a javascript file endpoint. final class CreateEndpointTask implements Callable<Void> { public CreateEndpointTask(Path file, EndpointSetupCompleteCallback callback) { this.file = file; this.callback = callback; } private final Path file; private final EndpointSetupCompleteCallback callback; @Override public Void call() { MakeJavaScriptEndPointDescriptor(baseScriptDirectory, file, scriptConfig, callback); return null; } } // Internal Callable task that gives us the ability to schedule a delayed unload of a deleted or obsoleted endpoint. // By delaying for a period of time longer than twice the socket timeout, we can safely call the endpoint's teardown method. final class DecommisionEndpointTask implements Callable<Void> { private DecommisionEndpointTask(ScriptObjectMirror endpoint) { this.endpoint = endpoint; } private final ScriptObjectMirror endpoint; @Override public Void call() { if (endpoint.hasMember("teardown")) endpoint.callMember("teardown"); return null; } } /** * Called by the WatchService when the contents of the script directory have changed. */ @Override public void onWatchEvent(Path watchDir, final Path oldFile, final Path newFile, FileChangeType change) { if (change == FileChangeType.eRenamed) { // If it was changed to something that does *not* end .js then it should no longer be considered an endpoint. if (oldFile.toString().toLowerCase().endsWith(".js")) if (!newFile.toString().toLowerCase().endsWith(".js")) change = FileChangeType.eDeleted; } if (change == FileChangeType.eModified || change == FileChangeType.eRenamed) { // Decommission the obsolete and load the update. try { assert newFile.toString().toLowerCase().endsWith(".js"); // Will be true because of the 'rename' check at the top of this method. ScriptCompilationExecutor .submit(new CreateEndpointTask(newFile, new NewEndpointSetupCallback() { @Override public ScriptObjectMirror setupComplete(JavaScriptEndPoint endpoint) { ScriptObjectMirror old = super.setupComplete(endpoint); assert old != null; // Yeah, it's hincky, but it won't be in use this long after we remove it from the Map. ScriptCompilationExecutor.schedule(new DecommisionEndpointTask(old), 6, TimeUnit.MINUTES); return null; } })); } catch (Throwable e) { Logger.error("Unable to compile modified script found at " + newFile.toAbsolutePath().toString(), e); } } else if (change == FileChangeType.eCreated) { // This is the easy one. If a javascript file was created, load it. if (newFile.toString().toLowerCase().endsWith(".js")) { try { ScriptCompilationExecutor.submit( new CreateEndpointTask(newFile, new NewEndpointSetupCallback())); } catch (Throwable e) { Logger.error("Unable to compile new script found at " + newFile.toAbsolutePath().toString(), e); } } } else if (change == FileChangeType.eDeleted) { // Endpoint should be decommisioned. if (oldFile.toString().toLowerCase().endsWith(".js")) { String uriKey = FileToUriKey(baseScriptDirectory, oldFile); ScriptObjectMirror desc = scripts.remove(uriKey); if (desc != null) { // Yeah, it's hincky, but it won't be in use this long after we remove it from the Map. ScriptCompilationExecutor.schedule(new DecommisionEndpointTask(desc), 6, TimeUnit.MINUTES); } } } } }); } catch (IOException e) { Logger.error("Unable to establish a real time watch on the script directory.", e); } } else // Not watching for changes, so we are done with the Executor. ScriptCompilationExecutor.shutdown(); return true; }
From source file:com.github.podd.resources.UploadArtifactResourceImpl.java
private InferredOWLOntologyID uploadFileAndLoadArtifactIntoPodd(final Representation entity) throws ResourceException { List<FileItem> items;// ww w.j a v a 2s .com Path filePath = null; String contentType = null; // 1: Create a factory for disk-based file items final DiskFileItemFactory factory = new DiskFileItemFactory(1000240, this.tempDirectory.toFile()); // 2: Create a new file upload handler final RestletFileUpload upload = new RestletFileUpload(factory); final Map<String, String> props = new HashMap<String, String>(); try { // 3: Request is parsed by the handler which generates a list of // FileItems items = upload.parseRequest(this.getRequest()); for (final FileItem fi : items) { final String name = fi.getName(); if (name == null) { props.put(fi.getFieldName(), new String(fi.get(), StandardCharsets.UTF_8)); } else { // FIXME: Strip everything up to the last . out of the // filename so that // the filename can be used for content type determination // where // possible. // InputStream uploadedFileInputStream = // fi.getInputStream(); try { // Note: These are Java-7 APIs contentType = fi.getContentType(); props.put("Content-Type", fi.getContentType()); filePath = Files.createTempFile(this.tempDirectory, "ontologyupload-", name); final File file = filePath.toFile(); file.deleteOnExit(); fi.write(file); } catch (final IOException ioe) { throw ioe; } catch (final Exception e) { // avoid throwing a generic exception just because the // apache // commons library throws Exception throw new IOException(e); } } } } catch (final IOException | FileUploadException e) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, e); } this.log.info("props={}", props.toString()); if (filePath == null) { throw new ResourceException(Status.CLIENT_ERROR_BAD_REQUEST, "Did not submit a valid file and filename"); } this.log.info("filename={}", filePath.toAbsolutePath().toString()); this.log.info("contentType={}", contentType); RDFFormat format = null; // If the content type was application/octet-stream then use the file // name instead // Browsers attach this content type when they are not sure what the // real type is if (MediaType.APPLICATION_OCTET_STREAM.getName().equals(contentType)) { format = Rio.getParserFormatForFileName(filePath.getFileName().toString()); this.log.info("octet-stream contentType filename format={}", format); } // Otherwise use the content type directly in preference to using the // filename else if (contentType != null) { format = Rio.getParserFormatForMIMEType(contentType); this.log.info("non-octet-stream contentType format={}", format); } // If the content type choices failed to resolve the type, then try the // filename if (format == null) { format = Rio.getParserFormatForFileName(filePath.getFileName().toString()); this.log.info("non-content-type filename format={}", format); } // Or fallback to RDF/XML which at minimum is able to detect when the // document is // structurally invalid if (format == null) { this.log.warn("Could not determine RDF format from request so falling back to RDF/XML"); format = RDFFormat.RDFXML; } try (final InputStream inputStream = new BufferedInputStream( Files.newInputStream(filePath, StandardOpenOption.READ));) { return this.uploadFileAndLoadArtifactIntoPodd(inputStream, format, DanglingObjectPolicy.REPORT, DataReferenceVerificationPolicy.DO_NOT_VERIFY); } catch (final IOException e) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL, "File IO error occurred", e); } }
From source file:de.dal33t.powerfolder.Controller.java
/** * #2526/*www . j ava 2 s . c o m*/ */ private void backupConfigAssets() { Path backupDir = getMiscFilesLocation().resolve("backups/" + Format.formatDateCanonical(new Date())); if (Files.notExists(backupDir)) { try { Files.createDirectories(backupDir); } catch (IOException ioe) { logInfo("Could not create directory '" + backupDir.toAbsolutePath().toString() + "'"); } } Path configBackup = backupDir.resolve(configFile.getFileName()); try { PathUtils.copyFile(configFile, configBackup); } catch (IOException e) { logWarning("Unable to backup file " + configFile + ". " + e); } if (Files.exists(configFolderFile)) { Path configFolderBackup = backupDir.resolve(configFolderFile.getFileName()); try { PathUtils.copyFile(configFolderFile, configFolderBackup); } catch (IOException e) { logWarning("Unable to backup file " + configFolderFile + ". " + e); } } Path myKeyFile = getMiscFilesLocation().resolve(getConfigName() + ".mykey"); Path mykeyBackup = backupDir.resolve(myKeyFile.getFileName()); if (Files.exists(myKeyFile)) { try { PathUtils.copyFile(myKeyFile, mykeyBackup); } catch (IOException e) { logWarning("Unable to backup file " + myKeyFile + ". " + e); } } Path dbFile = getMiscFilesLocation().resolve("Accounts.h2.db"); Path dbBackup = backupDir.resolve(dbFile.getFileName()); if (Files.exists(dbFile)) { try { PathUtils.copyFile(dbFile, dbBackup); } catch (IOException e) { logWarning("Unable to backup file " + dbFile + ". " + e); } } }
From source file:de.teamgrit.grit.checking.compile.JavaCompileChecker.java
/** * This Method generates the command required to start the compiler. It * generates a list of strings that can be passed to a process builder. * * @param pathToSourceFolder//from w w w . ja v a 2 s.c o m * Where to look for the source files that will be compiled. * @param outputFolder * Where .class files will be placed * @param compilerName * Which compiler to call * @param compilerFlags * User supplied flags to be passed * @throws BadCompilerSpecifiedException * When no compiler is given. * @throws FileNotFoundException * When the file to be compiled does not exist * @throws CompilerOutputFolderExistsException * The output folder may not exist. This is thrown when it does * exist. * @return List of string with the command for the process builder. */ private List<String> createCompilerInvocation(Path pathToSourceFolder, Path outputFolder, String compilerName, List<String> compilerFlags) throws BadCompilerSpecifiedException, FileNotFoundException, CompilerOutputFolderExistsException { List<String> compilerInvocation = new LinkedList<>(); // Check if a compiler has been supplied. Without one we abort // compiling. Else we start building the compiler command. if (("".equals(compilerName)) || (compilerName == null)) { throw new BadCompilerSpecifiedException("No compiler specified."); } else { compilerInvocation.add(compilerName); } // If compiler flags are passed, append them after the compiler name. // If we didn't get any we append nothing. Appending empty strings or // nulls to the compiler invocation must be avoided, since it can cause // javac to crash. Hence, we ignore such entries. if ((compilerFlags != null) && (!(compilerFlags.isEmpty()))) { for (String flag : compilerFlags) { // If javac gets passed a "" it dies due to a bug, so avoid // this if ((flag != null) && !"".equals(flag)) { compilerInvocation.add(flag); } } } // Add JUnit and the current directory to the classpath.s compilerInvocation.add("-cp"); String cp = ".:" + m_junitLocation.toAbsolutePath().toString(); // Add all additional .jar files contained in javalib directory to the classpath if (!m_libLocation.toFile().exists()) { m_libLocation.toFile().mkdir(); } else { for (File f : FileUtils.listFiles(m_libLocation.toFile(), new String[] { "jar" }, false)) { cp = cp + ":" + f.getAbsolutePath(); } } compilerInvocation.add(cp); //make sure java uses utf8 for encoding compilerInvocation.add("-encoding"); compilerInvocation.add("UTF-8"); // Check for the existence of the program file we are trying to // compile. if ((pathToSourceFolder == null) || !(pathToSourceFolder.toFile().exists())) { throw new FileNotFoundException("No file to compile specified"); } else { if (Files.isDirectory(pathToSourceFolder, LinkOption.NOFOLLOW_LINKS)) { // we are supposed to compile a folder. Hence we'll scan for // java files and pass them to the compiler. List<Path> foundFiles = exploreDirectory(pathToSourceFolder); for (Path matchedFile : foundFiles) { compilerInvocation.add(matchedFile.toFile().getAbsolutePath()); } compilerInvocation.add("-d"); compilerInvocation.add(outputFolder.toAbsolutePath().toString()); } else { throw new FileNotFoundException("Program file that should be compiled does not exist." + "Filename : \"" + pathToSourceFolder.toString() + "\""); } } return compilerInvocation; }
From source file:org.elasticsearch.test.ElasticsearchIntegrationTest.java
/** * Return settings that could be used to start a node that has the given zipped home directory. *///from w w w . j av a 2 s. com protected Settings prepareBackwardsDataDir(Path backwardsIndex, Object... settings) throws IOException { Path indexDir = createTempDir(); Path dataDir = indexDir.resolve("data"); try (InputStream stream = Files.newInputStream(backwardsIndex)) { TestUtil.unzip(stream, indexDir); } assertTrue(Files.exists(dataDir)); // list clusters in the datapath, ignoring anything from extrasfs final Path[] list; try (DirectoryStream<Path> stream = Files.newDirectoryStream(dataDir)) { List<Path> dirs = new ArrayList<>(); for (Path p : stream) { if (!p.getFileName().toString().startsWith("extra")) { dirs.add(p); } } list = dirs.toArray(new Path[0]); } if (list.length != 1) { throw new IllegalStateException( "Backwards index must contain exactly one cluster\n" + StringUtils.join(list, "\n")); } Path src = list[0]; Path dest = dataDir.resolve(internalCluster().getClusterName()); assertTrue(Files.exists(src)); Files.move(src, dest); assertFalse(Files.exists(src)); assertTrue(Files.exists(dest)); Settings.Builder builder = Settings.builder().put(settings).put("path.data", dataDir.toAbsolutePath()); Path configDir = indexDir.resolve("config"); if (Files.exists(configDir)) { builder.put("path.conf", configDir.toAbsolutePath()); } return builder.build(); }
From source file:org.tinymediamanager.core.movie.tasks.MovieUpdateDatasourceTask2.java
@Override public void doInBackground() { // check if there is at least one DS to update Utils.removeEmptyStringsFromList(dataSources); if (dataSources.isEmpty()) { LOGGER.info("no datasource to update"); MessageManager.instance.pushMessage( new Message(MessageLevel.ERROR, "update.datasource", "update.datasource.nonespecified")); return;//from ww w .j a v a2s . c om } // get existing movie folders List<Path> existing = new ArrayList<>(); for (Movie movie : movieList.getMovies()) { existing.add(movie.getPathNIO()); } try { StopWatch stopWatch = new StopWatch(); stopWatch.start(); List<Path> imageFiles = new ArrayList<>(); for (String ds : dataSources) { initThreadPool(3, "update"); setTaskName(BUNDLE.getString("update.datasource") + " '" + ds + "'"); publishState(); Path dsAsPath = Paths.get(ds); // first of all check if the DS is available; we can take the // Files.exist here: // if the DS exists (and we have access to read it): Files.exist = true if (!Files.exists(dsAsPath)) { // error - continue with next datasource MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, "update.datasource", "update.datasource.unavailable", new String[] { ds })); continue; } // just check datasource folder, parse NEW folders first List<Path> newMovieDirs = new ArrayList<>(); List<Path> existingMovieDirs = new ArrayList<>(); List<Path> rootList = listFilesAndDirs(dsAsPath); // when there is _nothing_ found in the ds root, it might be offline - // skip further processing; // not in Windows since that won't happen there if (rootList.isEmpty() && !Platform.isWindows()) { // error - continue with next datasource MessageManager.instance.pushMessage(new Message(MessageLevel.ERROR, "update.datasource", "update.datasource.unavailable", new String[] { ds })); continue; } List<Path> rootFiles = new ArrayList<>(); for (Path path : rootList) { if (Files.isDirectory(path)) { if (existing.contains(path)) { existingMovieDirs.add(path); } else { newMovieDirs.add(path); } } else { rootFiles.add(path); } } rootList.clear(); for (Path path : newMovieDirs) { searchAndParse(dsAsPath.toAbsolutePath(), path, Integer.MAX_VALUE); } for (Path path : existingMovieDirs) { searchAndParse(dsAsPath.toAbsolutePath(), path, Integer.MAX_VALUE); } if (rootFiles.size() > 0) { submitTask(new parseMultiMovieDirTask(dsAsPath.toAbsolutePath(), dsAsPath.toAbsolutePath(), rootFiles)); } waitForCompletionOrCancel(); newMovieDirs.clear(); existingMovieDirs.clear(); rootFiles.clear(); if (cancel) { break; } // cleanup cleanup(ds); // mediainfo gatherMediainfo(ds); if (cancel) { break; } // build image cache on import if (MovieModuleManager.MOVIE_SETTINGS.isBuildImageCacheOnImport()) { for (Movie movie : movieList.getMovies()) { if (!dsAsPath.equals(Paths.get(movie.getDataSource()))) { // check only movies matching datasource continue; } imageFiles.addAll(movie.getImagesToCache()); } } } // END datasource loop if (imageFiles.size() > 0) { ImageCacheTask task = new ImageCacheTask(imageFiles); TmmTaskManager.getInstance().addUnnamedTask(task); } if (MovieModuleManager.MOVIE_SETTINGS.getSyncTrakt()) { TmmTask task = new SyncTraktTvTask(true, true, false, false); TmmTaskManager.getInstance().addUnnamedTask(task); } stopWatch.stop(); LOGGER.info("Done updating datasource :) - took " + stopWatch); LOGGER.debug("FilesFound " + filesFound.size()); LOGGER.debug("moviesFound " + movieList.getMovieCount()); LOGGER.debug("PreDir " + preDir); LOGGER.debug("PostDir " + postDir); LOGGER.debug("VisFile " + visFile); LOGGER.debug("PreDir2 " + preDir2); LOGGER.debug("PostDir2 " + postDir2); LOGGER.debug("VisFile2 " + visFile2); } catch (Exception e) { LOGGER.error("Thread crashed", e); MessageManager.instance.pushMessage( new Message(MessageLevel.ERROR, "update.datasource", "message.update.threadcrashed")); } }