List of usage examples for java.io File getParent
public String getParent()
null
if this pathname does not name a parent directory. From source file:apps.quantification.LearnQuantificationSVMPerf.java
public static void main(String[] args) throws IOException { String cmdLineSyntax = LearnQuantificationSVMPerf.class.getName() + " [OPTIONS] <path to svm_perf_learn> <path to svm_perf_classify> <trainingIndexDirectory> <outputDirectory>"; Options options = new Options(); OptionBuilder.withArgName("f"); OptionBuilder.withDescription("Number of folds"); OptionBuilder.withLongOpt("f"); OptionBuilder.isRequired(true);/*from w w w .j av a 2s. com*/ OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("c"); OptionBuilder.withDescription("The c value for svm_perf (default 0.01)"); OptionBuilder.withLongOpt("c"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("t"); OptionBuilder.withDescription("Path for temporary files"); OptionBuilder.withLongOpt("t"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("l"); OptionBuilder.withDescription("The loss function to optimize (default 2):\n" + " 0 Zero/one loss: 1 if vector of predictions contains error, 0 otherwise.\n" + " 1 F1: 100 minus the F1-score in percent.\n" + " 2 Errorrate: Percentage of errors in prediction vector.\n" + " 3 Prec/Rec Breakeven: 100 minus PRBEP in percent.\n" + " 4 Prec@p: 100 minus precision at p in percent.\n" + " 5 Rec@p: 100 minus recall at p in percent.\n" + " 10 ROCArea: Percentage of swapped pos/neg pairs (i.e. 100 - ROCArea)."); OptionBuilder.withLongOpt("l"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("w"); OptionBuilder.withDescription("Choice of structural learning algorithm (default 9):\n" + " 0: n-slack algorithm described in [2]\n" + " 1: n-slack algorithm with shrinking heuristic\n" + " 2: 1-slack algorithm (primal) described in [5]\n" + " 3: 1-slack algorithm (dual) described in [5]\n" + " 4: 1-slack algorithm (dual) with constraint cache [5]\n" + " 9: custom algorithm in svm_struct_learn_custom.c"); OptionBuilder.withLongOpt("w"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("p"); OptionBuilder.withDescription("The value of p used by the prec@p and rec@p loss functions (default 0)"); OptionBuilder.withLongOpt("p"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("v"); OptionBuilder.withDescription("Verbose output"); OptionBuilder.withLongOpt("v"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); OptionBuilder.withArgName("s"); OptionBuilder.withDescription("Don't delete temporary training file in svm_perf format (default: delete)"); OptionBuilder.withLongOpt("s"); OptionBuilder.isRequired(false); OptionBuilder.hasArg(false); options.addOption(OptionBuilder.create()); SvmPerfLearnerCustomizer classificationLearnerCustomizer = null; SvmPerfClassifierCustomizer classificationCustomizer = null; int folds = -1; GnuParser parser = new GnuParser(); String[] remainingArgs = null; try { CommandLine line = parser.parse(options, args); remainingArgs = line.getArgs(); classificationLearnerCustomizer = new SvmPerfLearnerCustomizer(remainingArgs[0]); classificationCustomizer = new SvmPerfClassifierCustomizer(remainingArgs[1]); folds = Integer.parseInt(line.getOptionValue("f")); if (line.hasOption("c")) classificationLearnerCustomizer.setC(Float.parseFloat(line.getOptionValue("c"))); if (line.hasOption("w")) classificationLearnerCustomizer.setW(Integer.parseInt(line.getOptionValue("w"))); if (line.hasOption("p")) classificationLearnerCustomizer.setP(Integer.parseInt(line.getOptionValue("p"))); if (line.hasOption("l")) classificationLearnerCustomizer.setL(Integer.parseInt(line.getOptionValue("l"))); if (line.hasOption("v")) classificationLearnerCustomizer.printSvmPerfOutput(true); if (line.hasOption("s")) classificationLearnerCustomizer.setDeleteTrainingFiles(false); if (line.hasOption("t")) { classificationLearnerCustomizer.setTempPath(line.getOptionValue("t")); classificationCustomizer.setTempPath(line.getOptionValue("t")); } } catch (Exception exp) { System.err.println("Parsing failed. Reason: " + exp.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(cmdLineSyntax, options); System.exit(-1); } assert (classificationLearnerCustomizer != null); if (remainingArgs.length != 4) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(cmdLineSyntax, options); System.exit(-1); } String indexFile = remainingArgs[2]; File file = new File(indexFile); String indexName = file.getName(); String indexPath = file.getParent(); String outputPath = remainingArgs[3]; SvmPerfLearner classificationLearner = new SvmPerfLearner(); classificationLearner.setRuntimeCustomizer(classificationLearnerCustomizer); FileSystemStorageManager fssm = new FileSystemStorageManager(indexPath, false); fssm.open(); IIndex training = TroveReadWriteHelper.readIndex(fssm, indexName, TroveContentDBType.Full, TroveClassificationDBType.Full); final TextualProgressBar progressBar = new TextualProgressBar("Learning the quantifiers"); IOperationStatusListener status = new IOperationStatusListener() { @Override public void operationStatus(double percentage) { progressBar.signal((int) percentage); } }; QuantificationLearner quantificationLearner = new QuantificationLearner(folds, classificationLearner, classificationLearnerCustomizer, classificationCustomizer, ClassificationMode.PER_CATEGORY, new LogisticFunction(), status); IQuantifier[] quantifiers = quantificationLearner.learn(training); File executableFile = new File(classificationLearnerCustomizer.getSvmPerfLearnPath()); IDataManager classifierDataManager = new SvmPerfDataManager(new SvmPerfClassifierCustomizer( executableFile.getParentFile().getAbsolutePath() + Os.pathSeparator() + "svm_perf_classify")); String description = "_SVMPerf_C-" + classificationLearnerCustomizer.getC() + "_W-" + classificationLearnerCustomizer.getW() + "_L-" + classificationLearnerCustomizer.getL(); if (classificationLearnerCustomizer.getL() == 4 || classificationLearnerCustomizer.getL() == 5) description += "_P-" + classificationLearnerCustomizer.getP(); if (classificationLearnerCustomizer.getAdditionalParameters().length() > 0) description += "_" + classificationLearnerCustomizer.getAdditionalParameters(); String quantifierPrefix = indexName + "_Quantifier-" + folds + description; FileSystemStorageManager fssmo = new FileSystemStorageManager( outputPath + File.separatorChar + quantifierPrefix, true); fssmo.open(); QuantificationLearner.write(quantifiers, fssmo, classifierDataManager); fssmo.close(); BufferedWriter bfs = new BufferedWriter( new FileWriter(outputPath + File.separatorChar + quantifierPrefix + "_rates.txt")); TShortDoubleHashMap simpleTPRs = quantificationLearner.getSimpleTPRs(); TShortDoubleHashMap simpleFPRs = quantificationLearner.getSimpleFPRs(); TShortDoubleHashMap scaledTPRs = quantificationLearner.getScaledTPRs(); TShortDoubleHashMap scaledFPRs = quantificationLearner.getScaledFPRs(); ContingencyTableSet contingencyTableSet = quantificationLearner.getContingencyTableSet(); short[] cats = simpleTPRs.keys(); for (int i = 0; i < cats.length; ++i) { short cat = cats[i]; String catName = training.getCategoryDB().getCategoryName(cat); ContingencyTable contingencyTable = contingencyTableSet.getCategoryContingencyTable(cat); double simpleTPR = simpleTPRs.get(cat); double simpleFPR = simpleFPRs.get(cat); double scaledTPR = scaledTPRs.get(cat); double scaledFPR = scaledFPRs.get(cat); String line = quantifierPrefix + "\ttrain\tsimple\t" + catName + "\t" + cat + "\t" + contingencyTable.tp() + "\t" + contingencyTable.fp() + "\t" + contingencyTable.fn() + "\t" + contingencyTable.tn() + "\t" + simpleTPR + "\t" + simpleFPR + "\n"; bfs.write(line); line = quantifierPrefix + "\ttrain\tscaled\t" + catName + "\t" + cat + "\t" + contingencyTable.tp() + "\t" + contingencyTable.fp() + "\t" + contingencyTable.fn() + "\t" + contingencyTable.tn() + "\t" + scaledTPR + "\t" + scaledFPR + "\n"; bfs.write(line); } bfs.close(); }
From source file:org.ala.spatial.web.services.DownloadController.java
public static void main(String[] args) { // maxent - 1323641423144 // aloc - 1323844048457 String pid = "1323844048457"; try {//w w w.ja v a 2 s . c o m File dir = sfindFile(pid); if (dir != null) { //System.out.println("Found session data: " + dir.getAbsolutePath()); //return "Found session data: " + dir.getAbsolutePath(); String parentName = "ALA_"; String parentPath = dir.getParent().substring(dir.getParent().lastIndexOf("/") + 1); String zipfile = dir.getParent() + "/" + pid + ".zip"; if ("maxent".equals(parentPath)) { fixMaxentFiles(pid, dir); Zipper.zipDirectory(dir.getParent() + "/temp/" + pid, zipfile); } else if ("layers".equals(parentPath) || "aloc".equals(parentPath)) { fixAlocFiles(pid, dir); Zipper.zipDirectory(dir.getParent() + "/temp/" + pid, zipfile); } else { Zipper.zipDirectory(dir.getAbsolutePath(), zipfile); } System.out.println( "Found " + dir.getName() + " in " + dir.getParent() + " and zipped at: " + zipfile); //return "Found " + dir.getName() + " in " + dir.getParent() + " and zipped at: " + zipfile; if ("maxent".equals(parentPath)) { parentName = "ALA_Prediction_"; } else if ("sampling".equals(parentPath)) { parentName = "ALA_Species_Samples_"; } else if ("layers".equals(parentPath) || "aloc".equals(parentPath)) { parentName = "ALA_Classification_"; } else if ("gdm".equals(parentPath)) { parentName = "ALA_GDM_"; } else if ("filtering".equals(parentPath)) { parentName = "ALA_EnvFilter_"; } else if ("sitesbyspecies".equals(parentPath)) { parentName = "ALA_SitesBySpecies_"; } File file = new File(zipfile); System.out.println("File generated: " + file.getAbsolutePath()); } else { System.out.println("Could not find session data"); //return "Could not find session data"; } } catch (Exception e) { e.printStackTrace(System.out); } }
From source file:com.clustercontrol.agent.Agent.java
/** * ?/*from w ww. j av a 2s . c o m*/ * * @param args ?? */ public static void main(String[] args) throws Exception { // ? if (args.length != 1) { System.out.println("Usage : java Agent [Agent.properties File Path]"); System.exit(1); } try { // System m_log.info("starting Hinemos Agent..."); m_log.info("java.vm.version = " + System.getProperty("java.vm.version")); m_log.info("java.vm.vendor = " + System.getProperty("java.vm.vendor")); m_log.info("java.home = " + System.getProperty("java.home")); m_log.info("os.name = " + System.getProperty("os.name")); m_log.info("os.arch = " + System.getProperty("os.arch")); m_log.info("os.version = " + System.getProperty("os.version")); m_log.info("user.name = " + System.getProperty("user.name")); m_log.info("user.dir = " + System.getProperty("user.dir")); m_log.info("user.country = " + System.getProperty("user.country")); m_log.info("user.language = " + System.getProperty("user.language")); m_log.info("file.encoding = " + System.getProperty("file.encoding")); // System(SET) String limitKey = "jdk.xml.entityExpansionLimit"; // TODO JRE??????????????????? System.setProperty(limitKey, "0"); m_log.info(limitKey + " = " + System.getProperty(limitKey)); // TODO ???agentHome // ?????????? File file = new File(args[0]); agentHome = file.getParentFile().getParent() + "/"; m_log.info("agentHome=" + agentHome); // long startDate = HinemosTime.currentTimeMillis(); m_log.info("start date = " + new Date(startDate) + "(" + startDate + ")"); agentInfo.setStartupTime(startDate); // Agent?? m_log.info("Agent.properties = " + args[0]); // ? File scriptDir = new File(agentHome + "script/"); if (scriptDir.exists()) { File[] listFiles = scriptDir.listFiles(); if (listFiles != null) { for (File f : listFiles) { boolean ret = f.delete(); if (ret) { m_log.debug("delete script : " + f.getName()); } else { m_log.warn("delete script error : " + f.getName()); } } } else { m_log.warn("listFiles is null"); } } else { //???????? boolean ret = scriptDir.mkdir(); if (!ret) { m_log.warn("mkdir error " + scriptDir.getPath()); } } // queue? m_sendQueue = new SendQueue(); // Agent? Agent agent = new Agent(args[0]); //----------------- //-- //----------------- m_log.debug("exec() : create topic "); m_receiveTopic = new ReceiveTopic(m_sendQueue); m_receiveTopic.setName("ReceiveTopicThread"); m_log.info("receiveTopic start 1"); m_receiveTopic.start(); m_log.info("receiveTopic start 2"); // ? agent.exec(); m_log.info("Hinemos Agent started"); // ? agent.waitAwakeAgent(); } catch (Throwable e) { m_log.error("Agent.java: Runtime Exception Occurred. " + e.getClass().getName() + ", " + e.getMessage(), e); } }
From source file:main.RankerOCR.java
/** * Command line interface for RankerOCR. * <p>//from w w w. j a va2s . c om * <b>Command line input:</b> * <ul> * usage: java -jar Ranker-OCR [options] * </ul> * <b>Options list:</b> * <ul> * <li>-gui Launch a graphical user interface</li> * <li>-help Show the help</li> * <li>-indoc1 [arg] Set the file name of the original document</li> * <li>-indoc2 [arg] Set the file name of the document to compare</li> * <li>-ranker [arg] Set the ranker used for the comparison</li> * <li>-outdoc [arg] Set the document where write the results</li> * <li>-separator [arg] Set the delimiter char use in the CSV out file</li> * </ul> * <b>Return values are if error:</b> * <ul> * <li>(-1) The precision parameter is not a number.</li> * <li>(-2) The precision parameter is lower than 0.</li> * <li>(-3) The precision parameter is greater than 10.</li> * <li>(-11) The ranker name is wrong</li> * <li>(-21) The separator char is empty</li> * <li>(-22) The separator is not a char</li> * <li>(-31) File name doesn't exist</li> * <li>(-32) File name is not a file</li> * <li>(-33) Error when access to documents files</li> * <li>(-34) Output file can not be write</li> * <li>(-35) Output file can not be created</li> * <li>(-41) Error when parsing parameters</li> * <li>(-100) Internal error when creating the ranker. Please report a * bug</li> * <li>(-101) Internal error when get the ranker list. Please report a * bug.</li> * <li>(-102) Error when access to help file. Please report a bug.</li> * </ul> * <p> * @param args Argument array which can have the values from options list */ public static void main(String[] args) { //Parse command line CommandLineParser parser = new GnuParser(); try { CommandLine cmd = parser.parse(options, args); if (cmd.hasOption("help")) { showHelp(hf, options); } else if (cmd.hasOption("gui")) { display.DispalyRankerOCR.main(new String[] {}); } else if (cmd.hasOption("indoc1") && cmd.hasOption("indoc2") && cmd.hasOption("outdoc")) { //<editor-fold defaultstate="collapsed" desc="Rank documents"> //Prepare parameter Class ranker = evalRanker(cmd.getOptionValue("ranker", "SimpleRanker")); char separator = evalSeparator(cmd.getOptionValue("separator", "\t")); File f1 = evalInputFile(cmd.getOptionValue("indoc1", "")); File f2 = evalInputFile(cmd.getOptionValue("indoc2", "")); File f3 = evalOutputFile(cmd.getOptionValue("outdoc", ""), separator); //Read file String s1 = readInputDocText(f1); String s2 = readInputDocText(f2); //Compare file double percent = rankDocuments(s1, s2, ranker); //Write result String[] s = { Double.toString(percent), ranker.getSimpleName(), f1.getName(), f2.getName(), f1.getParent(), f2.getParent(), new Date().toString() }; writeOutpuDocCsv(f3, separator, s); //</editor-fold> } else { printFormated("java -jar Ranker-OCR [options] please type " + "-help for more info"); } } catch (ParseException ex) { printFormated(ex.getLocalizedMessage()); System.exit(-41); } }
From source file:com.cws.esolutions.security.main.PasswordUtility.java
public static void main(final String[] args) { final String methodName = PasswordUtility.CNAME + "#main(final String[] args)"; if (DEBUG) {/*from w w w .j a v a2 s .co m*/ DEBUGGER.debug("Value: {}", methodName); } if (args.length == 0) { HelpFormatter usage = new HelpFormatter(); usage.printHelp(PasswordUtility.CNAME, options, true); System.exit(1); } BufferedReader bReader = null; BufferedWriter bWriter = null; try { // load service config first !! SecurityServiceInitializer.initializeService(PasswordUtility.SEC_CONFIG, PasswordUtility.LOG_CONFIG, false); if (DEBUG) { DEBUGGER.debug("Options options: {}", options); for (String arg : args) { DEBUGGER.debug("Value: {}", arg); } } CommandLineParser parser = new PosixParser(); CommandLine commandLine = parser.parse(options, args); if (DEBUG) { DEBUGGER.debug("CommandLineParser parser: {}", parser); DEBUGGER.debug("CommandLine commandLine: {}", commandLine); DEBUGGER.debug("CommandLine commandLine.getOptions(): {}", (Object[]) commandLine.getOptions()); DEBUGGER.debug("CommandLine commandLine.getArgList(): {}", commandLine.getArgList()); } final SecurityConfigurationData secConfigData = PasswordUtility.svcBean.getConfigData(); final SecurityConfig secConfig = secConfigData.getSecurityConfig(); final PasswordRepositoryConfig repoConfig = secConfigData.getPasswordRepo(); final SystemConfig systemConfig = secConfigData.getSystemConfig(); if (DEBUG) { DEBUGGER.debug("SecurityConfigurationData secConfig: {}", secConfigData); DEBUGGER.debug("SecurityConfig secConfig: {}", secConfig); DEBUGGER.debug("RepositoryConfig secConfig: {}", repoConfig); DEBUGGER.debug("SystemConfig systemConfig: {}", systemConfig); } if (commandLine.hasOption("encrypt")) { if ((StringUtils.isBlank(repoConfig.getPasswordFile())) || (StringUtils.isBlank(repoConfig.getSaltFile()))) { System.err.println("The password/salt files are not configured. Entries will not be stored!"); } File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile()); File saltFile = FileUtils.getFile(repoConfig.getSaltFile()); if (DEBUG) { DEBUGGER.debug("File passwordFile: {}", passwordFile); DEBUGGER.debug("File saltFile: {}", saltFile); } final String entryName = commandLine.getOptionValue("entry"); final String username = commandLine.getOptionValue("username"); final String password = commandLine.getOptionValue("password"); final String salt = RandomStringUtils.randomAlphanumeric(secConfig.getSaltLength()); if (DEBUG) { DEBUGGER.debug("String entryName: {}", entryName); DEBUGGER.debug("String username: {}", username); DEBUGGER.debug("String password: {}", password); DEBUGGER.debug("String salt: {}", salt); } final String encodedSalt = PasswordUtils.base64Encode(salt); final String encodedUserName = PasswordUtils.base64Encode(username); final String encryptedPassword = PasswordUtils.encryptText(password, salt, secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(), systemConfig.getEncoding()); final String encodedPassword = PasswordUtils.base64Encode(encryptedPassword); if (DEBUG) { DEBUGGER.debug("String encodedSalt: {}", encodedSalt); DEBUGGER.debug("String encodedUserName: {}", encodedUserName); DEBUGGER.debug("String encodedPassword: {}", encodedPassword); } if (commandLine.hasOption("store")) { try { new File(passwordFile.getParent()).mkdirs(); new File(saltFile.getParent()).mkdirs(); boolean saltFileExists = (saltFile.exists()) ? true : saltFile.createNewFile(); if (DEBUG) { DEBUGGER.debug("saltFileExists: {}", saltFileExists); } // write the salt out first if (!(saltFileExists)) { throw new IOException("Unable to create salt file"); } boolean passwordFileExists = (passwordFile.exists()) ? true : passwordFile.createNewFile(); if (!(passwordFileExists)) { throw new IOException("Unable to create password file"); } if (commandLine.hasOption("replace")) { File[] files = new File[] { saltFile, passwordFile }; if (DEBUG) { DEBUGGER.debug("File[] files: {}", (Object) files); } for (File file : files) { if (DEBUG) { DEBUGGER.debug("File: {}", file); } String currentLine = null; File tmpFile = new File(FileUtils.getTempDirectory() + "/" + "tmpFile"); if (DEBUG) { DEBUGGER.debug("File tmpFile: {}", tmpFile); } bReader = new BufferedReader(new FileReader(file)); bWriter = new BufferedWriter(new FileWriter(tmpFile)); while ((currentLine = bReader.readLine()) != null) { if (!(StringUtils.equals(currentLine.trim().split(",")[0], entryName))) { bWriter.write(currentLine + System.getProperty("line.separator")); bWriter.flush(); } } bWriter.close(); FileUtils.deleteQuietly(file); FileUtils.copyFile(tmpFile, file); FileUtils.deleteQuietly(tmpFile); } } FileUtils.writeStringToFile(saltFile, entryName + "," + encodedUserName + "," + encodedSalt + System.getProperty("line.separator"), true); FileUtils.writeStringToFile(passwordFile, entryName + "," + encodedUserName + "," + encodedPassword + System.getProperty("line.separator"), true); } catch (IOException iox) { ERROR_RECORDER.error(iox.getMessage(), iox); } } System.out.println("Entry Name " + entryName + " stored."); } if (commandLine.hasOption("decrypt")) { String saltEntryName = null; String saltEntryValue = null; String decryptedPassword = null; String passwordEntryName = null; if ((StringUtils.isEmpty(commandLine.getOptionValue("entry")) && (StringUtils.isEmpty(commandLine.getOptionValue("username"))))) { throw new ParseException("No entry or username was provided to decrypt."); } if (StringUtils.isEmpty(commandLine.getOptionValue("username"))) { throw new ParseException("no entry provided to decrypt"); } String entryName = commandLine.getOptionValue("entry"); String username = commandLine.getOptionValue("username"); if (DEBUG) { DEBUGGER.debug("String entryName: {}", entryName); DEBUGGER.debug("String username: {}", username); } File passwordFile = FileUtils.getFile(repoConfig.getPasswordFile()); File saltFile = FileUtils.getFile(repoConfig.getSaltFile()); if (DEBUG) { DEBUGGER.debug("File passwordFile: {}", passwordFile); DEBUGGER.debug("File saltFile: {}", saltFile); } if ((!(saltFile.canRead())) || (!(passwordFile.canRead()))) { throw new IOException( "Unable to read configured password/salt file. Please check configuration and/or permissions."); } for (String lineEntry : FileUtils.readLines(saltFile, systemConfig.getEncoding())) { saltEntryName = lineEntry.split(",")[0]; if (DEBUG) { DEBUGGER.debug("String saltEntryName: {}", saltEntryName); } if (StringUtils.equals(saltEntryName, entryName)) { saltEntryValue = PasswordUtils.base64Decode(lineEntry.split(",")[2]); break; } } if (StringUtils.isEmpty(saltEntryValue)) { throw new SecurityException("No entries were found that matched the provided information"); } for (String lineEntry : FileUtils.readLines(passwordFile, systemConfig.getEncoding())) { passwordEntryName = lineEntry.split(",")[0]; if (DEBUG) { DEBUGGER.debug("String passwordEntryName: {}", passwordEntryName); } if (StringUtils.equals(passwordEntryName, saltEntryName)) { String decodedPassword = PasswordUtils.base64Decode(lineEntry.split(",")[2]); decryptedPassword = PasswordUtils.decryptText(decodedPassword, saltEntryValue, secConfig.getSecretAlgorithm(), secConfig.getIterations(), secConfig.getKeyBits(), secConfig.getEncryptionAlgorithm(), secConfig.getEncryptionInstance(), systemConfig.getEncoding()); break; } } if (StringUtils.isEmpty(decryptedPassword)) { throw new SecurityException("No entries were found that matched the provided information"); } System.out.println(decryptedPassword); } else if (commandLine.hasOption("encode")) { System.out.println(PasswordUtils.base64Encode((String) commandLine.getArgList().get(0))); } else if (commandLine.hasOption("decode")) { System.out.println(PasswordUtils.base64Decode((String) commandLine.getArgList().get(0))); } } catch (IOException iox) { ERROR_RECORDER.error(iox.getMessage(), iox); System.err.println("An error occurred during processing: " + iox.getMessage()); System.exit(1); } catch (ParseException px) { ERROR_RECORDER.error(px.getMessage(), px); System.err.println("An error occurred during processing: " + px.getMessage()); System.exit(1); } catch (SecurityException sx) { ERROR_RECORDER.error(sx.getMessage(), sx); System.err.println("An error occurred during processing: " + sx.getMessage()); System.exit(1); } catch (SecurityServiceException ssx) { ERROR_RECORDER.error(ssx.getMessage(), ssx); System.exit(1); } finally { try { if (bReader != null) { bReader.close(); } if (bWriter != null) { bReader.close(); } } catch (IOException iox) { } } System.exit(0); }
From source file:com.mvdb.etl.actions.ExtractDBChanges.java
public static void main(String[] args) throws JSONException { ActionUtils.setUpInitFileProperty(); // boolean success = ActionUtils.markActionChainBroken("Just Testing"); // System.exit(success ? 0 : 1); ActionUtils.assertActionChainNotBroken(); ActionUtils.assertEnvironmentSetupOk(); ActionUtils.assertFileExists("~/.mvdb", "~/.mvdb missing. Existing."); ActionUtils.assertFileExists("~/.mvdb/status.InitCustomerData.complete", "300init-customer-data.sh not executed yet. Exiting"); //This check is not required as data can be modified any number of times //ActionUtils.assertFileDoesNotExist("~/.mvdb/status.ModifyCustomerData.complete", "ModifyCustomerData already done. Start with 100init.sh if required. Exiting"); ActionUtils.createMarkerFile("~/.mvdb/status.ExtractDBChanges.start", true); //String schemaDescription = "{ 'root' : [{'table' : 'orders', 'keyColumn' : 'order_id', 'updateTimeColumn' : 'update_time'}]}"; String customerName = null;/* w ww.j a v a2 s .c o m*/ final CommandLineParser cmdLinePosixParser = new PosixParser(); final Options posixOptions = constructPosixOptions(); CommandLine commandLine; try { commandLine = cmdLinePosixParser.parse(posixOptions, args); if (commandLine.hasOption("customer")) { customerName = commandLine.getOptionValue("customer"); } } catch (ParseException parseException) // checked exception { System.err.println( "Encountered exception while parsing using PosixParser:\n" + parseException.getMessage()); } if (customerName == null) { System.err.println("Could not find customerName. Aborting..."); System.exit(1); } ApplicationContext context = Top.getContext(); final OrderDAO orderDAO = (OrderDAO) context.getBean("orderDAO"); final ConfigurationDAO configurationDAO = (ConfigurationDAO) context.getBean("configurationDAO"); final GenericDAO genericDAO = (GenericDAO) context.getBean("genericDAO"); File snapshotDirectory = getSnapshotDirectory(configurationDAO, customerName); try { FileUtils.writeStringToFile(new File("/tmp/etl.extractdbchanges.directory.txt"), snapshotDirectory.getName(), false); } catch (IOException e) { e.printStackTrace(); System.exit(1); return; } long currentTime = new Date().getTime(); Configuration lastRefreshTimeConf = configurationDAO.find(customerName, "last-refresh-time"); Configuration schemaDescriptionConf = configurationDAO.find(customerName, "schema-description"); long lastRefreshTime = Long.parseLong(lastRefreshTimeConf.getValue()); OrderJsonFileConsumer orderJsonFileConsumer = new OrderJsonFileConsumer(snapshotDirectory); Map<String, ColumnMetadata> metadataMap = orderDAO.findMetadata(); //write file schema-orders.dat in snapshotDirectory genericDAO.fetchMetadata("orders", snapshotDirectory); //writes files: header-orders.dat, data-orders.dat in snapshotDirectory JSONObject json = new JSONObject(schemaDescriptionConf.getValue()); JSONArray rootArray = json.getJSONArray("root"); int length = rootArray.length(); for (int i = 0; i < length; i++) { JSONObject jsonObject = rootArray.getJSONObject(i); String table = jsonObject.getString("table"); String keyColumnName = jsonObject.getString("keyColumn"); String updateTimeColumnName = jsonObject.getString("updateTimeColumn"); System.out.println("table:" + table + ", keyColumn: " + keyColumnName + ", updateTimeColumn: " + updateTimeColumnName); genericDAO.fetchAll2(snapshotDirectory, new Timestamp(lastRefreshTime), table, keyColumnName, updateTimeColumnName); } //Unlikely failure //But Need to factor this into a separate task so that extraction does not have to be repeated. //Extraction is an expensive task. try { String sourceDirectoryAbsolutePath = snapshotDirectory.getAbsolutePath(); File sourceRelativeDirectoryPath = getRelativeSnapShotDirectory(configurationDAO, sourceDirectoryAbsolutePath); String hdfsRoot = ActionUtils.getConfigurationValue(ConfigurationKeys.GLOBAL_CUSTOMER, ConfigurationKeys.GLOBAL_HDFS_ROOT); String targetDirectoryFullPath = hdfsRoot + "/data" + sourceRelativeDirectoryPath; ActionUtils.copyLocalDirectoryToHdfsDirectory(sourceDirectoryAbsolutePath, targetDirectoryFullPath); String dirName = snapshotDirectory.getName(); ActionUtils.setConfigurationValue(customerName, ConfigurationKeys.LAST_COPY_TO_HDFS_DIRNAME, dirName); } catch (Throwable e) { e.printStackTrace(); logger.error("Objects Extracted from database. But copy of snapshot directory<" + snapshotDirectory.getAbsolutePath() + "> to hdfs <" + "" + ">failed. Fix the problem and redo extract.", e); System.exit(1); } //Unlikely failure //But Need to factor this into a separate task so that extraction does not have to be repeated. //Extraction is an expensive task. String targetZip = null; try { File targetZipDirectory = new File(snapshotDirectory.getParent(), "archives"); if (!targetZipDirectory.exists()) { boolean success = targetZipDirectory.mkdirs(); if (success == false) { logger.error("Objects copied to hdfs. But able to create archive directory <" + targetZipDirectory.getAbsolutePath() + ">. Fix the problem and redo extract."); System.exit(1); } } targetZip = new File(targetZipDirectory, snapshotDirectory.getName() + ".zip").getAbsolutePath(); ActionUtils.zipFullDirectory(snapshotDirectory.getAbsolutePath(), targetZip); } catch (Throwable e) { e.printStackTrace(); logger.error("Objects copied to hdfs. But zipping of snapshot directory<" + snapshotDirectory.getAbsolutePath() + "> to <" + targetZip + ">failed. Fix the problem and redo extract.", e); System.exit(1); } //orderDAO.findAll(new Timestamp(lastRefreshTime), orderJsonFileConsumer); Configuration updateRefreshTimeConf = new Configuration(customerName, "last-refresh-time", String.valueOf(currentTime)); configurationDAO.update(updateRefreshTimeConf, String.valueOf(lastRefreshTimeConf.getValue())); ActionUtils.createMarkerFile("~/.mvdb/status.ExtractDBChanges.complete", true); }
From source file:de.ipbhalle.metfusion.main.SubstructureSearch.java
public static void main(String[] args) { String token = "eeca1d0f-4c03-4d81-aa96-328cdccf171a"; //String token = "a1004d0f-9d37-47e0-acdd-35e58e34f603"; //test();//from ww w .j a v a2 s. c o m //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/136m0498_MSMS.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/148m0859_MSMS.mf"); // File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/164m0445a_MSMS.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/192m0757a_MSMS.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/MetFusion_ChemSp_mfs/naringenin.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/Known_BT_MSMS_ChemSp/1MeBT_MSMS.mf"); //File file = new File("/home/mgerlich/projects/metfusion_tp/BTs/Unknown_BT_MSMS_ChemSp/mf_with_substruct_formula/150m0655a_MSMS.mf"); File file = new File( "C:/Users/Michael/Dropbox/Eawag_IPB_Shared_MassBank/BTs/Unknown_BT_MSMS_ChemSp/mf_with_substruct_formula/192m0757b_MSMS.mf"); MetFusionBatchFileHandler mbf = new MetFusionBatchFileHandler(file); try { mbf.readFile(); } catch (IOException e) { //System.out.println(e.getMessage()); System.err.println( "Error reading from MetFusion settings file [" + file.getAbsolutePath() + "]. Aborting!"); System.exit(-1); } MetFusionBatchSettings settings = mbf.getBatchSettings(); List<String> absent = settings.getSubstrucAbsent(); List<String> present = settings.getSubstrucPresent(); for (String s : present) { System.out.println("present -> " + s); } for (String s : absent) { System.out.println("absent -> " + s); } String formula = settings.getMfFormula(); System.out.println("formula -> " + formula); boolean useFormulaAsQuery = true; boolean useSDF = false; String sdfFile = ""; if (useSDF) { sdfFile = "C:/Users/Michael/Dropbox/Eawag_IPB_Shared_MassBank/BTs/Unknown_BT_MSMS_ChemSp/mf_with_substruct_formula/results_afterFormulaQuery/192m0757b_MSMS.sdf"; if (sdfFile.isEmpty()) { // TODO alternatively use SDF file from query file? System.err.println("SDF file needs to be specified! Exiting."); System.exit(-1); } } SubstructureSearch ss = new SubstructureSearch(present, absent, token, formula, mbf, useFormulaAsQuery, useSDF, sdfFile); ss.run(); List<ResultSubstructure> remaining = ss.getResultsRemaining(); List<Result> resultsForSDF = new ArrayList<Result>(); StringBuilder sb = new StringBuilder(); String sep = ","; for (ResultSubstructure rs : remaining) { sb.append(rs.getId()).append(sep); Result r = new Result(rs.getPort(), rs.getId(), rs.getName(), rs.getScore()); r.setMol(rs.getMol()); r.setSmiles(rs.getSmiles()); r.setInchi(rs.getInchi()); r.setInchikey(rs.getInchikey()); resultsForSDF.add(r); } String ids = sb.toString(); String fileSep = System.getProperty("file.separator"); if (!ids.isEmpty()) { ids = ids.substring(0, ids.length() - 1); System.out.println("ids -> " + ids); settings.setMfDatabaseIDs(ids); String filename = file.getName(); String prefix = filename.substring(0, filename.lastIndexOf(".")); filename = filename.replace(prefix, prefix + "_ids"); String dir = file.getParent(); System.out.println("dir -> " + dir); if (!dir.endsWith(fileSep)) dir += fileSep; File output = new File(file.getParent(), filename); mbf.writeFile(output, settings); SDFOutputHandler so = new SDFOutputHandler(dir + prefix + ".sdf"); boolean writeOK = so.writeOriginalResults(resultsForSDF, false); if (!writeOK) System.err.println("Error writing SDF [" + so.getFilename()); } }
From source file:Main.java
public static int getDepth(File file) { if (file.getParent() == null || new File(file.getParent()).getPath().equals(new File(file.getPath()))) return 1; return 1 + getDepth(new File(file.getParent())); }
From source file:Main.java
public static void saveFile(final String fileName, final String str) { try {/*from www . ja v a2 s.c o m*/ File f = new File(fileName); if (new File(f.getParent()).exists() == false) { f.getParentFile().mkdirs(); } f.createNewFile(); PrintStream p = new PrintStream(new FileOutputStream(f, false)); p.println(str); p.close(); } catch (Exception e) { e.printStackTrace(); System.err.println(fileName); } }
From source file:Main.java
/** * get parent path/* w w w. jav a2 s.c om*/ * @param path current file path * @return parent path */ public static String getParentPath(String path) { File file = new File(path); return file.getParent(); }