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:javaapplicationclientrest.JavaApplicationClientRest.java

/**
 * @param args the command line arguments
 *//*  ww w.j a  v a  2 s .com*/
public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    ControllerCliente controller = new ControllerCliente();
    while (true) {
        controller.getMenu();

        int op = 0;
        try {
            op = Integer.parseInt(input.nextLine());
        } catch (Exception e) {
        }

        //input.nextLine();
        switch (op) {
        case 1:
            controller.listarNoticias();
            break;
        case 2:

            System.out.println("Informe o titulo: ");
            String titulo = input.nextLine();
            if (titulo.trim().equals("")) {
                System.out.println("Ttulo invlido");
                break;
            }
            System.out.println("Informe o autor: ");
            String autor = input.nextLine();
            if (autor.trim().equals("")) {
                System.out.println("Autor invlido");
                break;
            }
            System.out.println("Informe o Conteudo: ");
            String conteudo = input.nextLine();
            if (conteudo.trim().equals("")) {
                System.out.println("Conteudo invlido");
                break;
            }
            //System.out.println(id);
            controller.cadastrarNoticia(titulo, autor, conteudo);
            break;

        case 3:

            try {
                System.out.println("Informe o id da notcia a ser removida: ");
                String idN = input.nextLine();
                Integer.parseInt(idN);
                controller.removerNoticia(idN);
            } catch (Exception e) {
                System.out.println("Numero invlido");
            }
            break;
        case 4:
            try {
                System.out.println("Informe o Id da notcia desejada:");
                String idN = input.nextLine();
                Integer.parseInt(idN);
                controller.getNoticia(idN);
            } catch (Exception e) {
                System.out.println("Id invlido");
                break;
            }
            break;
        case 5:
            try {
                System.out.println("Informe o Id da notcia para ser atualizada:");
                String idA = input.nextLine();
                Integer.parseInt(idA);
                System.out.println("Informe o novo titulo: ");
                String tituloN = input.nextLine();
                controller.atualizarNoticia(idA, tituloN);
            } catch (Exception e) {
                System.out.println("Id invlido");
            }
            break;

        default:
            System.out.println("Opo invlida. Escolha uma opo novamente");
            break;
        } // End switch
    } // End while

}

From source file:eu.fbk.dkm.sectionextractor.PageClassMerger.java

public static void main(String args[]) throws IOException {

    CommandLineWithLogger commandLineWithLogger = new CommandLineWithLogger();
    commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg()
            .withDescription("WikiData ID file").isRequired().withLongOpt("wikidata-id").create("i"));
    commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg()
            .withDescription("Airpedia Person file").isRequired().withLongOpt("airpedia").create("a"));
    commandLineWithLogger.addOption(OptionBuilder.withArgName("file").hasArg().withDescription("Output file")
            .isRequired().withLongOpt("output").create("o"));
    CommandLine commandLine = null;//w w w.  j  av  a 2s  .  c  o m
    try {
        commandLine = commandLineWithLogger.getCommandLine(args);
        PropertyConfigurator.configure(commandLineWithLogger.getLoggerProps());
    } catch (Exception e) {
        System.exit(1);
    }

    String wikiIDFileName = commandLine.getOptionValue("wikidata-id");
    String airpediaFileName = commandLine.getOptionValue("airpedia");
    String outputFileName = commandLine.getOptionValue("output");

    HashMap<Integer, String> wikiIDs = new HashMap<>();
    HashSet<Integer> airpediaClasses = new HashSet<>();

    List<String> strings;

    logger.info("Loading file " + wikiIDFileName);
    strings = Files.readLines(new File(wikiIDFileName), Charsets.UTF_8);
    for (String line : strings) {
        line = line.trim();
        if (line.length() == 0) {
            continue;
        }
        if (line.startsWith("#")) {
            continue;
        }

        String[] parts = line.split("\t");
        if (parts.length < 2) {
            continue;
        }

        int id;
        try {
            id = Integer.parseInt(parts[0]);
        } catch (Exception e) {
            continue;
        }
        wikiIDs.put(id, parts[1]);
    }

    logger.info("Loading file " + airpediaFileName);
    strings = Files.readLines(new File(airpediaFileName), Charsets.UTF_8);
    for (String line : strings) {
        line = line.trim();
        if (line.length() == 0) {
            continue;
        }
        if (line.startsWith("#")) {
            continue;
        }

        String[] parts = line.split("\t");
        if (parts.length < 2) {
            continue;
        }

        int id;
        try {
            id = Integer.parseInt(parts[0]);
        } catch (Exception e) {
            continue;
        }
        airpediaClasses.add(id);
    }

    logger.info("Saving information");
    BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileName));
    for (int i : wikiIDs.keySet()) {
        if (!airpediaClasses.contains(i)) {
            continue;
        }

        writer.append(wikiIDs.get(i)).append("\n");
    }
    writer.close();
}

