Example usage for java.lang String trim

List of usage examples for java.lang String trim

Introduction

In this page you can find the example usage for java.lang String trim.

Prototype

public String trim() 

Source Link

Document

Returns a string whose value is this string, with all leading and trailing space removed, where space is defined as any character whose codepoint is less than or equal to 'U+0020' (the space character).

Usage

From source file:nl.ordina.bag.etl.LoadMutatiesDirect.java

public static void main(String[] args) throws Exception {
    if (args.length > 0) {
        logger.info("LoadMutatiesDirect started");
        BeanLocator beanLocator = BeanLocator.getInstance("nl/ordina/bag/etl/applicationConfig.xml",
                "nl/ordina/bag/etl/datasource.xml", "nl/ordina/bag/etl/dao.xml",
                "nl/ordina/bag/etl/mutaties.xml");
        BAGMutatiesDAO bagMutatiesDAO = (BAGMutatiesDAO) beanLocator.get("bagMutatiesDAO");
        final MutatiesFileProcessor mutatiesFileProcessor = (MutatiesFileProcessor) beanLocator
                .get("mutatiesFileProcessor");
        final MutatiesProcessor mutatiesProcessor = (MutatiesProcessor) beanLocator.get("mutatiesProcessor");
        for (final String filename : args) {
            bagMutatiesDAO.doInTransaction(new TransactionCallbackWithoutResult() {
                @Override//from  w ww  .  j a v  a  2  s .  co  m
                protected void doInTransactionWithoutResult(TransactionStatus status) {
                    try {
                        logger.info("Processing Mutaties File " + filename + " started.");
                        mutatiesFileProcessor.execute(new FileInputStream(filename.trim()));
                        mutatiesProcessor.execute();
                    } catch (FileNotFoundException e) {
                        throw new ProcessingException(e);
                    } finally {
                        logger.info("Processing Mutaties File " + filename + " ended.");
                    }
                }
            });
        }
        logger.info("LoadMutatiesDirect finished");
    } else
        System.out.println("Usage: nl.ordina.bag.etl.LoadMutatiesDirect <filename> [<filename>]");
    System.exit(0);
}

From source file:it.anyplace.sync.client.Main.java

