Example usage for java.lang StringBuilder append

List of usage examples for java.lang StringBuilder append

Introduction

In this page you can find the example usage for java.lang StringBuilder append.

Prototype

@Override
    public StringBuilder append(double d) 

Source Link

Usage

From source file:com.mijecu25.sqlplus.SQLPlus.java

public static void main(String[] args) throws IOException {
    // Create and load the properties from the application properties file
    Properties properties = new Properties();
    properties.load(SQLPlus.class.getClassLoader().getResourceAsStream(SQLPlus.APPLICATION_PROPERTIES_FILE));

    SQLPlus.logger.info("Initializing " + SQLPlus.PROGRAM_NAME + " version "
            + properties.getProperty(SQLPlus.APPLICATION_PROPERTIES_FILE_VERSION));

    // Check if the user is using a valid console (i.e. not from Eclipse)
    if (System.console() == null) {
        // The Console object for the JVM could not be found. Alert the user 
        SQLPlus.logger.fatal(Messages.FATAL + "A JVM Console object was not found. Try running "
                + SQLPlus.PROGRAM_NAME + "from the command line");
        System.out.println(/*  ww w  .ja  v a 2 s .c om*/
                Messages.FATAL + SQLPlus.PROGRAM_NAME + " was not able to find your JVM's Console object. "
                        + "Try running " + SQLPlus.PROGRAM_NAME + " from the command line.");

        SQLPlus.exitSQLPlus();

        SQLPlus.logger.fatal(Messages.FATAL + Messages.QUIT_PROGRAM_ERROR(PROGRAM_NAME));
        return;
    }

    // UI intro
    System.out.println("Welcome to " + SQLPlus.PROGRAM_NAME
            + "! This program has a DSL to add alerts to various SQL DML events.");
    System.out.println("Be sure to use " + SQLPlus.PROGRAM_NAME + " from the command line.");
    System.out.println();

    // Get the version
    System.out.println("Version: " + properties.getProperty(SQLPlus.APPLICATION_PROPERTIES_FILE_VERSION));
    System.out.println();

    // Read the license file
    BufferedReader bufferedReader;
    bufferedReader = new BufferedReader(new FileReader(SQLPlus.LICENSE_FILE));

    // Read a line
    String line = bufferedReader.readLine();

    // While the line is not null
    while (line != null) {
        System.out.println(line);

        // Read a new lines
        line = bufferedReader.readLine();
    }

    // Close the buffer
    bufferedReader.close();
    System.out.println();

    // Create the jline console that allows us to remember commands, use arrow keys, and catch interruptions
    // from the user
    SQLPlus.console = new ConsoleReader();
    SQLPlus.console.setHandleUserInterrupt(true);

    try {
        // Get credentials from the user
        SQLPlus.logger.info("Create SQLPlusConnection");
        SQLPlus.createSQLPlusConnection();
    } catch (NullPointerException | SQLException | IllegalArgumentException e) {
        // NPE: This exception can occur if the user is running the program where the JVM Console
        // object cannot be found.
        // SQLE: TODO should I add here the error code?
        // This exception can occur when trying to establish a connection
        // IAE: This exception can occur when trying to establish a connection
        SQLPlus.logger
                .fatal(Messages.FATAL + Messages.FATAL_EXIT(SQLPlus.PROGRAM_NAME, e.getClass().getName()));
        System.out.println(Messages.FATAL + Messages.FATAL_EXCEPTION_ACTION(e.getClass().getSimpleName()) + " "
                + Messages.CHECK_LOG_FILES);
        SQLPlus.exitSQLPlus();

        SQLPlus.logger.fatal(Messages.FATAL + Messages.QUIT_PROGRAM_ERROR(SQLPlus.PROGRAM_NAME));
        return;
    } catch (UserInterruptException uie) {
        SQLPlus.logger.warn(Messages.WARNING + "The user typed an interrupt instruction.");
        SQLPlus.exitSQLPlus();

        return;
    }

    System.out.println("Connection established! Commands end with " + SQLPlus.END_OF_COMMAND);
    System.out.println("Type " + SQLPlus.EXIT + " or " + SQLPlus.QUIT + " to exit the application ");

    try {
        // Execute the input scanner
        while (true) {
            // Get a line from the user until the hit enter (carriage return, line feed/ new line).
            System.out.print(SQLPlus.PROMPT);
            try {
                line = SQLPlus.console.readLine().trim();
            } catch (NullPointerException npe) {
                // TODO test this behavior
                // If this exception is catch, it is very likely that the user entered the end of line command.
                // This means that the program should quit.
                SQLPlus.logger.warn(Messages.WARNING + "The input from the user is null. It is very likely that"
                        + "the user entered the end of line command and they want to quit.");
                SQLPlus.exitSQLPlus();

                return;
            }

            // If the user did not enter anything
            if (line.isEmpty()) {
                // Continue to the next iteration
                continue;
            }

            if (line.equals(".")) {
                line = "use courses;";
            }

            if (line.equals("-")) {
                line = "select created_at from classes;";
            }

            if (line.equals("--")) {
                line = "select name, year from classes;";
            }

            if (line.equals("*")) {
                line = "select * from classes;";
            }

            if (line.equals("x")) {
                line = "select name from classes, classes;";
            }

            if (line.equals("e")) {
                line = "select * feom classes;";
            }

            // Logic to quit
            if (line.equals(SQLPlus.QUIT) || line.equals(SQLPlus.EXIT)) {
                SQLPlus.logger.info("The user wants to quit " + SQLPlus.PROGRAM_NAME);
                SQLPlus.exitSQLPlus();
                break;
            }

            // Use a StringBuilder since jline works weird when it has read a line. The issue we were having was with the
            // end of command logic. jline does not keep the input from the user in the variable that was stored in. Each
            // time jline reads a new line, the variable is empty
            StringBuilder query = new StringBuilder();
            query.append(line);

            // While the user does not finish the command with the SQLPlus.END_OF_COMMAND
            while (query.charAt(query.length() - 1) != SQLPlus.END_OF_COMMAND) {
                // Print the wait for command prompt and get the next line for the user
                System.out.print(SQLPlus.WAIT_FOR_END_OF_COMMAND);
                query.append(" ");
                line = StringUtils.stripEnd(SQLPlus.console.readLine(), null);
                query.append(line);
            }

            SQLPlus.logger.info("Raw input from the user: " + query);

            try {
                Statement statement;

                try {
                    // Execute the antlr code to parse the user input
                    SQLPlus.logger.info("Will parse the user input to determine what to execute");
                    ANTLRStringStream input = new ANTLRStringStream(query.toString());
                    SQLPlusLex lexer = new SQLPlusLex(input);
                    CommonTokenStream tokens = new CommonTokenStream(lexer);
                    SQLPlusParser parser = new SQLPlusParser(tokens);

                    statement = parser.sqlplus();
                } catch (RecognitionException re) {
                    // TODO move this to somehwere else
                    //                        String message = Messages.WARNING + "You have an error in your SQL syntax. Check the manual"
                    //                                + " that corresponds to your " + SQLPlus.sqlPlusConnection.getCurrentDatabase()
                    //                                + " server or " + SQLPlus.PROGRAM_NAME + " for the correct syntax";
                    //                        SQLPlus.logger.warn(message);
                    //                        System.out.println(message);
                    statement = new StatementDefault();
                }

                statement.setStatement(query.toString());
                SQLPlus.sqlPlusConnection.execute(statement);
            } catch (UnsupportedOperationException uoe) {
                // This exception can occur when the user entered a command allowed by the parsers, but not currently
                // supported by SQLPlus. This can occur because the parser is written in such a way that supports
                // the addition of features.
                SQLPlus.logger.warn(Messages.WARNING + uoe);
                System.out.println(
                        Messages.WARNING + Messages.FATAL_EXCEPTION_ACTION(uoe.getClass().getSimpleName()) + " "
                                + Messages.CHECK_LOG_FILES);
                SQLPlus.logger.warn(Messages.WARNING + "The previous command is not currently supported.");
            }

        }
    } catch (IllegalArgumentException iae) {
        // This exception can occur when a command is executed but it had illegal arguments. Most likely
        // it is a programmer's error and should be addressed by the developer.
        SQLPlus.logger
                .fatal(Messages.FATAL + Messages.FATAL_EXIT(SQLPlus.PROGRAM_NAME, iae.getClass().getName()));
        SQLPlus.exitSQLPlus();

        SQLPlus.logger.fatal(Messages.FATAL + Messages.QUIT_PROGRAM_ERROR(SQLPlus.PROGRAM_NAME));
    } catch (UserInterruptException uie) {
        SQLPlus.logger.warn(Messages.WARNING + "The user typed an interrupt instruction.");
        SQLPlus.exitSQLPlus();
    }
}