From source file:CommandsFromZipFile.java

/**
 *  Sample test to retrieve command value using zip file
 * @param args//  w  w  w.j  av a  2  s.  c om
 */
public static void main(String[] args) {
    //by default it sets to Ctrl+D
    System.setProperty("jline.shutdownhook", "true");
    try {
        ConsoleReader consoleReader = new ConsoleReader();
        consoleReader.setPrompt("carbon>");
        consoleReader.addCompleter(new StringsCompleter(IOUtils.readLines(
                new GZIPInputStream(CommandsFromZipFile.class.getResourceAsStream("commandList.txt.gz")))));
        consoleReader.addCompleter(new FileNameCompleter());
        String line = "";
        String colored = "";

        while ((line = consoleReader.readLine()) != null) {
            if ("clear".equals(line.trim())) {
                System.out.print("\33[2J");
                System.out.flush();
                System.out.print("\33[1;1H");
                System.out.flush();
            } else if ("aback".equals(line.trim())) {
                colored = Ansi.ansi().fg(Ansi.Color.RED).a("Entered command : ")
                        .a(Ansi.Attribute.INTENSITY_BOLD).a(line).a(Ansi.Attribute.INTENSITY_BOLD_OFF)
                        .fg(Ansi.Color.DEFAULT).toString();
                consoleReader.println(colored);
            } else {
                consoleReader.println(line);
            }
        }
    } catch (IOException exception) {
        LOGGER.error(" Unable to load commands from the zip file ", exception);
    } finally {
        try {
            jline.TerminalFactory.get().restore();
        } catch (Exception exception) {
            LOGGER.error(" Unable to restore the terminal ", exception);
        }
    }
}

From source file:br.com.fabiopereira.quebrazip.JavaZipSplitter.java

public static void main(String[] args) {
    help();//  ww  w  . j  a  v  a 2s  .  c  o m
    boolean split = true;
    boolean zip_path = false, origin_path = false;
    boolean sizeinbytes = false;
    for (String arg : args) {
        if (arg.trim().equalsIgnoreCase("-join"))
            split = false;
        if (zip_path) {
            BIN_PATH = arg;
            zip_path = false;
        }
        if (origin_path) {
            ORIGEM_PATH = arg;
            origin_path = false;
        }
        if (sizeinbytes) {
            bytesSize = Integer.parseInt(arg);
            sizeinbytes = false;
        }
        if (arg.trim().equalsIgnoreCase("-bin"))
            zip_path = true;
        if (arg.trim().equalsIgnoreCase("-origin"))
            origin_path = true;
        if (arg.trim().equalsIgnoreCase("-sizeinbytes"))
            sizeinbytes = true;
    }
    if (zip_path || origin_path || sizeinbytes) {
        System.err.println("Error: invalid use of arguments");
        return;
    }

    if (split) {
        System.out.println("Spliting zip '" + BIN_PATH + "'");
        split();
    } else {
        System.out.println("Joining files at '" + ORIGEM_PATH + "'");
        join();
    }
}

From source file:com.mindquarry.management.user.UserManagementClient.java

public static void main(String[] args) {
    log = LogFactory.getLog(UserManagementClient.class);
    log.info("Starting user management client..."); //$NON-NLS-1$

    // parse command line arguments
    CommandLine line = null;//from   w ww .  j  ava2s.c o m
    CommandLineParser parser = new GnuParser();
    try {
        // parse the command line arguments
        line = parser.parse(options, args);
    } catch (ParseException e) {
        // oops, something went wrong
        log.error("Parsing of command line failed."); //$NON-NLS-1$
        printUsage();
        return;
    }
    // retrieve login data
    System.out.print("Please enter your login ID: "); //$NON-NLS-1$

    String user = readString();
    user = user.trim();

    System.out.print("Please enter your new password: "); //$NON-NLS-1$

    String password = readString();
    password = password.trim();
    password = new String(DigestUtils.md5(password));
    password = new String(Base64.encodeBase64(password.getBytes()));

    // start PWD change client
    UserManagementClient manager = new UserManagementClient();
    try {
        if (line.hasOption(O_DEL)) {
            manager.deleteUser(line.getOptionValue(O_REPO), ADMIN_LOGIN, ADMIN_PWD, user, password);
        } else {
            manager.changePwd(line.getOptionValue(O_REPO), ADMIN_LOGIN, ADMIN_PWD, user, password);
        }
    } catch (Exception e) {
        log.error("Error while applying password changes.", e); //$NON-NLS-1$
    }
    log.info("User management client finished successfully."); //$NON-NLS-1$
}