public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption("C", "set-config", true, "set config file for s-client");
    options.addOption("c", "config", false, "dump config");
    options.addOption("sp", "set-peers", true, "set peer, or comma-separated list of peers");
    options.addOption("q", "query", true, "query directory server for device id");
    options.addOption("d", "discovery", true, "discovery local network for device id");
    options.addOption("p", "pull", true, "pull file from network");
    options.addOption("P", "push", true, "push file to network");
    options.addOption("o", "output", true, "set output file/directory");
    options.addOption("i", "input", true, "set input file/directory");
    options.addOption("lp", "list-peers", false, "list peer addresses");
    options.addOption("a", "address", true, "use this peer addresses");
    options.addOption("L", "list-remote", false, "list folder (root) content from network");
    options.addOption("I", "list-info", false, "dump folder info from network");
    options.addOption("li", "list-info", false, "list folder info from local db");
    //        options.addOption("l", "list-local", false, "list folder content from local (saved) index");
    options.addOption("s", "search", true, "search local index for <term>");
    options.addOption("D", "delete", true, "push delete to network");
    options.addOption("M", "mkdir", true, "push directory create to network");
    options.addOption("h", "help", false, "print help");
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("h")) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("s-client", options);
        return;//  w w w  .j a v  a  2 s  .  c o m
    }

    File configFile = cmd.hasOption("C") ? new File(cmd.getOptionValue("C"))
            : new File(System.getProperty("user.home"), ".s-client.properties");
    logger.info("using config file = {}", configFile);
    ConfigurationService configuration = ConfigurationService.newLoader().loadFrom(configFile);
    FileUtils.cleanDirectory(configuration.getTemp());
    KeystoreHandler.newLoader().loadAndStore(configuration);
    if (cmd.hasOption("c")) {
        logger.info("configuration =\n{}", configuration.newWriter().dumpToString());
    } else {
        logger.trace("configuration =\n{}", configuration.newWriter().dumpToString());
    }
    logger.debug("{}", configuration.getStorageInfo().dumpAvailableSpace());

    if (cmd.hasOption("sp")) {
        List<String> peers = Lists.newArrayList(Lists.transform(
                Arrays.<String>asList(cmd.getOptionValue("sp").split(",")), new Function<String, String>() {
                    @Override
                    public String apply(String input) {
                        return input.trim();
                    }
                }));
        logger.info("set peers = {}", peers);
        configuration.edit().setPeers(Collections.<DeviceInfo>emptyList());
        for (String peer : peers) {
            KeystoreHandler.validateDeviceId(peer);
            configuration.edit().addPeers(new DeviceInfo(peer, null));
        }
        configuration.edit().persistNow();
    }

    if (cmd.hasOption("q")) {
        String deviceId = cmd.getOptionValue("q");
        logger.info("query device id = {}", deviceId);
        List<DeviceAddress> deviceAddresses = new GlobalDiscoveryHandler(configuration).query(deviceId);
        logger.info("server response = {}", deviceAddresses);
    }
    if (cmd.hasOption("d")) {
        String deviceId = cmd.getOptionValue("d");
        logger.info("discovery device id = {}", deviceId);
        List<DeviceAddress> deviceAddresses = new LocalDiscorveryHandler(configuration).queryAndClose(deviceId);
        logger.info("local response = {}", deviceAddresses);
    }

    if (cmd.hasOption("p")) {
        String path = cmd.getOptionValue("p");
        logger.info("file path = {}", path);
        String folder = path.split(":")[0];
        path = path.split(":")[1];
        try (SyncthingClient client = new SyncthingClient(configuration);
                BlockExchangeConnectionHandler connectionHandler = client.connectToBestPeer()) {
            InputStream inputStream = client.pullFile(connectionHandler, folder, path).waitForComplete()
                    .getInputStream();
            String fileName = client.getIndexHandler().getFileInfoByPath(folder, path).getFileName();
            File file;
            if (cmd.hasOption("o")) {
                File param = new File(cmd.getOptionValue("o"));
                file = param.isDirectory() ? new File(param, fileName) : param;
            } else {
                file = new File(fileName);
            }
            FileUtils.copyInputStreamToFile(inputStream, file);
            logger.info("saved file to = {}", file.getAbsolutePath());
        }
    }
    if (cmd.hasOption("P")) {
        String path = cmd.getOptionValue("P");
        File file = new File(cmd.getOptionValue("i"));
        checkArgument(!path.startsWith("/")); //TODO check path syntax
        logger.info("file path = {}", path);
        String folder = path.split(":")[0];
        path = path.split(":")[1];
        try (SyncthingClient client = new SyncthingClient(configuration);
                BlockPusher.FileUploadObserver fileUploadObserver = client.pushFile(new FileInputStream(file),
                        folder, path)) {
            while (!fileUploadObserver.isCompleted()) {
                fileUploadObserver.waitForProgressUpdate();
                logger.debug("upload progress {}", fileUploadObserver.getProgressMessage());
            }
            logger.info("uploaded file to network");
        }
    }
    if (cmd.hasOption("D")) {
        String path = cmd.getOptionValue("D");
        String folder = path.split(":")[0];
        path = path.split(":")[1];
        logger.info("delete path = {}", path);
        try (SyncthingClient client = new SyncthingClient(configuration);
                IndexEditObserver observer = client.pushDelete(folder, path)) {
            observer.waitForComplete();
            logger.info("deleted path");
        }
    }
    if (cmd.hasOption("M")) {
        String path = cmd.getOptionValue("M");
        String folder = path.split(":")[0];
        path = path.split(":")[1];
        logger.info("dir path = {}", path);
        try (SyncthingClient client = new SyncthingClient(configuration);
                IndexEditObserver observer = client.pushDir(folder, path)) {
            observer.waitForComplete();
            logger.info("uploaded dir to network");
        }
    }
    if (cmd.hasOption("L")) {
        try (SyncthingClient client = new SyncthingClient(configuration)) {
            client.waitForRemoteIndexAquired();
            for (String folder : client.getIndexHandler().getFolderList()) {
                try (IndexBrowser indexBrowser = client.getIndexHandler().newIndexBrowserBuilder()
                        .setFolder(folder).build()) {
                    logger.info("list folder = {}", indexBrowser.getFolder());
                    for (FileInfo fileInfo : indexBrowser.listFiles()) {
                        logger.info("\t\t{} {} {}", fileInfo.getType().name().substring(0, 1),
                                fileInfo.getPath(), fileInfo.describeSize());
                    }
                }
            }
        }
    }
    if (cmd.hasOption("I")) {
        try (SyncthingClient client = new SyncthingClient(configuration)) {
            if (cmd.hasOption("a")) {
                String deviceId = cmd.getOptionValue("a").substring(0, 63),
                        address = cmd.getOptionValue("a").substring(64);
                try (BlockExchangeConnectionHandler connection = client.getConnection(
                        DeviceAddress.newBuilder().setDeviceId(deviceId).setAddress(address).build())) {
                    client.getIndexHandler().waitForRemoteIndexAquired(connection);
                }
            } else {
                client.waitForRemoteIndexAquired();
            }
            String folderInfo = "";
            for (String folder : client.getIndexHandler().getFolderList()) {
                folderInfo += "\n\t\tfolder info : " + client.getIndexHandler().getFolderInfo(folder);
                folderInfo += "\n\t\tfolder stats : "
                        + client.getIndexHandler().newFolderBrowser().getFolderStats(folder).dumpInfo() + "\n";
            }
            logger.info("folders:\n{}\n", folderInfo);
        }
    }
    if (cmd.hasOption("li")) {
        try (SyncthingClient client = new SyncthingClient(configuration)) {
            String folderInfo = "";
            for (String folder : client.getIndexHandler().getFolderList()) {
                folderInfo += "\n\t\tfolder info : " + client.getIndexHandler().getFolderInfo(folder);
                folderInfo += "\n\t\tfolder stats : "
                        + client.getIndexHandler().newFolderBrowser().getFolderStats(folder).dumpInfo() + "\n";
            }
            logger.info("folders:\n{}\n", folderInfo);
        }
    }
    if (cmd.hasOption("lp")) {
        try (SyncthingClient client = new SyncthingClient(configuration);
                DeviceAddressSupplier deviceAddressSupplier = client.getDiscoveryHandler()
                        .newDeviceAddressSupplier()) {
            String deviceAddressesStr = "";
            for (DeviceAddress deviceAddress : Lists.newArrayList(deviceAddressSupplier)) {
                deviceAddressesStr += "\n\t\t" + deviceAddress.getDeviceId() + " : "
                        + deviceAddress.getAddress();
            }
            logger.info("device addresses:\n{}\n", deviceAddressesStr);
        }
    }
    if (cmd.hasOption("s")) {
        String term = cmd.getOptionValue("s");
        try (SyncthingClient client = new SyncthingClient(configuration);
                IndexFinder indexFinder = client.getIndexHandler().newIndexFinderBuilder().build()) {
            client.waitForRemoteIndexAquired();
            logger.info("search term = '{}'", term);
            IndexFinder.SearchCompletedEvent event = indexFinder.doSearch(term);
            if (event.hasGoodResults()) {
                logger.info("search results for term = '{}' :", term);
                for (FileInfo fileInfo : event.getResultList()) {
                    logger.info("\t\t{} {} {}", fileInfo.getType().name().substring(0, 1), fileInfo.getPath(),
                            fileInfo.describeSize());
                }
            } else if (event.hasTooManyResults()) {
                logger.info("too many results found for term = '{}'", term);
            } else {
                logger.info("no result found for term = '{}'", term);
            }
        }
    }
    //        if (cmd.hasOption("l")) {
    //            String indexDump = new IndexHandler(configuration).dumpIndex();
    //            logger.info("index dump = \n\n{}\n", indexDump);
    //        }
    IOUtils.closeQuietly(configuration);
}