From source file:org.eclipse.swt.snippets.Snippet196.java

public static void main(String[] args) {

    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Snippet 196");
    shell.setLayout(new GridLayout());
    final Text text = new Text(shell, SWT.BORDER);
    Font font = new Font(display, "Courier New", 10, SWT.NONE); //$NON-NLS-1$
    text.setFont(font);// ww  w. ja v  a 2  s.  c o m
    text.setText(template);
    text.addListener(SWT.Verify, new Listener() {
        //create the pattern for verification
        Pattern pattern = Pattern.compile(REGEX);
        //ignore event when caused by inserting text inside event handler
        boolean ignore;

        @Override
        public void handleEvent(Event e) {
            if (ignore)
                return;
            e.doit = false;
            if (e.start > 13 || e.end > 14)
                return;
            StringBuilder buffer = new StringBuilder(e.text);

            //handle backspace
            if (e.character == '\b') {
                for (int i = e.start; i < e.end; i++) {
                    // skip over separators
                    switch (i) {
                    case 0:
                        if (e.start + 1 == e.end) {
                            return;
                        } else {
                            buffer.append('(');
                        }
                        break;
                    case 4:
                        if (e.start + 1 == e.end) {
                            buffer.append(new char[] { '#', ')' });
                            e.start--;
                        } else {
                            buffer.append(')');
                        }
                        break;
                    case 8:
                        if (e.start + 1 == e.end) {
                            buffer.append(new char[] { '#', '-' });
                            e.start--;
                        } else {
                            buffer.append('-');
                        }
                        break;
                    default:
                        buffer.append('#');
                    }
                }
                text.setSelection(e.start, e.start + buffer.length());
                ignore = true;
                text.insert(buffer.toString());
                ignore = false;
                // move cursor backwards over separators
                if (e.start == 5 || e.start == 9)
                    e.start--;
                text.setSelection(e.start, e.start);
                return;
            }

            StringBuilder newText = new StringBuilder(defaultText);
            char[] chars = e.text.toCharArray();
            int index = e.start - 1;
            for (int i = 0; i < e.text.length(); i++) {
                index++;
                switch (index) {
                case 0:
                    if (chars[i] == '(')
                        continue;
                    index++;
                    break;
                case 4:
                    if (chars[i] == ')')
                        continue;
                    index++;
                    break;
                case 8:
                    if (chars[i] == '-')
                        continue;
                    index++;
                    break;
                }
                if (index >= newText.length())
                    return;
                newText.setCharAt(index, chars[i]);
            }
            // if text is selected, do not paste beyond range of selection
            if (e.start < e.end && index + 1 != e.end)
                return;
            Matcher matcher = pattern.matcher(newText);
            if (matcher.lookingAt()) {
                text.setSelection(e.start, index + 1);
                ignore = true;
                text.insert(newText.substring(e.start, index + 1));
                ignore = false;
            }
        }
    });

    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    font.dispose();
    display.dispose();
}