From source file:ArraySet.java

public static void main(String[] args) throws java.io.IOException {
    ArraySet set = new ArraySet();
    java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(System.in));
    while (true) {
        System.out.print(set.size() + ":"); //OK
        for (Iterator it = set.iterator(); it.hasNext();) {
            System.out.print(" " + it.next()); //OK
        }/*www.  java 2s  . c  o m*/
        System.out.println(); //OK
        System.out.print("> "); //OK
        String cmd = in.readLine();
        if (cmd == null)
            break;
        cmd = cmd.trim();
        if (cmd.equals("")) {
            ;
        } else if (cmd.startsWith("+")) {
            set.add(cmd.substring(1));
        } else if (cmd.startsWith("-")) {
            set.remove(cmd.substring(1));
        } else if (cmd.startsWith("?")) {
            boolean ret = set.contains(cmd.substring(1));
            System.out.println("  " + ret); //OK
        } else {
            System.out.println("unrecognized command"); //OK
        }
    }
}

From source file:org.bitcoinrt.Main.java

/**
 * Load the Spring Integration Application Context
 *
 * @param args - command line arguments//from   www . ja  v a2 s .c o  m
 */
public static void main(final String... args) {

    final Scanner scanner = new Scanner(System.in);

    System.out.println("\n========================================================="
            + "\n                                                         "
            + "\n    Welcome to the Spring Integration Bitcoin-rt Sample! "
            + "\n                                                         "
            + "\n=========================================================");

    System.out.println("Which WebSocket Client would you like to use? <enter>: ");
    System.out.println("\t1. Use Sonatype's Async HTTP Client implementation");
    System.out.println("\t2. Use Jetty's WebSocket client implementation");
    System.out.println("\t3. Use a Dummy client");

    System.out.println("\tq. Quit the application");
    System.out.print("Enter you choice: ");

    final GenericXmlApplicationContext context = new GenericXmlApplicationContext();

    while (true) {
        final String input = scanner.nextLine();

        if ("1".equals(input.trim())) {
            context.getEnvironment().setActiveProfiles("default");
            break;
        } else if ("2".equals(input.trim())) {
            context.getEnvironment().setActiveProfiles("jetty");
            break;
        } else if ("3".equals(input.trim())) {
            context.getEnvironment().setActiveProfiles("dummy");
            break;
        } else if ("q".equals(input.trim())) {
            System.out.println("Exiting application...bye.");
            System.exit(0);
        } else {
            System.out.println("Invalid choice\n\n");
            System.out.print("Enter you choice: ");
        }
    }

    context.load("classpath:META-INF/spring/integration/*-context.xml");
    context.registerShutdownHook();
    context.refresh();

    final ConnectionBroker connectionBroker = context.getBean(ConnectionBroker.class);

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("\n========================================================="
                + "\n                                                         "
                + "\n    Please press 'q + Enter' to quit the application.    "
                + "\n    For statistical information press 'i + Enter'.       "
                + "\n                                                         "
                + "\n    In your browser open:                                "
                + "\n    file:///.../src/main/webapp/index.html               "
                + "\n=========================================================");
    }

    while (true) {

        final String input = scanner.nextLine();

        if ("q".equals(input.trim())) {
            break;
        } else if ("i".equals(input.trim())) {
            LOGGER.info("\n========================================================="
                    + "\n                                                         "
                    + "\n Number of connected clients: " + connectionBroker.connectedClients()
                    + "\n                                                         "
                    + "\n=========================================================");
        }

    }

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Exiting application...bye.");
    }

    context.close();
    System.exit(0);

}

From source file:com.pureinfo.srm.reports.table.data.sci.SCIBySchoolStatistic.java

