List of usage examples for org.apache.commons.io FileUtils copyFile
public static void copyFile(File srcFile, File destFile) throws IOException
From source file:edu.uci.ics.asterix.transaction.management.service.locking.LockManagerDeterministicUnitTest.java
public static void main(String args[]) throws ACIDException, IOException, AsterixException { //prepare configuration file File cwd = new File(System.getProperty("user.dir")); File asterixdbDir = cwd.getParentFile(); File srcFile = new File(asterixdbDir.getAbsoluteFile(), "asterix-app/src/main/resources/asterix-build-configuration.xml"); File destFile = new File(cwd, "target/classes/asterix-configuration.xml"); FileUtils.copyFile(srcFile, destFile); //initialize controller thread String requestFileName = new String( "src/main/java/edu/uci/ics/asterix/transaction/management/service/locking/LockRequestFile"); Thread t = new Thread(new LockRequestController(requestFileName)); t.start();/*www .j a v a 2s .c om*/ }
From source file:edu.uci.ics.asterix.transaction.management.service.locking.LockManagerRandomUnitTest.java
public static void main(String args[]) throws ACIDException, AsterixException, IOException { int i;/* ww w . j a va2 s . c o m*/ //prepare configuration file File cwd = new File(System.getProperty("user.dir")); File asterixdbDir = cwd.getParentFile(); File srcFile = new File(asterixdbDir.getAbsoluteFile(), "asterix-app/src/main/resources/asterix-build-configuration.xml"); File destFile = new File(cwd, "target/classes/asterix-configuration.xml"); FileUtils.copyFile(srcFile, destFile); TransactionSubsystem txnProvider = new TransactionSubsystem("nc1", null, new AsterixTransactionProperties(new AsterixPropertiesAccessor())); rand = new Random(System.currentTimeMillis()); for (i = 0; i < MAX_NUM_OF_ENTITY_LOCK_JOB; i++) { System.out.println("Creating " + i + "th EntityLockJob.."); generateEntityLockThread(txnProvider); } for (i = 0; i < MAX_NUM_OF_DATASET_LOCK_JOB; i++) { System.out.println("Creating " + i + "th DatasetLockJob.."); generateDatasetLockThread(txnProvider); } for (i = 0; i < MAX_NUM_OF_UPGRADE_JOB; i++) { System.out.println("Creating " + i + "th EntityLockUpgradeJob.."); generateEntityLockUpgradeThread(txnProvider); } ((LogManager) txnProvider.getLogManager()).stop(false, null); }
From source file:de.codecentric.elasticsearch.plugin.kerberosrealm.support.EmbeddedKRBServer.java
public static void main(final String[] args) throws Exception { final File workDir = new File("."); final EmbeddedKRBServer eks = new EmbeddedKRBServer(); eks.realm = "DUMMY.COM"; eks.start(workDir);// w w w. j a v a 2s. c o m eks.getSimpleKdcServer().createPrincipal("kirk/admin@DUMMY.COM", "kirkpwd"); eks.getSimpleKdcServer().createPrincipal("uhura@DUMMY.COM", "uhurapwd"); eks.getSimpleKdcServer().createPrincipal("service/1@DUMMY.COM", "service1pwd"); eks.getSimpleKdcServer().createPrincipal("service/2@DUMMY.COM", "service2pwd"); eks.getSimpleKdcServer().exportPrincipal("service/1@DUMMY.COM", new File(workDir, "service1.keytab")); //server, acceptor eks.getSimpleKdcServer().exportPrincipal("service/2@DUMMY.COM", new File(workDir, "service2.keytab")); //server, acceptor eks.getSimpleKdcServer().createPrincipal("HTTP/localhost@DUMMY.COM", "httplocpwd"); eks.getSimpleKdcServer().exportPrincipal("HTTP/localhost@DUMMY.COM", new File(workDir, "httploc.keytab")); //server, acceptor eks.getSimpleKdcServer().createPrincipal("HTTP/localhost@DUMMY.COM", "httpcpwd"); eks.getSimpleKdcServer().exportPrincipal("HTTP/localhost@DUMMY.COM", new File(workDir, "http.keytab")); //server, acceptor final TgtTicket tgt = eks.getSimpleKdcServer().getKrbClient().requestTgtWithPassword("kirk/admin@DUMMY.COM", "kirkpwd"); eks.getSimpleKdcServer().getKrbClient().storeTicket(tgt, new File(workDir, "kirk.cc")); try { try { FileUtils.copyFile(new File("/etc/krb5.conf"), new File("/etc/krb5.conf.bak")); } catch (final Exception e) { //ignore } FileUtils.copyFileToDirectory(new File(workDir, "krb5.conf"), new File("/etc/")); System.out.println("Generated krb5.conf copied to /etc"); } catch (final Exception e) { System.out.println("Unable to copy generated krb5.conf to /etc die to " + e.getMessage()); } }
From source file:com.sanaldiyar.projects.nanohttpd.nanoinstaller.App.java
public static void main(String[] args) { try {/*ww w . ja v a 2 s .c o m*/ String executableName = new File( App.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getName(); Options options = new Options(); Option destination = OptionBuilder.withArgName("folder").withLongOpt("destination").hasArgs(1) .withDescription("destionation folder").withType(String.class).create("d"); Option lrfolder = OptionBuilder.withArgName("folder").withLongOpt("localrepo").hasArgs(1) .withDescription("local repository folder").withType(String.class).create("lr"); Option rmlrfolder = OptionBuilder.withLongOpt("deletelocalrepo").hasArg(false) .withDescription("delete local repository after installation").create("dlr"); Option help = OptionBuilder.withLongOpt("help").withDescription("print this help").create("h"); options.addOption(destination); options.addOption(lrfolder); options.addOption(rmlrfolder); options.addOption(help); HelpFormatter helpFormatter = new HelpFormatter(); CommandLineParser commandLineParser = new PosixParser(); CommandLine commands; try { commands = commandLineParser.parse(options, args); } catch (ParseException ex) { System.out.println("Error at parsing arguments"); helpFormatter.printHelp("java -jar " + executableName, options); return; } if (commands.hasOption("h")) { helpFormatter.printHelp("java -jar " + executableName, options); return; } String sdest = commands.getOptionValue("d", "./nanosystem"); System.out.println("The nano system will be installed into " + sdest); File dest = new File(sdest); if (dest.exists()) { FileUtils.deleteDirectory(dest); } dest.mkdirs(); File bin = new File(dest, "bin"); bin.mkdir(); File bundle = new File(dest, "bundle"); bundle.mkdir(); File conf = new File(dest, "conf"); conf.mkdir(); File core = new File(dest, "core"); core.mkdir(); File logs = new File(dest, "logs"); logs.mkdir(); File nanohttpdcore = new File(dest, "nanohttpd-core"); nanohttpdcore.mkdir(); File nanohttpdservices = new File(dest, "nanohttpd-services"); nanohttpdservices.mkdir(); File temp = new File(dest, "temp"); temp.mkdir(); File apps = new File(dest, "apps"); apps.mkdir(); File local = new File(commands.getOptionValue("lr", "./local-repository")); Collection<RemoteRepository> repositories = Arrays.asList( new RemoteRepository("sanaldiyar-snap", "default", "http://maven2.sanaldiyar.com/snap-repo"), new RemoteRepository("central", "default", "http://repo1.maven.org/maven2/")); Aether aether = new Aether(repositories, local); //Copy core felix main System.out.println("Downloading Felix main executable"); List<Artifact> felixmain = aether.resolve( new DefaultArtifact("org.apache.felix", "org.apache.felix.main", "jar", "LATEST"), "runtime"); for (Artifact artifact : felixmain) { if (artifact.getArtifactId().equals("org.apache.felix.main")) { FileUtils.copyFile(artifact.getFile(), new File(bin, "felix-main.jar")); System.out.println(artifact.getArtifactId()); break; } } System.out.println("OK"); //Copy core felix bundles System.out.println("Downloading Felix core bundles"); Collection<String> felixcorebundles = Arrays.asList("fileinstall", "bundlerepository", "gogo.runtime", "gogo.shell", "gogo.command"); for (String felixcorebunlde : felixcorebundles) { List<Artifact> felixcore = aether.resolve(new DefaultArtifact("org.apache.felix", "org.apache.felix." + felixcorebunlde, "jar", "LATEST"), "runtime"); for (Artifact artifact : felixcore) { if (artifact.getArtifactId().equals("org.apache.felix." + felixcorebunlde)) { FileUtils.copyFileToDirectory(artifact.getFile(), core); System.out.println(artifact.getArtifactId()); } } } System.out.println("OK"); //Copy nanohttpd core bundles System.out.println("Downloading nanohttpd core bundles and configurations"); List<Artifact> nanohttpdcorebundle = aether.resolve( new DefaultArtifact("com.sanaldiyar.projects.nanohttpd", "nanohttpd", "jar", "LATEST"), "runtime"); for (Artifact artifact : nanohttpdcorebundle) { if (!artifact.getArtifactId().equals("org.osgi.core")) { FileUtils.copyFileToDirectory(artifact.getFile(), nanohttpdcore); System.out.println(artifact.getArtifactId()); } } nanohttpdcorebundle = aether.resolve( new DefaultArtifact("com.sanaldiyar.projects", "engender", "jar", "LATEST"), "runtime"); for (Artifact artifact : nanohttpdcorebundle) { FileUtils.copyFileToDirectory(artifact.getFile(), nanohttpdcore); System.out.println(artifact.getArtifactId()); } nanohttpdcorebundle = aether.resolve( new DefaultArtifact("org.codehaus.jackson", "jackson-mapper-asl", "jar", "1.9.5"), "runtime"); for (Artifact artifact : nanohttpdcorebundle) { FileUtils.copyFileToDirectory(artifact.getFile(), nanohttpdcore); System.out.println(artifact.getArtifactId()); } nanohttpdcorebundle = aether .resolve(new DefaultArtifact("org.mongodb", "mongo-java-driver", "jar", "LATEST"), "runtime"); for (Artifact artifact : nanohttpdcorebundle) { FileUtils.copyFileToDirectory(artifact.getFile(), nanohttpdcore); System.out.println(artifact.getArtifactId()); } //Copy nanohttpd conf FileUtils.copyInputStreamToFile(App.class.getResourceAsStream("/nanohttpd.conf"), new File(dest, "nanohttpd.conf")); System.out.println("Configuration: nanohttpd.conf"); //Copy nanohttpd start script File startsh = new File(dest, "start.sh"); FileUtils.copyInputStreamToFile(App.class.getResourceAsStream("/start.sh"), startsh); startsh.setExecutable(true); System.out.println("Script: start.sh"); System.out.println("OK"); //Copy nanohttpd service bundles System.out.println("Downloading nanohttpd service bundles"); List<Artifact> nanohttpdservicebundle = aether .resolve(new DefaultArtifact("com.sanaldiyar.projects.nanohttpd", "mongodbbasedsessionhandler", "jar", "1.0-SNAPSHOT"), "runtime"); for (Artifact artifact : nanohttpdservicebundle) { if (artifact.getArtifactId().equals("mongodbbasedsessionhandler")) { FileUtils.copyFileToDirectory(artifact.getFile(), nanohttpdservices); System.out.println(artifact.getArtifactId()); break; } } //Copy nanohttpd mongodbbasedsessionhandler conf FileUtils.copyInputStreamToFile(App.class.getResourceAsStream("/mdbbasedsh.conf"), new File(dest, "mdbbasedsh.conf")); System.out.println("Configuration: mdbbasedsh.conf"); System.out.println("OK"); if (commands.hasOption("dlr")) { System.out.println("Local repository is deleting"); FileUtils.deleteDirectory(local); System.out.println("OK"); } System.out.println("You can reconfigure nanohttpd and services. To start system run start.sh script"); } catch (Exception ex) { System.out.println("Error at installing."); } }
From source file:com.sangupta.keepwalking.MergeRepo.java
/** * @param args/*from w w w . j a va 2s . c om*/ * @throws IOException */ public static void main(String[] args) throws IOException { if (args.length != 3) { usage(); return; } final String previousRepo = args[0]; final String newerRepo = args[1]; final String mergedRepo = args[2]; final File previous = new File(previousRepo); final File newer = new File(newerRepo); final File merged = new File(mergedRepo); if (!(previous.exists() && previous.isDirectory())) { System.out.println("The previous version does not exists or is not a directory."); return; } if (!(newer.exists() && newer.isDirectory())) { System.out.println("The newer version does not exists or is not a directory."); return; } final IOFileFilter directoryFilter = FileFilterUtils.makeCVSAware(FileFilterUtils.makeSVNAware(null)); final Collection<File> olderFiles = FileUtils.listFiles(previous, TrueFileFilter.TRUE, directoryFilter); final Collection<File> newerFiles = FileUtils.listFiles(newer, TrueFileFilter.TRUE, directoryFilter); // build a list of unique paths System.out.println("Reading files from older version..."); List<String> olderPaths = new ArrayList<String>(); for (File oldFile : olderFiles) { olderPaths.add(getRelativePath(oldFile, previous)); } System.out.println("Reading files from newer version..."); List<String> newerPaths = new ArrayList<String>(); for (File newerFile : newerFiles) { newerPaths.add(getRelativePath(newerFile, newer)); } // find which files have been removed from Perforce depot List<String> filesRemoved = new ArrayList<String>(olderPaths); filesRemoved.removeAll(newerPaths); System.out.println("Files removed in newer version: " + filesRemoved.size()); for (String removed : filesRemoved) { System.out.print(" "); System.out.println(removed); } // find which files have been added in Perforce depot List<String> filesAdded = new ArrayList<String>(newerPaths); filesAdded.removeAll(olderPaths); System.out.println("Files added in newer version: " + filesAdded.size()); for (String added : filesAdded) { System.out.print(" "); System.out.println(added); } // find which files are common // now check if they have modified or not newerPaths.retainAll(olderPaths); List<String> modified = checkModifiedFiles(newerPaths, previous, newer); System.out.println("Files modified in newer version: " + modified.size()); for (String modify : modified) { System.out.print(" "); System.out.println(modify); } // clean any previous existence of merged repo System.out.println("Cleaning any previous merged repositories..."); if (merged.exists() && merged.isDirectory()) { FileUtils.deleteDirectory(merged); } System.out.println("Merging from newer to older repository..."); // copy the original SVN repo to merged FileUtils.copyDirectory(previous, merged); // now remove all files that need to be for (String removed : filesRemoved) { File toRemove = new File(merged, removed); toRemove.delete(); } // now add all files that are new in perforce for (String added : filesAdded) { File toAdd = new File(newer, added); File destination = new File(merged, added); FileUtils.copyFile(toAdd, destination); } // now over-write modified files for (String changed : modified) { File change = new File(newer, changed); File destination = new File(merged, changed); destination.delete(); FileUtils.copyFile(change, destination); } System.out.println("Done merging."); }
From source file:edu.indiana.d2i.sloan.internal.CreateVMSimulator.java
public static void main(String[] args) { CreateVMSimulator simulator = new CreateVMSimulator(); CommandLineParser parser = new PosixParser(); try {/* w w w .j a v a 2 s . c o m*/ CommandLine line = simulator.parseCommandLine(parser, args); String imagePath = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.IMAGE_PATH)); int vcpu = Integer.parseInt(line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VCPU))); int mem = Integer.parseInt(line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.MEM))); if (!HypervisorCmdSimulator.resourceExist(imagePath)) { logger.error(String.format("Cannot find requested image: %s", imagePath)); System.exit(ERROR_CODE.get(ERROR_STATE.IMAGE_NOT_EXIST)); } if (!hasEnoughCPUs(vcpu)) { logger.error(String.format("Don't have enough cpus, requested %d", vcpu)); System.exit(ERROR_CODE.get(ERROR_STATE.NOT_ENOUGH_CPU)); } if (!hasEnoughMem(mem)) { logger.error(String.format("Don't have enough memory, requested %d", mem)); System.exit(ERROR_CODE.get(ERROR_STATE.NOT_ENOUGH_MEM)); } String wdir = line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.WORKING_DIR)); if (HypervisorCmdSimulator.resourceExist(wdir)) { logger.error(String.format("Working directory %s already exists ", wdir)); System.exit(ERROR_CODE.get(ERROR_STATE.VM_ALREADY_EXIST)); } // copy VM image to working directory File imageFile = new File(imagePath); FileUtils.copyFile(imageFile, new File(HypervisorCmdSimulator.cleanPath(wdir) + imageFile.getName())); // write state as property file so that we can query later Properties prop = new Properties(); prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.IMAGE_PATH), imagePath); prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VCPU), String.valueOf(vcpu)); prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.MEM), String.valueOf(mem)); prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.WORKING_DIR), wdir); prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VNC_PORT), line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VNC_PORT))); prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.SSH_PORT), line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.SSH_PORT))); prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.LOGIN_USERNAME), line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.LOGIN_USERNAME))); prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.LOGIN_PASSWD), line.getOptionValue(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.LOGIN_PASSWD))); // write VM state as shutdown prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_STATE), VMState.SHUTDOWN.toString()); // write VM mode as undefined prop.put(CMD_FLAG_VALUE.get(CMD_FLAG_KEY.VM_MODE), VMMode.NOT_DEFINED.toString()); prop.store( new FileOutputStream(new File( HypervisorCmdSimulator.cleanPath(wdir) + HypervisorCmdSimulator.VM_INFO_FILE_NAME)), ""); // do other related settings try { Thread.sleep(1000); } catch (InterruptedException e) { logger.error(e.getMessage()); } // success System.exit(0); } catch (ParseException e) { logger.error(String.format("Cannot parse input arguments: %s%n, expected:%n%s", StringUtils.join(args, " "), simulator.getUsage(100, "", 5, 5, ""))); System.exit(ERROR_CODE.get(ERROR_STATE.INVALID_INPUT_ARGS)); } catch (IOException e) { logger.error(e.getMessage(), e); System.exit(ERROR_CODE.get(ERROR_STATE.IO_ERR)); } }
From source file:com.hp.test.framework.Reporting.Utlis.java
public static void main(String ar[]) throws IOException { ArrayList<String> runs_list = new ArrayList<String>(); String basepath = replacelogs(); String path = basepath + "ATU Reports\\Results"; File directory = new File(path); File[] subdirs = directory.listFiles((FileFilter) DirectoryFileFilter.DIRECTORY); String htmlReport = basepath + "HTML_Design_Files\\CSS\\HtmlReport.html"; for (File dir : subdirs) { runs_list.add(dir.getName());/*from www . j av a 2 s .co m*/ } String Reports_path = basepath + "ATU Reports\\"; int LatestRun = Utlis.getLastRun(Reports_path); String Last_run_path = Reports_path + "Results\\Run_" + String.valueOf(LatestRun) + "\\"; HtmlParse.replaceMainTable(false, new File(Last_run_path + "/CurrentRun.html")); HtmlParse.replaceCountsinJSFile(new File("HTML_Design_Files/JS/3dChart.js"), Last_run_path); UpdateTestCaseDesciption.basepath = Last_run_path; UpdateTestCaseDesciption.getTestCaseHtmlPath(Last_run_path + "/CurrentRun.html"); UpdateTestCaseDesciption.replaceDetailsTable(Last_run_path + "/CurrentRun.html"); // GenerateFailReport.genarateFailureReport(new File(htmlReport), Reports_path + "Results\\Run_" + String.valueOf(LatestRun)); genarateFailureReport(new File(htmlReport), Reports_path + "Results\\"); Map<String, List<String>> runCounts = GetCountsrunsWise(runs_list, path); int success = replaceCounts(runCounts, path); if (success == 0) { File SourceFile = new File(path + "\\lineChart_temp.js"); File RenameFile = new File(path + "\\lineChart.js"); renameOriginalFile(SourceFile, RenameFile); File SourceFile1 = new File(path + "\\barChart_temp.js"); File RenameFile1 = new File(path + "\\barChart.js"); renameOriginalFile(SourceFile1, RenameFile1); Utlis.getpaths(Reports_path + "\\Results\\Run_" + String.valueOf(LatestRun)); try { Utlis.replaceMainTable(false, new File(Reports_path + "index.html")); Utlis.replaceMainTable(true, new File(Reports_path + "results\\" + "ConsolidatedPage.html")); Utlis.replaceMainTable(true, new File(Reports_path + "Results\\Run_" + String.valueOf(LatestRun) + "CurrentRun.html")); fileList.add( new File(Reports_path + "\\Results\\Run_" + String.valueOf(LatestRun) + "CurrentRun.html")); for (File f : fileList) { Utlis.replaceMainTable(true, f); } } catch (Exception ex) { log.info("Error in updating Report format" + ex.getMessage()); } Last_run_path = Reports_path + "Results\\Run_" + String.valueOf(LatestRun) + "\\"; // HtmlParse.replaceMainTable(false, new File(Last_run_path + "/CurrentRun.html")); // HtmlParse.replaceCountsinJSFile(new File("../HTML_Design_Files/JS/3dChart.js"), Last_run_path); ArrayList<String> to_list = new ArrayList<String>(); ReportingProperties reportingproperties = new ReportingProperties(); String temp_eml = reportingproperties.getProperty("TOLIST"); String JenkinsURL = reportingproperties.getProperty("JENKINSURL"); String ScreenShotsDir = reportingproperties.getProperty("ScreenShotsDirectory"); Boolean cleanScreenshotsDir = Boolean.valueOf(reportingproperties.getProperty("CleanPreScreenShots")); Boolean generatescreenshots = Boolean.valueOf(reportingproperties.getProperty("GenerateScreenShots")); String HtmlreportFilePrefix = reportingproperties.getProperty("HtmlreportFilePrefix"); if (cleanScreenshotsDir) { if (!CleanFilesinDir(ScreenShotsDir)) { log.error("Not able to Clean the Previous Run Details in the paht" + ScreenShotsDir); } else { log.info("Cleaning Previous Run Details in the paht" + ScreenShotsDir + "Sucess"); } } List<String> scr_fileList; List<String> html_fileList; if (generatescreenshots) { scr_fileList = GetFileListinDir(ScreenShotsDir, "png"); int len = scr_fileList.size(); len = len + 1; screenshot.generatescreenshot(Last_run_path + "CurrentRun.html", ScreenShotsDir + "screenshot_" + len + ".png"); File source = new File(Reports_path + "Results\\HtmlReport.html"); File dest = new File(ScreenShotsDir + HtmlreportFilePrefix + "_HtmlReport.html"); // Files.copy(f.toPath(), (new File((ScreenShotsDir+HtmlreportFilePrefix+"_HtmlReport.html").toPath(),StandardCopyOption.REPLACE_EXISTING); FileUtils.copyFile(source, dest); scr_fileList.clear(); } scr_fileList = GetFileListinDir(ScreenShotsDir, "png"); html_fileList = GetFileListinDir(ScreenShotsDir, "html"); if (temp_eml.length() > 1) { String[] to_list_temp = temp_eml.split(","); if (to_list_temp.length > 0) { for (String to_list_temp1 : to_list_temp) { to_list.add(to_list_temp1); } } if (to_list.size() > 0) { screenshot.generatescreenshot(Last_run_path + "CurrentRun.html", Last_run_path + "screenshot.png"); // cleanTempDir.cleanandCreate(Reports_path, LatestRun); // ZipUtils.ZipFolder(Reports_path + "temp", Reports_path + "ISTF_Reports.zip"); if (generatescreenshots) { SendingEmail.sendmail(to_list, JenkinsURL, scr_fileList, html_fileList); } else { SendingEmail.sendmail(to_list, JenkinsURL, Reports_path + "/Results/HtmlReport.html", Last_run_path + "screenshot.png"); } // FileUtils.deleteQuietly(new File(Reports_path + "ISTF_Reports.zip")); // FileUtils.deleteDirectory(new File(Reports_path + "temp")); } } } }
From source file:au.com.jwatmuff.eventmanager.Main.java
/** * Main method.//from w w w .j a v a 2s.c o m */ public static void main(String args[]) { LogUtils.setupUncaughtExceptionHandler(); /* Set timeout for RMI connections - TODO: move to external file */ System.setProperty("sun.rmi.transport.tcp.handshakeTimeout", "2000"); updateRmiHostName(); /* * Set up menu bar for Mac */ System.setProperty("apple.laf.useScreenMenuBar", "true"); System.setProperty("com.apple.mrj.application.apple.menu.about.name", "Event Manager"); /* * Set look and feel to 'system' style */ try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { log.info("Failed to set system look and feel"); } /* * Set workingDir to a writable folder for storing competitions, settings etc. */ String applicationData = System.getenv("APPDATA"); if (applicationData != null) { workingDir = new File(applicationData, "EventManager"); if (workingDir.exists() || workingDir.mkdirs()) { // redirect logging to writable folder LogUtils.reconfigureFileAppenders("log4j.properties", workingDir); } else { workingDir = new File("."); } } // log version for debugging log.info("Running version: " + VISIBLE_VERSION + " (Internal: " + VERSION + ")"); /* * Copy license if necessary */ File license1 = new File("license.lic"); File license2 = new File(workingDir, "license.lic"); if (license1.exists() && !license2.exists()) { try { FileUtils.copyFile(license1, license2); } catch (IOException e) { log.warn("Failed to copy license from " + license1 + " to " + license2, e); } } if (license1.exists() && license2.exists()) { if (license1.lastModified() > license2.lastModified()) { try { FileUtils.copyFile(license1, license2); } catch (IOException e) { log.warn("Failed to copy license from " + license1 + " to " + license2, e); } } } /* * Check if run lock exists, if so ask user if it is ok to continue */ if (!obtainRunLock(false)) { int response = JOptionPane.showConfirmDialog(null, "Unable to obtain run-lock.\nPlease ensure that no other instances of EventManager are running before continuing.\nDo you wish to continue?", "Run-lock detected", JOptionPane.YES_NO_OPTION); if (response == JOptionPane.YES_OPTION) obtainRunLock(true); else System.exit(0); } try { LoadWindow loadWindow = new LoadWindow(); loadWindow.setVisible(true); loadWindow.addMessage("Reading settings.."); /* * Read properties from file */ final Properties props = new Properties(); try { Properties defaultProps = PropertiesLoaderUtils .loadProperties(new ClassPathResource("eventmanager.properties")); props.putAll(defaultProps); } catch (IOException ex) { log.error(ex); } props.putAll(System.getProperties()); File databaseStore = new File(workingDir, "comps"); int rmiPort = Integer.parseInt(props.getProperty("eventmanager.rmi.port")); loadWindow.addMessage("Loading Peer Manager.."); log.info("Loading Peer Manager"); ManualDiscoveryService manualDiscoveryService = new ManualDiscoveryService(); JmDNSRMIPeerManager peerManager = new JmDNSRMIPeerManager(rmiPort, new File(workingDir, "peerid.dat")); peerManager.addDiscoveryService(manualDiscoveryService); monitorNetworkInterfaceChanges(peerManager); loadWindow.addMessage("Loading Database Manager.."); log.info("Loading Database Manager"); DatabaseManager databaseManager = new SQLiteDatabaseManager(databaseStore, peerManager); LicenseManager licenseManager = new LicenseManager(workingDir); loadWindow.addMessage("Loading Load Competition Dialog.."); log.info("Loading Load Competition Dialog"); LoadCompetitionWindow loadCompetitionWindow = new LoadCompetitionWindow(databaseManager, licenseManager, peerManager); loadCompetitionWindow.setTitle(WINDOW_TITLE); loadWindow.dispose(); log.info("Starting Load Competition Dialog"); while (true) { // reset permission checker to use our license licenseManager.updatePermissionChecker(); GUIUtils.runModalJFrame(loadCompetitionWindow); if (loadCompetitionWindow.getSuccess()) { DatabaseInfo info = loadCompetitionWindow.getSelectedDatabaseInfo(); if (!databaseManager.checkLock(info.id)) { String message = "EventManager did not shut down correctly the last time this competition was open. To avoid potential data corruption, you are advised to take the following steps:\n" + "1) Do NOT open this competition\n" + "2) Create a backup of this competition\n" + "3) Delete the competition from this computer\n" + "4) If possible, reload this competition from another computer on the network\n" + "5) Alternatively, you may manually load the backup onto all computers on the network, ensuring the 'Preserve competition ID' option is checked."; String title = "WARNING: Potential Data Corruption Detected"; int status = JOptionPane.showOptionDialog(null, message, title, JOptionPane.YES_NO_OPTION, JOptionPane.ERROR_MESSAGE, null, new Object[] { "Cancel (recommended)", "Open anyway" }, "Cancel (recommended)"); if (status == 0) continue; // return to load competition window } SynchronizingWindow syncWindow = new SynchronizingWindow(); syncWindow.setVisible(true); long t = System.nanoTime(); DistributedDatabase database = databaseManager.activateDatabase(info.id, info.passwordHash); long dt = System.nanoTime() - t; log.debug(String.format("Initial sync in %dms", TimeUnit.MILLISECONDS.convert(dt, TimeUnit.NANOSECONDS))); syncWindow.dispose(); if (loadCompetitionWindow.isNewDatabase()) { GregorianCalendar calendar = new GregorianCalendar(); Date today = calendar.getTime(); calendar.set(Calendar.MONTH, Calendar.DECEMBER); calendar.set(Calendar.DAY_OF_MONTH, 31); Date endOfYear = new java.sql.Date(calendar.getTimeInMillis()); CompetitionInfo ci = new CompetitionInfo(); ci.setName(info.name); ci.setStartDate(today); ci.setEndDate(today); ci.setAgeThresholdDate(endOfYear); //ci.setPasswordHash(info.passwordHash); License license = licenseManager.getLicense(); if (license != null) { ci.setLicenseName(license.getName()); ci.setLicenseType(license.getType().toString()); ci.setLicenseContact(license.getContactPhoneNumber()); } database.add(ci); } // Set PermissionChecker to use database's license type String competitionLicenseType = database.get(CompetitionInfo.class, null).getLicenseType(); PermissionChecker.setLicenseType(LicenseType.valueOf(competitionLicenseType)); TransactionNotifier notifier = new TransactionNotifier(); database.setListener(notifier); MainWindow mainWindow = new MainWindow(); mainWindow.setDatabase(database); mainWindow.setNotifier(notifier); mainWindow.setPeerManager(peerManager); mainWindow.setLicenseManager(licenseManager); mainWindow.setManualDiscoveryService(manualDiscoveryService); mainWindow.setTitle(WINDOW_TITLE); mainWindow.afterPropertiesSet(); TestUtil.setActivatedDatabase(database); // show main window (modally) GUIUtils.runModalJFrame(mainWindow); // shutdown procedures // System.exit(); database.shutdown(); databaseManager.deactivateDatabase(1500); if (mainWindow.getDeleteOnExit()) { for (File file : info.localDirectory.listFiles()) if (!file.isDirectory()) file.delete(); info.localDirectory.deleteOnExit(); } } else { // This can cause an RuntimeException - Peer is disconnected peerManager.stop(); System.exit(0); } } } catch (Throwable e) { log.error("Error in main function", e); String message = e.getMessage(); if (message == null) message = ""; if (message.length() > 100) message = message.substring(0, 97) + "..."; GUIUtils.displayError(null, "An unexpected error has occured.\n\n" + e.getClass().getSimpleName() + "\n" + message); System.exit(0); } }
From source file:edu.uthscsa.ric.papaya.builder.Builder.java
public static void main(final String[] args) { final Builder builder = new Builder(); // process command line final CommandLine cli = builder.createCLI(args); builder.setUseSample(cli.hasOption(ARG_SAMPLE)); builder.setUseAtlas(cli.hasOption(ARG_ATLAS)); builder.setLocal(cli.hasOption(ARG_LOCAL)); builder.setPrintHelp(cli.hasOption(ARG_HELP)); builder.setUseImages(cli.hasOption(ARG_IMAGE)); builder.setSingleFile(cli.hasOption(ARG_SINGLE)); builder.setUseParamFile(cli.hasOption(ARG_PARAM_FILE)); builder.setUseTitle(cli.hasOption(ARG_TITLE)); // print help, if necessary if (builder.isPrintHelp()) { builder.printHelp();/*from w w w .j a v a 2s . com*/ return; } // find project root directory if (cli.hasOption(ARG_ROOT)) { try { builder.projectDir = (new File(cli.getOptionValue(ARG_ROOT))).getCanonicalFile(); } catch (final IOException ex) { System.err.println("Problem finding root directory. Reason: " + ex.getMessage()); } } if (builder.projectDir == null) { builder.projectDir = new File(System.getProperty("user.dir")); } // clean output dir final File outputDir = new File(builder.projectDir + "/" + OUTPUT_DIR); System.out.println("Cleaning output directory..."); try { builder.cleanOutputDir(outputDir); } catch (final IOException ex) { System.err.println("Problem cleaning build directory. Reason: " + ex.getMessage()); } if (builder.isLocal()) { System.out.println("Building for local usage..."); } // write JS final File compressedFileJs = new File(outputDir, OUTPUT_JS_FILENAME); // build properties try { final File buildFile = new File(builder.projectDir + "/" + BUILD_PROP_FILE); builder.readBuildProperties(buildFile); builder.buildNumber++; // increment build number builder.writeBuildProperties(compressedFileJs, true); builder.writeBuildProperties(buildFile, false); } catch (final IOException ex) { System.err.println("Problem handling build properties. Reason: " + ex.getMessage()); } String htmlParameters = null; if (builder.isUseParamFile()) { final String paramFileArg = cli.getOptionValue(ARG_PARAM_FILE); if (paramFileArg != null) { try { System.out.println("Including parameters..."); final String parameters = FileUtils.readFileToString(new File(paramFileArg), "UTF-8"); htmlParameters = "var params = " + parameters + ";"; } catch (final IOException ex) { System.err.println("Problem reading parameters file! " + ex.getMessage()); } } } String title = null; if (builder.isUseTitle()) { String str = cli.getOptionValue(ARG_TITLE); if (str != null) { str = str.trim(); str = str.replace("\"", ""); str = str.replace("'", ""); if (str.length() > 0) { title = str; System.out.println("Using title: " + title); } } } try { final JSONArray loadableImages = new JSONArray(); // sample image if (builder.isUseSample()) { System.out.println("Including sample image..."); final File sampleFile = new File(builder.projectDir + "/" + SAMPLE_IMAGE_NII_FILE); final String filename = Utilities .replaceNonAlphanumericCharacters(Utilities.removeNiftiExtensions(sampleFile.getName())); if (builder.isLocal()) { loadableImages.put(new JSONObject("{\"nicename\":\"Sample Image\",\"name\":\"" + filename + "\",\"encode\":\"" + filename + "\"}")); final String sampleEncoded = Utilities.encodeImageFile(sampleFile); FileUtils.writeStringToFile(compressedFileJs, "var " + filename + "= \"" + sampleEncoded + "\";\n", "UTF-8", true); } else { loadableImages.put(new JSONObject("{\"nicename\":\"Sample Image\",\"name\":\"" + filename + "\",\"url\":\"" + SAMPLE_IMAGE_NII_FILE + "\"}")); FileUtils.copyFile(sampleFile, new File(outputDir + "/" + SAMPLE_IMAGE_NII_FILE)); } } // atlas if (builder.isUseAtlas()) { Atlas atlas = null; try { String atlasArg = cli.getOptionValue(ARG_ATLAS); if (atlasArg == null) { atlasArg = (builder.projectDir + "/" + SAMPLE_DEFAULT_ATLAS_FILE); } final File atlasXmlFile = new File(atlasArg); System.out.println("Including atlas " + atlasXmlFile); atlas = new Atlas(atlasXmlFile); final File atlasJavaScriptFile = atlas.createAtlas(builder.isLocal()); System.out.println("Using atlas image file " + atlas.getImageFile()); if (builder.isLocal()) { loadableImages.put( new JSONObject("{\"nicename\":\"Atlas\",\"name\":\"" + atlas.getImageFileNewName() + "\",\"encode\":\"" + atlas.getImageFileNewName() + "\",\"hide\":true}")); } else { final File atlasImageFile = atlas.getImageFile(); final String atlasPath = "data/" + atlasImageFile.getName(); loadableImages.put(new JSONObject("{\"nicename\":\"Atlas\",\"name\":\"" + atlas.getImageFileNewName() + "\",\"url\":\"" + atlasPath + "\",\"hide\":true}")); FileUtils.copyFile(atlasImageFile, new File(outputDir + "/" + atlasPath)); } builder.writeFile(atlasJavaScriptFile, compressedFileJs); } catch (final IOException ex) { System.err.println("Problem finding atlas file. Reason: " + ex.getMessage()); } } // additional images if (builder.isUseImages()) { final String[] imageArgs = cli.getOptionValues(ARG_IMAGE); if (imageArgs != null) { for (final String imageArg : imageArgs) { final File file = new File(imageArg); System.out.println("Including image " + file); final String filename = Utilities .replaceNonAlphanumericCharacters(Utilities.removeNiftiExtensions(file.getName())); if (builder.isLocal()) { loadableImages.put(new JSONObject( "{\"nicename\":\"" + Utilities.removeNiftiExtensions(file.getName()) + "\",\"name\":\"" + filename + "\",\"encode\":\"" + filename + "\"}")); final String sampleEncoded = Utilities.encodeImageFile(file); FileUtils.writeStringToFile(compressedFileJs, "var " + filename + "= \"" + sampleEncoded + "\";\n", "UTF-8", true); } else { final String filePath = "data/" + file.getName(); loadableImages.put(new JSONObject( "{\"nicename\":\"" + Utilities.removeNiftiExtensions(file.getName()) + "\",\"name\":\"" + filename + "\",\"url\":\"" + filePath + "\"}")); FileUtils.copyFile(file, new File(outputDir + "/" + filePath)); } } } } File tempFileJs = null; try { tempFileJs = builder.createTempFile(); } catch (final IOException ex) { System.err.println("Problem creating temp write file. Reason: " + ex.getMessage()); } // write image refs FileUtils.writeStringToFile(tempFileJs, "var " + PAPAYA_LOADABLE_IMAGES + " = " + loadableImages.toString() + ";\n", "UTF-8", true); // compress JS tempFileJs = builder.concatenateFiles(JS_FILES, "js", tempFileJs); System.out.println("Compressing JavaScript... "); FileUtils.writeStringToFile(compressedFileJs, "\n", "UTF-8", true); builder.compressJavaScript(tempFileJs, compressedFileJs, new YuiCompressorOptions()); //tempFileJs.deleteOnExit(); } catch (final IOException ex) { System.err.println("Problem concatenating JavaScript. Reason: " + ex.getMessage()); } // compress CSS final File compressedFileCss = new File(outputDir, OUTPUT_CSS_FILENAME); try { final File concatFile = builder.concatenateFiles(CSS_FILES, "css", null); System.out.println("Compressing CSS... "); builder.compressCSS(concatFile, compressedFileCss, new YuiCompressorOptions()); concatFile.deleteOnExit(); } catch (final IOException ex) { System.err.println("Problem concatenating CSS. Reason: " + ex.getMessage()); } // write HTML try { System.out.println("Writing HTML... "); if (builder.singleFile) { builder.writeHtml(outputDir, compressedFileJs, compressedFileCss, htmlParameters, title); } else { builder.writeHtml(outputDir, htmlParameters, title); } } catch (final IOException ex) { System.err.println("Problem writing HTML. Reason: " + ex.getMessage()); } System.out.println("Done! Output files located at " + outputDir); }
From source file:com.cloud.utils.FileUtil.java
public static void copyfile(File source, File destination) throws IOException { FileUtils.copyFile(source, destination); }