From source file:com.twitter.hraven.rest.client.HRavenRestClient.java

public static void main(String[] args) throws IOException {
    String apiHostname = null;//from  w  w w. j  av a 2 s .  c  o m
    String cluster = null;
    String username = null;
    String batchDesc = null;
    String signature = null;
    int limit = 2;
    boolean useHBaseAPI = false;
    boolean dumpJson = false;
    boolean hydrateTasks = false;
    List<String> taskResponseFilters = new ArrayList<String>();
    List<String> jobResponseFilters = new ArrayList<String>();
    List<String> flowResponseFilters = new ArrayList<String>();
    List<String> configFields = new ArrayList<String>();

    StringBuffer usage = new StringBuffer("Usage: java ");
    usage.append(HRavenRestClient.class.getName()).append(" [-options]\n");
    usage.append("Returns data from recent flows and their associated jobs\n");
    usage.append("where options include: \n");
    usage.append(" -a <API hostname> [required]\n");
    usage.append(" -c <cluster> [required]\n");
    usage.append(" -u <username> [required]\n");
    usage.append(" -f <flowName> [required]\n");
    usage.append(" -s <signature>\n");
    usage.append(" -l <limit>\n");
    usage.append(" -h - print this message and return\n");
    usage.append(" -H - use HBase API, not the REST API\n");
    usage.append(" -j - output json\n");
    usage.append(" -t - retrieve task information as well");
    usage.append(" -w - config field to be included in job response");
    usage.append(" -z - field to be included in task response");
    usage.append(" -y - field to be included in job response");
    usage.append(" -x - field to be included in flow response");

    for (int i = 0; i < args.length; i++) {
        if ("-a".equals(args[i])) {
            apiHostname = args[++i];
            continue;
        } else if ("-c".equals(args[i])) {
            cluster = args[++i];
            continue;
        } else if ("-u".equals(args[i])) {
            username = args[++i];
            continue;
        } else if ("-f".equals(args[i])) {
            batchDesc = args[++i];
            continue;
        } else if ("-s".equals(args[i])) {
            signature = args[++i];
            continue;
        } else if ("-l".equals(args[i])) {
            limit = Integer.parseInt(args[++i]);
            continue;
        } else if ("-H".equals(args[i])) {
            useHBaseAPI = true;
            continue;
        } else if ("-j".equals(args[i])) {
            dumpJson = true;
            continue;
        } else if ("-t".equals(args[i])) {
            hydrateTasks = true;
            continue;
        } else if ("-z".equals(args[i])) {
            String taskFilters = args[++i];
            taskResponseFilters = Arrays.asList(taskFilters.split(","));
            continue;
        } else if ("-y".equals(args[i])) {
            String jobFilters = args[++i];
            jobResponseFilters = Arrays.asList(jobFilters.split(","));
            continue;
        } else if ("-x".equals(args[i])) {
            String flowFilters = args[++i];
            flowResponseFilters = Arrays.asList(flowFilters.split(","));
            continue;
        } else if ("-w".equals(args[i])) {
            String configFilters = args[++i];
            configFields = Arrays.asList(configFilters.split(","));
            continue;
        } else if ("-h".equals(args[i])) {
            System.err.println(usage.toString());
            System.exit(1);
        } else {

        }
    }

    if (apiHostname == null || cluster == null || username == null || batchDesc == null) {
        System.err.println(usage.toString());
        System.exit(1);
    }

    List<Flow> flows;
    if (useHBaseAPI) {
        JobHistoryService jobHistoryService = new JobHistoryService(HBaseConfiguration.create());
        flows = jobHistoryService.getFlowSeries(cluster, username, batchDesc, signature, hydrateTasks, limit);
    } else {
        HRavenRestClient client = new HRavenRestClient(apiHostname, 100000, 100000);

        // use this call to call flows without configs
        flows = client.fetchFlows(cluster, username, batchDesc, signature, flowResponseFilters,
                jobResponseFilters, limit);
        // use this call to call flows with configs
        flows = client.fetchFlowsWithConfig(cluster, username, batchDesc, signature, limit, flowResponseFilters,
                jobResponseFilters, configFields);
        // use this call to call flows with config patterns
        flows = client.fetchFlowsWithConfig(cluster, username, batchDesc, signature, limit, flowResponseFilters,
                jobResponseFilters, configFields);

        if (hydrateTasks) {
            for (Flow flow : flows) {
                for (JobDetails jd : flow.getJobs()) {
                    String jobId = jd.getJobId();
                    List<TaskDetails> td = client.fetchTaskDetails(cluster, jobId, taskResponseFilters);
                    jd.addTasks(td);
                }
            }
        }
    }

    if (dumpJson) {
        ObjectMapper om = ObjectMapperProvider.createCustomMapper();
        SimpleModule module = new SimpleModule("hRavenModule", new Version(0, 4, 0, null));
        module.addSerializer(Flow.class, new FlowSerializer());
        module.addSerializer(JobDetails.class, new JobDetailsSerializer());
        om.registerModule(module);
        if (flows.size() > 0) {
            System.out.println(om.writeValueAsString(flows.get(0)));
        }
        return;
    }

    System.out.println("Found " + flows.size() + " flows");
    StringBuilder sb = new StringBuilder();
    sb.append("\t\t").append("jobId");
    sb.append("\t\t").append("version");
    sb.append("\t\t").append("status");
    sb.append("\t").append("maps");
    sb.append("\t").append("reduces");
    sb.append("\t").append("rBytesRead");
    sb.append("\t").append("feature");
    sb.append("\t\t\t").append("alias");
    System.out.println(sb.toString());

    int i = 0;
    for (Flow flow : flows) {
        long minSubmitTime = -1, maxFinishTime = -1;
        for (JobDetails job : flow.getJobs()) {
            if (minSubmitTime == -1 && job.getSubmitTime() > 0) {
                minSubmitTime = job.getSubmitTime();
            }
            minSubmitTime = Math.min(minSubmitTime, job.getSubmitTime());
            maxFinishTime = Math.max(maxFinishTime, job.getFinishTime());
        }

        if (minSubmitTime > 0 && maxFinishTime > 0) {
            System.out.println(String.format("Flow #%d: %s - %s", i++, DATE_FORMAT.format(minSubmitTime),
                    DATE_FORMAT.format(maxFinishTime)));
        } else {
            System.out.println(String.format("Flow #%d:", i++));
        }

        for (JobDetails job : flow.getJobs()) {
            sb = new StringBuilder();
            sb.append(" - ").append(job.getJobId());
            sb.append("\t").append(job.getVersion());
            sb.append("\t").append(job.getStatus());
            sb.append("\t").append(job.getTotalMaps());
            sb.append("\t").append(job.getTotalReduces());
            long reduceBytesRead = job.getReduceCounters().getCounter("FileSystemCounters",
                    "FILE_BYTES_READ") != null
                            ? job.getReduceCounters().getCounter("FileSystemCounters", "FILE_BYTES_READ")
                                    .getValue()
                            : -1;
            sb.append("\t").append(reduceBytesRead);
            sb.append("\t").append(job.getConfiguration().get("pig.job.feature"));
            sb.append("\t").append(job.getConfiguration().get("pig.alias"));
            System.out.println(sb.toString());
        }
    }
}

