List of usage examples for java.io File setLastModified
public boolean setLastModified(long time)
From source file:org.isatools.isatab.export.DataFilesDispatcher.java
/** * Dispatch the files about a given assay group * * @param outPath where the files go, no dispatch done if this is null. *///w w w . j a v a 2s .co m private void dispatchAssayGroup(final AssayGroup ag) throws IOException { SectionInstance assaySectionInstance = ag.getAssaySectionInstance(); if (assaySectionInstance == null) { return; } Study study = ag.getStudy(); // Copy the assay file to the submission repo String assayFileRelativePath = assaySectionInstance.getFileId(); dispatchFileToSubmissionRepo(ag.getStudy(), "Assay File Name", assayFileRelativePath); for (Record record : assaySectionInstance.getRecords()) { int recSize = record.size(); for (int fieldIndex = 0; fieldIndex < recSize; fieldIndex++) { // TODO: change this so that we get: field name, file-type, file-path String[] filePathPair = FormatExporter.getExternalFileValue(record, fieldIndex); if (filePathPair == null) { continue; } String fieldHeader = filePathPair[0], srcFileRelPath = filePathPair[1], srcFileType = filePathPair[2]; if (srcFileRelPath == null) { continue; } AnnotationTypes targetType; if ("raw".equals(srcFileType)) { targetType = AnnotationTypes.RAW_DATA_FILE_PATH; } else if ("processed".equals(srcFileType)) { targetType = AnnotationTypes.PROCESSED_DATA_FILE_PATH; } else { targetType = AnnotationTypes.GENERIC_DATA_FILE_PATH; } String targetPath = StringUtils.trimToNull(dataLocationMgr.getDataLocation(study, ag.getMeasurement(), ag.getTechnology(), targetType)); if (targetPath == null) { continue; } File srcFile = new File(sourcePath + "/" + srcFileRelPath); File targetDir = new File(targetPath); File targetFile = new File(targetPath + "/" + srcFileRelPath); if (!srcFile.exists()) { log.info("WARNING: Source file '" + srcFileRelPath + "' / '" + fieldHeader + "' not found"); } else { if (targetFile.exists() && targetFile.lastModified() == srcFile.lastModified()) { log.debug("Not copying " + srcFile.getCanonicalPath() + "' to '" + targetFile.getCanonicalPath() + "': they seem to be the same."); } else { log.trace("Copying data file '" + fieldHeader + "' / '" + srcFileRelPath + "' to data repository..."); FileUtils.copyFileToDirectory(srcFile, targetDir, true); // Needed cause of a bug in the previous function targetFile.setLastModified(srcFile.lastModified()); log.trace("...done"); log.info("Data file '" + fieldHeader + "' / '" + srcFile.getCanonicalPath() + "' copied to '" + targetDir.getCanonicalPath() + "'"); } } // if } // for ( field ) } // for ( record ) }
From source file:com.moviejukebox.scanner.AttachmentScanner.java
/** * Extract an attachment/*from w w w . j a v a2 s .c o m*/ * * @param attachment the attachment to extract * @param setImage true, if a set image should be extracted; in this case ".set" is append before file extension * @param counter a counter (only used for NFOs cause there may be multiple NFOs in one file) * @return */ private static File extractAttachment(Attachment attachment) { File sourceFile = attachment.getSourceFile(); if (sourceFile == null) { // source file must exist return null; } else if (!sourceFile.exists()) { // source file must exist return null; } // build return file name StringBuilder returnFileName = new StringBuilder(); returnFileName.append(tempDirectory.getAbsolutePath()); returnFileName.append(File.separatorChar); returnFileName.append(FilenameUtils.removeExtension(sourceFile.getName())); // add attachment id so the extracted file becomes unique per movie file returnFileName.append("."); returnFileName.append(attachment.getAttachmentId()); switch (attachment.getContentType()) { case NFO: returnFileName.append(".nfo"); break; case POSTER: case FANART: case BANNER: case SET_POSTER: case SET_FANART: case SET_BANNER: case VIDEOIMAGE: returnFileName.append(VALID_IMAGE_MIME_TYPES.get(attachment.getMimeType())); break; default: returnFileName.append(VALID_IMAGE_MIME_TYPES.get(attachment.getMimeType())); break; } File returnFile = new File(returnFileName.toString()); if (returnFile.exists() && (returnFile.lastModified() >= sourceFile.lastModified())) { // already present or extracted LOG.debug("File to extract already exists; no extraction needed"); return returnFile; } LOG.trace("Extract attachement ({})", attachment); try { // Create the command line List<String> commandMedia = new ArrayList<>(MT_EXTRACT_EXE); commandMedia.add("attachments"); commandMedia.add(sourceFile.getAbsolutePath()); commandMedia.add(attachment.getAttachmentId() + ":" + returnFileName.toString()); ProcessBuilder pb = new ProcessBuilder(commandMedia); pb.directory(MT_PATH); Process p = pb.start(); if (p.waitFor() != 0) { LOG.error("Error during extraction - ErrorCode={}", p.exitValue()); returnFile = null; } } catch (IOException | InterruptedException ex) { LOG.error(SystemTools.getStackTrace(ex)); returnFile = null; } if (returnFile != null) { if (returnFile.exists()) { // need to reset last modification date to last modification date // of source file to fulfill later checks try { returnFile.setLastModified(sourceFile.lastModified()); } catch (Exception ignore) { // nothing to do anymore } } else { // reset return file to null if not existent returnFile = null; } } return returnFile; }
From source file:org.geoserver.security.xml.XMLRoleServiceTest.java
@Test public void testDynamicReload() throws Exception { File xmlFile = File.createTempFile("roles", ".xml"); FileUtils.copyURLToFile(getClass().getResource("rolesTemplate.xml"), xmlFile); GeoServerRoleService service1 = createRoleService("reload1", xmlFile.getCanonicalPath()); GeoServerRoleService service2 = createRoleService("reload2", xmlFile.getCanonicalPath()); GeoServerRoleStore store1 = createStore(service1); GeoServerRole role_test1 = store1.createRoleObject("ROLE_TEST1"); checkEmpty(service1);/* w ww . ja v a2 s . co m*/ checkEmpty(service2); // prepare for syncing RoleLoadedListener listener = new RoleLoadedListener() { @Override public void rolesChanged(RoleLoadedEvent event) { synchronized (this) { this.notifyAll(); } } }; service2.registerRoleLoadedListener(listener); // modifiy store1 store1.addRole(role_test1); store1.store(); assertTrue(service1.getRoles().size() == 1); // increment lastmodified adding a second manually, the test is too fast xmlFile.setLastModified(xmlFile.lastModified() + 1000); // wait for the listener to unlock when // service 2 triggers a load event synchronized (listener) { listener.wait(); } // here comes the magic !!! assertTrue(service2.getRoles().size() == 1); }
From source file:cn.com.sinosoft.util.io.FileUtils.java
/** * Internal copy directory method./*from w w w . j av a 2s . co m*/ * * @param srcDir the validated source directory, must not be <code>null</code> * @param destDir the validated destination directory, must not be <code>null</code> * @param filter the filter to apply, null means copy all directories and files * @param preserveFileDate whether to preserve the file date * @param exclusionList List of files and directories to exclude from the copy, may be null * @throws IOException if an error occurs * @since Commons IO 1.1 */ private static void doCopyDirectory(File srcDir, File destDir, FileFilter filter, boolean preserveFileDate, List exclusionList) throws IOException { if (destDir.exists()) { if (destDir.isDirectory() == false) { throw new IOException("Destination '" + destDir + "' exists but is not a directory"); } } else { if (destDir.mkdirs() == false) { throw new IOException("Destination '" + destDir + "' directory cannot be created"); } if (preserveFileDate) { destDir.setLastModified(srcDir.lastModified()); } } if (destDir.canWrite() == false) { throw new IOException("Destination '" + destDir + "' cannot be written to"); } // recurse File[] files = filter == null ? srcDir.listFiles() : srcDir.listFiles(filter); if (files == null) { // null if security restricted throw new IOException("Failed to list contents of " + srcDir); } for (int i = 0; i < files.length; i++) { File copiedFile = new File(destDir, files[i].getName()); if (exclusionList == null || !exclusionList.contains(files[i].getCanonicalPath())) { if (files[i].isDirectory()) { doCopyDirectory(files[i], copiedFile, filter, preserveFileDate, exclusionList); } else { doCopyFile(files[i], copiedFile, preserveFileDate); } } } }
From source file:com.opera.core.systems.OperaPaths.java
/** * Tries to load the launcher executable from the jar file A copy of the * launcher is put into user directory and on each call is compared to the * content in jar file/*from w ww . j av a 2 s . c om*/ * * @return path to launcher executable */ public String getOperaLauncherPath() { String launcherName = getLauncherNameForOS(); String executablePath = null; // Get the launcher path URL res = OperaDriver.class.getClassLoader().getResource("launcher/" + launcherName); if (res != null) { String url = res.toExternalForm(); // If the launcher is inside the jar we will need to copy it out if ((url.startsWith("jar:")) || (url.startsWith("wsjar:"))) { executablePath = FileUtils.getUserDirectoryPath() + File.separatorChar + ".launcher" + File.separatorChar + launcherName; File cur_launcher = new File(executablePath); // Whether we need to copy a new launcher across, either because // it doesn't currently exist, or because its hash differs from // our launcher boolean copy = false; if (!cur_launcher.exists()) { copy = true; } else { try { // Copy if launchers don't match copy = !Arrays.equals(md5(executablePath), md5(res.openStream())); } catch (Exception e) { copy = true; } } if (copy == true) { try { if (!cur_launcher.exists()) FileUtils.touch(cur_launcher); InputStream is = res.openStream(); OutputStream os = new FileOutputStream(cur_launcher); IOUtils.copy(is, os); is.close(); os.close(); cur_launcher.setLastModified(cur_launcher.lastModified()); } catch (IOException e) { throw new WebDriverException("Cant write file to disk : " + e.getMessage()); } logger.fine("New launcher copied"); } // If launcher is not inside jar we can run it from it's current // location } else if (url.startsWith("file:")) { File f; try { f = new File(res.toURI()); } catch (URISyntaxException e) { f = new File(res.getPath()); } executablePath = f.getAbsolutePath(); } } if (executablePath != null) makeLauncherExecutable(executablePath); return executablePath; }
From source file:org.sonatype.nexus.proxy.M2RepositoryIT.java
/** * For expiration-related issues and stories see: NEXUS-1675 NEXUS-3065 NEXUS-4099 * <p />/* www.jav a2s . c o m*/ * * Note: This test is somewhat fragile on Windows in the past if IO is slow or * CPU is thrashing at time of test run. */ private void doTestExpiration(String path, final int age, final int... expectedHits) throws Exception { CounterListener ch = new CounterListener(); M2Repository repository = (M2Repository) getResourceStore(); eventBus().register(ch); File mdFile = new File(new File(getBasedir()), "target/test-classes/repo1" + path); long fileTimestamp = mdFile.lastModified(); assertThat(mdFile, exists()); try { repository.deleteItem(new ResourceStoreRequest("/spoof", true)); } catch (ItemNotFoundException e) { // ignore } repository.setMetadataMaxAge(age); repository.setArtifactMaxAge(age); repository.getCurrentCoreConfiguration().commitChanges(); for (int i = 0; i < 10 && !mdFile.setLastModified(System.currentTimeMillis() - (3L * A_DAY)); i++) { System.gc(); // helps with FS sync'ing on Windows Thread.sleep(500); // wait for FS } assertThat("File timestamp did not change, first pass", mdFile.lastModified(), not(equalTo(fileTimestamp))); fileTimestamp = mdFile.lastModified(); // We need to wait a bit to avoid the check that last remote check = current time Thread.sleep(500); final StorageItem item = repository.retrieveItem(new ResourceStoreRequest(path, false)); getLogger().info(path + " -> BEFORE assert 1 requestCount=" + expectedHits[0] + " at (" + System.currentTimeMillis() + ")"); assertThat("Remote hits count fail after first request at (" + System.currentTimeMillis() + ")", ch.getRequestCount(), equalTo(expectedHits[0])); getLogger().info(path + " -> AFTER assert 1 requestCount=" + expectedHits[0] + " at (" + System.currentTimeMillis() + ")"); for (int i = 0; i < 10 && !mdFile.setLastModified(System.currentTimeMillis() - (2L * A_DAY)); i++) { System.gc(); // helps with FS sync'ing on Windows Thread.sleep(500); // wait for FS } assertThat("File timestamp did not change, second pass", mdFile.lastModified(), not(equalTo(fileTimestamp))); fileTimestamp = mdFile.lastModified(); // We need to wait a bit to avoid the check that last remote check = current time Thread.sleep(500); // this goes remote depending on age setting repository.retrieveItem(new ResourceStoreRequest(path, false)); getLogger().info(path + " -> BEFORE assert 2 requestCount=" + expectedHits[1] + " at (" + System.currentTimeMillis() + ")"); assertThat("Remote hits count fail after second request at (" + System.currentTimeMillis() + ")", ch.getRequestCount(), equalTo(expectedHits[1])); getLogger().info(path + " -> AFTER assert 2 requestCount=" + expectedHits[1] + " at (" + System.currentTimeMillis() + ")"); for (int i = 0; i < 10 && !mdFile.setLastModified(System.currentTimeMillis() - (1L * A_DAY)); i++) { System.gc(); // helps with FS sync'ing on Windows Thread.sleep(500); // wait for FS } assertThat("File timestamp did not change, third pass", mdFile.lastModified(), not(equalTo(fileTimestamp))); fileTimestamp = mdFile.lastModified(); // set up last checked timestamp so that nexus should go remote final RepositoryItemUid uid = item.getRepositoryItemUid(); final AttributeStorage storage = uid.getRepository().getAttributesHandler().getAttributeStorage(); final Attributes attributes = item.getRepositoryItemAttributes(); attributes.setCheckedRemotely(System.currentTimeMillis() - ((Math.abs(age) + 1) * 60 * 1000)); storage.putAttributes(uid, attributes); // We need to wait a bit to avoid the check that last remote check = current time Thread.sleep(500); repository.retrieveItem(new ResourceStoreRequest(path, false)); getLogger().info(path + " -> BEFORE assert 3 requestCount=" + expectedHits[2] + " at (" + System.currentTimeMillis() + ")"); assertThat("Remote hits count fail after third request at (" + System.currentTimeMillis() + ")", ch.getRequestCount(), equalTo(expectedHits[2])); getLogger().info(path + " -> AFTER assert 3 requestCount=" + expectedHits[2] + " at (" + System.currentTimeMillis() + ")"); // cleanup counter listener for next test call to avoid added overhead, logging noise eventBus().unregister(ch); }
From source file:org.abstracthorizon.proximity.storage.remote.CommonsHttpClientRemotePeer.java
public Item retrieveItem(String path, boolean propsOnly) throws ItemNotFoundException, StorageException { // TODO: propsOnly is ignored, use HTTP HEAD? String originatingUrlString = getAbsoluteUrl(path); GetMethod get = new GetMethod(originatingUrlString); try {/*w w w . j a v a2 s . c o m*/ try { logger.info("Fetching item [{}] from remote location {}", path, originatingUrlString); int response = executeMethod(get); if (response == HttpStatus.SC_OK) { // ProxiedItemProperties properties = // constructItemPropertiesFromGetResponse(path, // originatingUrlString, get); Item result = new Item(); ItemProperties ip = null; // is it a file? // TODO: fix for #93 ticket? // Asking GET methods getPath() after execution will // result // in ACTUAL // path after eventual redirection. So, it will end with // "/" // if it is a dir. if (!get.getPath().endsWith(ItemProperties.PATH_SEPARATOR)) { // if (get.getResponseHeader("last-modified") != null) { File tmpFile = File.createTempFile(FilenameUtils.getName(path), null); tmpFile.deleteOnExit(); FileOutputStream fos = new FileOutputStream(tmpFile); try { InputStream is = get.getResponseBodyAsStream(); if (get.getResponseHeader("Content-Encoding") != null && "gzip".equals(get.getResponseHeader("Content-Encoding").getValue())) { is = new GZIPInputStream(is); } IOUtils.copy(is, fos); fos.flush(); } finally { fos.close(); } tmpFile.setLastModified(makeDateFromHeader(get.getResponseHeader("last-modified"))); ip = getProxiedItemPropertiesFactory().expandItemProperties(path, tmpFile, true); result.setStream(new DeleteOnCloseFileInputStream(tmpFile)); } else { // TODO: dirty hack, I am creating a dir named after the // directory retrieval just to get item properties!!! // Fix this! File tmpdir = new File(System.getProperty("java.io.tmpdir"), FilenameUtils.getName(path)); tmpdir.mkdir(); ip = getProxiedItemPropertiesFactory().expandItemProperties(path, tmpdir, true); tmpdir.delete(); result.setStream(null); } result.setProperties(ip); result.getProperties().setRemoteUrl(originatingUrlString); return result; } else { if (response == HttpStatus.SC_NOT_FOUND) { throw new ItemNotFoundException(path); } else { throw new StorageException("The method execution returned result code " + response); } } } catch (MalformedURLException ex) { throw new StorageException("The path " + path + " is malformed!", ex); } catch (IOException ex) { throw new StorageException("IO Error during response stream handling!", ex); } } finally { get.releaseConnection(); } }
From source file:org.jenkins_ci.update_center.repo.NexusRepositoryImpl.java
/** * Loads a remote repository index (.zip or .gz), convert it to Lucene index and return it. */// w w w. ja v a 2 s . c o m private static File loadIndex(String id, URL url) throws IOException, UnsupportedExistingLuceneIndexException { File dir = new File(new File(System.getProperty("java.io.tmpdir")), "maven-index/" + id); File local = new File(dir, "index" + getExtension(url)); File expanded = new File(dir, "expanded"); URLConnection con = url.openConnection(); if (url.getUserInfo() != null) { con.setRequestProperty("Authorization", "Basic " + new sun.misc.BASE64Encoder().encode(url.getUserInfo().getBytes())); } if (!expanded.exists() || !local.exists() || local.lastModified() != con.getLastModified()) { System.out.println("Downloading " + url); // if the download fail in the middle, only leave a broken tmp file dir.mkdirs(); File tmp = new File(dir, "index_" + getExtension(url)); FileOutputStream o = new FileOutputStream(tmp); try { IOUtils.copy(con.getInputStream(), o); } finally { o.close(); } if (expanded.exists()) { FileUtils.deleteDirectory(expanded); } expanded.mkdirs(); if (url.toExternalForm().endsWith(".gz")) { FSDirectory directory = FSDirectory.getDirectory(expanded); NexusIndexWriter w = new NexusIndexWriter(directory, new NexusAnalyzer(), true); FileInputStream in = new FileInputStream(tmp); try { IndexDataReader dr = new IndexDataReader(in); dr.readIndex(w, new DefaultIndexingContext(id, id, null, expanded, null, null, NexusIndexer.DEFAULT_INDEX, true)); } finally { IndexUtils.close(w); IOUtils.closeQuietly(in); directory.close(); } } else if (url.toExternalForm().endsWith(".zip")) { Expand e = new Expand(); e.setSrc(tmp); e.setDest(expanded); e.execute(); } else { throw new UnsupportedOperationException("Unsupported index format: " + url); } // as a proof that the expansion was properly completed tmp.renameTo(local); local.setLastModified(con.getLastModified()); } else { System.out.println("Reusing the locally cached " + url + " at " + local); } return expanded; }
From source file:com.streamsets.pipeline.stage.origin.spooldir.TestSpoolDirSource.java
@Test public void testMultipleFilesSameTimeStamp() throws Exception { File f = new File("target", UUID.randomUUID().toString()); f.mkdir();//from w ww . java2 s . c o m SpoolDirConfigBean conf = new SpoolDirConfigBean(); conf.dataFormat = DataFormat.DELIMITED; conf.useLastModified = FileOrdering.TIMESTAMP; conf.spoolDir = f.getAbsolutePath(); conf.batchSize = 10; conf.overrunLimit = 100; conf.poolingTimeoutSecs = 1; conf.filePattern = "*"; conf.pathMatcherMode = PathMatcherMode.GLOB; conf.maxSpoolFiles = 10; conf.dataFormatConfig.compression = Compression.NONE; conf.dataFormatConfig.filePatternInArchive = "*"; conf.dataFormatConfig.csvHeader = CsvHeader.WITH_HEADER; conf.errorArchiveDir = null; conf.postProcessing = PostProcessingOptions.NONE; conf.retentionTimeMins = 10; conf.allowLateDirectory = false; conf.dataFormatConfig.textMaxLineLen = 10; conf.dataFormatConfig.onParseError = OnParseError.ERROR; conf.dataFormatConfig.maxStackTraceLines = 0; long timestamp = System.currentTimeMillis() - 100000; for (int i = 0; i < 8; i++) { File current = new File(conf.spoolDir, Utils.format("file-{}.log", i)); try (FileOutputStream outputStream = new FileOutputStream(current)) { IOUtils.writeLines(ImmutableList.of("A,B", Utils.format("a-{},b-{}", i, i), "a,b"), "\n", outputStream); } Assert.assertTrue(current.setLastModified(timestamp)); } // for ctime delays, there's no way to set ctime (change timestamp) explicitly by rule Thread.sleep(5000L); File current = new File(conf.spoolDir, "a.log"); try (FileOutputStream outputStream = new FileOutputStream(current)) { IOUtils.writeLines(ImmutableList.of("A,B", "Gollum,Sauron", "Aragorn,Boromir"), "\n", outputStream); } Assert.assertTrue(current.setLastModified(System.currentTimeMillis())); SpoolDirSource source = new SpoolDirSource(conf); PushSourceRunner runner = new PushSourceRunner.Builder(SpoolDirDSource.class, source) .setOnRecordError(OnRecordError.TO_ERROR).addOutputLane("lane").build(); AtomicInteger batchCount = new AtomicInteger(0); runner.runInit(); Assert.assertEquals(0, runner.getErrors().size()); try { runner.runProduce(new HashMap<>(), 10, output -> { int i = batchCount.getAndIncrement(); if (i < 8) { List<Record> records = output.getRecords().get("lane"); Assert.assertNotNull(records); Assert.assertTrue(!records.isEmpty()); Assert.assertEquals(2, records.size()); Assert.assertEquals(Utils.format("file-{}.log", i), records.get(0).getHeader().getAttribute(HeaderAttributeConstants.FILE_NAME)); try { Assert.assertEquals( String.valueOf(Files .getLastModifiedTime( Paths.get(f.getAbsolutePath(), Utils.format("file-{}.log", i))) .toMillis()), records.get(0).getHeader() .getAttribute(HeaderAttributeConstants.LAST_MODIFIED_TIME)); } catch (IOException ex) { Assert.fail(ex.toString()); } Assert.assertEquals("a-" + i, records.get(0).get("/A").getValueAsString()); Assert.assertEquals("b-" + i, records.get(0).get("/B").getValueAsString()); Assert.assertEquals("a", records.get(1).get("/A").getValueAsString()); Assert.assertEquals("b", records.get(1).get("/B").getValueAsString()); // And error record List<Record> errorRecords = runner.getErrorRecords(); Assert.assertEquals(0, errorRecords.size()); } else if (i < 9) { List<Record> records = output.getRecords().get("lane"); Assert.assertNotNull(records); Assert.assertTrue(!records.isEmpty()); Assert.assertEquals(2, records.size()); Assert.assertEquals("a.log", records.get(0).getHeader().getAttribute(HeaderAttributeConstants.FILE_NAME)); Assert.assertEquals("Gollum", records.get(0).get("/A").getValueAsString()); Assert.assertEquals("Sauron", records.get(0).get("/B").getValueAsString()); Assert.assertEquals("Aragorn", records.get(1).get("/A").getValueAsString()); Assert.assertEquals("Boromir", records.get(1).get("/B").getValueAsString()); } else if (i < 10) { List<Record> records = output.getRecords().get("lane"); Assert.assertTrue(records.isEmpty()); // And error record records = runner.getErrorRecords(); Assert.assertEquals(0, records.size()); } else if (i < 11) { // And a bunch of event records... // new-file event, finished-file event for each file. // file-0.log through file-7.log and a.log (9 files) // two no-more-data events. Assert.assertEquals(20, runner.getEventRecords().size()); Map<String, Integer> map = new HashMap<>(); for (EventRecord rec : runner.getEventRecords()) { if (map.get(rec.getEventType()) != null) { map.put(rec.getEventType(), map.get(rec.getEventType()) + 1); } else { map.put(rec.getEventType(), 1); } } Assert.assertNotNull(map.get("new-file")); Assert.assertNotNull(map.get("finished-file")); Assert.assertNotNull(map.get("no-more-data")); int numEvents = map.get("new-file"); Assert.assertEquals(9, numEvents); numEvents = map.get("finished-file"); Assert.assertEquals(9, numEvents); numEvents = map.get("no-more-data"); Assert.assertEquals(2, numEvents); } else { runner.setStop(); } }); runner.waitOnProduce(); Assert.assertEquals(12, batchCount.get()); } finally { runner.runDestroy(); } }
From source file:org.exoplatform.services.jcr.ext.artifact.ArtifactManagingServiceImpl.java
private void mapRepositoryToFilefs(Node parentNode, File parentFolder) throws RepositoryException { NodeIterator folderIterator = parentNode.getNodes(); while (folderIterator.hasNext()) { Node folder = folderIterator.nextNode(); if (folder.isNodeType("exo:artifact")) { File levelfolder = new File(parentFolder.getAbsoluteFile() + File.separator + folder.getName()); levelfolder.mkdir();//w ww .java2s . c om mapRepositoryToFilefs(folder, levelfolder); // recursive call } else if (folder.isNodeType("exo:file")) { File content = new File(parentFolder + File.separator + folder.getName()); FileOutputStream fout = null; try { fout = new FileOutputStream(content); Node dataNode = folder.getNode("jcr:content"); Property data = dataNode.getProperty("jcr:data"); Property lastModified = dataNode.getProperty("jcr:lastModified"); content.setLastModified(lastModified.getLong()); IOUtils.copy(data.getStream(), fout); } catch (FileNotFoundException e) { LOG.error("!!Can't create content fo file", e); } catch (IOException e) { LOG.error("!!Can't write content fo file", e); } finally { IOUtils.closeQuietly(fout); } } } }