List of usage examples for java.util List size
int size();
From source file:asl.seedscan.SeedScan.java
public static void main(String args[]) { // Default locations of config and schema files File configFile = new File("config.xml"); File schemaFile = new File("schemas/SeedScanConfig.xsd"); boolean parseConfig = true; ArrayList<File> schemaFiles = new ArrayList<File>(); schemaFiles.add(schemaFile);//from ww w . j a v a 2 s . c o m // ==== Command Line Parsing ==== Options options = new Options(); Option opConfigFile = new Option("c", "config-file", true, "The config file to use for seedscan. XML format according to SeedScanConfig.xsd."); Option opSchemaFile = new Option("s", "schema-file", true, "The xsd schema file which should be used to verify the config file format. "); OptionGroup ogConfig = new OptionGroup(); ogConfig.addOption(opConfigFile); OptionGroup ogSchema = new OptionGroup(); ogConfig.addOption(opSchemaFile); options.addOptionGroup(ogConfig); options.addOptionGroup(ogSchema); PosixParser optParser = new PosixParser(); CommandLine cmdLine = null; try { cmdLine = optParser.parse(options, args, true); } catch (org.apache.commons.cli.ParseException e) { logger.error("Error while parsing command-line arguments."); System.exit(1); } Option opt; Iterator<?> iter = cmdLine.iterator(); while (iter.hasNext()) { opt = (Option) iter.next(); if (opt.getOpt().equals("c")) { configFile = new File(opt.getValue()); } else if (opt.getOpt().equals("s")) { schemaFile = new File(opt.getValue()); } } // ==== Configuration Read and Parse Actions ==== ConfigParser parser = new ConfigParser(schemaFiles); ConfigT config = parser.parseConfig(configFile); // Print out configuration file contents Formatter formatter = new Formatter(new StringBuilder(), Locale.US); // ===== CONFIG: LOCK FILE ===== File lockFile = new File(config.getLockfile()); logger.info("SeedScan lock file is '" + lockFile + "'"); LockFile lock = new LockFile(lockFile); if (!lock.acquire()) { logger.error("Could not acquire lock."); System.exit(1); } // ===== CONFIG: LOGGING ===== // MTH: This is now done in log4j.properties file // ===== CONFIG: DATABASE ===== MetricDatabase readDB = new MetricDatabase(config.getDatabase()); MetricDatabase writeDB = new MetricDatabase(config.getDatabase()); MetricReader reader = new MetricReader(readDB); MetricInjector injector = new MetricInjector(writeDB); // ===== CONFIG: SCANS ===== Hashtable<String, Scan> scans = new Hashtable<String, Scan>(); if (config.getScans().getScan() == null) { logger.error("No scans in configuration."); System.exit(1); } else { for (ScanT scanCfg : config.getScans().getScan()) { String name = scanCfg.getName(); if (scans.containsKey(name)) { logger.error("Duplicate scan name '" + name + "' encountered."); System.exit(1); } // This should really be handled by jaxb by setting it up in schemas/SeedScanConfig.xsd if (scanCfg.getStartDay() == null && scanCfg.getStartDate() == null) { logger.error( "== SeedScan Error: Must set EITHER cfg:start_day -OR- cfg:start_date in config.xml to start Scan!"); System.exit(1); } // Configure this Scan Scan scan = new Scan(scanCfg.getName()); scan.setPathPattern(scanCfg.getPath()); scan.setDatalessDir(scanCfg.getDatalessDir()); scan.setEventsDir(scanCfg.getEventsDir()); scan.setPlotsDir(scanCfg.getPlotsDir()); scan.setDaysToScan(scanCfg.getDaysToScan().intValue()); if (scanCfg.getStartDay() != null) { scan.setStartDay(scanCfg.getStartDay().intValue()); } if (scanCfg.getStartDate() != null) { scan.setStartDate(scanCfg.getStartDate().intValue()); } if (scanCfg.getNetworkSubset() != null) { logger.debug("Filter on Network Subset=[{}]", scanCfg.getNetworkSubset()); Filter filter = new Filter(false); for (String network : scanCfg.getNetworkSubset().split(",")) { logger.debug("Network =[{}]", network); filter.addFilter(network); } scan.setNetworks(filter); } if (scanCfg.getStationSubset() != null) { logger.debug("Filter on Station Subset=[{}]", scanCfg.getStationSubset()); Filter filter = new Filter(false); for (String station : scanCfg.getStationSubset().split(",")) { logger.debug("Station =[{}]", station); filter.addFilter(station); } scan.setStations(filter); } if (scanCfg.getLocationSubset() != null) { logger.debug("Filter on Location Subset=[{}]", scanCfg.getLocationSubset()); Filter filter = new Filter(false); for (String location : scanCfg.getLocationSubset().split(",")) { logger.debug("Location =[{}]", location); filter.addFilter(location); } scan.setLocations(filter); } if (scanCfg.getChannelSubset() != null) { logger.debug("Filter on Channel Subset=[{}]", scanCfg.getChannelSubset()); Filter filter = new Filter(false); for (String channel : scanCfg.getChannelSubset().split(",")) { logger.debug("Channel =[{}]", channel); filter.addFilter(channel); } scan.setChannels(filter); } for (MetricT met : scanCfg.getMetrics().getMetric()) { try { Class<?> metricClass = Class.forName(met.getClassName()); MetricWrapper wrapper = new MetricWrapper(metricClass); for (ArgumentT arg : met.getArgument()) { wrapper.add(arg.getName(), arg.getValue()); } scan.addMetric(wrapper); } catch (ClassNotFoundException ex) { logger.error("No such metric class '" + met.getClassName() + "'"); System.exit(1); } catch (InstantiationException ex) { logger.error("Could not dynamically instantiate class '" + met.getClassName() + "'"); System.exit(1); } catch (IllegalAccessException ex) { logger.error("Illegal access while loading class '" + met.getClassName() + "'"); System.exit(1); } catch (NoSuchFieldException ex) { logger.error("Invalid dynamic argument to Metric subclass '" + met.getClassName() + "'"); System.exit(1); } } scans.put(name, scan); } } // ==== Establish Database Connection ==== // TODO: State Tracking in the Database // - Record scan started in database. // - Track our progress as we go so a new process can pick up where // we left off if our process dies. // - Mark when each date-station-channel-operation is complete //LogDatabaseHandler logDB = new LogDatabaseHandler(configuration.get // For each day ((yesterday - scanDepth) to yesterday) // scan for these channel files, only process them if // they have not yet been scanned, or if changes have // occurred to the file since its last scan. Do this for // each scan type. Do not re-scan data for each type, // launch processes for each scan and use the same data set // for each. If we can pipe the data as it is read, do so. // If we need to push all of it at once, do these in sequence // in order to preserve overall system memory resources. Scan scan = null; // ==== Perform Scans ==== scan = scans.get("daily"); //MTH: This part could/should be moved up higher except that we need to know datalessDir, which, // at this point, is configured on a per scan basis ... so we need to know what scan we're doing MetaServer metaServer = null; if (config.getMetaserver() != null) { if (config.getMetaserver().getUseRemote().equals("yes") || config.getMetaserver().getUseRemote().equals("true")) { String remoteServer = config.getMetaserver().getRemoteUri(); try { metaServer = new MetaServer(new URI(remoteServer)); } catch (Exception e) { logger.error("caught URI exception:" + e.getMessage()); } } else { metaServer = new MetaServer(scan.getDatalessDir()); } } else { // Use local MetaServer metaServer = new MetaServer(scan.getDatalessDir()); } List<Station> stations = null; if (config.getStationList() == null) { // get StationList from MetaServer logger.info("Get StationList from MetaServer"); stations = metaServer.getStationList(); } else { // read StationList from config.xml logger.info("Read StationList from config.xml"); List<String> stationList = config.getStationList().getStation(); if (stationList.size() > 0) { stations = new ArrayList<Station>(); for (String station : stationList) { String[] words = station.split("_"); if (words.length != 2) { logger.warn(String.format("stationList: station=[%s] is NOT a valid station --> Skip", station)); } else { stations.add(new Station(words[0], words[1])); logger.info("config.xml: Read station:" + station); } } } else { logger.error("Error: No valid stations read from config.xml"); } } if (stations == null) { logger.error("Found NO stations to scan --> EXITTING SeedScan"); System.exit(1); } Thread readerThread = new Thread(reader); readerThread.start(); logger.info("Reader thread started."); Thread injectorThread = new Thread(injector); injectorThread.start(); logger.info("Injector thread started."); // Loop over scans and hand each one to a ScanManager logger.info("Hand scan to ScanManager"); for (String key : scans.keySet()) { scan = scans.get(key); logger.info(String.format("Scan=[%s] startDay=%d startDate=%d daysToScan=%d\n", key, scan.getStartDay(), scan.getStartDate(), scan.getDaysToScan())); ScanManager scanManager = new ScanManager(reader, injector, stations, scan, metaServer); } logger.info("ScanManager is [ FINISHED ] --> stop the injector and reader threads"); try { injector.halt(); logger.info("All stations processed. Waiting for injector thread to finish..."); synchronized (injectorThread) { //injectorThread.wait(); injectorThread.interrupt(); } logger.info("Injector thread halted."); } catch (InterruptedException ex) { logger.warn("The injector thread was interrupted while attempting to complete requests."); } try { reader.halt(); logger.info("All stations processed. Waiting for reader thread to finish..."); synchronized (readerThread) { //readerThread.wait(); readerThread.interrupt(); } logger.info("Reader thread halted."); } catch (InterruptedException ex) { logger.warn("The reader thread was interrupted while attempting to complete requests."); } try { lock.release(); } catch (IOException e) { ; } finally { logger.info("Release seedscan lock and quit metaServer"); lock = null; metaServer.quit(); } }
From source file:de.unisb.cs.st.javaslicer.jung.ShowJungGraph.java
public static void main(String[] args) throws InterruptedException { Options options = createOptions();//from www. j a v a2 s .c o m CommandLineParser parser = new GnuParser(); CommandLine cmdLine; try { cmdLine = parser.parse(options, args, true); } catch (ParseException e) { System.err.println("Error parsing the command line arguments: " + e.getMessage()); return; } if (cmdLine.hasOption('h')) { printHelp(options, System.out); System.exit(0); } String[] additionalArgs = cmdLine.getArgs(); if (additionalArgs.length != 2) { printHelp(options, System.err); System.exit(-1); } File traceFile = new File(additionalArgs[0]); String slicingCriterionString = additionalArgs[1]; Long threadId = null; if (cmdLine.hasOption('t')) { try { threadId = Long.parseLong(cmdLine.getOptionValue('t')); } catch (NumberFormatException e) { System.err.println("Illegal thread id: " + cmdLine.getOptionValue('t')); System.exit(-1); } } TraceResult trace; try { trace = TraceResult.readFrom(traceFile); } catch (IOException e) { System.err.format("Could not read the trace file \"%s\": %s%n", traceFile, e); System.exit(-1); return; } List<SlicingCriterion> sc = null; try { sc = StaticSlicingCriterion.parseAll(slicingCriterionString, trace.getReadClasses()); } catch (IllegalArgumentException e) { System.err.println("Error parsing slicing criterion: " + e.getMessage()); System.exit(-1); return; } List<ThreadId> threads = trace.getThreads(); if (threads.size() == 0) { System.err.println("The trace file contains no tracing information."); System.exit(-1); } ThreadId tracing = null; for (ThreadId t : threads) { if (threadId == null) { if ("main".equals(t.getThreadName()) && (tracing == null || t.getJavaThreadId() < tracing.getJavaThreadId())) tracing = t; } else if (t.getJavaThreadId() == threadId.longValue()) { tracing = t; } } if (tracing == null) { System.err.println(threadId == null ? "Couldn't find the main thread." : "The thread you specified was not found."); System.exit(-1); return; } Transformer<InstructionInstance, Object> transformer; Transformer<Object, String> vertexLabelTransformer; Transformer<Object, String> vertexTooltipTransformer; String granularity = cmdLine.getOptionValue("granularity"); if (granularity == null || "instance".equals(granularity)) { transformer = new Transformer<InstructionInstance, Object>() { @Override public InstructionInstance transform(InstructionInstance inst) { return inst; } }; vertexLabelTransformer = new Transformer<Object, String>() { @Override public String transform(Object inst) { return getShortInstructionText(((InstructionInstance) inst).getInstruction()); } }; vertexTooltipTransformer = new Transformer<Object, String>() { @Override public String transform(Object inst) { return getInstructionTooltip(((InstructionInstance) inst).getInstruction()); } }; } else if ("instruction".equals(granularity)) { transformer = new Transformer<InstructionInstance, Object>() { @Override public Instruction transform(InstructionInstance inst) { return inst.getInstruction(); } }; vertexLabelTransformer = new Transformer<Object, String>() { @Override public String transform(Object inst) { return getShortInstructionText(((Instruction) inst)); } }; vertexTooltipTransformer = new Transformer<Object, String>() { @Override public String transform(Object inst) { return getInstructionTooltip(((Instruction) inst)); } }; } else if ("line".equals(granularity)) { transformer = new Transformer<InstructionInstance, Object>() { @Override public Line transform(InstructionInstance inst) { return new Line(inst.getInstruction().getMethod(), inst.getInstruction().getLineNumber()); } }; vertexLabelTransformer = new Transformer<Object, String>() { @Override public String transform(Object inst) { Line line = (Line) inst; return line.getMethod().getName() + ":" + line.getLineNr(); } }; vertexTooltipTransformer = new Transformer<Object, String>() { @Override public String transform(Object inst) { Line line = (Line) inst; return "Line " + line.getLineNr() + " in method " + line.getMethod().getReadClass().getName() + "." + line.getMethod(); } }; } else { System.err.println("Illegal granularity specification: " + granularity); System.exit(-1); return; } int maxLevel = Integer.MAX_VALUE; if (cmdLine.hasOption("maxlevel")) { try { maxLevel = Integer.parseInt(cmdLine.getOptionValue("maxlevel")); } catch (NumberFormatException e) { System.err.println("Argument to \"maxlevel\" must be an integer."); System.exit(-1); return; } } long startTime = System.nanoTime(); ShowJungGraph<Object> showGraph = new ShowJungGraph<Object>(trace, transformer); showGraph.setMaxLevel(maxLevel); showGraph.setVertexLabelTransformer(vertexLabelTransformer); showGraph.setVertexTooltipTransformer(vertexTooltipTransformer); if (cmdLine.hasOption("progress")) showGraph.addProgressMonitor(new ConsoleProgressMonitor()); boolean multithreaded; if (cmdLine.hasOption("multithreaded")) { String multithreadedStr = cmdLine.getOptionValue("multithreaded"); multithreaded = ("1".equals(multithreadedStr) || "true".equals(multithreadedStr)); } else { multithreaded = Runtime.getRuntime().availableProcessors() > 1; } DirectedGraph<Object, SliceEdge<Object>> graph = showGraph.getGraph(tracing, sc, multithreaded); long endTime = System.nanoTime(); System.out.format((Locale) null, "%nSlice graph consists of %d nodes.%n", graph.getVertexCount()); System.out.format((Locale) null, "Computation took %.2f seconds.%n", 1e-9 * (endTime - startTime)); showGraph.displayGraph(graph); }
From source file:sdmx.net.service.insee.INSEERESTQueryable.java
public static void main(String args[]) { INSEERESTQueryable registry = new INSEERESTQueryable("FR1", "http://www.bdm.insee.fr/series/sdmx"); List<DataflowType> dfs = registry.listDataflows(); for (int i = 0; i < dfs.size(); i++) { System.out.println(dfs.get(i).getName()); }// w ww . jav a 2 s . c o m registry.find(dfs.get(0).getStructure()).dump(); }
From source file:com.doculibre.constellio.utils.license.ApplyLicenseUtils.java
/** * @param args/*from w ww . j a v a 2s.c o m*/ */ @SuppressWarnings("unchecked") public static void main(String[] args) throws Exception { URL licenceHeaderURL = ApplyLicenseUtils.class.getResource("LICENSE_HEADER"); File binDir = ClasspathUtils.getClassesDir(); File projectDir = binDir.getParentFile(); // File dryrunDir = new File(projectDir, "dryrun"); File licenceFile = new File(licenceHeaderURL.toURI()); List<String> licenceLines = readLines(licenceFile); // for (int i = 0; i < licenceLines.size(); i++) { // String licenceLine = licenceLines.get(i); // licenceLines.set(i, " * " + licenceLine); // } // licenceLines.add(0, "/**"); // licenceLines.add(" */"); List<File> javaFiles = (List<File>) org.apache.commons.io.FileUtils.listFiles(projectDir, new String[] { "java" }, true); for (File javaFile : javaFiles) { if (isValidPackage(javaFile)) { List<String> javaFileLines = readLines(javaFile); if (!javaFileLines.isEmpty()) { boolean modified = false; String firstLineTrim = javaFileLines.get(0).trim(); if (firstLineTrim.startsWith("package")) { modified = true; javaFileLines.addAll(0, licenceLines); } else if (firstLineTrim.startsWith("/**")) { int indexOfEndCommentLine = -1; loop2: for (int i = 0; i < javaFileLines.size(); i++) { String javaFileLine = javaFileLines.get(i); if (javaFileLine.indexOf("*/") != -1) { indexOfEndCommentLine = i; break loop2; } } if (indexOfEndCommentLine != -1) { modified = true; int i = 0; loop3: for (Iterator<String> it = javaFileLines.iterator(); it.hasNext();) { it.next(); if (i <= indexOfEndCommentLine) { it.remove(); } else { break loop3; } i++; } javaFileLines.addAll(0, licenceLines); } else { throw new RuntimeException( "Missing end comment for file " + javaFile.getAbsolutePath()); } } if (modified) { // String outputFilePath = javaFile.getPath().substring(projectDir.getPath().length()); // File outputFile = new File(dryrunDir, outputFilePath); // outputFile.getParentFile().mkdirs(); // System.out.println(outputFile.getPath()); // FileOutputStream fos = new FileOutputStream(outputFile); System.out.println(javaFile.getPath()); FileOutputStream fos = new FileOutputStream(javaFile); IOUtils.writeLines(javaFileLines, "\n", fos); IOUtils.closeQuietly(fos); } } } } }
From source file:de.unisb.cs.st.javaslicer.traceResult.TraceResult.java
public static void main(final String[] args) { Options options = createOptions();//from www . j a v a 2 s . c om CommandLineParser parser = new GnuParser(); CommandLine cmdLine; try { cmdLine = parser.parse(options, args, true); } catch (ParseException e) { System.err.println("Error parsing the command line arguments: " + e.getMessage()); return; } if (cmdLine.hasOption('h')) { printHelp(options, System.out); System.exit(0); } InstanceFilter<InstructionInstance> filter; if (cmdLine.hasOption("filter")) { if ("labels".equals(cmdLine.getOptionValue("filter"))) { filter = InstanceFilter.LabelFilter.instance; } else if ("additionals".equals(cmdLine.getOptionValue("filter"))) { filter = InstanceFilter.AdditionalLabelFilter.instance; } else if ("none".equals(cmdLine.getOptionValue("filter"))) { filter = null; } else { System.err.println("Illegal argument for filter: " + cmdLine.getOptionValue("filter")); return; } } else { // default: filter = InstanceFilter.AdditionalLabelFilter.instance; } String[] additionalArgs = cmdLine.getArgs(); if (additionalArgs.length != 1) { System.err.println("Error: No input file given."); printHelp(options, System.err); System.exit(-1); } final File traceFile = new File(additionalArgs[0]); Long threadToTrace = null; if (cmdLine.hasOption('t')) { try { threadToTrace = Long.parseLong(cmdLine.getOptionValue('t')); } catch (final NumberFormatException e) { System.err.println("Illegal thread id: " + cmdLine.getOptionValue('t')); System.exit(-1); } } System.out.println("Opening and reading trace file..."); TraceResult tr = null; try { tr = readFrom(traceFile); } catch (final IOException e) { System.err.println("Error opening trace file: " + e); System.exit(-1); return; } final List<ThreadId> threads = tr.getThreads(); if (threads.size() == 0) { System.err.println("The trace file contains no tracing information."); System.exit(-1); } System.out.println("The trace file contains traces for these threads:"); ThreadId tracing = null; for (final ThreadId t : threads) { if (threadToTrace == null) { if ("main".equals(t.getThreadName()) && (tracing == null || t.getJavaThreadId() < tracing.getJavaThreadId())) tracing = t; } else if (t.getJavaThreadId() == threadToTrace.longValue()) { tracing = t; } System.out.format("%15d: %s%n", t.getJavaThreadId(), t.getThreadName()); } System.out.println(); if (tracing == null) { System.out.println(threadToTrace == null ? "Couldn't find a main thread." : "The thread you selected was not found."); System.exit(-1); return; } System.out.println(threadToTrace == null ? "Selected:" : "You selected:"); System.out.format("%15d: %s%n", tracing.getJavaThreadId(), tracing.getThreadName()); try { if (cmdLine.hasOption("length")) { final BackwardTraceIterator<AbstractInstructionInstance> it = tr.getBackwardIterator(tracing, filter, new AbstractInstructionInstanceFactory()); ProgressMonitor monitor = null; if (cmdLine.hasOption("--progress")) { monitor = new ConsoleProgressMonitor(System.out, "Computing trace length", true, 100, true, true); monitor.start(it); } try { while (it.hasNext()) it.next(); } finally { if (monitor != null) monitor.end(); } System.out.format( "%nNumber of instructions: %d (+ %d additional = %d total instructions)%nReady%n", it.getNumInstructions(), it.getNumFilteredInstructions(), it.getNumInstructions() + it.getNumFilteredInstructions()); } else { System.out.println(); System.out.println("The backward trace:"); BackwardTraceIterator<AbstractInstructionInstance> it = tr.getBackwardIterator(tracing, filter, new AbstractInstructionInstanceFactory()); long nr = 0; String format = "%8d (%8d) %-100s -> %3d %7d %s%n"; System.out.format("%19s %-100s %3s %7s %s%n", "Nr ( intern)", "Location", "Dep", "OccNr", "Instruction"); while (it.hasNext()) { InstructionInstance inst = it.next(); ReadMethod method = inst.getInstruction().getMethod(); ReadClass class0 = method.getReadClass(); System.out.format(format, nr++, inst.getInstanceNr(), class0.getName() + "." + method.getName() + ":" + inst.getInstruction().getLineNumber(), inst.getStackDepth(), inst.getOccurrenceNumber(), inst.toString()); } System.out.format( "%nNumber of instructions: %d (+ %d additional = %d total instructions)%nReady%n", it.getNumInstructions(), it.getNumFilteredInstructions(), it.getNumInstructions() + it.getNumFilteredInstructions()); } } catch (final TracerException e) { System.err.print("Error while tracing: "); e.printStackTrace(System.err); System.exit(-1); } }
From source file:com.acapulcoapp.alloggiatiweb.FileReader.java
public static void main(String[] args) throws UnknownHostException, IOException { // TODO code application logic here SpringApplication app = new SpringApplication(AcapulcoappApp.class); SimpleCommandLinePropertySource source = new SimpleCommandLinePropertySource(args); addDefaultProfile(app, source);//w ww.ja va 2 s. com ConfigurableApplicationContext context = app.run(args); initBeans(context); Map<LocalDate, List<List<String>>> map = new TreeMap<>(); List<File> files = new ArrayList<>(FileUtils.listFiles(new File("/Users/chiccomask/Downloads/ALLOGGIATI"), new String[] { "txt" }, true)); Collections.reverse(files); int count = 0; for (File file : files) { // List<String> allLines = FileUtils.readLines(file, "windows-1252"); List<String> allLines = FileUtils.readLines(file, "UTF-8"); for (int i = 0; i < allLines.size();) { count++; List<String> record = new ArrayList<>(); String line = allLines.get(i); String type = TIPO_ALLOGGIO.parse(line); switch (type) { case "16": record.add(line); i++; break; case "17": { record.add(line); boolean out = false; while (!out) { i++; if (i < allLines.size()) { String subline = allLines.get(i); String subtype = TIPO_ALLOGGIO.parse(subline); if (!subtype.equals("19")) { out = true; } else { record.add(subline); } } else { out = true; } } break; } case "18": { record.add(line); boolean out = false; while (!out) { i++; if (i < allLines.size()) { String subline = allLines.get(i); String subtype = TIPO_ALLOGGIO.parse(subline); if (!subtype.equals("20")) { out = true; } else { record.add(subline); } } else { out = true; } } break; } default: break; } LocalDate arrived = LocalDate.parse(DATA_ARRIVO.parse(line), DateTimeFormatter.ofPattern(DATE_PATTERN)); if (!map.containsKey(arrived)) { map.put(arrived, new ArrayList<>()); } map.get(arrived).add(record); } } for (LocalDate date : map.keySet()) { System.out.println(); System.out.println("process day " + date); for (List<String> record : map.get(date)) { System.out.println(); System.out.println("process record "); for (String line : record) { System.out.println(line); } CheckinRecord checkinRecord = new CheckinRecord(); //non lo setto per adesso String firstLine = record.get(0); String typeStr = TIPO_ALLOGGIO.parse(firstLine); CheckinType cht = checkinTypeRepository.find(typeStr); checkinRecord.setCheckinType(cht); int days = Integer.parseInt(PERMANENZA.parse(firstLine)); checkinRecord.setDays(days); checkinRecord.setArrived(date); boolean isMain = true; List<Person> others = new ArrayList<>(); for (String line : record) { Person p = extractPerson(line); if (p.getDistrictOfBirth() == null) { System.out.println("district of birth not found " + p); } List<Person> duplicates = personRepository.findDuplicates(p.getSurname(), p.getName(), p.getDateOfBirth()); if (duplicates.isEmpty()) { System.out.println("add new person " + p.getId() + " " + p); personRepository.saveAndFlush(p); } else if (duplicates.size() == 1) { Person found = duplicates.get(0); if (p.getIdentityDocument() != null) { //we sorted by date so we suppose //the file version is newer so we update the entity p.setId(found.getId()); System.out.println("update person " + p.getId() + " " + p); personRepository.saveAndFlush(p); } else if (found.getIdentityDocument() != null) { //on db there are more data so I use them. p = found; System.out.println("use already saved person " + p.getId() + " " + p); } else { p.setId(found.getId()); System.out.println("update person " + p.getId() + " " + p); personRepository.saveAndFlush(p); } } else { throw new RuntimeException("More duplicated for " + p.getName()); } if (isMain) { checkinRecord.setMainPerson(p); isMain = false; } else { others.add(p); } } checkinRecord.setOtherPeople(new HashSet<>(others)); if (checkinRecordRepository.alreadyExists(checkinRecord.getMainPerson(), date) != null) { System.out.println("already exists " + date + " p " + checkinRecord.getMainPerson()); } else { System.out.println("save record "); checkinRecordRepository.saveAndFlush(checkinRecord); } } } // // if (type.equals("16")) { // List<String> record = new ArrayList<>(); // record.add(line); // keepOpen = false; // } // // map.get(arrived).add(record); // map.values().forEach((list) -> { // // for (String line : list) { // // Person p = null; // // try { // // p = extractPerson(line); // // List<Person> duplicates = personRepository.findDuplicates(p.getSurname(), p.getName(), p.getDateOfBirth()); // // if (duplicates.isEmpty()) { // personRepository.saveAndFlush(p); // // } else if (duplicates.size() > 1) { // System.out.println(); // System.out.println("MULIPLE DUPLICATED"); // // for (Person dd : duplicates) { // System.out.println(dd); // } // System.out.println("* " + p); // throw new RuntimeException(); // } else { // //// if (!duplicates.get(0).getDistrictOfBirth().equals(p.getDistrictOfBirth())) { //// int index = 0; //// //// System.out.println(); //// System.out.println("DUPLICATED"); //// //// for (Person dd : duplicates) { //// System.out.println(dd); //// index++; //// } //// System.out.println("* " + p); //// System.out.println(file.getAbsolutePath() + " " + p); //// //// System.out.println(); //// System.out.println(); //// } //// duplicates.remove(0); //// personRepository.deleteInBatch(duplicates); //// System.out.println(); //// System.out.println("Seleziona scelta"); //// Scanner s = new Scanner(System.in); //// int selected; //// try { //// selected = s.nextInt(); //// } catch (InputMismatchException e) { //// selected = 0; //// } //// //// if (duplicates.size() <= selected) { //// personRepository.deleteInBatch(duplicates); //// personRepository.saveAndFlush(p); //// } else { //// duplicates.remove(selected); //// personRepository.deleteInBatch(duplicates); //// } // } // // } catch (Exception e) { // // System.out.println(); //// System.out.println("ERROR READING lineCount=" + allLines.indexOf(line) + " line=" + line); //// System.out.println(file.getAbsolutePath()); // System.out.println(p); // e.printStackTrace(); // System.out.println(); // } // } // }); context.registerShutdownHook(); System.exit(0); }
From source file:edu.monash.merc.system.version.DSVCombination.java
public static void main(String[] args) { //testing//from ww w . j a v a 2s .c o m List<DSVersionTrack> nxVersionTracks = new ArrayList<DSVersionTrack>(); DSVersionTrack nxDsVersionTrack1 = new DSVersionTrack(); nxDsVersionTrack1.setTrackToken("1"); DSVersionTrack nxDsVersionTrack2 = new DSVersionTrack(); nxDsVersionTrack2.setTrackToken("0"); nxVersionTracks.add(nxDsVersionTrack1); nxVersionTracks.add(nxDsVersionTrack2); List<DSVersionTrack> gpmVersionTracks = new ArrayList<DSVersionTrack>(); DSVersionTrack gpmDsVersionTrack1 = new DSVersionTrack(); gpmDsVersionTrack1.setTrackToken("1"); DSVersionTrack gpmDsVersionTrack2 = new DSVersionTrack(); gpmDsVersionTrack2.setTrackToken("0"); gpmVersionTracks.add(gpmDsVersionTrack1); gpmVersionTracks.add(gpmDsVersionTrack2); DSVersion gpmPstyDsVersion = new DSVersion(); gpmPstyDsVersion.setDbSource(DbAcType.GPMPSYT.type()); gpmPstyDsVersion.setVersionNo(1); DSVersion gpmLysDsVersion = new DSVersion(); gpmLysDsVersion.setDbSource(DbAcType.GPMLYS.type()); gpmLysDsVersion.setVersionNo(3); DSVersion gpmNtaDsVersion = new DSVersion(); gpmNtaDsVersion.setDbSource(DbAcType.GPMNTA.type()); gpmNtaDsVersion.setVersionNo(6); List<DSVersionTrack> hpaVersionTracks = new ArrayList<DSVersionTrack>(); DSVersionTrack hpaDsVersionTrack2 = new DSVersionTrack(); hpaDsVersionTrack2.setTrackToken("1"); hpaVersionTracks.add(hpaDsVersionTrack2); DSVersionTrack hpaDsVersionTrack1 = new DSVersionTrack(); hpaDsVersionTrack1.setTrackToken("0"); hpaVersionTracks.add(hpaDsVersionTrack1); List<DSVersionTrack> bcVersionTracks = new ArrayList<DSVersionTrack>(); DSVersionTrack bcDsVersionTrack2 = new DSVersionTrack(); bcDsVersionTrack2.setTrackToken("1"); bcVersionTracks.add(bcDsVersionTrack2); DSVersionTrack bcDsVersionTrack1 = new DSVersionTrack(); bcDsVersionTrack1.setTrackToken("0"); bcVersionTracks.add(bcDsVersionTrack1); DSVersion bcHgu133aDsVersion = new DSVersion(); bcHgu133aDsVersion.setDbSource(DbAcType.BarcodeHgu133a.type()); bcHgu133aDsVersion.setVersionNo(1); DSVersion bcHgu133p2DsVersion = new DSVersion(); bcHgu133p2DsVersion.setDbSource(DbAcType.BarcodeHgu133plus2.type()); bcHgu133p2DsVersion.setVersionNo(10); List<TLVersionTrack> tlVersionTracks = DSVCombination.createTLVersionTracks(nxVersionTracks, gpmVersionTracks, gpmPstyDsVersion, gpmLysDsVersion, gpmNtaDsVersion, hpaVersionTracks, bcVersionTracks, bcHgu133aDsVersion, bcHgu133p2DsVersion); System.out.println("=========> total combination: " + tlVersionTracks.size()); if (tlVersionTracks != null) { for (TLVersionTrack tlVTrack : tlVersionTracks) { int trackToken = tlVTrack.getTrackToken(); System.out.println("======> DSVersion combinated token: " + trackToken); System.out.println("=========== > nx included? : " + tlVTrack.isNxDsIncluded()); System.out.println("=========== > barcode included? : " + tlVTrack.isBcDsIncluded()); } } System.out.println("==============> Another testing case:"); DSVersion nxDsVersion = new DSVersion(); DSVersion gpmDsVersion = null; DSVersion hpaDsVersion = null; bcHgu133aDsVersion = null; bcHgu133p2DsVersion = null; List<TLVersionTrack> tlVersionTracks2 = DSVCombination.createTLVersionTracks(nxDsVersion, gpmDsVersion, gpmPstyDsVersion, gpmLysDsVersion, gpmNtaDsVersion, hpaDsVersion, bcHgu133aDsVersion, bcHgu133p2DsVersion); System.out.println("=========> a total combination: " + tlVersionTracks2.size()); if (tlVersionTracks2 != null) { for (TLVersionTrack tlVTrack : tlVersionTracks2) { int trackToken = tlVTrack.getTrackToken(); System.out.println("======> DSVersion combinated token: " + trackToken); DSVersion gpmpstyV = tlVTrack.getGpmPstyDsVersion(); if (tlVTrack.isGpmDsIncluded() && gpmpstyV != null) { System.out.println("======> GpmPsty dbsource: " + tlVTrack.getGpmPstyDsVersion().getDbSource() + ", version: " + gpmpstyV.getVersionNo()); } DSVersion gpmLysV = tlVTrack.getGpmLysDsVersion(); if (tlVTrack.isGpmDsIncluded() && gpmLysV != null) { System.out.println("======> Gpm Lys dbsource: " + tlVTrack.getGpmLysDsVersion().getDbSource() + ", version: " + gpmLysV.getVersionNo()); } DSVersion gpmNtaV = tlVTrack.getGpmNtaDsVersion(); if (tlVTrack.isGpmDsIncluded() && gpmNtaV != null) { System.out.println("======> Gpm Nta dbsource: " + tlVTrack.getGpmNtaDsVersion().getDbSource() + ", version: " + gpmNtaV.getVersionNo()); } boolean bcDsIncluded = tlVTrack.isBcDsIncluded(); if (bcDsIncluded) { DSVersion bcHgu133aV = tlVTrack.getBcHgu133aDsVersion(); if (bcHgu133aV != null) { System.out.println("======> Barcode HGU 133a dbsource: " + bcHgu133aV.getDbSource() + ", version: " + bcHgu133aV.getVersionNo()); } DSVersion bcHgu133p2V = tlVTrack.getBcHgu133p2DsVersion(); if (bcHgu133p2V != null) { System.out.println("======> Barcode HGU 133plus2 dbsource: " + bcHgu133p2V.getDbSource() + ", version: " + bcHgu133p2V.getVersionNo()); } } } } }
From source file:com.act.lcms.db.io.PrintConstructInfo.java
public static void main(String[] args) throws Exception { Options opts = new Options(); for (Option.Builder b : OPTION_BUILDERS) { opts.addOption(b.build());/*from www .j a v a 2s .co 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); } try (DB db = DB.openDBFromCLI(cl)) { System.out.print("Loading/updating LCMS scan files into DB\n"); ScanFile.insertOrUpdateScanFilesInDirectory(db, lcmsDir); String construct = cl.getOptionValue(OPTION_CONSTRUCT); List<LCMSWell> lcmsWells = LCMSWell.getInstance().getByConstructID(db, construct); Collections.sort(lcmsWells, new Comparator<LCMSWell>() { @Override public int compare(LCMSWell o1, LCMSWell o2) { return o1.getId().compareTo(o2.getId()); } }); Set<String> uniqueMSIDs = new HashSet<>(); Map<Integer, Plate> platesById = new HashMap<>(); System.out.format("\n\n-- Construct %s --\n\n", construct); List<ChemicalAssociatedWithPathway> pathwayChems = ChemicalAssociatedWithPathway.getInstance() .getChemicalsAssociatedWithPathwayByConstructId(db, construct); System.out.print("Chemicals associated with pathway:\n"); System.out.format(" %-8s%-15s%-45s\n", "index", "kind", "chemical"); for (ChemicalAssociatedWithPathway chem : pathwayChems) { System.out.format(" %-8d%-15s%-45s\n", chem.getIndex(), chem.getKind(), chem.getChemical()); } System.out.print("\nLCMS wells:\n"); System.out.format(" %-15s%-6s%-15s%-15s%-15s\n", "barcode", "well", "msid", "fed", "lcms_count"); for (LCMSWell well : lcmsWells) { uniqueMSIDs.add(well.getMsid()); Plate p = platesById.get(well.getPlateId()); if (p == null) { // TODO: migrate Plate to be a subclass of BaseDBModel. p = Plate.getPlateById(db, well.getPlateId()); platesById.put(p.getId(), p); } String chem = well.getChemical(); List<ScanFile> scanFiles = ScanFile.getScanFileByPlateIDRowAndColumn(db, p.getId(), well.getPlateRow(), well.getPlateColumn()); System.out.format(" %-15s%-6s%-15s%-15s%-15d\n", p.getBarcode(), well.getCoordinatesString(), well.getMsid(), chem == null || chem.isEmpty() ? "--" : chem, scanFiles.size()); System.out.flush(); } List<Integer> plateIds = Arrays.asList(platesById.keySet().toArray(new Integer[platesById.size()])); Collections.sort(plateIds); System.out.print("\nAppears in plates:\n"); for (Integer id : plateIds) { Plate p = platesById.get(id); System.out.format(" %s: %s\n", p.getBarcode(), p.getName()); } List<String> msids = Arrays.asList(uniqueMSIDs.toArray(new String[uniqueMSIDs.size()])); Collections.sort(msids); System.out.format("\nMSIDS: %s\n", StringUtils.join(msids, ", ")); Set<String> availableNegativeControls = new HashSet<>(); for (Map.Entry<Integer, Plate> entry : platesById.entrySet()) { List<LCMSWell> wells = LCMSWell.getInstance().getByPlateId(db, entry.getKey()); for (LCMSWell well : wells) { if (!construct.equals(well.getComposition())) { availableNegativeControls.add(well.getComposition()); } } } // Print available standards for each step w/ plate barcodes and coordinates. System.out.format("\nAvailable Standards:\n"); Map<Integer, Plate> plateCache = new HashMap<>(); for (ChemicalAssociatedWithPathway chem : pathwayChems) { List<StandardWell> matchingWells = StandardWell.getInstance().getStandardWellsByChemical(db, chem.getChemical()); for (StandardWell well : matchingWells) { if (!plateCache.containsKey(well.getPlateId())) { Plate p = Plate.getPlateById(db, well.getPlateId()); plateCache.put(p.getId(), p); } } Map<Integer, List<StandardWell>> standardWellsByPlateId = new HashMap<>(); for (StandardWell well : matchingWells) { List<StandardWell> plateWells = standardWellsByPlateId.get(well.getPlateId()); if (plateWells == null) { plateWells = new ArrayList<>(); standardWellsByPlateId.put(well.getPlateId(), plateWells); } plateWells.add(well); } List<Pair<String, Integer>> plateBarcodes = new ArrayList<>(plateCache.size()); for (Plate p : plateCache.values()) { if (p.getBarcode() == null) { plateBarcodes.add(Pair.of("(no barcode)", p.getId())); } else { plateBarcodes.add(Pair.of(p.getBarcode(), p.getId())); } } Collections.sort(plateBarcodes); System.out.format(" %s:\n", chem.getChemical()); for (Pair<String, Integer> barcodePair : plateBarcodes) { // TODO: hoist this whole sorting/translation step into a utility class. List<StandardWell> wells = standardWellsByPlateId.get(barcodePair.getRight()); if (wells == null) { // Don't print plates that don't apply to this chemical, which can happen because we're caching the plates. continue; } Collections.sort(wells, new Comparator<StandardWell>() { @Override public int compare(StandardWell o1, StandardWell o2) { int c = o1.getPlateRow().compareTo(o2.getPlateRow()); if (c != 0) return c; return o1.getPlateColumn().compareTo(o2.getPlateColumn()); } }); List<String> descriptions = new ArrayList<>(wells.size()); for (StandardWell well : wells) { descriptions.add(String.format("%s in %s%s", well.getCoordinatesString(), well.getMedia(), well.getConcentration() == null ? "" : String.format(" c. %f", well.getConcentration()))); } System.out.format(" %s: %s\n", barcodePair.getLeft(), StringUtils.join(descriptions, ", ")); } } List<String> negativeControlStrains = Arrays .asList(availableNegativeControls.toArray(new String[availableNegativeControls.size()])); Collections.sort(negativeControlStrains); System.out.format("\nAvailable negative controls: %s\n", StringUtils.join(negativeControlStrains, ",")); System.out.print("\n----------\n"); System.out.print("\n\n"); } }
From source file:com.music.tools.ScaleTester.java
public static void main(String[] args) { System.out.println(//from w w w. java 2 s .c o m "Usage: java ScaleTester <fundamental frequency> <chromatic scale size> <scale size> <use ET>"); final AudioFormat af = new AudioFormat(sampleRate, 16, 1, true, true); try { fundamentalFreq = getArgument(args, 0, FUNDAMENTAL_FREQUENCY, Double.class); int pitchesInChromaticScale = getArgument(args, 1, CHROMATIC_SCALE_SILZE, Integer.class); List<Double> harmonicFrequencies = new ArrayList<>(); List<String> ratios = new ArrayList<>(); Set<Double> frequencies = new HashSet<Double>(); frequencies.add(fundamentalFreq); int octaveMultiplier = 2; for (int i = 2; i < 100; i++) { // Exclude the 7th harmonic TODO exclude the 11th as well? // http://www.phy.mtu.edu/~suits/badnote.html if (i % 7 == 0) { continue; } double actualFreq = fundamentalFreq * i; double closestTonicRatio = actualFreq / (fundamentalFreq * octaveMultiplier); if (closestTonicRatio < 1 || closestTonicRatio > 2) { octaveMultiplier *= 2; } double closestTonic = actualFreq - actualFreq % (fundamentalFreq * octaveMultiplier); double normalizedFreq = fundamentalFreq * (actualFreq / closestTonic); harmonicFrequencies.add(actualFreq); frequencies.add(normalizedFreq); if (frequencies.size() == pitchesInChromaticScale) { break; } } System.out.println("Harmonic (overtone) frequencies: " + harmonicFrequencies); System.out.println("Transposed harmonic frequencies: " + frequencies); List<Double> chromaticScale = new ArrayList<>(frequencies); Collections.sort(chromaticScale); // find the "perfect" interval (e.g. perfect fifth) int perfectIntervalIndex = 0; int idx = 0; for (Iterator<Double> it = chromaticScale.iterator(); it.hasNext();) { Double noteFreq = it.next(); long[] fraction = findCommonFraction(noteFreq / fundamentalFreq); fractionCache.put(noteFreq, fraction); if (fraction[0] == 3 && fraction[1] == 2) { perfectIntervalIndex = idx; System.out.println("Perfect interval (3/2) idx: " + perfectIntervalIndex); } idx++; ratios.add(Arrays.toString(fraction)); } System.out.println("Ratios to fundemental frequency: " + ratios); if (getBooleanArgument(args, 4, USE_ET)) { chromaticScale = temper(chromaticScale); } System.out.println(); System.out.println("Chromatic scale: " + chromaticScale); Set<Double> scaleSet = new HashSet<Double>(); scaleSet.add(chromaticScale.get(0)); idx = 0; List<Double> orderedInCircle = new ArrayList<>(); // now go around the circle of perfect intervals and put the notes // in order while (orderedInCircle.size() < chromaticScale.size()) { orderedInCircle.add(chromaticScale.get(idx)); idx += perfectIntervalIndex; idx = idx % chromaticScale.size(); } System.out.println("Pitches Ordered in circle of perfect intervals: " + orderedInCircle); List<Double> scale = new ArrayList<Double>(scaleSet); int currentIdxInCircle = orderedInCircle.size() - 1; // start with // the last // note in the // circle int scaleSize = getArgument(args, 3, SCALE_SIZE, Integer.class); while (scale.size() < scaleSize) { double pitch = orderedInCircle.get(currentIdxInCircle % orderedInCircle.size()); if (!scale.contains(pitch)) { scale.add(pitch); } currentIdxInCircle++; } Collections.sort(scale); System.out.println("Scale: " + scale); SourceDataLine line = AudioSystem.getSourceDataLine(af); line.open(af); line.start(); Double[] scaleFrequencies = scale.toArray(new Double[scale.size()]); // first play the whole scale WaveMelodyGenerator.playScale(line, scaleFrequencies); // then generate a random melody in the scale WaveMelodyGenerator.playMelody(line, scaleFrequencies); line.drain(); line.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.meidusa.venus.benchmark.FileLineRandomData.java
public static void main(String[] args) throws Exception { final FileLineRandomData mapping = new FileLineRandomData(); mapping.setFile(new File("./role.txt")); mapping.init();/* w w w .ja v a 2s . c o m*/ List<Thread> list = new ArrayList<Thread>(); long start = TimeUtil.currentTimeMillis(); for (int j = 0; j < 1; j++) { Thread thread = new Thread() { public void run() { for (int i = 0; i < 1000; i++) { System.out.println(((String[]) mapping.nextData())[1]); } } }; list.add(thread); thread.start(); } for (int i = 0; i < list.size(); i++) { list.get(i).join(); } System.out.println("time=" + (TimeUtil.currentTimeMillis() - start)); }