From source file:com.linkedin.databus2.client.util.DatabusClusterUtil.java

/**
 * @param args/* ww  w  .  j  av a  2 s.  c o  m*/
 *            DbusClusterUtil -z <zookeper-server> -c <cluster-name> [-p
 *            <partitionNumber] partitions readSCN writeSCN SCN remove
 *            clients
 */
public static void main(String[] args) {
    try {
        GnuParser cmdLineParser = new GnuParser();
        Options options = new Options();
        options.addOption("z", true, "zk-server").addOption("c", true, "cluster-name ")
                .addOption("p", true, "partition").addOption("l", false, "legacy")
                .addOption("h", false, "help");
        CommandLine cmdLineArgs = cmdLineParser.parse(options, args, false);

        if (cmdLineArgs.hasOption('h')) {
            usage();
            System.exit(0);
        }

        if (!cmdLineArgs.hasOption('c')) {
            usage();
            System.exit(1);
        }
        String clusterName = cmdLineArgs.getOptionValue('c');
        String zkServer = cmdLineArgs.getOptionValue('z');
        boolean isLegacyChkptLocation = cmdLineArgs.hasOption('l');
        if (zkServer == null || zkServer.isEmpty()) {
            zkServer = "localhost:2181";
        }

        String partitionStr = cmdLineArgs.getOptionValue('p');
        String partition = partitionStr;
        if ((partition != null) && partition.equals("all")) {
            partition = "";
        }

        String[] fns = cmdLineArgs.getArgs();
        if (fns.length < 1) {
            usage();
            System.exit(1);
        }

        DatabusClusterUtilHelper clusterState = new DatabusClusterUtilHelper(zkServer, clusterName);

        String function = fns[0];
        String arg1 = (fns.length > 1) ? fns[1] : null;
        String arg2 = (fns.length > 2) ? fns[2] : null;

        boolean clusterExists = clusterState.existsCluster();
        if (function.equals("create")) {
            if (!clusterExists) {
                if (arg1 == null) {
                    throw new DatabusClusterUtilException("create: please provide the number of partitions");
                }
                int part = Integer.parseInt(arg1);
                clusterState.createCluster(part);
                return;
            } else {
                throw new DatabusClusterUtilException("Cluster " + clusterName + " already exists");
            }
        }
        if (!clusterExists) {
            throw new DatabusClusterUtilException("Cluster doesn't exist! ");
        }

        if (function.equals("delete")) {
            clusterState.removeCluster();
        } else if (function.equals("partitions")) {
            int numParts = clusterState.getNumPartitions();
            System.out.println(numParts);
        } else {
            // all these functions require the notion of partition;
            Set<Integer> partitions = getPartitions(partition, clusterState.getNumPartitions());
            if (function.equals("sources")) {
                DatabusClusterCkptManager ckptMgr = new DatabusClusterCkptManager(zkServer, clusterName, null,
                        partitions, isLegacyChkptLocation);
                Set<String> sources = ckptMgr.getSourcesFromCheckpoint();
                if (sources != null) {
                    for (String s : sources) {
                        System.out.println(s);
                    }
                } else {
                    throw new DatabusClusterUtilException(
                            "sources: Sources not found for cluster " + clusterName);
                }
            } else if (function.equals("clients")) {
                clusterState.getClusterInfo();
                for (Integer p : partitions) {
                    String client = clusterState.getInstanceForPartition(p);
                    System.out.println(p + "\t" + client);
                }
            } else if (function.equals("readSCN")) {
                List<String> sources = getSources(arg1);
                if ((sources != null) && !sources.isEmpty()) {
                    DatabusClusterCkptManager ckptMgr = new DatabusClusterCkptManager(zkServer, clusterName,
                            sources, partitions, isLegacyChkptLocation);
                    Map<Integer, Checkpoint> ckpts = ckptMgr.readCheckpoint();
                    char delim = '\t';
                    for (Map.Entry<Integer, Checkpoint> mkPair : ckpts.entrySet()) {
                        StringBuilder output = new StringBuilder(64);
                        output.append(mkPair.getKey());
                        output.append(delim);
                        Checkpoint cp = mkPair.getValue();
                        if (cp == null) {
                            output.append(-1);
                            output.append(delim);
                            output.append(-1);
                        } else {
                            if (cp.getConsumptionMode() == DbusClientMode.ONLINE_CONSUMPTION) {
                                output.append(cp.getWindowScn());
                                output.append(delim);
                                output.append(cp.getWindowOffset());
                            } else if (cp.getConsumptionMode() == DbusClientMode.BOOTSTRAP_CATCHUP) {
                                output.append(cp.getWindowScn());
                                output.append(delim);
                                output.append(cp.getWindowOffset());
                            } else if (cp.getConsumptionMode() == DbusClientMode.BOOTSTRAP_SNAPSHOT) {
                                output.append(cp.getBootstrapSinceScn());
                                output.append(delim);
                                output.append(-1);
                            }
                        }
                        System.out.println(output.toString());
                    }
                } else {
                    throw new DatabusClusterUtilException("readSCN: please specify non-empty sources");
                }
            } else if (function.equals("checkpoint")) {
                List<String> sources = getSources(arg1);
                if ((sources != null) && !sources.isEmpty()) {
                    DatabusClusterCkptManager ckptMgr = new DatabusClusterCkptManager(zkServer, clusterName,
                            sources, partitions, isLegacyChkptLocation);
                    Map<Integer, Checkpoint> ckpts = ckptMgr.readCheckpoint();
                    char delim = '\t';
                    for (Map.Entry<Integer, Checkpoint> mkPair : ckpts.entrySet()) {
                        StringBuilder output = new StringBuilder(64);
                        output.append(mkPair.getKey());
                        output.append(delim);
                        Checkpoint cp = mkPair.getValue();
                        if (cp == null) {
                            output.append("null");
                        } else {
                            output.append(cp.toString());
                        }
                        System.out.println(output.toString());
                    }
                } else {
                    throw new DatabusClusterUtilException("readSCN: please specify non-empty sources");
                }
            } else if (function.equals("writeSCN")) {
                String scnStr = arg1;
                Long scn = Long.parseLong(scnStr);
                if (partitionStr != null) {
                    List<String> sources = getSources(arg2);
                    if ((sources != null) && !sources.isEmpty()) {
                        DatabusClusterCkptManager ckptMgr = new DatabusClusterCkptManager(zkServer, clusterName,
                                sources, partitions, isLegacyChkptLocation);
                        ckptMgr.writeCheckpoint(scn);
                    } else {
                        throw new DatabusClusterUtilException("writeSCN: please specify non-empty sources");
                    }
                } else {
                    throw new DatabusClusterUtilException(
                            "writeSCN: to write the SCN to all partitions please use '-p all'");
                }
            } else if (function.equals("removeSCN")) {
                if (partitionStr != null) {

                    List<String> sources = getSources(arg1);
                    if ((sources != null) && !sources.isEmpty()) {
                        DatabusClusterCkptManager ckptMgr = new DatabusClusterCkptManager(zkServer, clusterName,
                                sources, partitions, isLegacyChkptLocation);
                        ckptMgr.remove();
                    } else {
                        throw new DatabusClusterUtilException("remove: please specify non-empty sources");
                    }
                } else {
                    throw new DatabusClusterUtilException(
                            "remove: to remove SCN from all partitions please use '-p all'");
                }
            } else {
                usage();
                System.exit(1);
            }
        }
    } catch (ParseException e) {
        usage();
        System.exit(1);
    } catch (DatabusClusterUtilException e) {
        System.err.println("Error! " + e.toString());
        System.exit(1);
    }

}

