List of usage examples for java.io File getAbsolutePath
public String getAbsolutePath()
From source file:de.tudarmstadt.ukp.experiments.argumentation.convincingness.sampling.Step5GoldLabelEstimator.java
@SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { String inputDir = args[0];//from w w w. jav a 2s .c o m File outputDir = new File(args[1]); if (!outputDir.exists()) { outputDir.mkdirs(); } // we will process only a subset first List<AnnotatedArgumentPair> allArgumentPairs = new ArrayList<>(); Collection<File> files = IOHelper.listXmlFiles(new File(inputDir)); for (File file : files) { allArgumentPairs.addAll((List<AnnotatedArgumentPair>) XStreamTools.getXStream().fromXML(file)); } // collect turkers and csv List<String> turkerIDs = extractAndSortTurkerIDs(allArgumentPairs); String preparedCSV = prepareCSV(allArgumentPairs, turkerIDs); // save CSV and run MACE Path tmpDir = Files.createTempDirectory("mace"); File maceInputFile = new File(tmpDir.toFile(), "input.csv"); FileUtils.writeStringToFile(maceInputFile, preparedCSV, "utf-8"); File outputPredictions = new File(tmpDir.toFile(), "predictions.txt"); File outputCompetence = new File(tmpDir.toFile(), "competence.txt"); // run MACE MACE.main(new String[] { "--iterations", "500", "--threshold", String.valueOf(MACE_THRESHOLD), "--restarts", "50", "--outputPredictions", outputPredictions.getAbsolutePath(), "--outputCompetence", outputCompetence.getAbsolutePath(), maceInputFile.getAbsolutePath() }); // read back the predictions and competence List<String> predictions = FileUtils.readLines(outputPredictions, "utf-8"); // check the output if (predictions.size() != allArgumentPairs.size()) { throw new IllegalStateException("Wrong size of the predicted file; expected " + allArgumentPairs.size() + " lines but was " + predictions.size()); } String competenceRaw = FileUtils.readFileToString(outputCompetence, "utf-8"); String[] competence = competenceRaw.split("\t"); if (competence.length != turkerIDs.size()) { throw new IllegalStateException( "Expected " + turkerIDs.size() + " competence number, got " + competence.length); } // rank turkers by competence Map<String, Double> turkerIDCompetenceMap = new TreeMap<>(); for (int i = 0; i < turkerIDs.size(); i++) { turkerIDCompetenceMap.put(turkerIDs.get(i), Double.valueOf(competence[i])); } // sort by value descending Map<String, Double> sortedCompetences = IOHelper.sortByValue(turkerIDCompetenceMap, false); System.out.println("Sorted turker competences: " + sortedCompetences); // assign the gold label and competence for (int i = 0; i < allArgumentPairs.size(); i++) { AnnotatedArgumentPair annotatedArgumentPair = allArgumentPairs.get(i); String goldLabel = predictions.get(i).trim(); // might be empty if (!goldLabel.isEmpty()) { // so far the gold label has format aXXX_aYYY_a1, aXXX_aYYY_a2, or aXXX_aYYY_equal // strip now only the gold label annotatedArgumentPair.setGoldLabel(goldLabel); } // update turker competence for (AnnotatedArgumentPair.MTurkAssignment assignment : annotatedArgumentPair.mTurkAssignments) { String turkID = assignment.getTurkID(); int turkRank = getTurkerRank(turkID, sortedCompetences); assignment.setTurkRank(turkRank); double turkCompetence = turkerIDCompetenceMap.get(turkID); assignment.setTurkCompetence(turkCompetence); } } // now sort the data back according to their original file name Map<String, List<AnnotatedArgumentPair>> fileNameAnnotatedPairsMap = new HashMap<>(); for (AnnotatedArgumentPair argumentPair : allArgumentPairs) { String fileName = IOHelper.createFileName(argumentPair.getDebateMetaData(), argumentPair.getArg1().getStance()); if (!fileNameAnnotatedPairsMap.containsKey(fileName)) { fileNameAnnotatedPairsMap.put(fileName, new ArrayList<AnnotatedArgumentPair>()); } fileNameAnnotatedPairsMap.get(fileName).add(argumentPair); } // and save them to the output file for (Map.Entry<String, List<AnnotatedArgumentPair>> entry : fileNameAnnotatedPairsMap.entrySet()) { String fileName = entry.getKey(); List<AnnotatedArgumentPair> argumentPairs = entry.getValue(); File outputFile = new File(outputDir, fileName); // and save all sampled pairs into a XML file XStreamTools.toXML(argumentPairs, outputFile); System.out.println("Saved " + argumentPairs.size() + " pairs to " + outputFile); } }
From source file:DIA_Umpire_Quant.DIA_Umpire_IntLibSearch.java
/** * @param args the command line arguments *///from ww w . j av a 2 s .c o m public static void main(String[] args) throws FileNotFoundException, IOException, Exception { System.out.println( "================================================================================================="); System.out.println("DIA-Umpire targeted re-extraction analysis using internal library (version: " + UmpireInfo.GetInstance().Version + ")"); if (args.length != 1) { System.out.println( "command format error, the correct format should be : java -jar -Xmx10G DIA_Umpire_IntLibSearch.jar diaumpire_module.params"); return; } try { ConsoleLogger.SetConsoleLogger(Level.INFO); ConsoleLogger.SetFileLogger(Level.DEBUG, FilenameUtils.getFullPath(args[0]) + "diaumpire_intlibsearch.log"); } catch (Exception e) { } Logger.getRootLogger().info("Version: " + UmpireInfo.GetInstance().Version); Logger.getRootLogger().info("Parameter file:" + args[0]); BufferedReader reader = new BufferedReader(new FileReader(args[0])); String line = ""; String WorkFolder = ""; int NoCPUs = 2; String InternalLibID = ""; float ProbThreshold = 0.99f; float RTWindow_Int = -1f; float Freq = 0f; int TopNFrag = 6; TandemParam tandemPara = new TandemParam(DBSearchParam.SearchInstrumentType.TOF5600); HashMap<String, File> AssignFiles = new HashMap<>(); //<editor-fold defaultstate="collapsed" desc="Reading parameter file"> while ((line = reader.readLine()) != null) { line = line.trim(); Logger.getRootLogger().info(line); if (!"".equals(line) && !line.startsWith("#")) { //System.out.println(line); if (line.equals("==File list begin")) { do { line = reader.readLine(); line = line.trim(); if (line.equals("==File list end")) { continue; } else if (!"".equals(line)) { File newfile = new File(line); if (newfile.exists()) { AssignFiles.put(newfile.getAbsolutePath(), newfile); } else { Logger.getRootLogger().info("File: " + newfile + " does not exist."); } } } while (!line.equals("==File list end")); } if (line.split("=").length < 2) { continue; } String type = line.split("=")[0].trim(); String value = line.split("=")[1].trim(); switch (type) { case "Path": { WorkFolder = value; break; } case "path": { WorkFolder = value; break; } case "Thread": { NoCPUs = Integer.parseInt(value); break; } case "InternalLibID": { InternalLibID = value; break; } case "RTWindow_Int": { RTWindow_Int = Float.parseFloat(value); break; } case "ProbThreshold": { ProbThreshold = Float.parseFloat(value); break; } case "TopNFrag": { TopNFrag = Integer.parseInt(value); break; } case "Freq": { Freq = Float.parseFloat(value); break; } case "Fasta": { tandemPara.FastaPath = value; break; } } } } //</editor-fold> //Initialize PTM manager using compomics library PTMManager.GetInstance(); //Check if the fasta file can be found if (!new File(tandemPara.FastaPath).exists()) { Logger.getRootLogger().info("Fasta file :" + tandemPara.FastaPath + " cannot be found, the process will be terminated, please check."); System.exit(1); } //Generate DIA file list ArrayList<DIAPack> FileList = new ArrayList<>(); try { File folder = new File(WorkFolder); if (!folder.exists()) { Logger.getRootLogger().info("The path : " + WorkFolder + " cannot be found."); System.exit(1); } for (final File fileEntry : folder.listFiles()) { if (fileEntry.isFile() && (fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzxml") | fileEntry.getAbsolutePath().toLowerCase().endsWith(".mzml")) && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q1.mzxml") && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q2.mzxml") && !fileEntry.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) { AssignFiles.put(fileEntry.getAbsolutePath(), fileEntry); } if (fileEntry.isDirectory()) { for (final File fileEntry2 : fileEntry.listFiles()) { if (fileEntry2.isFile() && (fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzxml") | fileEntry2.getAbsolutePath().toLowerCase().endsWith(".mzml")) && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q1.mzxml") && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q2.mzxml") && !fileEntry2.getAbsolutePath().toLowerCase().endsWith("q3.mzxml")) { AssignFiles.put(fileEntry2.getAbsolutePath(), fileEntry2); } } } } Logger.getRootLogger().info("No. of files assigned :" + AssignFiles.size()); for (File fileEntry : AssignFiles.values()) { Logger.getRootLogger().info(fileEntry.getAbsolutePath()); } for (File fileEntry : AssignFiles.values()) { String mzXMLFile = fileEntry.getAbsolutePath(); if (mzXMLFile.toLowerCase().endsWith(".mzxml") | mzXMLFile.toLowerCase().endsWith(".mzml")) { DIAPack DiaFile = new DIAPack(mzXMLFile, NoCPUs); Logger.getRootLogger().info( "================================================================================================="); Logger.getRootLogger().info("Processing " + mzXMLFile); if (!DiaFile.LoadDIASetting()) { Logger.getRootLogger().info("Loading DIA setting failed, job is incomplete"); System.exit(1); } if (!DiaFile.LoadParams()) { Logger.getRootLogger().info("Loading parameters failed, job is incomplete"); System.exit(1); } Logger.getRootLogger().info("Loading identification results " + mzXMLFile + "...."); //If the serialization file for ID file existed if (DiaFile.ReadSerializedLCMSID()) { DiaFile.IDsummary.ReduceMemoryUsage(); DiaFile.IDsummary.FastaPath = tandemPara.FastaPath; FileList.add(DiaFile); } } } //<editor-fold defaultstate="collapsed" desc="Targete re-extraction using internal library"> Logger.getRootLogger().info( "================================================================================================="); if (FileList.size() > 1) { Logger.getRootLogger().info("Targeted re-extraction using internal library"); FragmentLibManager libManager = FragmentLibManager.ReadFragmentLibSerialization(WorkFolder, InternalLibID); if (libManager == null) { Logger.getRootLogger().info("Building internal spectral library"); libManager = new FragmentLibManager(InternalLibID); ArrayList<LCMSID> LCMSIDList = new ArrayList<>(); for (DIAPack dia : FileList) { LCMSIDList.add(dia.IDsummary); } libManager.ImportFragLibTopFrag(LCMSIDList, Freq, TopNFrag); libManager.WriteFragmentLibSerialization(WorkFolder); } libManager.ReduceMemoryUsage(); Logger.getRootLogger() .info("Building retention time prediction model and generate candidate peptide list"); for (int i = 0; i < FileList.size(); i++) { FileList.get(i).IDsummary.ClearMappedPep(); } for (int i = 0; i < FileList.size(); i++) { for (int j = i + 1; j < FileList.size(); j++) { RTAlignedPepIonMapping alignment = new RTAlignedPepIonMapping(WorkFolder, FileList.get(i).GetParameter(), FileList.get(i).IDsummary, FileList.get(j).IDsummary); alignment.GenerateModel(); alignment.GenerateMappedPepIon(); } FileList.get(i).ExportID(); FileList.get(i).IDsummary = null; } Logger.getRootLogger().info("Targeted matching........"); for (DIAPack diafile : FileList) { if (diafile.IDsummary == null) { diafile.ReadSerializedLCMSID(); } if (!diafile.IDsummary.GetMappedPepIonList().isEmpty()) { diafile.UseMappedIon = true; diafile.FilterMappedIonByProb = false; diafile.BuildStructure(); diafile.MS1FeatureMap.ReadPeakCluster(); diafile.MS1FeatureMap.ClearMonoisotopicPeakOfCluster(); diafile.GenerateMassCalibrationRTMap(); diafile.TargetedExtractionQuant(false, libManager, ProbThreshold, RTWindow_Int); diafile.MS1FeatureMap.ClearAllPeaks(); diafile.IDsummary.ReduceMemoryUsage(); diafile.IDsummary.RemoveLowProbMappedIon(ProbThreshold); diafile.ExportID(); Logger.getRootLogger().info("Peptide ions: " + diafile.IDsummary.GetPepIonList().size() + " Mapped ions: " + diafile.IDsummary.GetMappedPepIonList().size()); diafile.ClearStructure(); } diafile.IDsummary = null; System.gc(); } Logger.getRootLogger().info( "================================================================================================="); } //</editor-fold> Logger.getRootLogger().info("Job done"); Logger.getRootLogger().info( "================================================================================================="); } catch (Exception e) { Logger.getRootLogger().error(ExceptionUtils.getStackTrace(e)); throw e; } }
From source file:net.sf.xmm.moviemanager.MovieManager.java
public static void main(String args[]) { boolean sandbox = SysUtil.isRestrictedSandbox(); // Uses this to check if the app is running in a sandbox with limited privileges try {//w w w . j a v a2 s . c om /* Disable HTTPClient logging output */ System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog"); //$NON-NLS-1$ //$NON-NLS-2$ } catch (java.security.AccessControlException s) { s.printStackTrace(); sandbox = true; } if (!sandbox) { // Disables logging for cobra html renderer java.util.logging.Logger.getLogger("").setLevel(java.util.logging.Level.OFF); File log4jConfigFile = FileUtil.getFile("config/log4j.properties"); //$NON-NLS-1$ if (log4jConfigFile.isFile()) { PropertyConfigurator.configure(log4jConfigFile.getAbsolutePath()); } else { BasicConfigurator.configure(); } } else BasicConfigurator.configure(); log = Logger.getRootLogger(); // Places the Log file in the user directory (the program location) RollingFileAppender appndr = (RollingFileAppender) log.getAppender("FileAppender"); String logFile = null; try { if (SysUtil.isMac() || SysUtil.isWindowsVista() || SysUtil.isWindows7()) logFile = new File(SysUtil.getConfigDir(), "Log.txt").getAbsolutePath(); } catch (Exception e1) { e1.printStackTrace(); } finally { if (logFile == null) logFile = new File(SysUtil.getUserDir(), "Log.txt").getAbsolutePath(); } if (appndr != null && appndr.getFile() == null) { appndr.setFile(logFile); appndr.activateOptions(); } /* Writes the date. */ log.debug("================================================================================"); //$NON-NLS-1$ log.debug("Log Start: " + new Date(System.currentTimeMillis())); //$NON-NLS-1$ log.debug("MeD's Movie Manager v" + config.sysSettings.getVersion()); //$NON-NLS-1$ log.debug("MovieManager release:" + MovieManager.getConfig().sysSettings.getRelease() + " - " + "IMDb Lib release:" + IMDbLib.getRelease() + " (" + IMDbLib.getVersion() + ")"); log.debug(SysUtil.getSystemInfo(SysUtil.getLineSeparator())); //$NON-NLS-1$ /* Loads the config */ if (!sandbox) config.loadConfig(); // Calls the plugin startup method MovieManagerStartupHandler startupHandler = MovieManager.getConfig().getStartupHandler(); if (startupHandler != null) { startupHandler.startUp(); } if (!sandbox) { if (SysUtil.isAtLeastJRE6()) { SysUtil.includeJarFilesInClasspath("lib/LookAndFeels/1.6"); } SysUtil.includeJarFilesInClasspath("lib/LookAndFeels"); SysUtil.includeJarFilesInClasspath("lib/drivers"); /* Must be called before the GUI is created */ if (SysUtil.isMac()) { SysUtil.includeJarFilesInClasspath("lib/mac"); lookAndFeelManager.setupOSXLaF(); } } movieManager = new MovieManager(); movieManager.sandbox = sandbox; // Loads the HTML templates templateHandler.loadHTMLTemplates(); EventQueue.invokeLater(new Runnable() { public final void run() { try { /* Installs the Look&Feels */ lookAndFeelManager.instalLAFs(); if (!MovieManager.isApplet()) lookAndFeelManager.setLookAndFeel(); log.debug("Look & Feels installed."); log.debug("Creating MovieManager Dialog"); movieManager.createDialog(); /* Starts the MovieManager. */ MovieManager.getDialog().setUp(); log.debug("MovieManager Dialog - setup."); MovieManager.getDialog().showDialog(); /* SetUp the Application Menu for OSX */ if (SysUtil.isMac()) { LookAndFeelManager.macOSXRegistration(MovieManager.getDialog()); } // Calls the plugin startup method MovieManagerLoginHandler loginHandler = MovieManager.getConfig().getLoginHandler(); if (loginHandler != null) { loginHandler.loginStartUp(); } log.debug("Loading Database...."); /* Loads the database. */ databaseHandler.loadDatabase(true); log.debug("Database loaded."); AppUpdater.handleVersionUpdate(); } catch (Exception e) { log.error("Exception occured while intializing MeD's Movie Manager", e); } } }); }
From source file:at.spardat.xma.xdelta.JarPatcher.java
/** * Main method to make {@link #applyDelta(ZipFile, ZipFile, ZipArchiveOutputStream, BufferedReader)} available at * the command line.<br>/*from w w w. j a v a 2 s. c o m*/ * usage JarPatcher source patch output * * @param args the arguments * @throws IOException Signals that an I/O exception has occurred. */ public static void main(String[] args) throws IOException { String patchName = null; String outputName = null; String sourceName = null; if (args.length == 0) { System.err.println("usage JarPatcher patch [output [source]]"); System.exit(1); } else { patchName = args[0]; if (args.length > 1) { outputName = args[1]; if (args.length > 2) { sourceName = args[2]; } } } ZipFile patch = new ZipFile(patchName); ZipArchiveEntry listEntry = patch.getEntry("META-INF/file.list"); if (listEntry == null) { System.err.println("Invalid patch - list entry 'META-INF/file.list' not found"); System.exit(2); } BufferedReader list = new BufferedReader(new InputStreamReader(patch.getInputStream(listEntry))); String next = list.readLine(); if (sourceName == null) { sourceName = next; } next = list.readLine(); if (outputName == null) { outputName = next; } int ignoreSourcePaths = Integer.parseInt(System.getProperty("patcher.ignoreSourcePathElements", "0")); int ignoreOutputPaths = Integer.parseInt(System.getProperty("patcher.ignoreOutputPathElements", "0")); Path sourcePath = Paths.get(sourceName); Path outputPath = Paths.get(outputName); if (ignoreOutputPaths >= outputPath.getNameCount()) { patch.close(); StringBuilder b = new StringBuilder().append("Not enough path elements to ignore in output (") .append(ignoreOutputPaths).append(" in ").append(outputName).append(")"); throw new IOException(b.toString()); } if (ignoreSourcePaths >= sourcePath.getNameCount()) { patch.close(); StringBuilder b = new StringBuilder().append("Not enough path elements to ignore in source (") .append(sourcePath).append(" in ").append(sourceName).append(")"); throw new IOException(b.toString()); } sourcePath = sourcePath.subpath(ignoreSourcePaths, sourcePath.getNameCount()); outputPath = outputPath.subpath(ignoreOutputPaths, outputPath.getNameCount()); File sourceFile = sourcePath.toFile(); File outputFile = outputPath.toFile(); if (!(outputFile.getAbsoluteFile().getParentFile().mkdirs() || outputFile.getAbsoluteFile().getParentFile().exists())) { patch.close(); throw new IOException("Failed to create " + outputFile.getAbsolutePath()); } new JarPatcher(patchName, sourceFile.getName()).applyDelta(patch, new ZipFile(sourceFile), new ZipArchiveOutputStream(new FileOutputStream(outputFile)), list); list.close(); }
From source file:de.pniehus.odal.App.java
public static void main(String[] args) throws IOException { List<Filter> filters = new ArrayList<Filter>(); filters.add(new RegexFilter()); filters.add(new FileTypeFilter()); filters.add(new KeywordFilter()); filters.add(new BlacklistFilter()); Profile p = parseArgs(args, filters); String fileName = "log-" + new Date().toString().replace(":", "-") + ".txt"; fileName = fileName.replace(" ", "-"); File logPath = new File(p.getLogDirectory() + fileName); if (!logPath.getParentFile().isDirectory() && !logPath.getParentFile().mkdirs()) { logPath = new File(fileName); }//w w w. j av a 2 s . c o m if (logPath.getParentFile().canWrite() || logPath.getParentFile().setWritable(true)) { SimpleLoggingSetup.configureRootLogger(logPath.getAbsolutePath(), p.getLogLevel(), !p.isSilent()); } else { Logger root = Logger.getLogger(""); for (Handler h : root.getHandlers()) { // Removing default console handlers if (h instanceof ConsoleHandler) { root.removeHandler(h); } } ConsolePrintLogHandler cplh = new ConsolePrintLogHandler(); cplh.setFormatter(new ScribblerLogFormat(SimpleLoggingSetup.DEFAULT_DATE_FORMAT)); root.addHandler(cplh); System.out.println("Unable to create log: insufficient permissions!"); } Logger.getLogger("").setLevel(p.getLogLevel()); mainLogger = Logger.getLogger(App.class.getCanonicalName()); untrustedSSLSetup(); mainLogger.info("Successfully intitialized ODAL"); if (!p.isLogging()) mainLogger.setLevel(Level.OFF); if (p.isWindowsConsoleMode() && !p.isLogging()) { Logger root = Logger.getLogger(""); for (Handler h : root.getHandlers()) { if (h instanceof FileHandler) { root.removeHandler(h); // Removes FileHandler to allow console output through logging } } } OdalGui ogui = new OdalGui(p, filters); }
From source file:ValidateLicenseHeaders.java
/** * ValidateLicenseHeaders jboss-src-root * //from w w w. j a v a2 s. c om * @param args */ public static void main(String[] args) throws Exception { if (args.length == 0 || args[0].startsWith("-h")) { log.info("Usage: ValidateLicenseHeaders [-addheader] jboss-src-root"); System.exit(1); } int rootArg = 0; if (args.length == 2) { if (args[0].startsWith("-add")) addDefaultHeader = true; else { log.severe("Uknown argument: " + args[0]); log.info("Usage: ValidateLicenseHeaders [-addheader] jboss-src-root"); System.exit(1); } rootArg = 1; } File jbossSrcRoot = new File(args[rootArg]); if (jbossSrcRoot.exists() == false) { log.info("Src root does not exist, check " + jbossSrcRoot.getAbsolutePath()); System.exit(1); } URL u = Thread.currentThread().getContextClassLoader() .getResource("META-INF/services/javax.xml.parsers.DocumentBuilderFactory"); System.err.println(u); // Load the valid copyright statements for the licenses File licenseInfo = new File(jbossSrcRoot, "varia/src/etc/license-info.xml"); if (licenseInfo.exists() == false) { log.severe("Failed to find the varia/src/etc/license-info.xml under the src root"); System.exit(1); } DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder db = factory.newDocumentBuilder(); Document doc = db.parse(licenseInfo); NodeList licenses = doc.getElementsByTagName("license"); for (int i = 0; i < licenses.getLength(); i++) { Element license = (Element) licenses.item(i); String key = license.getAttribute("id"); ArrayList headers = new ArrayList(); licenseHeaders.put(key, headers); NodeList copyrights = license.getElementsByTagName("terms-header"); for (int j = 0; j < copyrights.getLength(); j++) { Element copyright = (Element) copyrights.item(j); copyright.normalize(); String id = copyright.getAttribute("id"); // The id will be blank if there is no id attribute if (id.length() == 0) continue; String text = getElementContent(copyright); if (text == null) continue; // Replace all duplicate whitespace and '*' with a single space text = text.replaceAll("[\\s*]+", " "); if (text.length() == 1) continue; text = text.toLowerCase().trim(); // Replace any copyright date0-date1,date2 with copyright ... text = text.replaceAll(COPYRIGHT_REGEX, "..."); LicenseHeader lh = new LicenseHeader(id, text); headers.add(lh); } } log.fine(licenseHeaders.toString()); File[] files = jbossSrcRoot.listFiles(dotJavaFilter); log.info("Root files count: " + files.length); processSourceFiles(files, 0); log.info("Processed " + totalCount); log.info("Updated jboss headers: " + jbossCount); // Files with no headers details log.info("Files with no headers: " + noheaders.size()); FileWriter fw = new FileWriter("NoHeaders.txt"); for (Iterator iter = noheaders.iterator(); iter.hasNext();) { File f = (File) iter.next(); fw.write(f.getAbsolutePath()); fw.write('\n'); } fw.close(); // Files with unknown headers details log.info("Files with invalid headers: " + invalidheaders.size()); fw = new FileWriter("InvalidHeaders.txt"); for (Iterator iter = invalidheaders.iterator(); iter.hasNext();) { File f = (File) iter.next(); fw.write(f.getAbsolutePath()); fw.write('\n'); } fw.close(); // License usage summary log.info("Creating HeadersSummary.txt"); fw = new FileWriter("HeadersSummary.txt"); for (Iterator iter = licenseHeaders.entrySet().iterator(); iter.hasNext();) { Map.Entry entry = (Map.Entry) iter.next(); String key = (String) entry.getKey(); fw.write("+++ License type=" + key); fw.write('\n'); List list = (List) entry.getValue(); Iterator jiter = list.iterator(); while (jiter.hasNext()) { LicenseHeader lh = (LicenseHeader) jiter.next(); fw.write('\t'); fw.write(lh.id); fw.write(", count="); fw.write("" + lh.count); fw.write('\n'); } } fw.close(); }
From source file:com.concursive.connect.web.modules.setup.utils.SetupUtils.java
/** * This method is used by the ant task to install any default data * * @param args database connection settings: driver, url, user, password *//*from ww w . ja va 2 s . com*/ public static void main(String[] args) { // Connection values String driver = args[0]; String url = args[1]; String user = args[2]; String password = args[3]; String fileLibraryPath = args[4]; String title = args[5]; String description = args[6]; String keywords = args[7]; String purpose = args[8]; String userfirst = args[9]; String userlast = args[10]; String useremail = args[11]; String userpass = args[12]; // Insert default data ConnectionPool cp = new ConnectionPool(); Connection db = null; try { ConnectionElement ce = new ConnectionElement(url, user, password); ce.setDriver(driver); db = cp.getConnection(ce, true); // Instantiate the caches CacheManager.create(); CacheContext cacheContext = new CacheContext(); cacheContext.setUpgradeConnection(db); Caches.addCaches(cacheContext); // Load the object map and services int SYSTEM_ID = 1; SyncTableList syncTableList = new SyncTableList(); syncTableList.setSystemId(SYSTEM_ID); // Load the core object map syncTableList.loadObjectMap(SyncTableList.class.getResourceAsStream("/object_map.xml")); // Load plug-in mappings in the services path File[] serviceFiles = new File("src/main/webapp/WEB-INF/services").listFiles(); if (serviceFiles != null && serviceFiles.length > 0) { for (File thisFile : serviceFiles) { if (thisFile.getAbsolutePath().endsWith(".xml")) { try { LOG.info("Adding services from... " + thisFile.getAbsolutePath()); syncTableList.loadObjectMap(new FileInputStream(thisFile)); } catch (Exception e) { LOG.error("getObjectMap exception", e); } } } } // The default category information insertDefaultCategories(db, syncTableList, fileLibraryPath); // Insert admin user if (useremail != null && userpass != null) { User adminUser = new User(); adminUser.setFirstName(userfirst); adminUser.setLastName(userlast); adminUser.setUsername(useremail); adminUser.setEmail(useremail); adminUser.setPassword1(userpass); adminUser.setPassword2(userpass); insertDefaultAdmin(db, adminUser, null, null); } // The default system profile Project project = new Project(); project.setTitle(title); project.setShortDescription(description); project.setKeywords(keywords); insertDefaultSiteConfig(db, fileLibraryPath, project, purpose, new ApplicationPrefs()); // The default profile content insertDefaultContent(db, syncTableList, fileLibraryPath, project); } catch (Exception e) { e.printStackTrace(System.out); LOG.error(e); System.exit(2); } finally { LOG.info("Cleaning up..."); CacheManager.getInstance().shutdown(); cp.free(db); } System.exit(0); }
From source file:com.athena.peacock.agent.sample.CommandExecutorSample.java
/** * <pre>//from w w w .java 2 s .com * * </pre> * @param args * @throws CommandLineException * @throws IOException */ public static void main(String[] args) throws CommandLineException, IOException { // Windows wmic usage // http://blog.naver.com/PostView.nhn?blogId=diadld2&logNo=30157625015 // http://www.petenetlive.com/KB/Article/0000619.htm OSType osType = OSUtil.getOSName(); File executable = null; Commandline commandLine = null; if (osType.equals(OSType.WINDOWS)) { executable = new File("C:\\Windows\\System32\\wbem\\WMIC.exe"); commandLine = new Commandline(); commandLine.setExecutable(executable.getAbsolutePath()); //commandLine.setExecutable("wmic"); // available only that command is in path /** change working directory if necessary */ commandLine.setWorkingDirectory("/"); /** invoke createArg() and setValue() one by one for each arguments */ commandLine.createArg().setValue("product"); commandLine.createArg().setValue("get"); commandLine.createArg().setValue("name,vendor,version"); /** invoke createArg() and setLine() for entire arguments */ //commandLine.createArg().setLine("product get name,vendor,version"); /** verify command string */ System.out.println("C:\\> " + commandLine.toString() + "\n"); } else { executable = new File("/bin/cat"); commandLine = new Commandline(); commandLine.setExecutable(executable.getAbsolutePath()); /** change working directory if necessary */ commandLine.setWorkingDirectory("/"); /** invoke createArg() and setValue() one by one for each arguments */ commandLine.createArg().setValue("-n"); commandLine.createArg().setValue("/etc/hosts"); /** invoke createArg() and setLine() for entire arguments */ //commandLine.createArg().setLine("-n /etc/hosts"); /** verify command string */ System.out.println("~]$ " + commandLine.toString() + "\n"); } /** also enable StringWriter, PrintWriter, WriterStreamConsumer and etc. */ StringStreamConsumer consumer = new CommandLineUtils.StringStreamConsumer(); int returnCode = CommandLineUtils.executeCommandLine(commandLine, consumer, consumer, Integer.MAX_VALUE); if (returnCode == 0) { // success System.out.println("==============[SUCCEED]=============="); System.out.println("[" + consumer.getOutput().substring(0, consumer.getOutput().length() - 1) + "]"); if (osType.equals(OSType.WINDOWS)) { List<Product> productList = parse(consumer.getOutput()); for (Product product : productList) { System.out.println(product); } int UTF_8 = 0x01; int EUC_KR = 0x02; int KSC5601 = 0x04; int MS949 = 0x08; int ISO8859_1 = 0x10; int mode = 0x00; //mode ^= UTF_8; //mode ^= EUC_KR; //mode ^= KSC5601; //mode ^= MS949; //mode ^= ISO8859_1; if ((mode & UTF_8) == UTF_8) { System.out.println("+:+:+:+: UTF-8 +:+:+:+:"); System.out.println(new String(consumer.getOutput().getBytes(), "UTF-8")); System.out.println("+:+:+:+: EUC-KR => UTF-8 +:+:+:+:"); System.out.println(new String(consumer.getOutput().getBytes("EUC-KR"), "UTF-8")); System.out.println("+:+:+:+: KSC5601 => UTF-8 +:+:+:+:"); System.out.println(new String(consumer.getOutput().getBytes("KSC5601"), "UTF-8")); System.out.println("+:+:+:+: MS949 => UTF-8 +:+:+:+:"); System.out.println(new String(consumer.getOutput().getBytes("MS949"), "UTF-8")); System.out.println("+:+:+:+: ISO8859_1 => UTF-8 +:+:+:+:"); System.out.println(new String(consumer.getOutput().getBytes("ISO8859_1"), "UTF-8")); } if ((mode & EUC_KR) == EUC_KR) { System.out.println("+:+:+:+: EUC-KR +:+:+:+:"); System.out.println(new String(consumer.getOutput().getBytes(), "EUC-KR")); System.out.println("+:+:+:+: UTF-8 => EUC-KR +:+:+:+:"); System.out.println(new String(consumer.getOutput().getBytes("UTF-8"), "EUC-KR")); System.out.println("+:+:+:+: KSC5601 => EUC-KR +:+:+:+:"); System.out.println(new String(consumer.getOutput().getBytes("KSC5601"), "EUC-KR")); System.out.println("+:+:+:+: MS949 => EUC-KR +:+:+:+:"); System.out.println(new String(consumer.getOutput().getBytes("MS949"), "EUC-KR")); System.out.println("+:+:+:+: ISO8859_1 => EUC-KR +:+:+:+:"); System.out.println(new String(consumer.getOutput().getBytes("ISO8859_1"), "EUC-KR")); } if ((mode & KSC5601) == KSC5601) { System.out.println("+:+:+:+: KSC5601 +:+:+:+:"); System.out.println(new String(consumer.getOutput().getBytes(), "KSC5601")); System.out.println("+:+:+:+: EUC-KR => KSC5601 +:+:+:+:"); System.out.println(new String(consumer.getOutput().getBytes("EUC-KR"), "KSC5601")); System.out.println("+:+:+:+: UTF-8 => KSC5601 +:+:+:+:"); System.out.println(new String(consumer.getOutput().getBytes("UTF-8"), "KSC5601")); System.out.println("+:+:+:+: MS949 => KSC5601 +:+:+:+:"); System.out.println(new String(consumer.getOutput().getBytes("MS949"), "KSC5601")); System.out.println("+:+:+:+: ISO8859_1 => KSC5601 +:+:+:+:"); System.out.println(new String(consumer.getOutput().getBytes("ISO8859_1"), "KSC5601")); } if ((mode & MS949) == MS949) { System.out.println("+:+:+:+: MS949 +:+:+:+:"); System.out.println(new String(consumer.getOutput().getBytes(), "MS949")); System.out.println("+:+:+:+: EUC-KR => MS949 +:+:+:+:"); System.out.println(new String(consumer.getOutput().getBytes("EUC-KR"), "MS949")); System.out.println("+:+:+:+: UTF-8 => MS949 +:+:+:+:"); System.out.println(new String(consumer.getOutput().getBytes("UTF-8"), "MS949")); System.out.println("+:+:+:+: KSC5601 => MS949 +:+:+:+:"); System.out.println(new String(consumer.getOutput().getBytes("KSC5601"), "MS949")); System.out.println("+:+:+:+: ISO8859_1 => MS949 +:+:+:+:"); System.out.println(new String(consumer.getOutput().getBytes("ISO8859_1"), "MS949")); } if ((mode & ISO8859_1) == ISO8859_1) { System.out.println("+:+:+:+: ISO8859_1 +:+:+:+:"); System.out.println(new String(consumer.getOutput().getBytes(), "ISO8859_1")); System.out.println("+:+:+:+: EUC-KR => ISO8859_1 +:+:+:+:"); System.out.println(new String(consumer.getOutput().getBytes("EUC-KR"), "ISO8859_1")); System.out.println("+:+:+:+: UTF-8 => ISO8859_1 +:+:+:+:"); System.out.println(new String(consumer.getOutput().getBytes("UTF-8"), "ISO8859_1")); System.out.println("+:+:+:+: KSC5601 => ISO8859_1 +:+:+:+:"); System.out.println(new String(consumer.getOutput().getBytes("KSC5601"), "ISO8859_1")); System.out.println("+:+:+:+: MS949 => ISO8859_1 +:+:+:+:"); System.out.println(new String(consumer.getOutput().getBytes("MS949"), "ISO8859_1")); } } } else { // fail System.err.println("==============[FAILED]=============="); System.err.println(consumer.getOutput()); } }
From source file:com.act.lcms.db.analysis.IonSearchAnalysis.java
public static void main(String[] args) throws Exception { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());/*from w ww . j a v a 2 s . c o m*/ } CommandLine cl = null; try { CommandLineParser parser = new DefaultParser(); cl = parser.parse(opts, args); } catch (ParseException e) { System.err.format("Argument parsing failed: %s\n", e.getMessage()); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } if (cl.hasOption("help")) { HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); return; } File lcmsDir = new File(cl.getOptionValue(OPTION_DIRECTORY)); if (!lcmsDir.isDirectory()) { System.err.format("File at %s is not a directory\n", lcmsDir.getAbsolutePath()); HELP_FORMATTER.printHelp(LoadPlateCompositionIntoDB.class.getCanonicalName(), HELP_MESSAGE, opts, null, true); System.exit(1); } Double fontScale = null; if (cl.hasOption("font-scale")) { try { fontScale = Double.parseDouble(cl.getOptionValue("font-scale")); } catch (IllegalArgumentException e) { System.err.format("Argument for font-scale must be a floating point number.\n"); System.exit(1); } } try (DB db = DB.openDBFromCLI(cl)) { Set<String> includeIons = null; if (cl.hasOption("include-ions")) { String[] ionNames = cl.getOptionValues("include-ions"); includeIons = new HashSet<>(Arrays.asList(ionNames)); System.out.format("Including ions in search: %s\n", StringUtils.join(includeIons, ", ")); } Set<String> excludeIons = null; if (cl.hasOption("exclude-ions")) { String[] ionNames = cl.getOptionValues("exclude-ions"); excludeIons = new HashSet<>(Arrays.asList(ionNames)); System.out.format("Excluding ions from search: %s\n", StringUtils.join(excludeIons, ", ")); } Set<Integer> takeSamplesFromPlateIds = null; if (cl.hasOption(OPTION_FILTER_BY_PLATE_BARCODE)) { String[] plateBarcodes = cl.getOptionValues(OPTION_FILTER_BY_PLATE_BARCODE); System.out.format("Considering only sample wells in plates: %s\n", StringUtils.join(plateBarcodes, ", ")); takeSamplesFromPlateIds = new HashSet<>(plateBarcodes.length); for (String plateBarcode : plateBarcodes) { Plate p = Plate.getPlateByBarcode(db, plateBarcode); if (p == null) { System.err.format("WARNING: unable to find plate in DB with barcode %s\n", plateBarcode); } else { takeSamplesFromPlateIds.add(p.getId()); } } // Allow filtering on barcode even if we couldn't find any in the DB. } System.out.format("Loading/updating LCMS scan files into DB\n"); ScanFile.insertOrUpdateScanFilesInDirectory(db, lcmsDir); System.out.format("Processing LCMS scans\n"); Pair<List<LCMSWell>, Set<Integer>> positiveWellsAndPlateIds = Utils.extractWellsAndPlateIds(db, cl.getOptionValues(OPTION_STRAINS), cl.getOptionValues(OPTION_CONSTRUCTS), takeSamplesFromPlateIds, false); List<LCMSWell> positiveWells = positiveWellsAndPlateIds.getLeft(); if (positiveWells.size() == 0) { throw new RuntimeException("Found no LCMS wells for specified strains/constructs"); } // Only take negative samples from the plates where we found the positive samples. Pair<List<LCMSWell>, Set<Integer>> negativeWellsAndPlateIds = Utils.extractWellsAndPlateIds(db, cl.getOptionValues(OPTION_NEGATIVE_STRAINS), cl.getOptionValues(OPTION_NEGATIVE_CONSTRUCTS), positiveWellsAndPlateIds.getRight(), true); List<LCMSWell> negativeWells = negativeWellsAndPlateIds.getLeft(); if (negativeWells == null || negativeWells.size() == 0) { System.err.format("WARNING: no valid negative samples found in same plates as positive samples\n"); } // Extract the reference MZ that will be used in the LCMS trace processing. List<Pair<String, Double>> searchMZs = null; Set<CuratedChemical> standardChemicals = null; List<ChemicalAssociatedWithPathway> pathwayChems = null; if (cl.hasOption(OPTION_SEARCH_MZ)) { // Assume mz can be an FP number of a chemical name. String massStr = cl.getOptionValue(OPTION_SEARCH_MZ); Pair<String, Double> searchMZ = Utils.extractMassFromString(db, massStr); if (searchMZ != null) { searchMZs = Collections.singletonList(searchMZ); } standardChemicals = Utils.extractTargetsForWells(db, positiveWells); } else { CuratedChemical targetChemical = Utils.requireOneTarget(db, positiveWells); if (targetChemical == null) { throw new RuntimeException( "Unable to find a curated chemical entry for specified strains'/constructs' targets. " + "Please specify a chemical name or m/z explicitly or update the curated chemicals list in the DB."); } System.out.format("Using reference M/Z for positive target %s (%f)\n", targetChemical.getName(), targetChemical.getMass()); searchMZs = Collections.singletonList(Pair.of(targetChemical.getName(), targetChemical.getMass())); standardChemicals = Collections.singleton(targetChemical); } // Look up the standard by name, or use the target if none is specified. List<StandardWell> standardWells = null; if (cl.hasOption(OPTION_NO_STANDARD)) { System.err.format("WARNING: skipping standard comparison (no-standard option specified)\n"); standardWells = new ArrayList<>(0); } else if (cl.hasOption(OPTION_STANDARD_WELLS)) { String[] standardCoordinates = cl.getOptionValues(OPTION_STANDARD_WELLS); standardWells = new ArrayList<>(standardCoordinates.length); Plate standardPlate = Plate.getPlateByBarcode(db, cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE)); List<String> foundCoordinates = new ArrayList<>(standardCoordinates.length); for (String stringCoords : standardCoordinates) { Pair<Integer, Integer> coords = Utils.parsePlateCoordinates(stringCoords); StandardWell well = StandardWell.getInstance().getStandardWellsByPlateIdAndCoordinates(db, standardPlate.getId(), coords.getLeft(), coords.getRight()); if (well == null) { System.err.format("Unable to find standard well at %s [%s]\n", standardPlate.getBarcode(), stringCoords); continue; } standardWells.add(well); foundCoordinates.add(stringCoords); } System.out.format("Using explicitly specified standard wells %s [%s]\n", standardPlate.getBarcode(), StringUtils.join(foundCoordinates, ", ")); } else if (cl.hasOption(OPTION_STANDARD_NAME)) { String standardName = cl.getOptionValue(OPTION_STANDARD_NAME); System.out.format("Using explicitly specified standard %s\n", standardName); standardWells = Collections.singletonList(Utils.extractStandardWellFromPlate(db, cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE), standardName)); } else if (standardChemicals != null && standardChemicals.size() > 0) { // Default to using the target chemical(s) as a standard if none is specified. standardWells = new ArrayList<>(standardChemicals.size()); for (CuratedChemical c : standardChemicals) { String standardName = c.getName(); System.out.format("Searching for well containing standard %s\n", standardName); standardWells.add(Utils.extractStandardWellFromPlate(db, cl.getOptionValue(OPTION_STANDARD_PLATE_BARCODE), standardName)); } } boolean useFineGrainedMZ = cl.hasOption("fine-grained-mz"); boolean useSNR = cl.hasOption(OPTION_USE_SNR); /* Process the standard, positive, and negative wells, producing ScanData containers that will allow them to be * iterated over for graph writing. */ HashMap<Integer, Plate> plateCache = new HashMap<>(); Pair<List<ScanData<StandardWell>>, Double> allStandardScans = AnalysisHelper.processScans(db, lcmsDir, searchMZs, ScanData.KIND.STANDARD, plateCache, standardWells, useFineGrainedMZ, includeIons, excludeIons, useSNR); Pair<List<ScanData<LCMSWell>>, Double> allPositiveScans = AnalysisHelper.processScans(db, lcmsDir, searchMZs, ScanData.KIND.POS_SAMPLE, plateCache, positiveWells, useFineGrainedMZ, includeIons, excludeIons, useSNR); Pair<List<ScanData<LCMSWell>>, Double> allNegativeScans = AnalysisHelper.processScans(db, lcmsDir, searchMZs, ScanData.KIND.NEG_CONTROL, plateCache, negativeWells, useFineGrainedMZ, includeIons, excludeIons, useSNR); String fmt = "pdf"; String outImg = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + "." + fmt; String outData = cl.getOptionValue(OPTION_OUTPUT_PREFIX) + ".data"; System.err.format("Writing combined scan data to %s and graphs to %s\n", outData, outImg); produceLCMSSearchPlots(lcmsDir, outData, outImg, allStandardScans, allPositiveScans, allNegativeScans, fontScale, useFineGrainedMZ, cl.hasOption(OPTION_USE_HEATMAP), useSNR); } }
From source file:ViewImageTest.java
/** * Test image(s) (default : JPEG_example_JPG_RIP_100.jpg) are parsed and * rendered to an output foler. Result can then be checked with program of * your choice.//w ww . j a va2s . co m * * @param args * may be empty or contain parameters to override defaults : * <ul> * <li>args[0] : input image file URL or folder containing image * files URL. Default : * viewImageTest/test/JPEG_example_JPG_RIP_100.jpg</li> * <li>args[1] : output format name (for example : "jpg") for * rendered image</li> * <li>args[2] : ouput folder URL</li> * <li>args[3] : max width (in pixels) for rendered image. * Default : no value.</li> * <li>args[4] : max height (in pixels) for rendered image. * Default : no value.</li> * </ul> * @throws IOException * when a read/write error occured */ public static void main(String args[]) throws IOException { File inURL = getInputURL(args); String ext = getEncodingExt(args); File outDir = getOuputDir(args); serverObjects post = makePostParams(args); outDir.mkdirs(); File[] inFiles; if (inURL.isFile()) { inFiles = new File[1]; inFiles[0] = inURL; System.out.println("Testing ViewImage rendering with input file : " + inURL.getAbsolutePath() + " encoded To : " + ext); } else if (inURL.isDirectory()) { FileFilter filter = FileFileFilter.FILE; inFiles = inURL.listFiles(filter); System.out.println("Testing ViewImage rendering with input files in folder : " + inURL.getAbsolutePath() + " encoded To : " + ext); } else { inFiles = new File[0]; } if (inFiles.length == 0) { throw new IllegalArgumentException(inURL.getAbsolutePath() + " is not a valid file or folder url."); } System.out.println("Rendered images will be written in dir : " + outDir.getAbsolutePath()); Map<String, Exception> failures = new HashMap<String, Exception>(); try { for (File inFile : inFiles) { /* Delete eventual previous result file */ File outFile = new File(outDir, inFile.getName() + "." + ext); if (outFile.exists()) { outFile.delete(); } byte[] resourceb = getBytes(inFile); String urlString = inFile.getAbsolutePath(); EncodedImage img = null; Exception error = null; try { img = ViewImage.parseAndScale(post, true, urlString, ext, false, resourceb); } catch (Exception e) { error = e; } if (img == null) { failures.put(urlString, error); } else { FileOutputStream outFileStream = null; try { outFileStream = new FileOutputStream(outFile); img.getImage().writeTo(outFileStream); } finally { if (outFileStream != null) { outFileStream.close(); } img.getImage().close(); } } } displayResults(inFiles, failures); } finally { ConcurrentLog.shutdown(); } }