List of usage examples for java.lang String isEmpty
public boolean isEmpty()
From source file:co.turnus.analysis.buffers.MpcBoundedSchedulingCliLauncher.java
public static void main(String[] args) { try {/* w w w.j a va2 s. c om*/ CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(cliOptions, args); Configuration config = parseCommandLine(cmd); // init models AnalysisActivator.init(); // set logger verbosity if (config.getBoolean(VERBOSE, false)) { TurnusLogger.setLevel(TurnusLevel.ALL); } File tDir = new File(config.getString(TRACE_PROJECT)); TraceProject project = TraceProject.load(tDir); MpcBoundedScheduling mpc = new MpcBoundedScheduling(project); mpc.setConfiguration(config); BufferMinimizationData data = mpc.run(); TurnusLogger.info("Storing results..."); File outPath = new File(config.getString(OUTPUT_PATH)); // store the analysis report String uuid = UUID.randomUUID().toString(); File rFile = new File(outPath, uuid + "." + TurnusExtension.REPORT); Report report = DataFactory.eINSTANCE.createReport(); report.setDate(new Date()); report.setComment("Report with only Bounded Buffer Scheduling results analysis"); report.getDataSet().add(data); EcoreHelper.storeEObject(report, new ResourceSetImpl(), rFile); TurnusLogger.info("TURNUS report stored in " + rFile); // store formatted reports String xlsName = config.getString(XLS, ""); if (!xlsName.isEmpty()) { File xlsFile = new File(outPath, xlsName + ".xls"); new XlsBufferMinimizationDataWriter().write(data, xlsFile); TurnusLogger.info("XLS report stored in " + xlsFile); } String bxdfName = config.getString(BXDF, ""); if (!bxdfName.isEmpty()) { File bxdfFile = new File(outPath, bxdfName + ".bxdf"); new XmlBufferMinimizationDataWriter().write(data, bxdfFile); TurnusLogger.info("BXDF files (one for each configuration) " + "stored in " + outPath); } TurnusLogger.info("Analysis Done!"); } catch (ParseException e) { TurnusLogger.error(e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(AlgorithmicBottlenecksCliLauncher.class.getSimpleName(), cliOptions); } catch (Exception e) { TurnusLogger.error(e.getMessage()); } }
From source file:ca.ualberta.exemplar.core.Exemplar.java
public static void main(String[] rawArgs) throws FileNotFoundException, UnsupportedEncodingException { CommandLineParser cli = new BasicParser(); Options options = new Options(); options.addOption("h", "help", false, "shows this message"); options.addOption("b", "benchmark", true, "expects input to be a benchmark file (type = binary | nary)"); options.addOption("p", "parser", true, "defines which parser to use (parser = stanford | malt)"); CommandLine line = null;/* w w w .jav a 2 s . com*/ try { line = cli.parse(options, rawArgs); } catch (ParseException exp) { System.err.println(exp.getMessage()); System.exit(1); } String[] args = line.getArgs(); String parserName = line.getOptionValue("parser", "malt"); if (line.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("sh ./exemplar", options); System.exit(0); } if (args.length != 2) { System.out.println("error: exemplar requires an input file and output file."); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("sh ./exemplar <input> <output>", options); System.exit(0); } File input = new File(args[0]); File output = new File(args[1]); String benchmarkType = line.getOptionValue("benchmark", ""); if (!benchmarkType.isEmpty()) { if (benchmarkType.equals("binary")) { BenchmarkBinary evaluation = new BenchmarkBinary(input, output, parserName); evaluation.runAndTime(); System.exit(0); } else { if (benchmarkType.equals("nary")) { BenchmarkNary evaluation = new BenchmarkNary(input, output, parserName); evaluation.runAndTime(); System.exit(0); } else { System.out.println("error: benchmark option has to be either 'binary' or 'nary'."); System.exit(0); } } } Parser parser = null; if (parserName.equals("stanford")) { parser = new ParserStanford(); } else { if (parserName.equals("malt")) { parser = new ParserMalt(); } else { System.out.println(parserName + " is not a valid parser."); System.exit(0); } } System.out.println("Starting EXEMPLAR..."); RelationExtraction exemplar = null; try { exemplar = new RelationExtraction(parser); } catch (FileNotFoundException e) { e.printStackTrace(); } BlockingQueue<String> inputQueue = new ArrayBlockingQueue<String>(QUEUE_SIZE); PlainTextReader reader = null; reader = new PlainTextReader(inputQueue, input); Thread readerThread = new Thread(reader); readerThread.start(); PrintStream statementsOut = null; try { statementsOut = new PrintStream(output, "UTF-8"); } catch (FileNotFoundException e1) { e1.printStackTrace(); System.exit(0); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); System.exit(0); } statementsOut.println("Subjects\tRelation\tObjects\tNormalized Relation\tSentence"); while (true) { String doc = null; try { doc = inputQueue.take(); } catch (InterruptedException e) { e.printStackTrace(); } if (doc.isEmpty()) { break; } List<RelationInstance> instances = exemplar.extractRelations(doc); for (RelationInstance instance : instances) { // Output SUBJ arguments in a separate field, for clarity boolean first = true; for (Argument arg : instance.getArguments()) { if (arg.argumentType.equals("SUBJ")) { if (first) { first = false; } else { statementsOut.print(",,"); } statementsOut.print(arg.argumentType + ":" + arg.entityId); } } // Output the original relation statementsOut.print("\t" + instance.getOriginalRelation() + "\t"); // Output the DOBJ arguments, followed by POBJ first = true; for (Argument arg : instance.getArguments()) { if (arg.argumentType.equals("DOBJ")) { if (first) { first = false; } else { statementsOut.print(",,"); } statementsOut.print(arg.argumentType + ":" + arg.entityId); } } for (Argument arg : instance.getArguments()) { if (arg.argumentType.startsWith("POBJ")) { if (first) { first = false; } else { statementsOut.print(",,"); } statementsOut.print(arg.argumentType + ":" + arg.entityId); } } statementsOut.print("\t" + instance.getNormalizedRelation()); statementsOut.print("\t" + instance.getSentence()); statementsOut.println(); } } System.out.println("Done!"); statementsOut.close(); }
From source file:edu.cmu.lti.oaqa.knn4qa.apps.LuceneIndexer.java
public static void main(String[] args) { Options options = new Options(); options.addOption(CommonParams.ROOT_DIR_PARAM, null, true, CommonParams.ROOT_DIR_DESC); options.addOption(CommonParams.SUB_DIR_TYPE_PARAM, null, true, CommonParams.SUB_DIR_TYPE_DESC); options.addOption(CommonParams.MAX_NUM_REC_PARAM, null, true, CommonParams.MAX_NUM_REC_DESC); options.addOption(CommonParams.SOLR_FILE_NAME_PARAM, null, true, CommonParams.SOLR_FILE_NAME_DESC); options.addOption(CommonParams.OUT_INDEX_PARAM, null, true, CommonParams.OUT_MINDEX_DESC); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); try {// ww w .j a v a2s . c om CommandLine cmd = parser.parse(options, args); String rootDir = null; rootDir = cmd.getOptionValue(CommonParams.ROOT_DIR_PARAM); if (null == rootDir) Usage("Specify: " + CommonParams.ROOT_DIR_DESC, options); String outputDirName = cmd.getOptionValue(CommonParams.OUT_INDEX_PARAM); if (null == outputDirName) Usage("Specify: " + CommonParams.OUT_MINDEX_DESC, options); String subDirTypeList = cmd.getOptionValue(CommonParams.SUB_DIR_TYPE_PARAM); if (null == subDirTypeList || subDirTypeList.isEmpty()) Usage("Specify: " + CommonParams.SUB_DIR_TYPE_DESC, options); String solrFileName = cmd.getOptionValue(CommonParams.SOLR_FILE_NAME_PARAM); if (null == solrFileName) Usage("Specify: " + CommonParams.SOLR_FILE_NAME_DESC, options); int maxNumRec = Integer.MAX_VALUE; String tmp = cmd.getOptionValue(CommonParams.MAX_NUM_REC_PARAM); if (tmp != null) { try { maxNumRec = Integer.parseInt(tmp); if (maxNumRec <= 0) { Usage("The maximum number of records should be a positive integer", options); } } catch (NumberFormatException e) { Usage("The maximum number of records should be a positive integer", options); } } File outputDir = new File(outputDirName); if (!outputDir.exists()) { if (!outputDir.mkdirs()) { System.out.println("couldn't create " + outputDir.getAbsolutePath()); System.exit(1); } } if (!outputDir.isDirectory()) { System.out.println(outputDir.getAbsolutePath() + " is not a directory!"); System.exit(1); } if (!outputDir.canWrite()) { System.out.println("Can't write to " + outputDir.getAbsolutePath()); System.exit(1); } String subDirs[] = subDirTypeList.split(","); int docNum = 0; // No English analyzer here, all language-related processing is done already, // here we simply white-space tokenize and index tokens verbatim. Analyzer analyzer = new WhitespaceAnalyzer(); FSDirectory indexDir = FSDirectory.open(outputDir); IndexWriterConfig indexConf = new IndexWriterConfig(analyzer.getVersion(), analyzer); System.out.println("Creating a new Lucene index, maximum # of docs to process: " + maxNumRec); indexConf.setOpenMode(OpenMode.CREATE); IndexWriter indexWriter = new IndexWriter(indexDir, indexConf); for (int subDirId = 0; subDirId < subDirs.length && docNum < maxNumRec; ++subDirId) { String inputFileName = rootDir + "/" + subDirs[subDirId] + "/" + solrFileName; System.out.println("Input file name: " + inputFileName); BufferedReader inpText = new BufferedReader( new InputStreamReader(CompressUtils.createInputStream(inputFileName))); String docText = XmlHelper.readNextXMLIndexEntry(inpText); for (; docText != null && docNum < maxNumRec; docText = XmlHelper.readNextXMLIndexEntry(inpText)) { ++docNum; Map<String, String> docFields = null; Document luceneDoc = new Document(); try { docFields = XmlHelper.parseXMLIndexEntry(docText); } catch (Exception e) { System.err.println(String.format("Parsing error, offending DOC #%d:\n%s", docNum, docText)); System.exit(1); } String id = docFields.get(UtilConst.TAG_DOCNO); if (id == null) { System.err.println(String.format("No ID tag '%s', offending DOC #%d:\n%s", UtilConst.TAG_DOCNO, docNum, docText)); } luceneDoc.add(new StringField(UtilConst.TAG_DOCNO, id, Field.Store.YES)); for (Map.Entry<String, String> e : docFields.entrySet()) if (!e.getKey().equals(UtilConst.TAG_DOCNO)) { luceneDoc.add(new TextField(e.getKey(), e.getValue(), Field.Store.YES)); } indexWriter.addDocument(luceneDoc); if (docNum % 1000 == 0) System.out.println("Indexed " + docNum + " docs"); } System.out.println("Indexed " + docNum + " docs"); } indexWriter.commit(); indexWriter.close(); } catch (ParseException e) { Usage("Cannot parse arguments", options); } catch (Exception e) { System.err.println("Terminating due to an exception: " + e); System.exit(1); } }
From source file:bookChapter.theoretical.AnalyzeTheoreticalMSMSCalculation.java
/** * * @param args/*from w w w . j a va 2 s. c om*/ * @throws IOException * @throws FileNotFoundException * @throws ClassNotFoundException * @throws InterruptedException * @throws MzMLUnmarshallerException */ public static void main(String[] args) throws IOException, FileNotFoundException, ClassNotFoundException, IOException, InterruptedException, MzMLUnmarshallerException { Logger l = Logger.getLogger("AnalyzeTheoreticalMSMSCalculation"); Date date = Calendar.getInstance().getTime(); DateFormat formatter = new SimpleDateFormat("EEEE, dd MMMM yyyy, hh:mm:ss.SSS a"); String now = formatter.format(date); l.log(Level.INFO, "Calculation starts at {0}", now); double precursorTolerance = ConfigHolder.getInstance().getDouble("precursor.tolerance"), fragmentTolerance = ConfigHolder.getInstance().getDouble("fragment.tolerance"); String databaseName = ConfigHolder.getInstance().getString("database.name"), spectraName = ConfigHolder.getInstance().getString("spectra.name"), output = ConfigHolder.getInstance().getString("output"); int correctionFactor = ConfigHolder.getInstance().getInt("correctionFactor"); boolean theoFromAllCharges = ConfigHolder.getInstance().getBoolean("hasAllPossCharge"); BufferedWriter bw = new BufferedWriter(new FileWriter(output)); bw.write("SpectrumTitle" + "\t" + "PrecursorMZ" + "\t" + "PrecursorCharge" + "\t" + "Observed Mass (M+H)" + "\t" + "AndromedaLikeScore" + "\t" + "SequestLikeScore" + "\t" + "PeptideByAndromedaLikeScore" + "\t" + "PeptideBySequestLikeScore" + "\t" + "LevenshteinDistance" + "\t" + "TotalScoredPeps" + "\t" + "isCorrectMatchByAndromedaLike" + "\t" + "isCorrectMatchBySequestLikeScore" + "\n"); l.info("Getting database entries"); // first load all sequences into the memory HashSet<DBEntry> dbEntries = getDBEntries(databaseName); // for every spectrum-calculate both score... // now convert to binExperimental spectrum int num = 0; SpectrumFactory fct = SpectrumFactory.getInstance(); num = 0; File f = new File(spectraName); if (spectraName.endsWith(".mgf")) { fct.addSpectra(f, new WaitingHandlerCLIImpl()); l.log(Level.INFO, "Spectra scoring starts at {0}", now); for (String title : fct.getSpectrumTitles(f.getName())) { num++; MSnSpectrum ms = (MSnSpectrum) fct.getSpectrum(f.getName(), title); // here calculate all except this is an empty spectrum... if (ms.getPeakList().size() > 2) { // to check a spectrum with negative values.. String text = result(ms, precursorTolerance, dbEntries, fragmentTolerance, correctionFactor, theoFromAllCharges); if (!text.isEmpty()) { bw.write(text); } } if (num % 500 == 0) { l.info("Running " + num + " spectra." + Calendar.getInstance().getTime()); } } } l.info("Program finished at " + Calendar.getInstance().getTime()); bw.close(); }
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 ww w.jav a 2s. c om 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:com.crushpaper.Main.java
public static void main(String[] args) throws IOException { Options options = new Options(); options.addOption("help", false, "print this message"); options.addOption("properties", true, "file system path to the crushpaper properties file"); // Parse the command line. CommandLineParser parser = new BasicParser(); CommandLine commandLine = null;//from w w w . j a v a 2 s . co m try { commandLine = parser.parse(options, args); } catch (ParseException e) { System.err.println("crushpaper: Sorry, could not parse command line because `" + e.getMessage() + "`."); System.exit(1); } if (commandLine == null || commandLine.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("crushpaper", options); return; } // Get the properties path. String properties = null; if (commandLine.hasOption("properties")) { properties = commandLine.getOptionValue("properties"); } if (properties == null || properties.isEmpty()) { System.err.println("crushpaper: Sorry, the `properties` command argument must be specified."); System.exit(1); } Configuration configuration = new Configuration(); if (!configuration.load(new File(properties))) { System.exit(1); } // Get values. File databaseDirectory = configuration.getDatabaseDirectory(); File keyStorePath = configuration.getKeyStoreFile(); Integer httpPort = configuration.getHttpPort(); Integer httpsPort = configuration.getHttpsPort(); Integer httpsProxiedPort = configuration.getHttpsProxiedPort(); String keyStorePassword = configuration.getKeyStorePassword(); String keyManagerPassword = configuration.getKeyManagerPassword(); File temporaryDirectory = configuration.getTemporaryDirectory(); String singleUserName = configuration.getSingleUserName(); Boolean allowSelfSignUp = configuration.getAllowSelfSignUp(); Boolean allowSaveIfNotSignedIn = configuration.getAllowSaveIfNotSignedIn(); File logDirectory = configuration.getLogDirectory(); Boolean loopbackIsAdmin = configuration.getLoopbackIsAdmin(); File sessionStoreDirectory = configuration.getSessionStoreDirectory(); Boolean isOfficialSite = configuration.getIsOfficialSite(); File extraHeaderFile = configuration.getExtraHeaderFile(); // Validate the values. if (httpPort != null && httpsPort != null && httpPort.equals(httpsPort)) { System.err.println("crushpaper: Sorry, `" + configuration.getHttpPortKey() + "` and `" + configuration.getHttpsPortKey() + "` must not be set to the same value."); System.exit(1); } if ((httpsPort == null) != (keyStorePath == null)) { System.err.println("crushpaper: Sorry, `" + configuration.getHttpsPortKey() + "` and `" + configuration.getKeyStoreKey() + "` must either both be set or not set."); System.exit(1); } if (httpsProxiedPort != null && httpsPort == null) { System.err.println("crushpaper: Sorry, `" + configuration.getHttpsProxiedPortKey() + "` can only be set if `" + configuration.getHttpsPortKey() + "` is set."); System.exit(1); } if (databaseDirectory == null) { System.err.println("crushpaper: Sorry, `" + configuration.getDatabaseDirectoryKey() + "` must be set."); System.exit(1); } if (singleUserName != null && !AccountAttributeValidator.isUserNameValid(singleUserName)) { System.err.println( "crushpaper: Sorry, the username in `" + configuration.getSingleUserKey() + "` is not valid."); return; } if (allowSelfSignUp == null || allowSaveIfNotSignedIn == null || loopbackIsAdmin == null) { System.exit(1); } String extraHeader = null; if (extraHeaderFile != null) { extraHeader = readFile(extraHeaderFile); if (extraHeader == null) { System.err.println("crushpaper: Sorry, the file `" + extraHeaderFile.getPath() + "` set in `" + configuration.getExtraHeaderKey() + "` could not be read."); System.exit(1); } } final DbLogic dbLogic = new DbLogic(databaseDirectory); dbLogic.createDb(); final Servlet servlet = new Servlet(dbLogic, singleUserName, allowSelfSignUp, allowSaveIfNotSignedIn, loopbackIsAdmin, httpPort, httpsPort, httpsProxiedPort, keyStorePath, keyStorePassword, keyManagerPassword, temporaryDirectory, logDirectory, sessionStoreDirectory, isOfficialSite, extraHeader); servlet.run(); }
From source file:Main.java
public static void main(String[] args) { final DefaultListModel<String> model = new DefaultListModel<>(); final JList<String> list = new JList<>(model); JFrame f = new JFrame(); model.addElement("A"); model.addElement("B"); model.addElement("C"); model.addElement("D"); model.addElement("E"); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); JPanel leftPanel = new JPanel(); JPanel rightPanel = new JPanel(); leftPanel.setLayout(new BorderLayout()); rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS)); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); list.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { int index = list.locationToIndex(e.getPoint()); Object item = model.getElementAt(index); String text = JOptionPane.showInputDialog("Rename item", item); String newitem = ""; if (text != null) newitem = text.trim(); else return; if (!newitem.isEmpty()) { model.remove(index); model.add(index, newitem); ListSelectionModel selmodel = list.getSelectionModel(); selmodel.setLeadSelectionIndex(index); }//from w ww .j av a 2 s . co m } } }); leftPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); leftPanel.add(new JScrollPane(list)); JButton removeall = new JButton("Remove All"); JButton add = new JButton("Add"); JButton rename = new JButton("Rename"); JButton delete = new JButton("Delete"); add.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String text = JOptionPane.showInputDialog("Add a new item"); String item = null; if (text != null) item = text.trim(); else return; if (!item.isEmpty()) model.addElement(item); } }); delete.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { ListSelectionModel selmodel = list.getSelectionModel(); int index = selmodel.getMinSelectionIndex(); if (index >= 0) model.remove(index); } }); rename.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ListSelectionModel selmodel = list.getSelectionModel(); int index = selmodel.getMinSelectionIndex(); if (index == -1) return; Object item = model.getElementAt(index); String text = JOptionPane.showInputDialog("Rename item", item); String newitem = null; if (text != null) { newitem = text.trim(); } else return; if (!newitem.isEmpty()) { model.remove(index); model.add(index, newitem); } } }); removeall.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { model.clear(); } }); rightPanel.add(add); rightPanel.add(rename); rightPanel.add(delete); rightPanel.add(removeall); rightPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 20)); panel.add(leftPanel); panel.add(rightPanel); f.add(panel); f.setSize(350, 250); f.setLocationRelativeTo(null); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); }
From source file:List.java
public static void main(String[] args) { final DefaultListModel model = new DefaultListModel(); final JList list = new JList(model); JFrame f = new JFrame(); f.setTitle("JList models"); model.addElement("A"); model.addElement("B"); model.addElement("C"); model.addElement("D"); model.addElement("E"); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS)); JPanel leftPanel = new JPanel(); JPanel rightPanel = new JPanel(); leftPanel.setLayout(new BorderLayout()); rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS)); list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); list.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2)); list.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 2) { int index = list.locationToIndex(e.getPoint()); Object item = model.getElementAt(index); String text = JOptionPane.showInputDialog("Rename item", item); String newitem = ""; if (text != null) newitem = text.trim(); else return; if (!newitem.isEmpty()) { model.remove(index); model.add(index, newitem); ListSelectionModel selmodel = list.getSelectionModel(); selmodel.setLeadSelectionIndex(index); }//w w w. ja v a 2 s.c om } } }); leftPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20)); leftPanel.add(new JScrollPane(list)); JButton removeall = new JButton("Remove All"); JButton add = new JButton("Add"); JButton rename = new JButton("Rename"); JButton delete = new JButton("Delete"); add.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String text = JOptionPane.showInputDialog("Add a new item"); String item = null; if (text != null) item = text.trim(); else return; if (!item.isEmpty()) model.addElement(item); } }); delete.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { ListSelectionModel selmodel = list.getSelectionModel(); int index = selmodel.getMinSelectionIndex(); if (index >= 0) model.remove(index); } }); rename.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { ListSelectionModel selmodel = list.getSelectionModel(); int index = selmodel.getMinSelectionIndex(); if (index == -1) return; Object item = model.getElementAt(index); String text = JOptionPane.showInputDialog("Rename item", item); String newitem = null; if (text != null) { newitem = text.trim(); } else return; if (!newitem.isEmpty()) { model.remove(index); model.add(index, newitem); } } }); removeall.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { model.clear(); } }); rightPanel.add(add); rightPanel.add(rename); rightPanel.add(delete); rightPanel.add(removeall); rightPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 20)); panel.add(leftPanel); panel.add(rightPanel); f.add(panel); f.setSize(350, 250); f.setLocationRelativeTo(null); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setVisible(true); }
From source file:com.linkedin.databus2.client.util.DbusClientClusterUtil.java
/** * @param args/*from www.j a v a2s. c o m*/ * DbusClientClusterUtil -s <serverList> -n <namespace> -g <group> -d <dir> members * leader * keys * readSCN <key> * writeSCN <key> SCN [OFFSET] * remove <key> * readLastTS * writeLastTS TIMESTAMP */ public static void main(String[] args) { try { GnuParser cmdLineParser = new GnuParser(); Options options = new Options(); options.addOption("n", true, "Zookeeper namespace [/DatabusClient") .addOption("g", true, "Groupname [default-group-name] ") .addOption("d", true, "Shared directory name [shareddata] ") .addOption("s", true, "Zookeeper server list [localhost:2181] ").addOption("h", false, "help"); CommandLine cmdLineArgs = cmdLineParser.parse(options, args, false); if (cmdLineArgs.hasOption('h')) { usage(); System.exit(0); } String namespace = cmdLineArgs.getOptionValue('n'); if (namespace == null || namespace.isEmpty()) { namespace = "/DatabusClient"; } String groupname = cmdLineArgs.getOptionValue('g'); if (groupname == null || groupname.isEmpty()) { groupname = "default-group-name"; } String sharedDir = cmdLineArgs.getOptionValue('d'); if (sharedDir == null || sharedDir.isEmpty()) { sharedDir = "shareddata"; } String serverList = cmdLineArgs.getOptionValue('s'); if (serverList == null || serverList.isEmpty()) { serverList = "localhost:2181"; } String[] fns = cmdLineArgs.getArgs(); if (fns.length < 1) { usage(); System.exit(1); } String function = fns[0]; String arg1 = (fns.length > 1) ? fns[1] : null; String arg2 = (fns.length > 2) ? fns[2] : null; try { String memberName = "cmd-line-tool"; DatabusClientNode clusterNode = new DatabusClientNode(new DatabusClientNode.StaticConfig(true, serverList, 2000, 5000, namespace, groupname, memberName, false, sharedDir)); DatabusClientGroupMember member = clusterNode.getMember(namespace, groupname, memberName); if (member == null || !member.joinWithoutLeadershipDuties()) { System.err.println("Initialization failed for: " + member); System.exit(1); } if (function.equals("members")) { List<String> mlist = member.getMembers(); for (String m : mlist) { System.out.println(m); } } else if (function.equals("leader")) { String leader = member.getLeader(); System.out.println(leader); } else if (function.equals("keys")) { List<String> keyList = member.getSharedKeys(); if (keyList != null) { for (String m : keyList) { System.out.println(m); } } } else if (function.equals("readSCN")) { List<String> keyList; if (arg1 == null) { keyList = member.getSharedKeys(); } else { keyList = new ArrayList<String>(); keyList.add(arg1); } if (keyList != null) { for (String k : keyList) { if (!k.equals(DatabusClientDSCUpdater.DSCKEY)) { Checkpoint cp = (Checkpoint) member.readSharedData(k); if (cp != null) { System.out.println(k + " " + cp.getWindowScn() + " " + cp.getWindowOffset()); } else { System.err.println(k + " null null"); } } } } } else if (function.equals("writeSCN")) { if (arg1 != null && arg2 != null) { Checkpoint cp = new Checkpoint(); cp.setConsumptionMode(DbusClientMode.ONLINE_CONSUMPTION); cp.setWindowScn(Long.parseLong(arg2)); if (fns.length > 3) { cp.setWindowOffset(Integer.parseInt(fns[3])); } else { cp.setWindowOffset(-1); } if (member.writeSharedData(arg1, cp)) { System.out.println(arg1 + " " + cp.getWindowScn() + " " + cp.getWindowOffset()); } else { System.err.println("Write failed! " + member + " couldn't write key=" + arg1); System.exit(1); } } else { usage(); System.exit(1); } } else if (function.equals("readLastTs")) { Long timeInMs = (Long) member.readSharedData(DatabusClientDSCUpdater.DSCKEY); if (timeInMs != null) { System.out.println(DatabusClientDSCUpdater.DSCKEY + " " + timeInMs.longValue()); } else { System.err.println(DatabusClientDSCUpdater.DSCKEY + " null"); } } else if (function.equals("writeLastTs")) { if (arg1 != null) { Long ts = Long.parseLong(arg1); if (member.writeSharedData(DatabusClientDSCUpdater.DSCKEY, ts)) { System.out.println(DatabusClientDSCUpdater.DSCKEY + " " + ts); } else { System.err.println("Write failed! " + member + " couldn't write key=" + DatabusClientDSCUpdater.DSCKEY); System.exit(1); } } else { usage(); System.exit(1); } } else if (function.equals("remove")) { if (!member.removeSharedData(arg1)) { System.err.println("Remove failed! " + arg1); System.exit(1); } } else if (function.equals("create")) { if (!member.createPaths()) { System.err.println("Create path failed!"); System.exit(1); } } else { usage(); System.exit(1); } } catch (InvalidConfigException e) { e.printStackTrace(); usage(); System.exit(1); } } catch (ParseException e) { usage(); System.exit(1); } }
From source file:com.ibm.watson.app.common.tools.services.classifier.TrainClassifier.java
public static void main(String[] args) throws Exception { Option urlOption = createOption(URL_OPTION, URL_OPTION_LONG, true, "The absolute URL of the NL classifier service to connect to. If omitted, the default will be used (" + DEFAULT_URL + ")", false, "url"); Option usernameOption = createOption(USERNAME_OPTION, USERNAME_OPTION_LONG, true, "The username to use during authentication to the NL classifier service", true, "username"); Option passwordOption = createOption(PASSWORD_OPTION, PASSWORD_OPTION_LONG, true, "The password to use during authentication to the NL classifier service", true, "password"); Option fileOption = createOption(FILE_OPTION, FILE_OPTION_LONG, true, "The filepath to be used as training data", false, "file"); Option deleteOption = createOption(DELETE_OPTION, DELETE_OPTION_LONG, false, "If specified, the classifier instance will be deleted if training is not successful"); final Options options = buildOptions(urlOption, usernameOption, passwordOption, fileOption, deleteOption); CommandLine cmd;/*w w w.java 2s . c om*/ try { CommandLineParser parser = new GnuParser(); cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println(MessageKey.AQWEGA14016E_could_not_parse_cmd_line_args_1.getMessage(e.getMessage()) .getFormattedMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(120, "java " + TrainClassifier.class.getName(), null, options, null); return; } final String url = cmd.hasOption(URL_OPTION) ? cmd.getOptionValue(URL_OPTION) : DEFAULT_URL; final String username = cmd.getOptionValue(USERNAME_OPTION).trim(); final String password = cmd.getOptionValue(PASSWORD_OPTION).trim(); if (username.isEmpty() || password.isEmpty()) { throw new IllegalArgumentException( MessageKey.AQWEGA14014E_username_and_password_cannot_empty.getMessage().getFormattedMessage()); } final NLClassifierRestClient client = new NLClassifierRestClient(url, username, password); listClassifiers(client); System.out.println(MessageKey.AQWEGA10012I_h_help.getMessage().getFormattedMessage()); String userInput; boolean exit = false; NLClassifier classifier = null; boolean isTraining = false; if (cmd.hasOption(FILE_OPTION)) { // File option was specified, go directly to training classifier = train(client, cmd.getOptionValue(FILE_OPTION)); isTraining = true; } try (final Scanner scanner = new Scanner(System.in)) { while (!exit) { System.out.print("> "); userInput = scanner.nextLine().trim(); if (userInput.equals("q") || userInput.equals("quit") || userInput.equals("exit")) { exit = true; } else if (userInput.equals("h") || userInput.equals("help")) { printHelp(); } else if (userInput.equals("l") || userInput.equals("list")) { listClassifiers(client); } else if (userInput.equals("t") || userInput.equals("train")) { if (!isTraining) { System.out.print("Enter filename: "); String filename = scanner.nextLine().trim(); classifier = train(client, filename); isTraining = true; } else { System.err.println(MessageKey.AQWEGA10013I_t_cannot_used_during_training.getMessage() .getFormattedMessage()); } } else if (userInput.equals("s") || userInput.equals("status")) { if (isTraining) { exit = getStatus(client, classifier, cmd.hasOption(DELETE_OPTION)); } else { System.err.println(MessageKey.AQWEGA10014I_s_can_used_during_training.getMessage() .getFormattedMessage()); } } else if (userInput.equals("c") || userInput.equals("classify")) { if (classifier != null && classifier.getStatus().equals(Status.AVAILABLE)) { isTraining = false; System.out.print(MessageKey.AQWEGA10015I_text_classify.getMessage().getFormattedMessage()); String text = scanner.nextLine().trim(); classify(client, classifier, text); } else { System.err.println(MessageKey.AQWEGA10016I_c_can_used_after_training_has_completed .getMessage().getFormattedMessage()); } } else { System.err.println( MessageKey.AQWEGA14017E_unknown_command_1.getMessage(userInput).getFormattedMessage()); } Thread.sleep(100); // Give the out / err consoles time to battle it out before printing the command prompt } } }