From source file:com.sccl.attech.common.utils.excel.ExportExcel.java

/**
 * //www. j a  v a  2 s .co  m
 */
public static void main(String[] args) throws Throwable {

    List<String> headerList = Lists.newArrayList();
    headerList.add("??");
    headerList.add("??");
    headerList.add("");
    headerList.add("?");
    headerList.add("");

    List<String> dataRowList = Lists.newArrayList();
    for (int i = 1; i <= headerList.size(); i++) {
        dataRowList.add("?" + i);
    }

    List<List<String>> dataList = Lists.newArrayList();
    for (int i = 1; i <= 100; i++) {
        dataList.add(dataRowList);
    }

    ExportExcel ee = new ExportExcel(null, headerList);

    for (int i = 0; i < dataList.size(); i++) {
        Row row = ee.addRow();
        for (int j = 0; j < dataList.get(i).size(); j++) {
            ee.addCell(row, j, dataList.get(i).get(j));
        }
    }
    ee.createAddMergedRegion();
    StringBuilder sb = new StringBuilder();
    sb.append("????").append("\r\n");
    sb.append(
            "???64????? ?: ; { } !  @ $  ^ & | , . / ? [ ] ~ * # <+ - = ")
            .append("\r");
    sb.append("??:").append("").append("'").append("%")
            .append("\\").append("?   ")
            .append("\r");
    sb.append(
            "?? ?60?????? : ; { } !  @ $  ^ & | , . / ? [ ] ~ * # < +- = ")
            .append("\r");
    sb.append(
            " ????")
            .append("\r");
    sb.append(
            "??180???1590???15???? :")
            .append("\r");
    sb.append(
            "79.000000000000000?GPS???????6?")
            .append("\r");
    sb.append(
            "* ??2000??2000?????")
            .append("\r");
    sb.append("* EXCEL???.xls97-2003").append("\r");
    sb.append("* ??????").append("\r");
    sb.append(
            "*   ??")
            .append("\r");
    sb.append(
            "* ????POI??POI??????")
            .append("\r");
    ee.addCellStyle(ee.getExistRow(1), 6, sb.toString());

    //demo
    ee.initializeDemo(null, headerList);
    ee.addCellStyle(ee.getExistRow(25), 6, "?");
    ee.addCellStyle(ee.getExistRow(25), 7, "");
    ee.addCellStyle(ee.getExistRow(25), 8, "");
    ee.addCellStyle(ee.getExistRow(25), 9, "116.35526644472");
    ee.addCellStyle(ee.getExistRow(25), 10, "40.03711432476");
    //ee.addCell(ee.getExistRow(26), 6, dataList.get(i).get(j));

    ee.writeFile("D:\\export.xlsx");

    ee.dispose();

    log.debug("Export success.");

}