public static void main(String[] args) throws PureException {
    IProductMgr mgr = (IProductMgr) ArkContentHelper.getContentMgrOf(Product.class);
    IStatement stat = mgr.createQuery(//ww w . j a v a 2  s.c om
            "select count({this.id}) _NUM, {this.englishScience} AS _SUB from {this} group by _SUB", 0);
    IObjects nums = stat.executeQuery(false);
    DolphinObject num = null;
    Map map = new HashedMap();
    while ((num = nums.next()) != null) {
        String subest = num.getStrProperty("_SUB");
        if (subest == null || subest.trim().length() == 0)
            continue;
        String[] subs = subest.split(";");
        int nNum = num.getIntProperty("_NUM", 0);
        for (int i = 0; i < subs.length; i++) {
            String sSub = subs[i].trim();
            Integer odValue = (Integer) map.get(sSub);
            int sum = odValue == null ? nNum : (nNum + odValue.intValue());
            map.put(sSub, new Integer(sum));
        }
    }
    List l = new ArrayList(map.size());

    for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) {
        Map.Entry en = (Map.Entry) iter.next();
        l.add(new Object[] { en.getKey(), en.getValue() });
    }
    Collections.sort(l, new Comparator() {

        public int compare(Object _sO1, Object _sO2) {
            Object[] arr1 = (Object[]) _sO1;
            Object[] arr2 = (Object[]) _sO2;
            Comparable s1 = (Comparable) arr1[1];
            Comparable s2 = (Comparable) arr2[01];
            return s1.compareTo(s2);
        }
    });
    for (Iterator iter = l.iterator(); iter.hasNext();) {
        Object[] arr = (Object[]) iter.next();
        System.out.println(arr[0] + " = " + arr[1]);
    }

}

From source file:SequentialPageRank.java

@SuppressWarnings({ "static-access" })
public static void main(String[] args) throws IOException {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT));
    options.addOption(/*from ww w.  j  a  v  a2  s.  c o  m*/
            OptionBuilder.withArgName("val").hasArg().withDescription("random jump factor").create(JUMP));

    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());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT)) {
        System.out.println("args: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp(SequentialPageRank.class.getName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String infile = cmdline.getOptionValue(INPUT);
    float alpha = cmdline.hasOption(JUMP) ? Float.parseFloat(cmdline.getOptionValue(JUMP)) : 0.15f;

    int edgeCnt = 0;
    DirectedSparseGraph<String, Integer> graph = new DirectedSparseGraph<String, Integer>();

    BufferedReader data = new BufferedReader(new InputStreamReader(new FileInputStream(infile)));

    String line;
    while ((line = data.readLine()) != null) {
        line.trim();
        String[] arr = line.split("\\t");

        for (int i = 1; i < arr.length; i++) {
            graph.addEdge(new Integer(edgeCnt++), arr[0], arr[i]);
        }
    }

    data.close();

    WeakComponentClusterer<String, Integer> clusterer = new WeakComponentClusterer<String, Integer>();

    Set<Set<String>> components = clusterer.transform(graph);
    int numComponents = components.size();
    System.out.println("Number of components: " + numComponents);
    System.out.println("Number of edges: " + graph.getEdgeCount());
    System.out.println("Number of nodes: " + graph.getVertexCount());
    System.out.println("Random jump factor: " + alpha);

    // Compute PageRank.
    PageRank<String, Integer> ranker = new PageRank<String, Integer>(graph, alpha);
    ranker.evaluate();

    // Use priority queue to sort vertices by PageRank values.
    PriorityQueue<Ranking<String>> q = new PriorityQueue<Ranking<String>>();
    int i = 0;
    for (String pmid : graph.getVertices()) {
        q.add(new Ranking<String>(i++, ranker.getVertexScore(pmid), pmid));
    }

    // Print PageRank values.
    System.out.println("\nPageRank of nodes, in descending order:");
    Ranking<String> r = null;
    while ((r = q.poll()) != null) {
        System.out.println(r.rankScore + "\t" + r.getRanked());
    }
}

From source file:aes_encryption.AES_Encryption.java

/**
 * @param args the command line arguments
 */// ww  w.  j  a v a  2  s  . co  m
public static void main(String[] args) {
    // TODO code application logic here
    final String strtoEncrypt = "TEST";
    final String strPassword = "1234567890";
    AES_Encryption.setKey(strPassword);

    AES_Encryption.encrypt(strtoEncrypt.trim());

    System.out.println("String to Encrypt: " + strtoEncrypt);
    System.out.println("Encrypted: " + AES_Encryption.getEncryptedString());

    final String strToDecrypt = AES_Encryption.getEncryptedString();
    AES_Encryption.decrypt(strToDecrypt.trim());

    System.out.println("String To Decrypt : " + strToDecrypt);
    System.out.println("Decrypted : " + AES_Encryption.getDecryptedString());

}