List of usage examples for java.lang String isEmpty
public boolean isEmpty()
From source file:es.us.isa.ideas.utilities.HashPassword.java
public static void main(String[] args) throws IOException { Md5PasswordEncoder encoder;/*from w w w .j a v a 2 s .co m*/ InputStreamReader stream; BufferedReader reader; String line, hash; encoder = new Md5PasswordEncoder(); stream = new InputStreamReader(System.in); reader = new BufferedReader(stream); System.out.println("Enter passwords to be hashed or <ENTER> to quit"); line = reader.readLine(); while (!line.isEmpty()) { hash = encoder.encodePassword(line, null); System.out.println(hash); line = reader.readLine(); } }
From source file:co.turnus.analysis.partitioning.CommunicationCostPartitioningCli.java
public static void main(String[] args) { try {//from w w w . jav a2s . c o m CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(cliOptions, args); Configuration config = parseCommandLine(cmd); // init models AnalysisActivator.init(); // init models AnalysisActivator.init(); // set logger verbosity if (config.getBoolean(VERBOSE, false)) { TurnusLogger.setLevel(TurnusLevel.ALL); } // load trace project File tDir = new File(config.getString(TRACE_PROJECT)); TraceProject project = TraceProject.load(tDir); CommunicationCostPartitioning ccp = new CommunicationCostPartitioning(project); ccp.setConfiguration(config); PartitioningData data = ccp.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 Communication cost partitioning 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 XlsPartitioningDataWriter().write(data, xlsFile); TurnusLogger.info("XLS report stored in " + xlsFile); } String bxdfName = config.getString(XCF, ""); if (!bxdfName.isEmpty()) { File xcfFile = new File(outPath, bxdfName + ".xcf"); new XmlPartitioningDataWriter().write(data, xcfFile); TurnusLogger.info("XCF 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(CommunicationCostPartitioningCli.class.getSimpleName(), cliOptions); } catch (Exception e) { TurnusLogger.error(e.getMessage()); } }
From source file:co.turnus.analysis.buffers.BoundedBufferSchedulingCliLauncher.java
public static void main(String[] args) { try {//from w ww .j av a 2s.co m 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); BoundedBufferScheduling bbs = new BoundedBufferScheduling(project); bbs.setConfiguration(config); BufferMinimizationData data = bbs.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(BoundedBufferSchedulingCliLauncher.class.getSimpleName(), cliOptions); } catch (Exception e) { TurnusLogger.error(e.getCause().toString()); } }
From source file:co.turnus.analysis.bottlenecks.AlgorithmicBottlenecksCliLauncher.java
public static void main(String[] args) { try {/* w w w.j a v a 2s. c o m*/ 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); } // load trace project File tDir = new File(config.getString(TRACE_PROJECT)); TraceProject project = TraceProject.load(tDir); // load profiling weights File wFile = new File(config.getString(PROFILING_WEIGHTS)); ProfilingWeights weights = new XmlProfilingWeightsReader().read(project.getNetwork(), wFile); // build the trace weighter StatisticalTraceWeighter tw = new StatisticalTraceWeighter(); tw.configure(weights, ActionWeightsDistribution.class); // run the analysis AlgorithmicBottlenecks ab = new AlgorithmicBottlenecks(project, tw); ab.setConfiguration(config); AlgoBottlenecksData data = ab.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 Algorithmic Bottlenecks 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 XlsAlgoBottlenecksDataWriter().write(data, xlsFile); TurnusLogger.info("XLS report stored in " + xlsFile); } 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:org.biopax.validator.Main.java
public static void main(String[] args) throws Exception { setUpLogger();//from w w w . j a v a 2 s . co m if (args == null || args.length == 0) { log.warn("At least input file/dir must be specified."); printHelpAndQuit(); } String input = args[0]; if (input == null || input.isEmpty() || input.startsWith("--")) { log.warn("Input (file, url, or directory) is probably missing"); printHelpAndQuit(); } // match optional parameters for (int i = 1; i < args.length; i++) { if ("--auto-fix".equalsIgnoreCase(args[i])) { autofix = true; } else if (args[i].startsWith("--max-errors=")) { String n = args[i].substring(13); maxErrors = Integer.parseInt(n); } else if (args[i].startsWith("--profile=")) { profile = args[i].substring(10); } else if (args[i].startsWith("--xmlBase=")) { xmlBase = args[i].substring(10); } else if (args[i].startsWith("--output=")) { output = args[i].substring(9); } else if (args[i].startsWith("--out-format=")) { outFormat = args[i].substring(13); if (outFormat.isEmpty()) outFormat = "html"; } } // this does 90% of the job ;) ctx = new ClassPathXmlApplicationContext(new String[] { "META-INF/spring/appContext-loadTimeWeaving.xml", "META-INF/spring/appContext-validator.xml" }); // Rules are now loaded, and AOP is listening for BioPAX model method calls. // get the beans to work with Validator validator = (Validator) ctx.getBean("validator"); // go validate all runBatch(validator, getResourcesToValidate(input)); }
From source file:edu.cmu.lti.oaqa.annographix.apps.SolrQueryApp.java
public static void main(String[] args) { Options options = new Options(); options.addOption("u", null, true, "Solr URI"); options.addOption("q", null, true, "Query"); options.addOption("n", null, true, "Max # of results"); options.addOption("o", null, true, "An optional TREC-style output file"); options.addOption("w", null, false, "Do a warm-up query call, before each query"); CommandLineParser parser = new org.apache.commons.cli.GnuParser(); BufferedWriter trecOutFile = null; try {/*from ww w . j av a 2 s . c o m*/ CommandLine cmd = parser.parse(options, args); String queryFile = null, solrURI = null; if (cmd.hasOption("u")) { solrURI = cmd.getOptionValue("u"); } else { Usage("Specify Solr URI"); } SolrServerWrapper solr = new SolrServerWrapper(solrURI); if (cmd.hasOption("q")) { queryFile = cmd.getOptionValue("q"); } else { Usage("Specify Query file"); } int numRet = 100; if (cmd.hasOption("n")) { numRet = Integer.parseInt(cmd.getOptionValue("n")); } if (cmd.hasOption("o")) { trecOutFile = new BufferedWriter(new FileWriter(new File(cmd.getOptionValue("o")))); } List<String> fieldList = new ArrayList<String>(); fieldList.add(UtilConst.ID_FIELD); fieldList.add(UtilConst.SCORE_FIELD); double totalTime = 0; double retQty = 0; ArrayList<Double> queryTimes = new ArrayList<Double>(); boolean bDoWarmUp = cmd.hasOption("w"); if (bDoWarmUp) { System.out.println("Using a warmup step!"); } int queryQty = 0; for (String t : FileUtils.readLines(new File(queryFile))) { t = t.trim(); if (t.isEmpty()) continue; int ind = t.indexOf('|'); if (ind < 0) throw new Exception("Wrong format, line: '" + t + "'"); String qID = t.substring(0, ind); String q = t.substring(ind + 1); SolrDocumentList res = null; if (bDoWarmUp) { res = solr.runQuery(q, fieldList, numRet); } Long tm1 = System.currentTimeMillis(); res = solr.runQuery(q, fieldList, numRet); Long tm2 = System.currentTimeMillis(); retQty += res.getNumFound(); System.out.println(qID + " Obtained: " + res.getNumFound() + " entries in " + (tm2 - tm1) + " ms"); double delta = (tm2 - tm1); totalTime += delta; queryTimes.add(delta); ++queryQty; if (trecOutFile != null) { ArrayList<SolrRes> resArr = new ArrayList<SolrRes>(); for (SolrDocument doc : res) { String id = (String) doc.getFieldValue(UtilConst.ID_FIELD); float score = (Float) doc.getFieldValue(UtilConst.SCORE_FIELD); resArr.add(new SolrRes(id, "", score)); } SolrRes[] results = resArr.toArray(new SolrRes[resArr.size()]); Arrays.sort(results); SolrEvalUtils.saveTrecResults(qID, results, trecOutFile, TREC_RUN, results.length); } } double devTime = 0, meanTime = totalTime / queryQty; for (int i = 0; i < queryQty; ++i) { double d = queryTimes.get(i) - meanTime; devTime += d * d; } devTime = Math.sqrt(devTime / (queryQty - 1)); System.out.println(String.format("Query time, mean/standard dev: %.2f/%.2f (ms)", meanTime, devTime)); System.out.println(String.format("Avg # of docs returned: %.2f", retQty / queryQty)); solr.close(); trecOutFile.close(); } catch (ParseException e) { Usage("Cannot parse arguments"); } catch (Exception e) { System.err.println("Terminating due to an exception: " + e); System.exit(1); } }
From source file:com.ibm.watson.app.qaclassifier.tools.PopulateAnswerStore.java
public static void main(String[] args) throws Exception { Option urlOption = createOption(URL_OPTION, URL_OPTION_LONG, true, "The root URL of the application to connect to. If omitted, the default will be used (" + DEFAULT_URL + ")", false, URL_OPTION_LONG); Option fileOption = createOption(FILE_OPTION, FILE_OPTION_LONG, true, "The file to be used to populate the answers, can point to the file system or the class path", true, FILE_OPTION_LONG);//from w w w .j ava 2s . c o m Option dirOption = createOption(DIR_OPTION, DIR_OPTION_LONG, true, "The directory containing the html answer files, can point to the file system or the class path", true, DIR_OPTION_LONG); Option userOption = createOption(USER_OPTION, USER_OPTION_LONG, true, "The username for the manage API", true, USER_OPTION_LONG); Option passwordOption = createOption(PASSWORD_OPTION, PASSWORD_OPTION_LONG, true, "The password for the manage API", true, PASSWORD_OPTION_LONG); final Options options = buildOptions(urlOption, fileOption, dirOption, userOption, passwordOption); CommandLine cmd; try { CommandLineParser parser = new GnuParser(); cmd = parser.parse(options, args); } catch (ParseException e) { System.err.println(MessageKey.AQWQAC24008E_could_not_parse_cmd_line_args_1.getMessage(e.getMessage()) .getFormattedMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(120, "java " + PopulateAnswerStore.class.getName(), null, options, null); return; } final String url = cmd.getOptionValue(URL_OPTION, DEFAULT_URL); final String file = cmd.getOptionValue(FILE_OPTION); final String dir = cmd.getOptionValue(DIR_OPTION); final String user = cmd.getOptionValue(USER_OPTION); final String password = cmd.getOptionValue(PASSWORD_OPTION); System.out.println(MessageKey.AQWQAC20002I_checking_answer_store_at_url_2.getMessage(url, DEFAULT_ENDPOINT) .getFormattedMessage()); try { AnswerStoreRestClient client = new AnswerStoreRestClient(url, user, password); // we only want to populate if there is nothing in the database already // start with the assumption that we do want to populate and stop if we find answers in there already boolean doPopulate = true; String answersResult = getAnswers(client); if (answersResult != null && !answersResult.isEmpty()) { Gson gson = new Gson(); Type type = new TypeToken<List<ManagedAnswer>>() { }.getType(); List<ManagedAnswer> answers = gson.fromJson(answersResult, type); if (answers != null && answers.size() > 0) { System.out.println(MessageKey.AQWQAC20006I_found_answers_in_stop_1.getMessage(answers.size()) .getFormattedMessage()); doPopulate = false; } } if (doPopulate) { System.out.println(MessageKey.AQWQAC20003I_populating_answer_store_at_url_2 .getMessage(url, DEFAULT_ENDPOINT).getFormattedMessage()); boolean success = populate(client, file, dir); if (!success) { throw new RuntimeException(MessageKey.AQWQAC24005E_error_populating_answer_store.getMessage() .getFormattedMessage()); } } else { System.out.println(MessageKey.AQWQAC20001I_answer_store_already_populated_doing_nothing.getMessage() .getFormattedMessage()); } System.out.println(MessageKey.AQWQAC20005I_done_population_answers.getMessage().getFormattedMessage()); } catch (IOException e) { System.err.println(MessageKey.AQWQAC24007E_error_populating_answer_store_1.getMessage(e.getMessage()) .getFormattedMessage()); e.printStackTrace(System.err); } }
From source file:com.game.GameLauncherApplication.java
public static void main(String[] args) throws Exception { // System.exit is common for Batch applications since the exit code can be used to // drive a workflow // System.exit(SpringApplication.exit(SpringApplication.run( // SampleBatchApplication.class, args))); String s = "Y"; while ("Y".equalsIgnoreCase(s.trim())) { ticTacToeGame.startGame();/* w w w.j a va2 s. c o m*/ System.out.println(" Do you want to play more to Play more enter Y "); BufferedReader BR = new BufferedReader(new InputStreamReader(System.in)); s = BR.readLine(); if (s != null && !s.isEmpty()) { s = s.trim(); } } }
From source file:com.linecorp.platform.channel.sample.Main.java
public static void main(String[] args) { BusinessConnect bc = new BusinessConnect(); /**// www . j a va 2 s . co m * Prepare the required channel secret and access token */ String channelSecret = System.getenv("CHANNEL_SECRET"); String channelAccessToken = System.getenv("CHANNEL_ACCESS_TOKEN"); if (channelSecret == null || channelSecret.isEmpty() || channelAccessToken == null || channelAccessToken.isEmpty()) { System.err.println("Error! Environment variable CHANNEL_SECRET and CHANNEL_ACCESS_TOKEN not defined."); return; } port(Integer.valueOf(System.getenv("PORT"))); staticFileLocation("/public"); /** * Define the callback url path */ post("/events", (request, response) -> { String requestBody = request.body(); /** * Verify whether the channel signature is valid or not */ String channelSignature = request.headers("X-LINE-CHANNELSIGNATURE"); if (channelSignature == null || channelSignature.isEmpty()) { response.status(400); return "Please provide valid channel signature and try again."; } if (!bc.validateBCRequest(requestBody, channelSecret, channelSignature)) { response.status(401); return "Invalid channel signature."; } /** * Parse the http request body */ ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME, true); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); objectMapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false); objectMapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector(TypeFactory.defaultInstance())); objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); EventList events; try { events = objectMapper.readValue(requestBody, EventList.class); } catch (IOException e) { response.status(400); return "Invalid request body."; } ApiHttpClient apiHttpClient = new ApiHttpClient(channelAccessToken); /** * Process the incoming messages/operations one by one */ List<String> toUsers; for (Event event : events.getResult()) { switch (event.getEventType()) { case Constants.EventType.MESSAGE: toUsers = new ArrayList<>(); toUsers.add(event.getContent().getFrom()); // @TODO: We strongly suggest you should modify this to process the incoming message/operation async bc.sendTextMessage(toUsers, "You said: " + event.getContent().getText(), apiHttpClient); break; case Constants.EventType.OPERATION: if (event.getContent().getOpType() == Constants.OperationType.ADDED_AS_FRIEND) { String newFriend = event.getContent().getParams().get(0); Profile profile = bc.getProfile(newFriend, apiHttpClient); String displayName = profile == null ? "Unknown" : profile.getDisplayName(); toUsers = new ArrayList<>(); toUsers.add(newFriend); bc.sendTextMessage(toUsers, displayName + ", welcome to be my friend!", apiHttpClient); Connection connection = null; connection = DatabaseUrl.extract().getConnection(); toUsers = bc.getFriends(newFriend, connection); if (toUsers.size() > 0) { bc.sendTextMessage(toUsers, displayName + " just join us, let's welcome him/her!", apiHttpClient); } bc.addFriend(newFriend, displayName, connection); if (connection != null) { connection.close(); } } break; default: // Unknown type? } } return "Events received successfully."; }); get("/", (request, response) -> { Map<String, Object> attributes = new HashMap<>(); attributes.put("message", "Hello World!"); return new ModelAndView(attributes, "index.ftl"); }, new FreeMarkerEngine()); }
From source file:org.eclipse.swt.snippets.Snippet363.java
public static void main(String[] args) { Display display = new Display(); errorIcon = display.getSystemImage(SWT.ICON_ERROR); Shell shell = new Shell(display); shell.setText("Snippet 363"); shell.setLayout(new GridLayout(2, false)); shell.setText("LiveRegion Test"); icon = new Label(shell, SWT.NONE); icon.setLayoutData(new GridData(32, 32)); liveLabel = new Text(shell, SWT.READ_ONLY); GC gc = new GC(liveLabel); Point pt = gc.textExtent(errorMessage); GridData data = new GridData(SWT.FILL, SWT.CENTER, true, false); data.minimumWidth = (int) (pt.x + gc.getFontMetrics().getAverageCharacterWidth() * 2); gc.dispose();/*from w w w . j a v a2 s .co m*/ liveLabel.setLayoutData(data); liveLabel.setText(""); liveLabel.getAccessible().addAccessibleAttributeListener(new AccessibleAttributeAdapter() { @Override public void getAttributes(AccessibleAttributeEvent e) { e.attributes = new String[] { "container-live", "polite", "live", "polite", "container-live-role", "status", }; } }); final Label textFieldLabel = new Label(shell, SWT.NONE); textFieldLabel.setText("Type a number:"); textFieldLabel.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); final Text textField = new Text(shell, SWT.SINGLE | SWT.BORDER); textField.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 2, 1)); final Button okButton = new Button(shell, SWT.PUSH); okButton.setText("OK"); okButton.setLayoutData(new GridData(SWT.END, SWT.CENTER, false, false, 2, 1)); okButton.setEnabled(false); textField.addModifyListener(e -> { boolean isNumber = false; String textValue = textField.getText(); try { Integer.parseInt(textValue); isNumber = true; setMessageText(false, "Thank-you"); } catch (NumberFormatException ex) { if (textValue.isEmpty()) { setMessageText(false, ""); } else { setMessageText(true, "Error: Number expected."); } } okButton.setEnabled(isNumber); }); textField.setFocus(); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); }