From source file:com.linkedin.restli.tools.idlcheck.RestLiResourceModelCompatibilityChecker.java

public static void main(String[] args) {
    final Options options = new Options();
    options.addOption("h", "help", false, "Print help");
    options.addOption(OptionBuilder.withArgName("compatibility_level").withLongOpt("compat").hasArg()
            .withDescription("Compatibility level " + listCompatLevelOptions()).create('c'));
    options.addOption(OptionBuilder.withLongOpt("report").withDescription(
            "Prints a report at the end of the execution that can be parsed for reporting to other tools")
            .create("report"));
    final String cmdLineSyntax = RestLiResourceModelCompatibilityChecker.class.getCanonicalName()
            + " [pairs of <prevRestspecPath currRestspecPath>]";

    final CommandLineParser parser = new PosixParser();
    final CommandLine cmd;

    try {/* ww w  .j a  v  a 2 s.  c o m*/
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        new HelpFormatter().printHelp(cmdLineSyntax, options, true);
        System.exit(255);
        return; // to suppress IDE warning
    }

    final String[] targets = cmd.getArgs();
    if (cmd.hasOption('h') || targets.length < 2 || targets.length % 2 != 0) {
        new HelpFormatter().printHelp(cmdLineSyntax, options, true);
        System.exit(255);
    }

    final String compatValue;
    if (cmd.hasOption('c')) {
        compatValue = cmd.getOptionValue('c');
    } else {
        compatValue = CompatibilityLevel.DEFAULT.name();
    }

    final CompatibilityLevel compat;
    try {
        compat = CompatibilityLevel.valueOf(compatValue.toUpperCase());
    } catch (IllegalArgumentException e) {
        new HelpFormatter().printHelp(cmdLineSyntax, options, true);
        System.exit(255);
        return;
    }

    final StringBuilder allSummaries = new StringBuilder();
    final RestLiResourceModelCompatibilityChecker checker = new RestLiResourceModelCompatibilityChecker();
    for (int i = 1; i < targets.length; i += 2) {
        checker.setResolverPath(System.getProperty(AbstractGenerator.GENERATOR_RESOLVER_PATH));

        String prevTarget = targets[i - 1];
        String currTarget = targets[i];
        checker.check(prevTarget, currTarget, compat);
    }

    allSummaries.append(checker.getInfoMap().createSummary());

    if (compat != CompatibilityLevel.OFF && allSummaries.length() > 0) {
        System.out.println(allSummaries);
    }

    if (cmd.hasOption("report")) {
        System.out.println(new CompatibilityReport(checker.getInfoMap(), compat).createReport());
        System.exit(0);
    }

    System.exit(checker.getInfoMap().isCompatible(compat) ? 0 : 1);
}

From source file:org.eclipse.swt.snippets.Snippet179.java

