List of usage examples for java.util List contains
boolean contains(Object o);
From source file:MainClass.java
public static void main(String[] a) { List list = Arrays.asList(new String[] { "A", "B", "C", "D" }); System.out.println(list.contains("C")); }
From source file:Main.java
public static void main(String[] args) { List list = new ArrayList(); list.add("Item 1"); list.add("Item 2"); if (list.contains("Item 1")) { System.out.println("True"); } else {//from www . ja v a 2s. c o m System.out.println("False"); } }
From source file:MainClass.java
public static void main(String[] a) { List list = Arrays.asList(new String[] { "A", "B", "C", "D" }); List list2 = Arrays.asList(new String[] { "B", "A" }); System.out.println(list.contains(list2)); }
From source file:com.ethercamp.harmony.Application.java
/** * Does one of:/*from ww w .ja va 2 s . c o m*/ * - start Harmony peer; * - perform action and exit on completion. */ public static void main(String[] args) throws Exception { final List<String> actions = asList("importBlocks"); final Optional<String> foundAction = asList(args).stream().filter(arg -> actions.contains(arg)).findFirst(); if (foundAction.isPresent()) { foundAction.ifPresent(action -> System.out.println("Performing action: " + action)); Start.main(args); // system is expected to exit after action performed } else { if (!SystemProperties.getDefault().blocksLoader().equals("")) { SystemProperties.getDefault().setSyncEnabled(false); SystemProperties.getDefault().setDiscoveryEnabled(false); } ConfigurableApplicationContext context = SpringApplication.run(new Object[] { Application.class }, args); Ethereum ethereum = context.getBean(Ethereum.class); if (!SystemProperties.getDefault().blocksLoader().equals("")) { ethereum.getBlockLoader().loadBlocks(); } } }
From source file:mujava.cli.testnew.java
public static void main(String[] args) throws IOException { testnewCom jct = new testnewCom(); String[] argv = { "Flower", "/Users/dmark/mujava/src/Flower" }; new JCommander(jct, args); muJavaHomePath = Util.loadConfig(); // muJavaHomePath= "/Users/dmark/mujava"; // check if debug mode if (jct.isDebug() || jct.isDebugMode()) { Util.debug = true;/*from w w w . ja v a 2 s.c o m*/ } System.out.println(jct.getParameters().size()); sessionName = jct.getParameters().get(0); // set first parameter as the // session name ArrayList<String> srcFiles = new ArrayList<>(); for (int i = 1; i < jct.getParameters().size(); i++) { srcFiles.add(jct.getParameters().get(i)); // retrieve all src file // names from parameters } // get all existing session name File folder = new File(muJavaHomePath); if (!folder.isDirectory()) { Util.Error("ERROR: cannot locate the folder specified in mujava.config"); return; } File[] listOfFiles = folder.listFiles(); // null checking // check the specified folder has files or not if (listOfFiles == null) { Util.Error("ERROR: no files in the muJava home folder " + muJavaHomePath); return; } List<String> fileNameList = new ArrayList<>(); for (File file : listOfFiles) { fileNameList.add(file.getName()); } // check if the session is new or not if (fileNameList.contains(sessionName)) { Util.Error("Session already exists."); } else { // create sub-directory for the session setupSessionDirectory(sessionName); // move src files into session folder for (String srcFile : srcFiles) { // new (dir, name) // check abs path or not // need to check if srcFile has .java at the end or not if (srcFile.length() > 5) { if (srcFile.substring(srcFile.length() - 5).equals(".java")) // name has .java at the end, e.g. cal.java { // delete .java, e.g. make it cal srcFile = srcFile.substring(0, srcFile.length() - 5); } } File source = new File(srcFile + ".java"); if (!source.isAbsolute()) // relative path, attach path, e.g. cal.java, make it c:\mujava\cal.java { source = new File(muJavaHomePath + "/src" + java.io.File.separator + srcFile + ".java"); } File desc = new File(muJavaHomePath + "/" + sessionName + "/src"); FileUtils.copyFileToDirectory(source, desc); // compile src files // String srcName = "t"; boolean result = compileSrc(srcFile); if (result) Util.Print("Session is built successfully."); } } // System.exit(0); }
From source file:com.mapr.PurchaseLog.java
public static void main(String[] args) throws IOException { Options opts = new Options(); CmdLineParser parser = new CmdLineParser(opts); try {//from w w w.j a v a 2s . c o m parser.parseArgument(args); } catch (CmdLineException e) { System.err.println("Usage: -count <number>G|M|K [ -users number ] log-file user-profiles"); return; } Joiner withTab = Joiner.on("\t"); // first generate lots of user definitions SchemaSampler users = new SchemaSampler( Resources.asCharSource(Resources.getResource("user-schema.txt"), Charsets.UTF_8).read()); File userFile = File.createTempFile("user", "tsv"); BufferedWriter out = Files.newBufferedWriter(userFile.toPath(), Charsets.UTF_8); for (int i = 0; i < opts.users; i++) { out.write(withTab.join(users.sample())); out.newLine(); } out.close(); // now generate a session for each user Splitter onTabs = Splitter.on("\t"); Splitter onComma = Splitter.on(","); Random gen = new Random(); SchemaSampler intermediate = new SchemaSampler( Resources.asCharSource(Resources.getResource("hit_step.txt"), Charsets.UTF_8).read()); final int COUNTRY = users.getFieldNames().indexOf("country"); final int CAMPAIGN = intermediate.getFieldNames().indexOf("campaign_list"); final int SEARCH_TERMS = intermediate.getFieldNames().indexOf("search_keywords"); Preconditions.checkState(COUNTRY >= 0, "Need country field in user schema"); Preconditions.checkState(CAMPAIGN >= 0, "Need campaign_list field in step schema"); Preconditions.checkState(SEARCH_TERMS >= 0, "Need search_keywords field in step schema"); out = Files.newBufferedWriter(new File(opts.out).toPath(), Charsets.UTF_8); for (String line : Files.readAllLines(userFile.toPath(), Charsets.UTF_8)) { long t = (long) (TimeUnit.MILLISECONDS.convert(30, TimeUnit.DAYS) * gen.nextDouble()); List<String> user = Lists.newArrayList(onTabs.split(line)); // pick session length int n = (int) Math.floor(-30 * Math.log(gen.nextDouble())); for (int i = 0; i < n; i++) { // time on page int dt = (int) Math.floor(-20000 * Math.log(gen.nextDouble())); t += dt; // hit specific values JsonNode step = intermediate.sample(); // check for purchase double p = 0.01; List<String> campaigns = Lists.newArrayList(onComma.split(step.get("campaign_list").asText())); List<String> keywords = Lists.newArrayList(onComma.split(step.get("search_keywords").asText())); if ((user.get(COUNTRY).equals("us") && campaigns.contains("5")) || (user.get(COUNTRY).equals("jp") && campaigns.contains("7")) || keywords.contains("homer") || keywords.contains("simpson")) { p = 0.5; } String events = gen.nextDouble() < p ? "1" : "-"; out.write(Long.toString(t)); out.write("\t"); out.write(line); out.write("\t"); out.write(withTab.join(step)); out.write("\t"); out.write(events); out.write("\n"); } } out.close(); }
From source file:de.tu.darmstadt.lt.ner.preprocessing.GermaNERMain.java
public static void main(String[] arg) throws Exception { long startTime = System.currentTimeMillis(); String usage = "USAGE: java -jar germanner.jar [-c config.properties] \n" + " [-f trainingFileName] -t testFileName -d ModelOutputDirectory-o outputFile"; long start = System.currentTimeMillis(); ChangeColon c = new ChangeColon(); List<String> argList = Arrays.asList(arg); try {// w w w . j a v a 2s .co m if (argList.contains("-c") && argList.get(argList.indexOf("-c") + 1) != null) { if (!new File(argList.get(argList.indexOf("-c") + 1)).exists()) { LOG.error("Default configuration is read from the system\n"); } else { configFile = new FileInputStream(argList.get(argList.indexOf("-c") + 1)); } } if (argList.contains("-t") && argList.get(argList.indexOf("-t") + 1) != null) { if (!new File(argList.get(argList.indexOf("-t") + 1)).exists()) { LOG.error("There is no test file to tag"); System.exit(1); } Configuration.testFileName = argList.get(argList.indexOf("-t") + 1); } if (argList.contains("-f") && argList.get(argList.indexOf("-f") + 1) != null) { if (!new File(argList.get(argList.indexOf("-f") + 1)).exists()) { LOG.error("The system is running in tagging mode. No training data provided"); } else { Configuration.trainFileName = argList.get(argList.indexOf("-f") + 1); } } if (argList.contains("-d") && argList.get(argList.indexOf("-d") + 1) != null) { if (new File(argList.get(argList.indexOf("-d") + 1)).exists()) { Configuration.modelDir = argList.get(argList.indexOf("-d") + 1); } else { File dir = new File(argList.get(argList.indexOf("-d") + 1)); dir.mkdirs(); Configuration.modelDir = dir.getAbsolutePath(); } } // load a properties file initNERModel(); } catch (IOException ex) { ex.printStackTrace(); } try { setModelDir(); File outputtmpFile = new File(modelDirectory, "result.tmp"); File outputFile = null; if (argList.contains("-o") && argList.get(argList.indexOf("-o") + 1) != null) { outputFile = new File(argList.get(argList.indexOf("-o") + 1)); } else { LOG.error("The directory for this output file does not exist. Output file " + "will be found in the current directury under folder \"output\""); outputFile = new File(modelDirectory, "result.tsv"); } if (Configuration.mode.equals("ft") && (Configuration.trainFileName == null || Configuration.testFileName == null)) { LOG.error(usage); System.exit(1); } if (Configuration.mode.equals("f") && Configuration.trainFileName == null) { LOG.error(usage); System.exit(1); } if (Configuration.mode.equals("t") && Configuration.testFileName == null) { LOG.error(usage); System.exit(1); } if (Configuration.mode.equals("f") && Configuration.trainFileName != null) { c.normalize(Configuration.trainFileName, Configuration.trainFileName + ".normalized"); System.out.println("Start model generation"); writeModel(new File(Configuration.trainFileName + ".normalized"), modelDirectory); System.out.println("Start model generation -- done"); System.out.println("Start training"); trainModel(modelDirectory); System.out.println("Start training ---done"); } else if (Configuration.mode.equals("ft") && Configuration.trainFileName != null && Configuration.testFileName != null) { c.normalize(Configuration.trainFileName, Configuration.trainFileName + ".normalized"); c.normalize(Configuration.testFileName, Configuration.testFileName + ".normalized"); System.out.println("Start model generation"); writeModel(new File(Configuration.trainFileName + ".normalized"), modelDirectory); System.out.println("Start model generation -- done"); System.out.println("Start training"); trainModel(modelDirectory); System.out.println("Start training ---done"); System.out.println("Start tagging"); classifyTestFile(modelDirectory, new File(Configuration.testFileName + ".normalized"), outputtmpFile, null, null); System.out.println("Start tagging ---done"); // re-normalized the colon changed text c.deNormalize(outputtmpFile.getAbsolutePath(), outputFile.getAbsolutePath()); } else { c.normalize(Configuration.testFileName, Configuration.testFileName + ".normalized"); System.out.println("Start tagging"); classifyTestFile(modelDirectory, new File(Configuration.testFileName + ".normalized"), outputtmpFile, null, null); // re-normalized the colon changed text c.deNormalize(outputtmpFile.getAbsolutePath(), outputFile.getAbsolutePath()); System.out.println("Start tagging ---done"); } long now = System.currentTimeMillis(); UIMAFramework.getLogger().log(Level.INFO, "Time: " + (now - start) + "ms"); } catch (Exception e) { LOG.error(usage); e.printStackTrace(); } long endTime = System.currentTimeMillis(); long totalTime = endTime - startTime; System.out.println("NER tarin/test done in " + totalTime / 1000 + " seconds"); }
From source file:EVT.java
/** * @param args/*w ww.j a v a 2 s. c om*/ */ public static void main(final String[] args) throws MalformedURLException { try { URL url = new EVT().getClass().getClassLoader().getResource("general.properties"); config = new PropertiesConfiguration(url); } catch (ConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); System.exit(1); } final Map parameters = parseParameters(args); if (parameters.containsKey("-v")) verboseMode = 1; if (parameters.containsKey("-V") || parameters.containsKey("-vv")) verboseMode = 2; //the from version and the to version must be put in property file String supportedVersions = PropertiesUtil.concatenatePropsValues(config, ALFRESCO_VERSION, ","); List<String> supportedVersionsList = Arrays.asList(supportedVersions.split(",")); String alfrescoVersion = (String) parameters.get(ALFRESCO_VERSION); boolean supportedVersion = (alfrescoVersion != null) && supportedVersionsList.contains(alfrescoVersion); System.out.println( "\nAlfresco Environment Validation Tool (for Alfresco Enterprise " + supportedVersions + ")"); System.out.println("------------------------------------------------------------------"); if (parameters.isEmpty() || parameters.containsKey("-?") || parameters.containsKey("--help") || parameters.containsKey("/?") || !parameters.containsKey(DBValidator.PARAMETER_DATABASE_TYPE) || !parameters.containsKey(DBValidator.PARAMETER_DATABASE_HOSTNAME) || !parameters.containsKey(DBValidator.PARAMETER_DATABASE_LOGIN) || !parameters.containsKey(ALFRESCO_VERSION) || !parameters.containsKey(IndexDiskSpeedValidator.PARAMETER_DISK_LOCATION)) { System.out.println(""); System.out.println("usage: evt[.sh|.cmd] [-?|--help] [-v] [-V|-vv]"); System.out.println(" -a alfrescoversion -t databaseType -h databaseHost [-r databasePort]"); System.out.println( " [-d databaseName] -l databaseLogin [-p databasePassword] -i indexlocation"); System.out.println(""); System.out.println("where: -?|--help - display this help"); System.out.println(" -v - produce verbose output"); System.out.println(" -V|-vv - produce super-verbose output (stack traces)"); System.out.println( " alfrescoversion - Version for which the verification is made . May be one of:"); System.out.println( " 4.0.0,4.0.1,4.0.2,4.1.1,4.1.2,4.1.3,4.1.4,4.1.5,4.1.6,4.2"); System.out.println(" databaseType - the type of database. May be one of:"); System.out.println(" mysql, postgresql, oracle, mssqlserver, db2"); System.out.println(" databaseHost - the hostname of the database server"); System.out.println(" databasePort - the port the database is listening on (optional -"); System.out.println(" defaults to default for the database type)"); System.out.println(" databaseName - the name of the Alfresco database (optional -"); System.out.println(" defaults to 'alfresco')"); System.out.println(" databaseLogin - the login Alfresco will use to connect to the"); System.out.println(" database"); System.out.println(" databasePassword - the password for that user (optional)"); System.out.println( " indexlocation - a path to a folder that will contain Alfresco indexes"); System.out.println(""); System.out.println("The tool must be run as the OS user that Alfreso will run as. In particular"); System.out.println("it will report erroneous results if run as \"root\" (or equivalent on other"); System.out.println("OSes) if Alfresco is not intended to be run as that user."); System.out.println(""); } else if (!supportedVersion) { System.out.println(""); System.out.println("Version " + alfrescoVersion + " is not in the list of the Alfresco versions supported by this tool."); System.out.println("Please specify one of the following versions: " + supportedVersions); } else { final StdoutValidatorCallback callback = new StdoutValidatorCallback(); (new AllValidators()).validate(parameters, callback); System.out.println("\n\n **** FINAL GRADE: " + TestResult.typeToString(callback.worstResult) + " ****\n"); } }
From source file:fr.inria.atlanmod.emf.graphs.Connectedness.java
public static void main(String[] args) { Options options = createOptions();/* w ww. ja v a 2s . c o m*/ CommandLineParser parser = new PosixParser(); try { CommandLine commandLine = parser.parse(options, args); String inputMetamodel = commandLine.getOptionValue(INPUT_METAMODEL); String inputModel = commandLine.getOptionValue(INPUT_MODEL); Boolean logUnreachable = commandLine.hasOption(LOG_UNREACHABLE); ResourceSet resourceSet = new ResourceSetImpl(); Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap() .put(Resource.Factory.Registry.DEFAULT_EXTENSION, new XMIResourceFactoryImpl()); { LOG.log(Level.INFO, "Loading input metamodel"); URI uri = URI.createFileURI(inputMetamodel); Resource resource = resourceSet.getResource(uri, true); registerEPackages(resource); } URI uri = URI.createFileURI(inputModel); LOG.log(Level.INFO, "Loading input model"); Resource resource = resourceSet.getResource(uri, true); LOG.log(Level.INFO, "Getting input model contents"); Set<EObject> resourceContents = getResourceContents(resource); int totalCount = resourceContents.size(); LOG.log(Level.INFO, MessageFormat.format("Input model contains {0} elements", totalCount)); List<EClassifier> candidateEClassifiers = buildCandidateEClassifiers(); for (Iterator<EObject> it = resource.getAllContents(); it.hasNext();) { EObject eObject = it.next(); if (candidateEClassifiers.contains(eObject.eClass())) { Set<EObject> reachableEObjects = getReachableEObjects(eObject); int i = reachableEObjects.size(); LOG.log(Level.INFO, MessageFormat.format("Found {0} reachable objects from {1} (EClass {2})", i, EcoreUtil.getURI(eObject), eObject.eClass().getName())); if (logUnreachable) { Set<EObject> unreachableEObjects = new HashSet<>(resourceContents); unreachableEObjects.removeAll(reachableEObjects); LOG.log(Level.INFO, MessageFormat.format("{0} elements are unreachable from {1} (EClass {2})", unreachableEObjects.size(), EcoreUtil.getURI(eObject), eObject.eClass().getName())); for (EObject unreachableEObject : unreachableEObjects) { LOG.log(Level.INFO, MessageFormat.format("Unreachable EObject {0} is of type {1}", EcoreUtil.getURI(unreachableEObject), unreachableEObject.eClass())); } } } } } catch (ParseException e) { LOG.log(Level.SEVERE, e.getLocalizedMessage(), e); LOG.log(Level.INFO, "Current arguments: " + Arrays.toString(args)); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar <this-file.jar>", options, true); } catch (Throwable e) { LOG.log(Level.SEVERE, e.getLocalizedMessage(), e); MessageUtil.showError(e.toString()); } }
From source file:com.edduarte.protbox.Protbox.java
public static void main(String... args) { // activate debug / verbose mode if (args.length != 0) { List<String> argsList = Arrays.asList(args); if (argsList.contains("-v")) { Constants.verbose = true;/* w w w .j a va 2 s . c o m*/ } } // use System's look and feel try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (Exception ex) { // If the System's look and feel is not obtainable, continue execution with JRE look and feel } // check this is a single instance try { new ServerSocket(1882); } catch (IOException ex) { JOptionPane.showMessageDialog(null, "Another instance of Protbox is already running.\n" + "Please close the other instance first.", "Protbox already running", JOptionPane.ERROR_MESSAGE); System.exit(1); } // check if System Tray is supported by this operative system if (!SystemTray.isSupported()) { JOptionPane.showMessageDialog(null, "Your operative system does not support system tray functionality.\n" + "Please try running Protbox on another operative system.", "System tray not supported", JOptionPane.ERROR_MESSAGE); System.exit(1); } // add PKCS11 providers FileFilter fileFilter = new AndFileFilter(new WildcardFileFilter(Lists.newArrayList("*.config")), HiddenFileFilter.VISIBLE); File[] providersConfigFiles = new File(Constants.PROVIDERS_DIR).listFiles(fileFilter); if (providersConfigFiles != null) { for (File f : providersConfigFiles) { try { List<String> lines = FileUtils.readLines(f); String aliasLine = lines.stream().filter(line -> line.contains("alias")).findFirst().get(); lines.remove(aliasLine); String alias = aliasLine.split("=")[1].trim(); StringBuilder sb = new StringBuilder(); for (String s : lines) { sb.append(s); sb.append("\n"); } Provider p = new SunPKCS11(new ReaderInputStream(new StringReader(sb.toString()))); Security.addProvider(p); pkcs11Providers.put(p.getName(), alias); } catch (IOException | ProviderException ex) { if (ex.getMessage().equals("Initialization failed")) { ex.printStackTrace(); String s = "The following error occurred:\n" + ex.getCause().getMessage() + "\n\nIn addition, make sure you have " + "an available smart card reader connected before opening the application."; JTextArea textArea = new JTextArea(s); textArea.setColumns(60); textArea.setLineWrap(true); textArea.setWrapStyleWord(true); textArea.setSize(textArea.getPreferredSize().width, 1); JOptionPane.showMessageDialog(null, textArea, "Error loading PKCS11 provider", JOptionPane.ERROR_MESSAGE); System.exit(1); } else { ex.printStackTrace(); JOptionPane.showMessageDialog(null, "Error while setting up PKCS11 provider from configuration file " + f.getName() + ".\n" + ex.getMessage(), "Error loading PKCS11 provider", JOptionPane.ERROR_MESSAGE); } } } } // adds a shutdown hook to save instantiated directories into files when the application is being closed Runtime.getRuntime().addShutdownHook(new Thread(Protbox::exit)); // get system tray and run tray applet tray = SystemTray.getSystemTray(); SwingUtilities.invokeLater(() -> { if (Constants.verbose) { logger.info("Starting application"); } //Start a new TrayApplet object trayApplet = TrayApplet.getInstance(); }); // prompts the user to choose which provider to use ProviderListWindow.showWindow(Protbox.pkcs11Providers.keySet(), providerName -> { // loads eID token eIDTokenLoadingWindow.showPrompt(providerName, (returnedUser, returnedCertificateData) -> { user = returnedUser; certificateData = returnedCertificateData; // gets a password to use on the saved registry files (for loading and saving) final AtomicReference<Consumer<SecretKey>> consumerHolder = new AtomicReference<>(null); consumerHolder.set(password -> { registriesPasswordKey = password; try { // if there are serialized files, load them if they can be decoded by this user's private key final List<SavedRegistry> serializedDirectories = new ArrayList<>(); if (Constants.verbose) { logger.info("Reading serialized registry files..."); } File[] registryFileList = new File(Constants.REGISTRIES_DIR).listFiles(); if (registryFileList != null) { for (File f : registryFileList) { if (f.isFile()) { byte[] data = FileUtils.readFileToByteArray(f); try { Cipher cipher = Cipher.getInstance("AES"); cipher.init(Cipher.DECRYPT_MODE, registriesPasswordKey); byte[] registryDecryptedData = cipher.doFinal(data); serializedDirectories.add(new SavedRegistry(f, registryDecryptedData)); } catch (GeneralSecurityException ex) { if (Constants.verbose) { logger.info("Inserted Password does not correspond to " + f.getName()); } } } } } // if there were no serialized directories, show NewDirectory window to configure the first folder if (serializedDirectories.isEmpty() || registryFileList == null) { if (Constants.verbose) { logger.info("No registry files were found: running app as first time!"); } NewRegistryWindow.start(true); } else { // there were serialized directories loadRegistry(serializedDirectories); trayApplet.repaint(); showTrayApplet(); } } catch (AWTException | IOException | GeneralSecurityException | ReflectiveOperationException | ProtboxException ex) { JOptionPane.showMessageDialog(null, "The inserted password was invalid! Please try another one!", "Invalid password!", JOptionPane.ERROR_MESSAGE); insertPassword(consumerHolder.get()); } }); insertPassword(consumerHolder.get()); }); }); }