From source file:com.cyberway.issue.util.SurtPrefixSet.java

/**
 * Allow class to be used as a command-line tool for converting 
 * URL lists (or naked host or host/path fragments implied
 * to be HTTP URLs) to implied SURT prefix form. 
 * //from  w w  w. ja  va2 s. c o m
 * Read from stdin or first file argument. Writes to stdout. 
 *
 * @param args cmd-line arguments: may include input file
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    InputStream in = args.length > 0 ? new BufferedInputStream(new FileInputStream(args[0])) : System.in;
    PrintStream out = args.length > 1 ? new PrintStream(new BufferedOutputStream(new FileOutputStream(args[1])))
            : System.out;
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String line;
    while ((line = br.readLine()) != null) {
        if (line.indexOf("#") > 0)
            line = line.substring(0, line.indexOf("#"));
        line = line.trim();
        if (line.length() == 0)
            continue;
        out.println(prefixFromPlain(line));
    }
    br.close();
    out.close();
}

From source file:com.taobao.tddl.common.SQLPreParserTest.java

public static void main(String[] args) throws IOException {
    //String fileName = "D:/12_code/tddl/trunk/tddl/tddl-parser/sqlsummary-icsg-db0-db15-group-20100901100337-export.xlsx";
    //String fileName = "D:/12_code/tddl/trunk/tddl/tddl-parser/sqlsummary-tcsg-instance-group-20100901100641-export.xlsx";

    int count = 0;
    long time = 0;

    File home = new File(System.getProperty("user.dir") + "/appsqls");
    for (File f : home.listFiles()) {
        if (f.isDirectory() || !f.getName().endsWith(".xlsx")) {
            continue;
        }// www.j a  v  a 2 s .c o m
        log.info("---------------------- " + f.getAbsolutePath());
        faillog.info("---------------------- " + f.getAbsolutePath());
        Workbook wb = new XSSFWorkbook(new FileInputStream(f));
        Sheet sheet = wb.getSheetAt(0);
        for (Row row : sheet) {
            Cell cell = row.getCell(2);
            if (cell != null && cell.getCellType() == Cell.CELL_TYPE_STRING) {
                String sql = cell.getStringCellValue();

                long t0 = System.currentTimeMillis();
                String tableName = SQLPreParser.findTableName(sql);
                time += System.currentTimeMillis() - t0;
                count++;

                log.info(tableName + " <-- " + sql);
                if (tableName == null) {
                    sql = sql.trim().toLowerCase();
                    if (isCRUD(sql)) {
                        System.out.println("failed:" + sql);
                        faillog.error("failed:" + sql);
                    }
                }
            }
        }
        wb = null;
    }
    faillog.fatal("------------------------------- finished --------------------------");
    faillog.fatal(count + " sql parsed, total time:" + time + ". average time use per sql:"
            + (double) time / count + "ms/sql");
}

From source file:com.act.biointerpretation.BiointerpretationDriver.java

public static void main(String[] args) throws Exception {
    Options opts = new Options();
    for (Option.Builder b : OPTION_BUILDERS) {
        opts.addOption(b.build());/*from   w  w  w.jav a2s .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(ReactionDesalter.class.getCanonicalName(), HELP_MESSAGE, opts, null, true);
        return;
    }

    if (cl.hasOption(OPTION_CONFIGURATION_FILE)) {
        List<BiointerpretationStep> steps;
        File configFile = new File(cl.getOptionValue(OPTION_CONFIGURATION_FILE));
        if (!configFile.exists()) {
            String msg = String.format("Cannot find configuration file at %s", configFile.getAbsolutePath());
            LOGGER.error(msg);
            throw new RuntimeException(msg);
        }
        // Read the whole config file.
        try (InputStream is = new FileInputStream(configFile)) {
            steps = OBJECT_MAPPER.readValue(is, new TypeReference<List<BiointerpretationStep>>() {
            });
        } catch (IOException e) {
            LOGGER.error("Caught IO exception when attempting to read configuration file: %s", e.getMessage());
            throw e; // Crash after logging if the config file can't be read.
        }

        // Ask for explicit confirmation before dropping databases.
        LOGGER.info("Biointerpretation plan:");
        for (BiointerpretationStep step : steps) {
            crashIfInvalidDBName(step.getReadDBName());
            crashIfInvalidDBName(step.getWriteDBName());
            LOGGER.info("%s: %s -> %s", step.getOperation(), step.getReadDBName(), step.getWriteDBName());
        }
        LOGGER.warn("WARNING: each DB to be written will be dropped before the writing step commences");
        LOGGER.info("Proceed? [y/n]");
        String readLine;
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
            readLine = reader.readLine();
        }
        readLine.trim();
        if ("y".equalsIgnoreCase(readLine) || "yes".equalsIgnoreCase(readLine)) {
            LOGGER.info("Biointerpretation plan confirmed, commencing");
            for (BiointerpretationStep step : steps) {
                performOperation(step, true);
            }
            LOGGER.info("Biointerpretation plan completed");
        } else {
            LOGGER.info("Biointerpretation plan not confirmed, exiting");
        }
    } else if (cl.hasOption(OPTION_SINGLE_OPERATION)) {
        if (!cl.hasOption(OPTION_SINGLE_READ_DB) || !cl.hasOption(OPTION_SINGLE_WRITE_DB)) {
            String msg = "Must specify read and write DB names when performing a single operation";
            LOGGER.error(msg);
            throw new RuntimeException(msg);
        }
        BiointerpretationOperation operation;
        try {
            operation = BiointerpretationOperation.valueOf(cl.getOptionValue(OPTION_SINGLE_OPERATION));
        } catch (IllegalArgumentException e) {
            LOGGER.error("Caught IllegalArgumentException when trying to parse operation '%s': %s",
                    cl.getOptionValue(OPTION_SINGLE_OPERATION), e.getMessage());
            throw e; // Crash if we can't interpret the operation.
        }
        String readDB = crashIfInvalidDBName(cl.getOptionValue(OPTION_SINGLE_READ_DB));
        String writeDB = crashIfInvalidDBName(cl.getOptionValue(OPTION_SINGLE_WRITE_DB));

        performOperation(new BiointerpretationStep(operation, readDB, writeDB), false);
    } else {
        String msg = "Must specify either a config file or a single operation to perform.";
        LOGGER.error(msg);
        throw new RuntimeException(msg);
    }
}

From source file:com.metadave.kash.KashConsole.java

public static void main(String[] args) throws IOException {
    CommandLine commandLine = processArgs(args);
    ConsoleReader reader = new ConsoleReader();
    reader.setBellEnabled(false);//w ww .  j  a  va2  s.  c o  m
    reader.setExpandEvents(false); // TODO: look into this
    // TODO: Pasting in text with tabs prints out a ton of completions
    //reader.addCompleter(new jline.console.completer.StringsCompleter(keywords));

    String line;
    PrintWriter out = new PrintWriter(System.out);

    KashRuntimeContext ctx = new KashRuntimeContext();
    if (!commandLine.hasOption("nosignals")) {
        ConsoleSignalHander.install("INT", ctx);
    }

    boolean nextLinePrompt = false;

    ANSIBuffer buf = new ANSIBuffer();
    buf.setAnsiEnabled(!commandLine.hasOption("nocolor"));
    buf.blue("Welcome to Kash\n");
    buf.blue("(c) 2015 Dave Parfitt\n");
    System.out.println(buf.toString());

    if (!commandLine.hasOption("noconfig")) {
        String config = null;
        try {
            config = readConfig();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (config != null && !config.trim().isEmpty()) {
            processInput(config, ctx);
            processOutput(ctx, out, !commandLine.hasOption("nocolor"));
        }
    }

    //        if (commandLine.hasOption("infile")) {
    //            String filename = commandLine.getOptionValue("infile");
    //            readInputFile(filename, ctx);
    //            ctx.getActionListener().term();
    //            System.exit(0);
    //        }

    StringBuffer lines = new StringBuffer();
    ANSIBuffer ansiprompt = new ANSIBuffer();
    ansiprompt.setAnsiEnabled(true);
    ansiprompt.green("> ");
    String prompt = ansiprompt.toString(!commandLine.hasOption("nocolor"));
    boolean inHereDoc = false;

    while ((line = reader.readLine(nextLinePrompt ? "" : prompt)) != null) {
        out.flush();
        String chunks[] = line.split(" ");
        String consoleCommandCheck = chunks[0].toLowerCase().trim();
        if (consoleOnlyCommands.containsKey(consoleCommandCheck)) {
            consoleOnlyCommands.get(consoleCommandCheck).run(line, reader);
            continue;
        }

        if (line.contains("~%~") && !line.contains("\\~%~")) {
            inHereDoc = !inHereDoc;
        }

        if (!line.trim().endsWith(";")) {
            nextLinePrompt = true;
            lines.append(line);
            lines.append("\n");
        } else if (line.trim().endsWith(";") && !inHereDoc) {
            lines.append(line);
            String input = lines.toString();
            nextLinePrompt = false;
            processInput(input, ctx);
            processOutput(ctx, out, !commandLine.hasOption("nocolor"));
            lines = new StringBuffer();
        } else if (inHereDoc) {
            lines.append(line);
            lines.append("\n");
        }

    }
}

From source file:de.uniwue.info6.database.SQLParserTest.java

public static void main(String[] args) throws Exception {
    String test = "Dies ist ein einfacher Test";
    System.out.println(StringTools.forgetOneWord(test));

    System.exit(0);//from w w w  .j  a  v a  2 s.  co m
    // SimpleTupel<String, Integer> test1 =  new SimpleTupel<String, Integer>("test1", 1);
    // SimpleTupel<String, Integer> test2 =  new SimpleTupel<String, Integer>("test1", 12);

    // ArrayList<SimpleTupel<String, Integer>> test = new ArrayList<SimpleTupel<String, Integer>>();
    // test.add(test1);
    // System.out.println(test1.equals(test2));
    // System.exit(0);

    final boolean resetDb = true;
    // Falls nur nach einer bestimmten Aufgabe gesucht wird
    final Integer exerciseID = 39;
    final Integer scenarioID = null;
    final int threadSize = 1;

    final EquivalenceLock<Long[]> equivalenceLock = new EquivalenceLock<Long[]>();
    final Long[] performance = new Long[] { 0L, 0L };

    // ------------------------------------------------ //
    final ScenarioDao scenarioDao = new ScenarioDao();
    final ExerciseDao exerciseDao = new ExerciseDao();
    final ExerciseGroupDao groupDao = new ExerciseGroupDao();
    final UserDao userDao = new UserDao();
    final ArrayList<Thread> threads = new ArrayList<Thread>();

    // ------------------------------------------------ //
    try {
        ConnectionManager.offline_instance();
        if (resetDb) {
            Cfg.inst().setProp(MAIN_CONFIG, IMPORT_EXAMPLE_SCENARIO, true);
            Cfg.inst().setProp(MAIN_CONFIG, FORCE_RESET_DATABASE, true);
            new GenerateData().resetDB();
            ConnectionTools.inst().addSomeTestData();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    // ------------------------------------------------ //

    final List<Scenario> scenarios = scenarioDao.findAll();

    try {
        // ------------------------------------------------ //
        String userID;
        for (int i = 2; i < 100; i++) {
            userID = "user_" + i;
            User userToInsert = new User();
            userToInsert.setId(userID);
            userToInsert.setIsAdmin(false);
            userDao.insertNewInstance(userToInsert);
        }
        // ------------------------------------------------ //

        for (int i = 0; i < threadSize; i++) {
            Thread thread = new Thread() {

                public void run() {
                    // ------------------------------------------------ //
                    try {
                        Thread.sleep(new Random().nextInt(30));
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    // ------------------------------------------------ //

                    User user = userDao.getRandom();
                    Thread.currentThread().setName(user.getId());
                    System.err.println(
                            "\n\nINFO (ueps): Thread '" + Thread.currentThread().getName() + "' started\n");

                    // ------------------------------------------------ //

                    for (Scenario scenario : scenarios) {
                        if (scenarioID != null && !scenario.getId().equals(scenarioID)) {
                            continue;
                        }

                        System.out.println(StringUtils.repeat("#", 90));
                        System.out.println("SCENARIO: " + scenario.getId());

                        // ------------------------------------------------ //
                        for (ExerciseGroup group : groupDao.findByScenario(scenario)) {
                            System.out.println(StringUtils.repeat("#", 90));
                            System.out.println("GROUP: " + group.getId());
                            System.out.println(StringUtils.repeat("#", 90));
                            List<Exercise> exercises = exerciseDao.findByExGroup(group);

                            // ------------------------------------------------ //
                            for (Exercise exercise : exercises) {
                                if (exerciseID != null && !exercise.getId().equals(exerciseID)) {
                                    continue;
                                }
                                long startTime = System.currentTimeMillis();

                                for (int i = 0; i < 100; i++) {
                                    String userID = "user_" + new Random().nextInt(100000);
                                    User userToInsert = new User();
                                    userToInsert.setId(userID);
                                    userToInsert.setIsAdmin(false);
                                    userDao.insertNewInstance(userToInsert);
                                    user = userDao.getById(userID);

                                    List<SolutionQuery> solutions = new ExerciseDao().getSolutions(exercise);
                                    String solution = solutions.get(0).getQuery();
                                    ExerciseController exc = new ExerciseController().init_debug(scenario,
                                            exercise, user);
                                    exc.setUserString(solution);

                                    String fd = exc.getFeedbackList().get(0).getFeedback();
                                    System.out.println("Used Query: " + solution);
                                    if (fd.trim().toLowerCase().equals("bestanden")) {
                                        System.out.println(exercise.getId() + ": " + fd);
                                    } else {
                                        System.err.println(exercise.getId() + ": " + fd + "\n");
                                    }
                                    System.out.println(StringUtils.repeat("-", 90));
                                }

                                long elapsedTime = System.currentTimeMillis() - startTime;

                                // if (i > 5) {
                                //   try {
                                //     equivalenceLock.lock(performance);
                                //     performance[0] += elapsedTime;
                                //     performance[1]++;
                                //   } catch (Exception e) {
                                //   } finally {
                                //     equivalenceLock.release(performance);
                                //   }
                                // }
                            }
                        }
                    }

                    System.err
                            .println("INFO (ueps): Thread '" + Thread.currentThread().getName() + "' stopped");
                }
            };
            thread.start();
            threads.add(thread);
        }

        for (Thread thread : threads) {
            thread.join();
        }

        // try {
        //   equivalenceLock.lock(performance);

        //   long elapsedTime = (performance[0] / performance[1]);
        //   System.out.println("\n" + String.format("perf : %d.%03dsec", elapsedTime / 1000, elapsedTime % 1000));
        // } catch (Exception e) {
        // } finally {
        //   equivalenceLock.release(performance);
        // }

    } finally {
    }
}

From source file:com.metadave.eql.EQLConsole.java

public static void main(String[] args) throws IOException {
    CommandLine commandLine = processArgs(args);
    ConsoleReader reader = new ConsoleReader();
    reader.setBellEnabled(false);/*from  w w  w  . j ava  2  s.c  o m*/
    reader.setExpandEvents(false); // TODO: look into this
    // TODO: Pasting in text with tabs prints out a ton of completions
    //reader.addCompleter(new jline.console.completer.StringsCompleter(keywords));

    String line;
    PrintWriter out = new PrintWriter(System.out);

    RuntimeContext ctx = new RuntimeContext();
    if (!commandLine.hasOption("nosignals")) {
        ConsoleSignalHander.install("INT", ctx);
    }

    boolean nextLinePrompt = false;

    ANSIBuffer buf = new ANSIBuffer();
    buf.setAnsiEnabled(!commandLine.hasOption("nocolor"));
    buf.blue("Welcome to EQL\n");
    buf.blue("(c) 2015 Dave Parfitt\n");
    System.out.println(buf.toString());

    if (!commandLine.hasOption("noconfig")) {
        String config = null;
        try {
            config = readConfig();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (config != null && !config.trim().isEmpty()) {
            processInput(config, ctx);
            processOutput(ctx, out, !commandLine.hasOption("nocolor"));
        }
    }

    //        if (commandLine.hasOption("infile")) {
    //            String filename = commandLine.getOptionValue("infile");
    //            readInputFile(filename, ctx);
    //            ctx.getActionListener().term();
    //            System.exit(0);
    //        }

    StringBuffer lines = new StringBuffer();
    ANSIBuffer ansiprompt = new ANSIBuffer();
    ansiprompt.setAnsiEnabled(true);
    ansiprompt.green("> ");
    String prompt = ansiprompt.toString(!commandLine.hasOption("nocolor"));
    boolean inHereDoc = false;

    while ((line = reader.readLine(nextLinePrompt ? "" : prompt)) != null) {
        out.flush();
        String chunks[] = line.split(" ");
        String consoleCommandCheck = chunks[0].toLowerCase().trim();
        if (consoleOnlyCommands.containsKey(consoleCommandCheck)) {
            consoleOnlyCommands.get(consoleCommandCheck).run(line, reader);
            continue;
        }

        if (line.contains("~%~") && !line.contains("\\~%~")) {
            inHereDoc = !inHereDoc;
        }

        if (!line.trim().endsWith(";")) {
            nextLinePrompt = true;
            lines.append(line);
            lines.append("\n");
        } else if (line.trim().endsWith(";") && !inHereDoc) {
            lines.append(line);
            String input = lines.toString();
            nextLinePrompt = false;
            processInput(input, ctx);
            processOutput(ctx, out, !commandLine.hasOption("nocolor"));
            lines = new StringBuffer();
        } else if (inHereDoc) {
            lines.append(line);
            lines.append("\n");
        }

    }
}

