List of usage examples for org.apache.commons.io FileUtils cleanDirectory
public static void cleanDirectory(File directory) throws IOException
From source file:it.isislab.dmason.util.SystemManagement.Worker.thrower.DMasonWorkerWithGui.java
public static DMasonWorkerWithGui newInstance(String args[]) { RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean(); ///* w w w .j a v a 2s .com*/ // Get name representing the running Java virtual machine. // It returns something like 6460@AURORA. Where the value // before the @ symbol is the PID. // String jvmName = bean.getName(); //Used for log4j properties System.setProperty("logfile.name", "worker" + jvmName); //Used for log4j properties System.setProperty("steplog.name", "workerStep" + jvmName); DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH_mm_ss_SS"); Date date = new Date(); dateFormat.format(date); System.setProperty("timestamp", date.toLocaleString()); System.setProperty("paramsfile.name", "params"); try { File logPath = new File("Logs/workers"); if (logPath.exists()) FileUtils.cleanDirectory(logPath); } catch (IOException e) { //not a problem } logger = Logger.getLogger(DMasonWorker.class.getCanonicalName()); logger.debug("StartWorker " + VERSION); autoStart = false; String ip = null; String port = null; String topic = ""; updated = false; isBatch = false; topicPrefix = ""; // ip, post, autoconnect if (args.length == 3) { ip = args[0]; port = args[1]; if (args[2].equals("autoconnect")) { autoStart = true; } } // ip, post, topic, event if (args.length == 4) { autoStart = true; if (args[3].equals("update")) { updated = true; } if (args[3].equals("reset")) { updated = false; isBatch = false; } if (args[3].contains("Batch")) { updated = false; isBatch = true; topicPrefix = args[3]; } ip = args[0]; port = args[1]; topic = args[2]; } /*if(args.length == 2 && args[0].equals("auto")) { autoStart = true; updated = true; topic = args[1]; } if(args.length == 1 && args[0].equals("auto")) { autoStart = true; }*/ return new DMasonWorkerWithGui(autoStart, updated, isBatch, topic, ip, port); }
From source file:fr.gael.dhus.database.DatabasePostInit.java
private boolean doIncomingRepopulate() { boolean force_relocate = Boolean.getBoolean("Archive.incoming.relocate"); logger.info("Archives incoming relocate (Archive.incoming.relocate)" + " requested by user (" + force_relocate + ")"); if (!force_relocate) return false; String incoming_path = System.getProperty("Archive.incoming.relocate.path", incomingManager.getIncomingBuilder().getRoot().getPath()); // Force reset the counter. HierarchicalDirectoryBuilder output_builder = new HierarchicalDirectoryBuilder(new File(incoming_path), cfgManager.getArchiveConfiguration().getIncomingConfiguration().getMaxFileNo()); Iterator<Product> products = productDao.getAllProducts(); while (products.hasNext()) { Product product = products.next(); boolean shared_path = false; // Copy the product path File old_path = new File(product.getPath().getPath()); File new_path = null; // Check is same products are use for path and download if (product.getDownloadablePath().equals(old_path.getPath())) shared_path = true;// w w w . j a va 2 s .co m if (incomingManager.isInIncoming(old_path)) { new_path = getNewProductPath(output_builder); try { logger.info("Relocate " + old_path.getPath() + " to " + new_path.getPath()); FileUtils.moveToDirectory(old_path, new_path, true); File path = old_path; while (!incomingManager.isAnIncomingElement(path)) { path = path.getParentFile(); } FileUtils.cleanDirectory(path); } catch (IOException e) { logger.error("Cannot move directory " + old_path.getPath() + " to " + new_path.getPath(), e); logger.error("Aborting relocation process."); return false; } URL product_path = null; try { product_path = new File(new_path, old_path.getName()).toURI().toURL(); } catch (MalformedURLException e) { logger.error("Unrecoverable error : aboting relocate.", e); return false; } product.setPath(product_path); // Commit this change productDao.update(product); searchService.index(product); } // copy the downloadable path if (product.getDownload().getPath() != null) { if (shared_path) { product.getDownload().setPath(product.getPath().getPath()); } else { new_path = getNewProductPath(output_builder); old_path = new File(product.getDownload().getPath()); try { logger.info("Relocate " + old_path.getPath() + " to " + new_path.getPath()); FileUtils.moveFileToDirectory(old_path, new_path, false); } catch (IOException e) { logger.error( "Cannot move downloadable file " + old_path.getPath() + " to " + new_path.getPath(), e); logger.error("Aborting relocation process."); return false; } product.getDownload().setPath(new File(new_path, old_path.getName()).getPath()); // Commit this change } productDao.update(product); } // Copy Quicklooks new_path = null; if (product.getQuicklookFlag()) { old_path = new File(product.getQuicklookPath()); if (new_path == null) new_path = output_builder.getDirectory(); try { logger.info("Relocate " + old_path.getPath() + " to " + new_path.getPath()); FileUtils.moveToDirectory(old_path, new_path, false); } catch (IOException e) { logger.error("Cannot move quicklook file " + old_path.getPath() + " to " + new_path.getPath(), e); logger.error("Aborting relocation process."); return false; } File f = new File(new_path, old_path.getName()); product.setQuicklookPath(f.getPath()); product.setQuicklookSize(f.length()); productDao.update(product); } // Copy Thumbnails in the same incoming path as quicklook if (product.getThumbnailFlag()) { old_path = new File(product.getThumbnailPath()); if (new_path == null) new_path = output_builder.getDirectory(); try { logger.info("Relocate " + old_path.getPath() + " to " + new_path.getPath()); FileUtils.moveToDirectory(old_path, new_path, false); } catch (IOException e) { logger.error("Cannot move thumbnail file " + old_path.getPath() + " to " + new_path.getPath(), e); logger.error("Aborting relocation process."); return false; } File f = new File(new_path, old_path.getName()); product.setThumbnailPath(f.getPath()); product.setThumbnailSize(f.length()); productDao.update(product); } } // Remove unused directories try { cleanupIncoming(incomingManager.getIncomingBuilder().getRoot()); } catch (Exception e) { logger.error("Cannot cleanup incoming folder", e); } return true; }
From source file:net.orzo.lib.Files.java
/** * @param path//from ww w . j a v a2s.c o m * @throws IOException */ public void cleanDirectory(String path) throws IOException { FileUtils.cleanDirectory(new File(path)); }
From source file:edu.ku.brc.specify.tasks.subpane.JasperReportsCache.java
public static void clearCache() { try {// w w w.jav a 2 s.c o m FileUtils.cleanDirectory(getCachePath()); } catch (Exception ex) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(JasperReportsCache.class, ex); log.error(ex); } }
From source file:io.heming.accountbook.ui.MainFrame.java
private void importRecords() { final JFileChooser chooser = new JFileChooser(); chooser.setFileSelectionMode(JFileChooser.FILES_ONLY); chooser.addChoosableFileFilter(new AbbFileFilter()); chooser.setAcceptAllFileFilterUsed(false); int value = chooser.showOpenDialog(this); if (value == JFileChooser.APPROVE_OPTION) { // ?/*from w w w. j a v a 2 s . c om*/ disableAllControls(); new Thread() { @Override public void run() { try { statusLabel.setIcon(new ImageIcon(getClass().getResource("loader.gif"))); setStatusText("?..."); FacadeUtil.shutdown(); File file = chooser.getSelectedFile(); setStatusText("??..."); FileUtils.cleanDirectory(new File(Constants.DATA_DIR)); setStatusText("??..."); ZIPUtil.decompress(file, new File(Constants.HOME_DIR)); setStatusText("?..."); FacadeUtil.restart(); // ?? setStatusText("????..."); categories = categoryFacade.listBySale(); // ???? setStatusText("?..."); searchRecords(); enableAllControls(); setStatusText(""); statusLabel.setIcon(new ImageIcon(getClass().getResource("stopped-loader.png"))); JOptionPane.showMessageDialog(MainFrame.this, "???", "?", JOptionPane.INFORMATION_MESSAGE); } catch (Exception e) { JOptionPane.showMessageDialog(MainFrame.this, e.getMessage(), "", JOptionPane.ERROR_MESSAGE); } } }.start(); } }
From source file:de.thischwa.pmcms.view.renderer.ExportRenderer.java
private void renderRenderables() throws RenderingException { exportController.addAll(buildThreads(exportController, renderableObjects)); SWTUtils.asyncExec(exportController, display); int oldThreadCount = 0; do {//from w w w.j av a2s. c o m isInterruptByUser = (monitor != null && monitor.isCanceled()); try { Thread.sleep(25); } catch (InterruptedException e) { logger.debug("Controller interrupted."); } int threadCount = exportController.getTerminatedThreadCount(); if (oldThreadCount < threadCount) { incProgressValue(threadCount - oldThreadCount); oldThreadCount = threadCount; } } while (!exportController.isError() && !exportController.isTerminated() && !isInterruptByUser); if (exportController.isError()) throw new RenderingException(exportController.getThreadException()); if (isInterruptByUser) { exportController.cancel(); try { FileUtils.cleanDirectory(exportDir); } catch (IOException e) { logger.error("While cleaning the export directory: " + e.getLocalizedMessage(), e); } logger.debug("Export was interrupt by user, export dir will be deleted!"); } }
From source file:com.athomas.androidkickstartr.Kickstartr.java
public void clean() { File targetDir = fileHelper.getTargetDir(); try {//w w w . j av a 2 s . co m FileUtils.cleanDirectory(targetDir); } catch (IOException e) { LOGGER.error("a problem occured during target dir cleaning", e); } }
From source file:com.vsquaresystem.safedeals.location.LocationService.java
public boolean saveExcelToDatabase() throws IOException { Vector dataHolder = read();//w w w.j a v a 2s . co m dataHolder.remove(0); Location location = new Location(); String id = ""; String name = ""; String description = ""; String cityId = ""; String locationTypeId = ""; String locationCategories = ""; String safedealZoneId = ""; String majorApproachRoad = ""; String advantage = ""; String disadvantage = ""; String population = ""; String latitude = ""; String longitude = ""; String sourceOfWater = ""; String publicTransport = ""; String migrationRate = ""; String distanceCenterCity = ""; String isCommercialCenter = ""; String distanceCommercialCenter = ""; String imageUrl = ""; System.out.println("line1785SAVE sop" + dataHolder); DataFormatter formatter = new DataFormatter(); for (Iterator iterator = dataHolder.iterator(); iterator.hasNext();) { List list = (List) iterator.next(); name = list.get(0).toString(); description = list.get(1).toString(); cityId = list.get(2).toString(); locationTypeId = list.get(3).toString(); locationCategories = list.get(4).toString(); safedealZoneId = list.get(5).toString(); majorApproachRoad = list.get(6).toString(); advantage = list.get(7).toString(); disadvantage = list.get(8).toString(); population = list.get(9).toString(); latitude = list.get(10).toString(); longitude = list.get(11).toString(); sourceOfWater = list.get(12).toString(); publicTransport = list.get(13).toString(); migrationRate = list.get(14).toString(); distanceCenterCity = list.get(15).toString(); isCommercialCenter = list.get(16).toString(); distanceCommercialCenter = list.get(17).toString(); imageUrl = list.get(18).toString(); List<String> strList = new ArrayList<String>(Arrays.asList(locationCategories.split(","))); List<Integer> numberList = new ArrayList<Integer>(); for (String number : strList) { numberList.add(Integer.parseInt(number)); } try { location.setName(name); location.setDescription(description); location.setCityId(Integer.parseInt(cityId)); location.setLocationTypeId(Integer.parseInt(locationTypeId)); location.setLocationCategories(numberList); location.setSafedealZoneId(Integer.parseInt(safedealZoneId)); location.setMajorApproachRoad(majorApproachRoad); location.setAdvantage(advantage); location.setDisadvantage(disadvantage); location.setPopulation(Integer.parseInt(population)); location.setLatitude(Double.parseDouble(latitude)); location.setLongitude(Double.parseDouble(longitude)); location.setMigrationRatePerAnnum(MigrationRatePerAnnum.valueOf(migrationRate)); location.setDistanceFromCentreOfCity(Double.parseDouble(distanceCenterCity)); location.setDistanceFromCommercialCenter(Double.parseDouble(distanceCommercialCenter)); location.setIsCommercialCenter(Boolean.valueOf(isCommercialCenter)); location.setImageUrl(imageUrl); System.out.println("location line167 CHECKcheck" + location); System.out.println("numberList" + numberList); locationDAL.insert(location); } catch (Exception e) { e.printStackTrace(); } } File excelFile = attachmentUtils.getDirectoryByAttachmentType(AttachmentUtils.AttachmentType.LOCATION); FileUtils.cleanDirectory(excelFile); return true; }
From source file:com.linkedin.databus2.relay.TestGoldenGateEventProducer.java
/** * test collection of parser stats, especially lag between parsed and added files * @throws Exception/* w ww . jav a 2 s. c o m*/ */ @Test public void testGGParserStats() throws Exception { short[] sourceIds = new short[] { 505, 506 }; String[] sourceNames = new String[] { "source1", "source2" }; // setup trail Files directory File ggTrailDir = new File("/tmp/ggTrailTestFiles"); if (ggTrailDir.exists()) { FileUtils.cleanDirectory(ggTrailDir); } if (!ggTrailDir.exists()) { ggTrailDir.mkdir(); } // configure phisical source String uri = "gg://" + ggTrailDir.getAbsolutePath() + ":x3"; PhysicalSourceStaticConfig pssc = buildSimplePssc(sourceIds, sourceNames, uri); LOG.info("Uri=" + uri); // create schema Schema s = Schema.parse(sourceAvroSchema); VersionedSchema vs = new VersionedSchema(new VersionedSchemaId("source1", (short) 3), s, null); // mock for schema registry SchemaRegistryService srs = EasyMock.createMock(SchemaRegistryService.class); EasyMock.expect(srs.fetchLatestVersionedSchemaBySourceName("source1")).andReturn(vs).anyTimes(); EasyMock.expect(srs.fetchLatestVersionedSchemaBySourceName("source2")).andReturn(vs).anyTimes(); EasyMock.expect(srs.fetchLatestVersionedSchemaBySourceName(null)).andReturn(vs); // mock for MaxSCNReadWriter MaxSCNReaderWriter mscn = EasyMock.createMock(MaxSCNReaderWriter.class); EasyMock.expect(mscn.getMaxScn()).andReturn((long) -2).atLeastOnce(); mscn.saveMaxScn(EasyMock.anyLong()); EasyMock.expectLastCall().anyTimes(); EasyMock.replay(mscn); EasyMock.replay(srs); int totalTransWritten = 0; int totalFilesWritten = 0; // buffer DbusEventBufferAppendable mb = createBufMult(pssc); // start GG producer GoldenGateEventProducer gg = new GoldenGateEventProducer(pssc, srs, mb, null, mscn); //create first 2 files addToTrailFile(new File(ggTrailDir.getAbsolutePath() + "/x301"), 100, 4); addToTrailFile(new File(ggTrailDir.getAbsolutePath() + "/x302"), 200, 4); totalTransWritten = 8; totalFilesWritten = 2; // get hold of parser stats object final GGParserStatistics ggParserStats = gg.getParserStats(); // all should be 0 Assert.assertEquals(0, ggParserStats.getNumFilesParsed()); Assert.assertEquals(0, ggParserStats.getNumFilesAdded()); Assert.assertEquals(0, ggParserStats.getFilesLag()); Assert.assertEquals(0, ggParserStats.getTimeLag()); Assert.assertEquals(0, ggParserStats.getBytesLag()); try { LOG.info("starting event producer"); gg.start(-2); // -2 here does nothing. actual setting happens thru the mock of MaxSCNReadWriter // let it parse first files TestUtil.assertWithBackoff(new ConditionCheck() { @Override public boolean check() { return ggParserStats.getNumFilesParsed() == 2 && (8 * _transactionPatternSize == ggParserStats.getNumBytesTotalParsed()); } }, "First two files parsed", 2000, LOG); // stats in the interim Assert.assertEquals(2, ggParserStats.getNumFilesParsed()); Assert.assertEquals(2, ggParserStats.getNumFilesAdded()); Assert.assertEquals(0, ggParserStats.getFilesLag()); Assert.assertEquals(0, ggParserStats.getTimeLag()); Assert.assertEquals(0, ggParserStats.getBytesLag()); Assert.assertEquals(totalTransWritten * _transactionPatternSize, ggParserStats.getNumBytesTotalParsed()); gg.pause(); // the file will get parsed but not processed addToTrailFile(new File(ggTrailDir.getAbsolutePath() + "/x303"), 300, 4); totalTransWritten += 4; totalFilesWritten++; TestUtil.sleep(2000); // to get more then a ms lag time addToTrailFile(new File(ggTrailDir.getAbsolutePath() + "/x304"), 400, 4); totalTransWritten += 4; totalFilesWritten++; TestUtil.sleep(6000); // to guarantee we picked up stats update (stats are updated every 5 seconds) // now we should be 2 files behind. parser thread gets paused AFTER it start processing the file // so the actuall value will be 1 file behind int lagFiles = 1; //303(already started being parsed), only 304 is behind long lagBytes = 1 * 4 * _transactionPatternSize; // 1 file, 4 transactions each /* Assert.assertEquals(totalFilesWritten-1, ggParserStats.getNumFilesParsed()); Assert.assertEquals(totalFilesWritten, ggParserStats.getNumFilesAdded()); Assert.assertEquals(lagFiles, ggParserStats.getFilesLag()); // because 303 got parsed // we added 4 files and parsed 3 , so the diff should be 1 file size (4 trasactions in 1 file) Assert.assertEquals(lagBytes, ggParserStats.getBytesLag()); Assert.assertTrue(ggParserStats.getTimeLag()>0); */ gg.unpause(); TestUtil.sleep(5000); // now we should catchup Assert.assertEquals(4, ggParserStats.getNumFilesParsed()); Assert.assertEquals(4, ggParserStats.getNumFilesAdded()); Assert.assertEquals(0, ggParserStats.getFilesLag()); Assert.assertEquals(0, ggParserStats.getTimeLag()); Assert.assertEquals(0, ggParserStats.getBytesLag()); // append to a file LOG.info("pausing again"); gg.pause(); addToTrailFile(new File(ggTrailDir.getAbsolutePath() + "/x304"), 410, 4); totalTransWritten += 4; TestUtil.sleep(1000); addToTrailFile(new File(ggTrailDir.getAbsolutePath() + "/x304"), 420, 4); totalTransWritten += 4; TestUtil.sleep(2000); gg.unpause(); TestUtil.sleep(5500); // should be still up Assert.assertEquals(4, ggParserStats.getNumFilesParsed()); Assert.assertEquals(4, ggParserStats.getNumFilesAdded()); Assert.assertEquals(0, ggParserStats.getFilesLag()); Assert.assertEquals(0, ggParserStats.getTimeLag()); Assert.assertEquals(0, ggParserStats.getBytesLag()); // assert the stats int totalFilesSize = totalTransWritten * _transactionPatternSize; Assert.assertEquals((totalFilesSize / totalFilesWritten), ggParserStats.getAvgFileSize()); Assert.assertEquals(true, ggParserStats.getAvgParseTransactionTimeNs() > 0); Assert.assertEquals("part1", ggParserStats.getPhysicalSourceName()); Assert.assertEquals(totalFilesSize / totalTransWritten, ggParserStats.getAvgTransactionSize()); Assert.assertEquals(423, ggParserStats.getMaxScn()); Assert.assertEquals(totalTransWritten * 2, ggParserStats.getNumTotalEvents()); // 2 events per transaction Assert.assertEquals(totalTransWritten, ggParserStats.getNumTransactionsTotal()); Assert.assertEquals(totalTransWritten, ggParserStats.getNumTransactionsWithEvents()); Assert.assertEquals(0, ggParserStats.getNumTransactionsWithoutEvents()); Assert.assertEquals(true, ggParserStats.getTimeSinceLastAccessMs() > 0); Assert.assertEquals(totalTransWritten * _transactionPatternSize, ggParserStats.getNumBytesTotalParsed()); } finally { gg.shutdown(); } return; }
From source file:com.theserverlabs.maven.utplsq.UtplsqlMojo.java
/** * Clears any old reports and sets up new path * @return/*from w w w .j a va 2 s. c om*/ * @throws IOException */ protected File getSurefireDir() throws IOException { File surefireDir = new File(outputDirectory, "surefire-reports"); FileUtils.forceMkdir(surefireDir); FileUtils.cleanDirectory(surefireDir); return surefireDir; }