List of usage examples for java.nio.file Path getFileName
Path getFileName();
From source file:de.unirostock.sems.caroweb.Converter.java
private void run(HttpServletRequest request, HttpServletResponse response, String uploadedName, String[] req, File tmp, File out, Path STORAGE) throws ServletException, IOException { cleanUp();/*w w w . j a v a2 s .c om*/ uploadedName.replaceAll("[^A-Za-z0-9 ]", "_"); if (uploadedName.length() < 3) uploadedName += "container"; CaRoConverter conv = null; if (req[1].equals("caro")) conv = new CaToRo(tmp); else if (req[1].equals("roca")) conv = new RoToCa(tmp); else { error(request, response, "do not know what to do"); return; } conv.convertTo(out); List<CaRoNotification> notifications = conv.getNotifications(); Path result = null; if (out.exists()) { result = Files.createTempFile(STORAGE, uploadedName, "-converted-" + CaRoWebutils.getTimeStamp() + "." + (req[1].equals("caro") ? "ro" : "omex")); try { Files.copy(out.toPath(), result, StandardCopyOption.REPLACE_EXISTING); } catch (Exception e) { notifications.add(new CaRoNotification(CaRoNotification.SERVERITY_ERROR, "wasn't able to copy converted container to storage")); } } JSONArray errors = new JSONArray(); JSONArray warnings = new JSONArray(); JSONArray notes = new JSONArray(); for (CaRoNotification note : notifications) if (note.getSeverity() == CaRoNotification.SERVERITY_ERROR) errors.add(note.getMessage()); else if (note.getSeverity() == CaRoNotification.SERVERITY_WARN) warnings.add(note.getMessage()); else if (note.getSeverity() == CaRoNotification.SERVERITY_NOTE) notes.add(note.getMessage()); JSONObject json = new JSONObject(); json.put("errors", errors); json.put("warnings", warnings); json.put("notifications", notes); if (result != null && Files.exists(result)) { json.put("checkout", result.getFileName().toString()); if (request.getParameter("redirect") != null && request.getParameter("redirect").equals("checkout")) { response.sendRedirect("/checkout/" + result.getFileName().toString()); } } response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter outWriter = response.getWriter(); outWriter.print(json); out.delete(); }
From source file:org.apache.openaz.xacml.pdp.test.TestBase.java
/** * This processes a response. Saves the response out to disk. If there is a corresponding response file * for the request located in the "responses" sub-directory, then this method will compare that response * file with what the engine returned to see if it matched. * * @param requestFile/*from w w w. j a v a2s .c o m*/ * @param request * @param response * @param group * @param count * @throws Exception */ protected void processResponse(Path requestFile, Request request, Response response, String group, int count) throws Exception { // // Construct the output filename // Path responseFile = null; Path resultFile = null; int num = requestFile.getNameCount(); if (num < 2) { logger.error("Too few dir's in request filename."); throw new Exception( "Too few dir's in request filename. Format should be Request.[0-9]+.{Permit|Deny|NA|Indeterminate}.{json|xml}"); } String filename = requestFile.getFileName().toString(); if (group.equals("Generate")) { // // Using count variable, construct a filename // // i.e. Response.03.Generate.{count}.json // filename = "Response" + filename.substring(filename.indexOf('.'), filename.lastIndexOf('.')) + String.format("%03d", count) + filename.substring(filename.lastIndexOf('.')); } else { // // Construct filename // filename = "Response" + filename.substring(filename.indexOf('.')); } // // Determine equivalent response file path // responseFile = Paths.get(requestFile.subpath(0, num - 2).toString(), "responses"); if (Files.notExists(responseFile)) { // // Create it // logger.warn(responseFile.toString() + " does NOT exist, creating..."); try { Files.createDirectories(responseFile); } catch (IOException e) { logger.error(e); throw new Exception("Cannot proceed without an output directory."); } } responseFile = Paths.get(responseFile.toString(), filename); // // Determine path to write result file // if (this.output != null) { // // User specified an output path // resultFile = this.output; } else { // // Default path // resultFile = Paths.get(requestFile.subpath(0, num - 2).toString(), "results"); } // // Check if the path exists // if (Files.notExists(resultFile)) { // // Create it // logger.warn(resultFile.toString() + " does NOT exist, creating..."); try { Files.createDirectories(resultFile); } catch (IOException e) { logger.error(e); throw new Exception("Cannot proceed without an output directory."); } } // // Add the filename to the path // resultFile = Paths.get(resultFile.toString(), filename); // // Check if there is an equivalent response in the response // directory. If so, compare our response result with that one. // boolean succeeded = true; if (responseFile != null && Files.exists(responseFile)) { // // Do comparison // Response expectedResponse = null; if (TestBase.isJSON(responseFile)) { expectedResponse = JSONResponse.load(responseFile); } else if (TestBase.isXML(responseFile)) { expectedResponse = DOMResponse.load(responseFile); } if (expectedResponse != null) { // // Do the compare // if (response == null) { logger.error("NULL response returned."); this.responseNotMatches++; succeeded = false; } else { if (response.equals(expectedResponse)) { logger.info("Response matches expected response."); this.responseMatches++; } else { logger.error("Response does not match expected response."); logger.error("Expected: "); logger.error(expectedResponse.toString()); this.responseNotMatches++; succeeded = false; } } } } // // Write the response to the result file // logger.info("Request: " + requestFile.getFileName() + " response is: " + (response == null ? "null" : response.toString())); if (resultFile != null && response != null) { if (TestBase.isJSON(resultFile)) { Files.write(resultFile, JSONResponse.toString(response, true).getBytes()); } else if (TestBase.isXML(resultFile)) { Files.write(resultFile, DOMResponse.toString(response, true).getBytes()); } } // // Stats // if (group.equals("Permit")) { this.expectedPermits++; } else if (group.equals("Deny")) { this.expectedDenies++; } else if (group.equals("NA")) { this.expectedNotApplicables++; } else if (group.equals("Indeterminate")) { this.expectedIndeterminates++; } if (response != null) { for (Result result : response.getResults()) { Decision decision = result.getDecision(); if (group.equals("Generate")) { if (decision.equals(Decision.PERMIT)) { this.generatedpermits++; } else if (decision.equals(Decision.DENY)) { this.generateddenies++; } else if (decision.equals(Decision.NOTAPPLICABLE)) { this.generatednotapplicables++; } else if (decision.equals(Decision.INDETERMINATE)) { this.generatedindeterminates++; } continue; } if (decision.equals(Decision.PERMIT)) { this.permits++; if (!group.equals("Permit")) { succeeded = false; logger.error("Expected " + group + " got " + decision); } } else if (decision.equals(Decision.DENY)) { this.denies++; if (!group.equals("Deny")) { succeeded = false; logger.error("Expected " + group + " got " + decision); } } else if (decision.equals(Decision.NOTAPPLICABLE)) { this.notapplicables++; if (!group.equals("NA")) { succeeded = false; logger.error("Expected " + group + " got " + decision); } } else if (decision.equals(Decision.INDETERMINATE)) { this.indeterminates++; if (!group.equals("Indeterminate")) { succeeded = false; logger.error("Expected " + group + " got " + decision); } } } } if (succeeded) { logger.info("REQUEST SUCCEEDED"); } else { logger.info("REQUEST FAILED"); } }
From source file:us.colloquy.index.IndexHandler.java
@Test public void loadDiariesIndex() { Properties properties = loadProperties(); List<DiaryEntry> diaryEntries = new ArrayList<>(); List<DocumentPointer> documentPointers = new ArrayList<>(); // getURIForAllDiaries(documentPointers, System.getProperty("user.home") + "/Documents/Tolstoy/openDiaries"); ///*www. j a v a 2s . co m*/ String strPathToDiaries = "samples/diaries"; //find all volumes with diaries Path pathToDiaries = FileSystems.getDefault().getPath(strPathToDiaries); List<Path> listOfDiaryVolumes = new ArrayList<>(); int maxDepth = 1; try (Stream<Path> stream = Files.find(pathToDiaries, maxDepth, (path, attr) -> { return String.valueOf(path).contains("dnevnik"); })) { stream.forEach(listOfDiaryVolumes::add); } catch (IOException e) { e.printStackTrace(); } int diaryCounter = 0; File entries_debug = new File("entries_debug.txt"); entries_debug.delete(); try (FileWriter fw = new FileWriter("entries_debug.txt", true); BufferedWriter bw = new BufferedWriter(fw); PrintWriter outDebug = new PrintWriter(bw)) { outDebug.println("start file"); //more code for (Path path : listOfDiaryVolumes) { documentPointers.clear(); getURIForAllDiaries(documentPointers, path); diaryEntries.clear(); for (DocumentPointer pointer : documentPointers) { List<DiaryEntry> diaryEntriesInPointer = new ArrayList<>(); DiaryParser.parseDiaries(pointer, diaryCounter++, diaryEntriesInPointer, outDebug); //test case "temp/OEBPS/Text/0001_1006_2002.xhtml" //find if anything is wrong in a pointer for (DiaryEntry diaryEntry : diaryEntriesInPointer) { if (diaryEntry.getDate() == null || diaryEntry.getEntry().length() < 20) { System.out.println(" Missing entry: --------------- " + pointer.getUri() + " ---------------------------------"); System.out.println(diaryEntry.toString()); } } diaryEntries.addAll(diaryEntriesInPointer); } System.out.println("Total number of diaries in " + path.getFileName() + ": " + diaryEntries.size()); //code below to set ids and check a few letters int i = 0; for (DiaryEntry diaryEntry : diaryEntries) { i++; String id = "D-" + path.getFileName().toString().replaceAll(".*_", "") + "-" + i; diaryEntry.setId(id); } System.out.println("Total number of diaries in volume: " + diaryEntries.size()); //export json files try { ObjectWriter ow = new com.fasterxml.jackson.databind.ObjectMapper().writer() .withDefaultPrettyPrinter(); String json = ow.writeValueAsString(diaryEntries); System.out.println("-------------------- Start exporting diaries in Volume " + path.getFileName() + " ------------- "); // String origin = diaryEntries.get(0).getSource(); String fileName = "parsed/diaries/" + path.getFileName() + ".json"; try (Writer out = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8"))) { out.write(json); } System.out.println("-------------------- End of export in Volume " + path.getFileName() + " ------------- "); } catch (Exception e) { e.printStackTrace(); } if (properties.getProperty("upload_to_elastic").equalsIgnoreCase("true")) { ElasticLoader.uploadDiariesToElasticServer(properties, diaryEntries); } } outDebug.println("end file"); //more code } catch (IOException e) { //exception handling left as an exercise for the reader } }
From source file:org.testeditor.fixture.swt.SwtBotFixture.java
/** * Cleans the Workspace of the AUT and creates a demo Project. * /*from w w w.j ava2 s .c o m*/ * @throws IOException * on reset the workspace. * @throws URISyntaxException * on reset the workspace. */ private void prepareAUTWorkspace() throws IOException, URISyntaxException { File wsPathFile = new File(getWorkspacePath()); Path wsPath = wsPathFile.toPath(); if (wsPathFile.exists()) { Files.walkFileTree(wsPath, getDeleteFileVisitor()); LOGGER.info("Removed AUT_WS: " + getWorkspacePath()); } Files.createDirectory(wsPath); Map<String, String> env = new HashMap<String, String>(); env.put("create", "true"); FileSystem fs = FileSystems.newFileSystem(getClass().getResource("/DemoWebTests.zip").toURI(), env); Iterable<Path> rootDirectories = fs.getRootDirectories(); for (Path root : rootDirectories) { DirectoryStream<Path> directoryStream = Files.newDirectoryStream(root); for (Path path : directoryStream) { if (path.getFileName().startsWith("DemoWebTests.zip")) { LOGGER.info("Found DemoWebTest."); Files.copy(path, Paths.get(wsPath.toString(), "DemoWebTests.zip")); URI uriDemoZip = new URI("jar:" + Paths.get(wsPath.toString(), "/DemoWebTests.zip").toUri()); LOGGER.info(uriDemoZip); FileSystem zipFs = FileSystems.newFileSystem(uriDemoZip, env); copyFolder(zipFs.getPath("/"), Paths.get(getWorkspacePath())); zipFs.close(); } } } fs.close(); LOGGER.info("Created Demoproject in: " + getWorkspacePath()); }
From source file:net.mozq.picto.core.ProcessCore.java
public static void findFiles(ProcessCondition processCondition, Consumer<ProcessData> processDataSetter, BooleanSupplier processStopper) throws IOException { Set<FileVisitOption> fileVisitOptionSet; if (processCondition.isFollowLinks()) { fileVisitOptionSet = EnumSet.of(FileVisitOption.FOLLOW_LINKS); } else {/*from ww w .jav a2 s .c om*/ fileVisitOptionSet = Collections.emptySet(); } Files.walkFileTree(processCondition.getSrcRootPath(), fileVisitOptionSet, processCondition.getDept(), new SimpleFileVisitor<Path>() { @Override public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException { if (processStopper.getAsBoolean()) { return FileVisitResult.TERMINATE; } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (attrs.isDirectory()) { return FileVisitResult.SKIP_SUBTREE; } if (processStopper.getAsBoolean()) { return FileVisitResult.TERMINATE; } if (!processCondition.getPathFilter().accept(file, attrs)) { return FileVisitResult.SKIP_SUBTREE; } Path rootRelativeSubPath = processCondition.getSrcRootPath().relativize(file.getParent()); ImageMetadata imageMetadata = getImageMetadata(file); Date baseDate; if (processCondition.isChangeFileCreationDate() || processCondition.isChangeFileModifiedDate() || processCondition.isChangeFileAccessDate() || processCondition.isChangeExifDate()) { baseDate = getBaseDate(processCondition, file, attrs, imageMetadata); } else { baseDate = null; } String destSubPathname = processCondition.getDestSubPathFormat().format(varName -> { try { switch (varName) { case "Now": return new Date(); case "ParentSubPath": return rootRelativeSubPath.toString(); case "FileName": return file.getFileName().toString(); case "BaseName": return FileUtilz.getBaseName(file.getFileName().toString()); case "Extension": return FileUtilz.getExt(file.getFileName().toString()); case "Size": return Long.valueOf(Files.size(file)); case "CreationDate": return (processCondition.isChangeFileCreationDate()) ? baseDate : new Date(attrs.creationTime().toMillis()); case "ModifiedDate": return (processCondition.isChangeFileModifiedDate()) ? baseDate : new Date(attrs.lastModifiedTime().toMillis()); case "AccessDate": return (processCondition.isChangeFileAccessDate()) ? baseDate : new Date(attrs.lastAccessTime().toMillis()); case "PhotoTakenDate": return (processCondition.isChangeExifDate()) ? baseDate : getPhotoTakenDate(file, imageMetadata); case "Width": return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_EXIF_IMAGE_WIDTH); case "Height": return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_EXIF_IMAGE_LENGTH); case "FNumber": return getEXIFDoubleValue(imageMetadata, ExifTagConstants.EXIF_TAG_FNUMBER); case "Aperture": return getEXIFDoubleValue(imageMetadata, ExifTagConstants.EXIF_TAG_APERTURE_VALUE); case "MaxAperture": return getEXIFDoubleValue(imageMetadata, ExifTagConstants.EXIF_TAG_MAX_APERTURE_VALUE); case "ISO": return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_ISO); case "FocalLength": return getEXIFDoubleValue(imageMetadata, ExifTagConstants.EXIF_TAG_FOCAL_LENGTH); // ? case "FocalLength35mm": return getEXIFDoubleValue(imageMetadata, ExifTagConstants.EXIF_TAG_FOCAL_LENGTH_IN_35MM_FORMAT); case "ShutterSpeed": return getEXIFDoubleValue(imageMetadata, ExifTagConstants.EXIF_TAG_SHUTTER_SPEED_VALUE); case "Exposure": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_EXPOSURE); // case "ExposureTime": return getEXIFDoubleValue(imageMetadata, ExifTagConstants.EXIF_TAG_EXPOSURE_TIME); // case "ExposureMode": return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_EXPOSURE_MODE); case "ExposureProgram": return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_EXPOSURE_PROGRAM); case "Brightness": return getEXIFDoubleValue(imageMetadata, ExifTagConstants.EXIF_TAG_BRIGHTNESS_VALUE); case "WhiteBalance": return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_WHITE_BALANCE_1); case "LightSource": return getEXIFIntValue(imageMetadata, ExifTagConstants.EXIF_TAG_LIGHT_SOURCE); case "Lens": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_LENS); case "LensMake": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_LENS_MAKE); case "LensModel": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_LENS_MODEL); case "LensSerialNumber": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_LENS_SERIAL_NUMBER); case "Make": return getEXIFStringValue(imageMetadata, TiffTagConstants.TIFF_TAG_MAKE); case "Model": return getEXIFStringValue(imageMetadata, TiffTagConstants.TIFF_TAG_MODEL); case "SerialNumber": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_SERIAL_NUMBER); case "Software": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_SOFTWARE); case "ProcessingSoftware": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_PROCESSING_SOFTWARE); case "OwnerName": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_OWNER_NAME); case "CameraOwnerName": return getEXIFStringValue(imageMetadata, ExifTagConstants.EXIF_TAG_CAMERA_OWNER_NAME); case "GPSLat": return getEXIFGpsLat(imageMetadata); case "GPSLatDeg": return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE, 0); case "GPSLatMin": return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE, 1); case "GPSLatSec": return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE, 2); case "GPSLatRef": return getEXIFStringValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LATITUDE_REF); case "GPSLon": return getEXIFGpsLon(imageMetadata); case "GPSLonDeg": return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE, 0); case "GPSLonMin": return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE, 1); case "GPSLonSec": return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE, 2); case "GPSLonRef": return getEXIFStringValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_LONGITUDE_REF); case "GPSAlt": return getEXIFDoubleValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_ALTITUDE); case "GPSAltRef": return getEXIFIntValue(imageMetadata, GpsTagConstants.GPS_TAG_GPS_ALTITUDE_REF); default: throw new PictoInvalidDestinationPathException(Messages .getString("message.warn.invalid.destSubPath.varName", varName)); } } catch (PictoException e) { throw e; } catch (Exception e) { throw new PictoInvalidDestinationPathException( Messages.getString("message.warn.invalid.destSubPath.pattern"), e); } }); Path destSubPath = processCondition.getDestRootPath().resolve(destSubPathname).normalize(); if (!destSubPath.startsWith(processCondition.getDestRootPath())) { throw new PictoInvalidDestinationPathException( Messages.getString("message.warn.invalid.destination.path", destSubPath)); } ProcessData processData = new ProcessData(); processData.setSrcPath(file); processData.setSrcFileAttributes(attrs); processData.setDestPath(destSubPath); processData.setBaseDate(baseDate); processDataSetter.accept(processData); return FileVisitResult.CONTINUE; } }); }
From source file:org.testeditor.fixture.swt.SwtBotFixture.java
/** * copies the directories.//from ww w . j ava 2 s .c o m * * @param src * source-directory * @param dest * destination-directory * @throws IOException * IOException */ private void copyFolder(Path src, Path dest) throws IOException { if (Files.isDirectory(src)) { // if directory not exists, create it if (!Files.exists(dest)) { Files.createDirectory(dest); } DirectoryStream<Path> directoryStream = Files.newDirectoryStream(src); for (Path path : directoryStream) { Path srcFile = path; Path destFile = Paths.get(dest.toString() + "/" + path.getFileName()); copyFolder(srcFile, destFile); } } else { Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING); } }
From source file:de.dal33t.powerfolder.Controller.java
/** * Answers the path, where to load/store miscellanouse files created by * PowerFolder. e.g. .nodes files/* w ww . java2 s . c o m*/ * * @return the file base, a directory */ public static Path getMiscFilesLocation() { Path base; Path unixConfigDir = Paths.get(System.getProperty("user.home"), "." + Constants.MISC_DIR_NAME) .toAbsolutePath(); if (OSUtil.isWindowsSystem() && Feature.WINDOWS_MISC_DIR_USE_APP_DATA.isEnabled()) { String appData; if (Feature.CONFIGURATION_ALL_USERS.isEnabled()) { appData = WinUtils.getAppDataAllUsers(); } else { appData = WinUtils.getAppDataCurrentUser(); } if (StringUtils.isBlank(appData)) { // Appdata not found. Fallback. return unixConfigDir; } Path windowsConfigDir = Paths.get(appData, Constants.MISC_DIR_NAME).toAbsolutePath(); base = windowsConfigDir; // Check if migration is necessary if (Files.exists(unixConfigDir)) { boolean migrateConfig; if (Files.exists(windowsConfigDir)) { // APPDATA/PowerFolder does not yet contain a config file OR Filter<Path> filter = new Filter<Path>() { @Override public boolean accept(Path entry) { return entry.getFileName().toString().endsWith("config"); } }; try (DirectoryStream<Path> stream = Files.newDirectoryStream(windowsConfigDir, filter)) { migrateConfig = !stream.iterator().hasNext(); } catch (IOException ioe) { log.info(ioe.getMessage()); migrateConfig = true; } } else { // Migrate if APPDATA/PowerFolder not existing yet. migrateConfig = true; } if (migrateConfig) { boolean migrationOk = migrateWindowsMiscLocation(unixConfigDir, windowsConfigDir); if (!migrationOk) { // Fallback, migration failed. base = unixConfigDir; } } } } else { base = unixConfigDir; } if (Files.notExists(base)) { try { Files.createDirectories(base); } catch (IOException ioe) { log.severe("Failed to create " + base.toAbsolutePath().toString() + ". " + ioe); } } return base; }
From source file:gov.nasa.jpl.memex.pooledtimeseries.PoT.java
public static void evaluateSimilarity(ArrayList<Path> files, int save_mode) { // PoT level set ArrayList<double[]> tws = getTemporalWindows(4); // computing feature vectors ArrayList<FeatureVector> fv_list = new ArrayList<FeatureVector>(); for (int k = 0; k < files.size(); k++) { try {/*from w w w . j ava 2s . co m*/ LOG.fine(files.get(k).toString()); ArrayList<double[][]> multi_series = new ArrayList<double[][]>(); Path file = files.get(k); // optical flow descriptors String series_name1 = file.toString(); if ((!series_name1.endsWith(".of.txt")) && (!series_name1.endsWith(".hog.txt"))) { series_name1 += ".of.txt"; } Path series_path1 = Paths.get(series_name1); double[][] series1; if (save_mode == 0) { series1 = getOpticalTimeSeries(file, 5, 5, 8); saveVectors(series1, series_path1); } else { series1 = loadTimeSeries(series_path1); } multi_series.add(series1); // gradients descriptors String series_name2 = file.toString(); if ((!series_name2.endsWith(".hog.txt")) && (!series_name2.endsWith(".of.txt"))) { series_name2 += ".hog.txt"; } Path series_path2 = Paths.get(series_name2); double[][] series2; if (save_mode == 0) { series2 = getGradientTimeSeries(file, 5, 5, 8); saveVectors(series2, series_path2); } else { series2 = loadTimeSeries(series_path2); } multi_series.add(series2); // computing features from series of descriptors FeatureVector fv = new FeatureVector(); for (int i = 0; i < multi_series.size(); i++) { fv.feature.add(computeFeaturesFromSeries(multi_series.get(i), tws, 1)); fv.feature.add(computeFeaturesFromSeries(multi_series.get(i), tws, 2)); fv.feature.add(computeFeaturesFromSeries(multi_series.get(i), tws, 5)); } LOG.info((k + 1) + "/" + files.size() + " files done. " + "Finished processing file: " + file.getFileName()); fv_list.add(fv); } catch (PoTException e) { LOG.severe("PoTException occurred: " + e.message + ": Skipping file " + files.get(k)); continue; } } double[][] similarities = calculateSimilarities(fv_list); writeSimilarityOutput(files, similarities); }
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. *//* www . j a v a2 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:com.liferay.sync.engine.file.system.SyncWatchEventProcessor.java
protected void addFolder(SyncWatchEvent syncWatchEvent) throws Exception { Path targetFilePath = Paths.get(syncWatchEvent.getFilePathName()); if (sanitizeFileName(targetFilePath) || isInErrorState(targetFilePath)) { return;/*w w w.ja va 2s. c o m*/ } Path parentTargetFilePath = targetFilePath.getParent(); SyncFile parentSyncFile = SyncFileService.fetchSyncFile(parentTargetFilePath.toString()); if ((parentSyncFile == null) || (!parentSyncFile.isSystem() && (parentSyncFile.getTypePK() == 0))) { queueSyncWatchEvent(parentTargetFilePath.toString(), syncWatchEvent); return; } SyncFile syncFile = SyncFileService.fetchSyncFile(targetFilePath.toString()); if (syncFile == null) { syncFile = SyncFileService.fetchSyncFile(FileKeyUtil.getFileKey(targetFilePath)); if (!verifySite(syncFile, parentSyncFile)) { syncFile = null; } } if (syncFile == null) { SyncFileService.addFolderSyncFile(targetFilePath, parentSyncFile.getTypePK(), parentSyncFile.getRepositoryId(), _syncAccountId); return; } Path sourceFilePath = Paths.get(syncFile.getFilePathName()); if (targetFilePath.equals(sourceFilePath)) { if (isPendingTypePK(syncFile)) { queueSyncWatchEvent(syncFile.getFilePathName(), syncWatchEvent); return; } FileKeyUtil.writeFileKey(targetFilePath, String.valueOf(syncFile.getSyncFileId()), true); } else if (FileUtil.exists(sourceFilePath)) { SyncFileService.addFolderSyncFile(targetFilePath, parentSyncFile.getTypePK(), parentSyncFile.getRepositoryId(), _syncAccountId); return; } else if (parentTargetFilePath.equals(sourceFilePath.getParent())) { if (isPendingTypePK(syncFile)) { queueSyncWatchEvent(syncFile.getFilePathName(), syncWatchEvent); return; } SyncFileService.updateFolderSyncFile(targetFilePath, _syncAccountId, syncFile); } else { if (isPendingTypePK(syncFile)) { queueSyncWatchEvent(syncFile.getFilePathName(), syncWatchEvent); return; } SyncFileService.moveFolderSyncFile(targetFilePath, parentSyncFile.getTypePK(), _syncAccountId, syncFile); Path sourceFileNameFilePath = sourceFilePath.getFileName(); if (!sourceFileNameFilePath.equals(targetFilePath.getFileName())) { SyncFileService.updateFolderSyncFile(targetFilePath, _syncAccountId, syncFile); } } SyncAccount syncAccount = SyncAccountService.fetchSyncAccount(_syncAccountId); if (syncAccount.getState() == SyncAccount.STATE_CONNECTED) { SyncWatchEvent relatedSyncWatchEvent = SyncWatchEventService.fetchSyncWatchEvent( SyncWatchEvent.EVENT_TYPE_DELETE, syncWatchEvent.getFilePathName(), syncWatchEvent.getTimestamp()); if (relatedSyncWatchEvent != null) { _processedSyncWatchEventIds.add(relatedSyncWatchEvent.getSyncWatchEventId()); } } }