From source file:nab.detectors.htmjava.HTMModel.java

/**
 * Launch htm.java NAB detector/*  w w  w .  j a  va2  s  . c om*/
 *
 * Usage:
 *      As a standalone application (for debug purpose only):
 *
 *          java -jar htm.java-nab.jar "{\"modelParams\":{....}}" < nab_data.csv > anomalies.out
 *
 *      For complete list of command line options use:
 *
 *          java -jar htm.java-nab.jar --help
 *
 *      As a NAB detector (see 'htmjava_detector.py'):
 *
 *          python run.py --detect --score --normalize -d htmjava
 *
 *      Logging options, see "log4j.properties":
 *
 *          - "LOGLEVEL": Controls log output (default: "OFF")
 *          - "LOGGER": Either "CONSOLE" or "FILE" (default: "CONSOLE")
 *          - "LOGFILE": Log file destination (default: "htmjava.log")
 *
 *      For example:
 *
 *          java -DLOGLEVEL=TRACE -DLOGGER=FILE -jar htm.java-nab.jar "{\"modelParams\":{....}}" < nab_data.csv > anomalies.out
 *
 */
@SuppressWarnings("resource")
public static void main(String[] args) {
    try {
        LOGGER.trace("main({})", Arrays.asList(args));
        // Parse command line args
        OptionParser parser = new OptionParser();
        parser.nonOptions("OPF parameters object (JSON)");
        parser.acceptsAll(Arrays.asList("p", "params"),
                "OPF parameters file (JSON).\n(default: first non-option argument)").withOptionalArg()
                .ofType(File.class);
        parser.acceptsAll(Arrays.asList("i", "input"), "Input data file (csv).\n(default: stdin)")
                .withOptionalArg().ofType(File.class);
        parser.acceptsAll(Arrays.asList("o", "output"), "Output results file (csv).\n(default: stdout)")
                .withOptionalArg().ofType(File.class);
        parser.acceptsAll(Arrays.asList("s", "skip"), "Header lines to skip").withOptionalArg()
                .ofType(Integer.class).defaultsTo(0);
        parser.acceptsAll(Arrays.asList("h", "?", "help"), "Help");
        OptionSet options = parser.parse(args);
        if (args.length == 0 || options.has("h")) {
            parser.printHelpOn(System.out);
            return;
        }

        // Get in/out files
        final PrintStream output;
        final InputStream input;
        if (options.has("i")) {
            input = new FileInputStream((File) options.valueOf("i"));
        } else {
            input = System.in;
        }
        if (options.has("o")) {
            output = new PrintStream((File) options.valueOf("o"));
        } else {
            output = System.out;
        }

        // Parse OPF Model Parameters
        JsonNode params;
        ObjectMapper mapper = new ObjectMapper();
        if (options.has("p")) {
            params = mapper.readTree((File) options.valueOf("p"));
        } else if (options.nonOptionArguments().isEmpty()) {
            try {
                input.close();
            } catch (Exception ignore) {
            }
            if (options.has("o")) {
                try {
                    output.flush();
                    output.close();
                } catch (Exception ignore) {
                }
            }
            throw new IllegalArgumentException("Expecting OPF parameters. See 'help' for more information");
        } else {
            params = mapper.readTree((String) options.nonOptionArguments().get(0));
        }

        // Number of header lines to skip
        int skip = (int) options.valueOf("s");

        // Force timezone to UTC
        DateTimeZone.setDefault(DateTimeZone.UTC);

        // Create NAB Network Model
        HTMModel model = new HTMModel(params);
        Network network = model.getNetwork();
        network.observe().subscribe((inference) -> {
            double score = inference.getAnomalyScore();
            int record = inference.getRecordNum();
            LOGGER.trace("record = {}, score = {}", record, score);
            // Output raw anomaly score
            output.println(score);
        }, (error) -> {
            LOGGER.error("Error processing data", error);
        }, () -> {
            LOGGER.trace("Done processing data");
            if (LOGGER.isDebugEnabled()) {
                model.showDebugInfo();
            }
        });
        network.start();

        // Pipe data to network
        Publisher publisher = model.getPublisher();
        BufferedReader in = new BufferedReader(new InputStreamReader(input));
        String line;
        while ((line = in.readLine()) != null && line.trim().length() > 0) {
            // Skip header lines
            if (skip > 0) {
                skip--;
                continue;
            }
            publisher.onNext(line);
        }
        publisher.onComplete();
        in.close();
        LOGGER.trace("Done publishing data");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:cc.osint.graphd.client.ProtographClient.java

public static void main(String[] args) throws Exception {
    if (args.length != 2) {
        System.err.println("Usage: " + ProtographClient.class.getSimpleName() + " <host> <port>");
        return;/* w w w . j ava  2s .c  om*/
    }
    String host = args[0];
    int port = Integer.parseInt(args[1]);
    ProtographClient client = new ProtographClient(host, port);

    // Read commands from the stdin.
    ConsoleReader reader = new ConsoleReader();
    for (;;) {
        String line = reader.readLine();
        if (line == null) {
            break;
        }

        // Sends the received line to the server.
        //client.send(line + "\r\n");
        List<JSONObject> results = client.exec(line.trim() + "\n");
        if (null == results) {
            log.info("no result!");
        } else {
            if (results.size() == 0) {
                log.info("OK");
            } else {
                int c = 0;
                for (JSONObject result : results) {
                    c++;
                    log.info(c + ": " + result.toString(4));
                }
            }
        }

        // If user typed the 'bye' command, wait until the server closes
        // the connection.
        if (line.toLowerCase().equals("bye")) {
            client.disconnect();
            break;
        }
    }
    client.disconnect();
}