public static void main(String[] args) {
    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Snippet 179");
    shell.setLayout(new GridLayout());
    final Text text = new Text(shell, SWT.BORDER);
    text.setText("YYYY/MM/DD");
    final Calendar calendar = Calendar.getInstance();
    text.addListener(SWT.Verify, new Listener() {
        boolean ignore;

        @Override//from   w  w  w. j av  a  2s . c  o  m
        public void handleEvent(Event e) {
            if (ignore)
                return;
            e.doit = false;
            StringBuilder buffer = new StringBuilder(e.text);
            char[] chars = new char[buffer.length()];
            buffer.getChars(0, chars.length, chars, 0);
            if (e.character == '\b') {
                for (int i = e.start; i < e.end; i++) {
                    switch (i) {
                    case 0: /* [Y]YYY */
                    case 1: /* Y[Y]YY */
                    case 2: /* YY[Y]Y */
                    case 3: /* YYY[Y] */ {
                        buffer.append('Y');
                        break;
                    }
                    case 5: /* [M]M*/
                    case 6: /* M[M] */ {
                        buffer.append('M');
                        break;
                    }
                    case 8: /* [D]D */
                    case 9: /* D[D] */ {
                        buffer.append('D');
                        break;
                    }
                    case 4: /* YYYY[/]MM */
                    case 7: /* MM[/]DD */ {
                        buffer.append('/');
                        break;
                    }
                    default:
                        return;
                    }
                }
                text.setSelection(e.start, e.start + buffer.length());
                ignore = true;
                text.insert(buffer.toString());
                ignore = false;
                text.setSelection(e.start, e.start);
                return;
            }

            int start = e.start;
            if (start > 9)
                return;
            int index = 0;
            for (int i = 0; i < chars.length; i++) {
                if (start + index == 4 || start + index == 7) {
                    if (chars[i] == '/') {
                        index++;
                        continue;
                    }
                    buffer.insert(index++, '/');
                }
                if (chars[i] < '0' || '9' < chars[i])
                    return;
                if (start + index == 5 && '1' < chars[i])
                    return; /* [M]M */
                if (start + index == 8 && '3' < chars[i])
                    return; /* [D]D */
                index++;
            }
            String newText = buffer.toString();
            int length = newText.length();
            StringBuilder date = new StringBuilder(text.getText());
            date.replace(e.start, e.start + length, newText);
            calendar.set(Calendar.YEAR, 1901);
            calendar.set(Calendar.MONTH, Calendar.JANUARY);
            calendar.set(Calendar.DATE, 1);
            String yyyy = date.substring(0, 4);
            if (yyyy.indexOf('Y') == -1) {
                int year = Integer.parseInt(yyyy);
                calendar.set(Calendar.YEAR, year);
            }
            String mm = date.substring(5, 7);
            if (mm.indexOf('M') == -1) {
                int month = Integer.parseInt(mm) - 1;
                int maxMonth = calendar.getActualMaximum(Calendar.MONTH);
                if (0 > month || month > maxMonth)
                    return;
                calendar.set(Calendar.MONTH, month);
            }
            String dd = date.substring(8, 10);
            if (dd.indexOf('D') == -1) {
                int day = Integer.parseInt(dd);
                int maxDay = calendar.getActualMaximum(Calendar.DATE);
                if (1 > day || day > maxDay)
                    return;
                calendar.set(Calendar.DATE, day);
            } else {
                if (calendar.get(Calendar.MONTH) == Calendar.FEBRUARY) {
                    char firstChar = date.charAt(8);
                    if (firstChar != 'D' && '2' < firstChar)
                        return;
                }
            }
            text.setSelection(e.start, e.start + length);
            ignore = true;
            text.insert(newText);
            ignore = false;
        }
    });
    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:com.icantrap.collections.dawg.Dawg.java

public static void main(String[] args) throws IOException {
    Dawg dawg = Dawg.load(Dawg.class.getResourceAsStream("/twl06.dat"));

    InputStreamReader isr = new InputStreamReader(System.in);
    BufferedReader reader = new BufferedReader(isr);

    StopWatch stopWatch = new StopWatch();

    while (true) {
        System.out.print("letters:  ");
        String letters = reader.readLine();
        System.out.print("pattern:  ");
        String pattern = reader.readLine();

        stopWatch.reset();/*from w ww. j av  a  2  s  .  c  om*/
        stopWatch.start();
        Result[] results = dawg.subwords(letters.toUpperCase(), pattern.toUpperCase());
        stopWatch.stop();

        if (results != null) {
            System.out.println();

            for (Result result : results) {
                StringBuilder message = new StringBuilder(result.word);
                if (result.wildcardPositions != null) {
                    message.append(" with wildcards at");
                    for (int position : result.wildcardPositions)
                        message.append(" ").append(position);
                }
                System.out.println(message.toString());
                System.out.println();
            }

            System.out.println("Found " + results.length + " matches in " + stopWatch.getTime() + " ms.");
        }

        System.out.println();
    }
}

From source file:com.ctriposs.rest4j.tools.idlcheck.Rest4JResourceModelCompatibilityChecker.java

@SuppressWarnings({ "static" })
public static void main(String[] args) {
    final Options options = new Options();
    options.addOption("h", "help", false, "Print help");
    options.addOption(OptionBuilder.withArgName("compatibility_level").withLongOpt("compat").hasArg()
            .withDescription("Compatibility level " + listCompatLevelOptions()).create('c'));
    final String cmdLineSyntax = Rest4JResourceModelCompatibilityChecker.class.getCanonicalName()
            + " [pairs of <prevRestspecPath currRestspecPath>]";

    final CommandLineParser parser = new PosixParser();
    final CommandLine cmd;

    try {//from w ww  . j  a  v  a 2s.  c  o  m
        cmd = parser.parse(options, args);
    } catch (ParseException e) {
        new HelpFormatter().printHelp(cmdLineSyntax, options, true);
        System.exit(1);
        return; // to suppress IDE warning
    }

    final String[] targets = cmd.getArgs();
    if (cmd.hasOption('h') || targets.length < 2 || targets.length % 2 != 0) {
        new HelpFormatter().printHelp(cmdLineSyntax, options, true);
        System.exit(1);
    }

    final String compatValue;
    if (cmd.hasOption('c')) {
        compatValue = cmd.getOptionValue('c');
    } else {
        compatValue = CompatibilityLevel.DEFAULT.name();
    }

    final CompatibilityLevel compat;
    try {
        compat = CompatibilityLevel.valueOf(compatValue.toUpperCase());
    } catch (IllegalArgumentException e) {
        new HelpFormatter().printHelp(cmdLineSyntax, options, true);
        System.exit(1);
        return;
    }

    final StringBuilder allSummaries = new StringBuilder();
    boolean result = true;
    for (int i = 1; i < targets.length; i += 2) {
        final Rest4JResourceModelCompatibilityChecker checker = new Rest4JResourceModelCompatibilityChecker();
        checker.setResolverPath(System.getProperty(AbstractGenerator.GENERATOR_RESOLVER_PATH));

        String prevTarget = targets[i - 1];
        String currTarget = targets[i];
        result &= checker.check(prevTarget, currTarget, compat);
        allSummaries.append(checker.getInfoMap().createSummary(prevTarget, currTarget));
    }

    if (compat != CompatibilityLevel.OFF && allSummaries.length() > 0) {
        System.out.println(allSummaries);
    }

    System.exit(result ? 0 : 1);
}

From source file:cc.twittertools.stream.GatherStatusStream.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws TwitterException {
    Options options = new Options();
    options.addOption(OptionBuilder.withArgName("list").hasArgs()
            .withDescription("comma-separated list of BCP 47 language identifiers").withLongOpt(LANGUAGE_OPTION)
            .create('l'));
    options.addOption(OptionBuilder.withArgName("list").hasArgs()
            .withDescription(// ww  w . j ava  2 s  .  c o m
                    "comma-separated list of longitude,latitude pairs specifying a set of bounding boxes")
            .withLongOpt(LOCATIONS_OPTION).create('g'));
    options.addOption("n", NO_BOUNDING_BOX_OPTION, false, "do not consider places' bounding box");

    CommandLine cmdline = null;
    CommandLineParser parser = new GnuParser();
    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(RunQueriesThrift.class.getName(), options);
        System.exit(-1);
    }

    PatternLayout layoutStandard = new PatternLayout();
    layoutStandard.setConversionPattern("[%p] %d %c %M - %m%n");

    PatternLayout layoutSimple = new PatternLayout();
    layoutSimple.setConversionPattern("%m%n");

    // Filter for the statuses: we only want INFO messages
    LevelRangeFilter filter = new LevelRangeFilter();
    filter.setLevelMax(Level.INFO);
    filter.setLevelMin(Level.INFO);
    filter.setAcceptOnMatch(true);
    filter.activateOptions();

    TimeBasedRollingPolicy statusesRollingPolicy = new TimeBasedRollingPolicy();
    statusesRollingPolicy.setFileNamePattern("statuses.log" + HOUR_ROLL);
    statusesRollingPolicy.activateOptions();

    RollingFileAppender statusesAppender = new RollingFileAppender();
    statusesAppender.setRollingPolicy(statusesRollingPolicy);
    statusesAppender.addFilter(filter);
    statusesAppender.setLayout(layoutSimple);
    statusesAppender.activateOptions();

    TimeBasedRollingPolicy warningsRollingPolicy = new TimeBasedRollingPolicy();
    warningsRollingPolicy.setFileNamePattern("warnings.log" + HOUR_ROLL);
    warningsRollingPolicy.activateOptions();

    RollingFileAppender warningsAppender = new RollingFileAppender();
    warningsAppender.setRollingPolicy(statusesRollingPolicy);
    warningsAppender.setThreshold(Level.WARN);
    warningsAppender.setLayout(layoutStandard);
    warningsAppender.activateOptions();

    ConsoleAppender consoleAppender = new ConsoleAppender();
    consoleAppender.setThreshold(Level.WARN);
    consoleAppender.setLayout(layoutStandard);
    consoleAppender.activateOptions();

    // configures the root logger
    Logger rootLogger = Logger.getRootLogger();
    rootLogger.setLevel(Level.INFO);
    rootLogger.removeAllAppenders();
    rootLogger.addAppender(consoleAppender);
    rootLogger.addAppender(statusesAppender);
    rootLogger.addAppender(warningsAppender);

    // creates filters for the query
    FilterQuery fq = new FilterQuery();
    StringBuilder criteria = new StringBuilder();

    /*
     * @see https://dev.twitter.com/docs/streaming-apis/parameters#language
     */
    final boolean filterLanguage = cmdline.hasOption(LANGUAGE_OPTION);
    String[] languages = null;
    if (filterLanguage) {
        languages = cmdline.getOptionValue(LANGUAGE_OPTION).split(",");
        fq.language(languages);
        criteria.append("languages: [" + cmdline.getOptionValue(LANGUAGE_OPTION) + "]\t");
    }
    final String[] langs = languages;

    /*
     * @see https://dev.twitter.com/docs/streaming-apis/parameters#locations
     */
    double[][] locations = null;
    if (cmdline.hasOption(LOCATIONS_OPTION)) {
        String[] locationsArg = cmdline.getOptionValue(LOCATIONS_OPTION).split(",");
        int nCoords = locationsArg.length;
        if (nCoords % 2 == 0) {
            int pairs = nCoords / 2;
            locations = new double[pairs][2];
            int cnt = 0;
            for (int i = 0; i < pairs; i++) {
                locations[i][0] = Double.parseDouble(locationsArg[cnt]);
                cnt++;
                locations[i][1] = Double.parseDouble(locationsArg[cnt]);
                cnt++;
            }
            fq.locations(locations);
            criteria.append("locations: [" + cmdline.getOptionValue(LOCATIONS_OPTION) + "]\t");
        } else {
            System.err.println("There is a missing coordinate. See "
                    + "https://dev.twitter.com/docs/streaming-apis/parameters#locations");
            System.exit(-1);
        }
    } else {
        fq.locations(new double[][] { { -180, -90 }, { 180, 90 } });
    }
    final double[][] loc = locations;

    final boolean no_bounding_box = cmdline.hasOption(NO_BOUNDING_BOX_OPTION);
    if (no_bounding_box) {
        criteria.append("--no-bounding-box\t");
    }

    // creates a custom logger and log messages
    final Logger logger = Logger.getLogger(GatherStatusStream.class);

    logger.info(criteria);

    RawStreamListener rawListener = new RawStreamListener() {

        @Override
        public void onMessage(String rawString) {
            if (no_bounding_box && loc != null) {
                try {
                    JSONObject status = new JSONObject(rawString);
                    JSONObject coordObj = status.getJSONObject("coordinates");
                    JSONArray coords = coordObj.getJSONArray("coordinates");
                    double longitude = coords.getDouble(0);
                    double latitude = coords.getDouble(1);

                    // checks location
                    for (int i = 0; i < loc.length; i += 2) {
                        if (((loc[i][0] <= longitude) && (longitude <= loc[i + 1][0]))
                                || ((loc[i][1] <= latitude) && (latitude <= loc[i + 1][1]))) {
                            break;
                        } else if (i == loc.length - 1)
                            return;
                    }
                } catch (JSONException e) { /* Either "Coordinates" is null or trash is coming*/
                    return;
                }
            }

            if (filterLanguage) {
                try {
                    JSONObject status = new JSONObject(rawString);
                    // checks language
                    String lang = status.getString("lang");
                    for (int i = 0; i < langs.length; i++) {
                        if (langs[i].equals(lang))
                            break;
                        else if (i == langs.length - 1)
                            return;
                    }
                } catch (JSONException e) { /* Trash is coming */
                    return;
                }
            }
            cnt++;
            logger.info(rawString);
            if (cnt % 1000 == 0) {
                System.out.println(cnt + " messages received.");
            }
        }

        @Override
        public void onException(Exception ex) {
            logger.warn(ex);
        }
    };

    TwitterStream twitterStream = new TwitterStreamFactory().getInstance();
    twitterStream.addListener(rawListener);
    twitterStream.filter(fq);
}