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:com.sencko.basketball.stats.advanced.FIBAJsonParser.java

public static void main(String[] args) throws Exception {
    //http://nalb.bg/%D1%81%D0%BB%D0%B5%D0%B4%D0%B5%D1%82%D0%B5-%D0%BC%D0%B0%D1%87%D0%BE%D0%B2%D0%B5%D1%82%D0%B5-%D0%BE%D1%82-%D0%BD%D0%B0%D0%BB%D0%B1-%D0%BD%D0%B0-%D0%B6%D0%B8%D0%B2%D0%BE/
    //http://nalb.bg/%D1%81%D0%BB%D0%B5%D0%B4%D0%B5%D1%82%D0%B5-%D0%B4%D0%B2%D1%83%D0%B1%D0%BE%D0%B8%D1%82%D0%B5-%D0%BE%D1%82-%D0%BD%D0%B0%D0%BB%D0%B1-%D0%BD%D0%B0-%D0%B6%D0%B8%D0%B2%D0%BE-%D0%B8-%D0%B2-%D0%BF%D0%B5%D1%82/
    //http://nalb.bg/%D1%81%D0%BB%D0%B5%D0%B4%D0%B5%D1%82%D0%B5-%D0%B4%D0%B2%D1%83%D0%B1%D0%BE%D0%B8%D1%82%D0%B5-%D0%BE%D1%82-%D0%BD%D0%B0%D0%BB%D0%B1-%D0%B8-%D0%B2-%D1%87%D0%B5%D1%82%D0%B2%D1%8A%D1%80%D1%82%D0%B8%D1%8F/

    builder = new GsonBuilder().registerTypeAdapter(Integer.class, new IntegerAdapter())
            .registerTypeAdapter(String.class, new StringAdapter())
            .registerTypeAdapter(Action.class, new ActionAdapter()).setPrettyPrinting();
    BufferedReader reader = new BufferedReader(
            new InputStreamReader(FIBAJsonParser.class.getResourceAsStream("/games.txt")));
    String location = null;
    while ((location = reader.readLine()) != null) {
        location = location.trim();
        try {//from w  w  w . jav  a  2  s  .  c o  m
            readLocation(location);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /*
     readLocation("48965/13/13/23/68uR30BQLmzJM");
     readLocation("48965/13/15/86/78CJrCjRx5mh6");
     readLocation("48965/13/13/18/12pOKqzKs5nE");
     readLocation("48965/13/29/11/33upB2PIPn3MI");
            
     readLocation("48965/13/13/21/38Gqht27dPT1");
     readLocation("48965/13/15/84/999JtqK7Eao");
     readLocation("48965/13/29/07/66ODts76QU17A");
     */
}

From source file:Main.java

public static void main(String[] args) {
    final DefaultListModel<String> model = new DefaultListModel<>();
    final JList<String> list = new JList<>(model);
    JFrame f = new JFrame();

    model.addElement("A");
    model.addElement("B");
    model.addElement("C");
    model.addElement("D");
    model.addElement("E");

    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));

    JPanel leftPanel = new JPanel();
    JPanel rightPanel = new JPanel();

    leftPanel.setLayout(new BorderLayout());
    rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));

    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));

    list.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
                int index = list.locationToIndex(e.getPoint());
                Object item = model.getElementAt(index);
                String text = JOptionPane.showInputDialog("Rename item", item);
                String newitem = "";
                if (text != null)
                    newitem = text.trim();
                else
                    return;

                if (!newitem.isEmpty()) {
                    model.remove(index);
                    model.add(index, newitem);
                    ListSelectionModel selmodel = list.getSelectionModel();
                    selmodel.setLeadSelectionIndex(index);
                }/*from w  w  w. j a v a2 s . co  m*/
            }
        }
    });
    leftPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

    leftPanel.add(new JScrollPane(list));

    JButton removeall = new JButton("Remove All");
    JButton add = new JButton("Add");
    JButton rename = new JButton("Rename");
    JButton delete = new JButton("Delete");

    add.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String text = JOptionPane.showInputDialog("Add a new item");
            String item = null;

            if (text != null)
                item = text.trim();
            else
                return;

            if (!item.isEmpty())
                model.addElement(item);
        }
    });

    delete.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            ListSelectionModel selmodel = list.getSelectionModel();
            int index = selmodel.getMinSelectionIndex();
            if (index >= 0)
                model.remove(index);
        }

    });

    rename.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            ListSelectionModel selmodel = list.getSelectionModel();
            int index = selmodel.getMinSelectionIndex();
            if (index == -1)
                return;
            Object item = model.getElementAt(index);
            String text = JOptionPane.showInputDialog("Rename item", item);
            String newitem = null;

            if (text != null) {
                newitem = text.trim();
            } else
                return;

            if (!newitem.isEmpty()) {
                model.remove(index);
                model.add(index, newitem);
            }
        }
    });

    removeall.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            model.clear();
        }
    });

    rightPanel.add(add);
    rightPanel.add(rename);
    rightPanel.add(delete);
    rightPanel.add(removeall);

    rightPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 20));

    panel.add(leftPanel);
    panel.add(rightPanel);

    f.add(panel);

    f.setSize(350, 250);
    f.setLocationRelativeTo(null);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);

}

From source file:List.java

public static void main(String[] args) {
    final DefaultListModel model = new DefaultListModel();
    final JList list = new JList(model);
    JFrame f = new JFrame();
    f.setTitle("JList models");

    model.addElement("A");
    model.addElement("B");
    model.addElement("C");
    model.addElement("D");
    model.addElement("E");

    JPanel panel = new JPanel();
    panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));

    JPanel leftPanel = new JPanel();
    JPanel rightPanel = new JPanel();

    leftPanel.setLayout(new BorderLayout());
    rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));

    list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    list.setBorder(BorderFactory.createEmptyBorder(2, 2, 2, 2));

    list.addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            if (e.getClickCount() == 2) {
                int index = list.locationToIndex(e.getPoint());
                Object item = model.getElementAt(index);
                String text = JOptionPane.showInputDialog("Rename item", item);
                String newitem = "";
                if (text != null)
                    newitem = text.trim();
                else
                    return;

                if (!newitem.isEmpty()) {
                    model.remove(index);
                    model.add(index, newitem);
                    ListSelectionModel selmodel = list.getSelectionModel();
                    selmodel.setLeadSelectionIndex(index);
                }//from   ww w.j a  v  a2  s.  c o  m
            }
        }
    });
    leftPanel.setBorder(BorderFactory.createEmptyBorder(20, 20, 20, 20));

    leftPanel.add(new JScrollPane(list));

    JButton removeall = new JButton("Remove All");
    JButton add = new JButton("Add");
    JButton rename = new JButton("Rename");
    JButton delete = new JButton("Delete");

    add.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            String text = JOptionPane.showInputDialog("Add a new item");
            String item = null;

            if (text != null)
                item = text.trim();
            else
                return;

            if (!item.isEmpty())
                model.addElement(item);
        }
    });

    delete.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent event) {
            ListSelectionModel selmodel = list.getSelectionModel();
            int index = selmodel.getMinSelectionIndex();
            if (index >= 0)
                model.remove(index);
        }

    });

    rename.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            ListSelectionModel selmodel = list.getSelectionModel();
            int index = selmodel.getMinSelectionIndex();
            if (index == -1)
                return;
            Object item = model.getElementAt(index);
            String text = JOptionPane.showInputDialog("Rename item", item);
            String newitem = null;

            if (text != null) {
                newitem = text.trim();
            } else
                return;

            if (!newitem.isEmpty()) {
                model.remove(index);
                model.add(index, newitem);
            }
        }
    });

    removeall.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            model.clear();
        }
    });

    rightPanel.add(add);
    rightPanel.add(rename);
    rightPanel.add(delete);
    rightPanel.add(removeall);

    rightPanel.setBorder(BorderFactory.createEmptyBorder(0, 0, 0, 20));

    panel.add(leftPanel);
    panel.add(rightPanel);

    f.add(panel);

    f.setSize(350, 250);
    f.setLocationRelativeTo(null);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);

}

From source file:de.nava.informa.parsers.FeedParser.java

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

    if (args.length < 2) {
        System.err.println("Usage: java " + FeedParser.class.getName() + " [-f <filename> | -u <url>]");
        System.exit(1);//  w w w  .ja va  2  s.c  om
    }

    String option = args[0];
    String data = args[1];

    ChannelBuilderIF builder = new de.nava.informa.impl.basic.ChannelBuilder();
    ChannelIF channel;
    if (option.trim().startsWith("-f")) {
        channel = FeedParser.parse(builder, new File(data));
    } else {
        channel = FeedParser.parse(builder, new URL(data));
    }

    System.out.println("Channel format: " + channel.getFormat().toString());
    System.out.println(channel);
    System.out.println("containing " + channel.getItems().size() + " items");
    for (Object item : channel.getItems()) {
        System.out.println("  - " + item);
    }
}

From source file:PersistentEcho.java

public static void main(String[] args) {
    String argString = "";
    boolean notProperty = true;

    // Are there arguments? 
    // If so retrieve them.
    if (args.length > 0) {
        for (String arg : args) {
            argString += arg + " ";
        }//  ww w .ja v a2 s  .  co m
        argString = argString.trim();
    }
    // No arguments, is there
    // an environment variable?
    // If so, //retrieve it.
    else if ((argString = System.getenv("PERSISTENTECHO")) != null) {
    }
    // No environment variable
    // either. Retrieve property value.
    else {
        notProperty = false;
        // Set argString to null.
        // If it's still null after
        // we exit the try block,
        // we've failed to retrieve
        // the property value.
        argString = null;
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream("PersistentEcho.txt");
            Properties inProperties = new Properties();
            inProperties.load(fileInputStream);
            argString = inProperties.getProperty("argString");
        } catch (IOException e) {
            System.err.println("Can't read property file.");
            System.exit(1);
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                }
                ;
            }
        }
    }
    if (argString == null) {
        System.err.println("Couldn't find argString property");
        System.exit(1);
    }

    // Somehow, we got the
    // value. Echo it already!
    System.out.println(argString);

    // If we didn't retrieve the
    // value from the property,
    // save it //in the property.
    if (notProperty) {
        Properties outProperties = new Properties();
        outProperties.setProperty("argString", argString);
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream("PersistentEcho.txt");
            outProperties.store(fileOutputStream, "PersistentEcho properties");
        } catch (IOException e) {
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                }
                ;
            }
        }
    }
}

From source file:net.turnbig.jdbcx.utilities.JsonMapper.java

@SuppressWarnings("deprecation")
public static void main(String[] args) {

    String json = "[{\"asddd\":1}";

    boolean isJson = true;

    try {//from  w  ww.ja v a 2s . c  om
        ObjectMapper m = new ObjectMapper();
        if (json.trim().startsWith("[")) {
            JavaType typeRef = TypeFactory.defaultInstance().constructParametricType(List.class, Map.class);
            m.readValue(json, typeRef);
        } else {
            JavaType typeRef = TypeFactory.defaultInstance().constructMapType(HashMap.class, String.class,
                    Object.class);
            m.readValue(json, typeRef);
            m.readValue(json, typeRef);
        }
    } catch (Exception e) {
        isJson = false;
    }

    System.out.println(isJson);
}

From source file:TwitterClustering.java

public static void main(String[] args) throws FileNotFoundException, IOException {
    // TODO code application logic here

    File outFile = new File(args[3]);
    Scanner s = new Scanner(new File(args[1])).useDelimiter(",");
    JSONParser parser = new JSONParser();
    Set<Cluster> clusterSet = new HashSet<Cluster>();
    HashMap<String, Tweet> tweets = new HashMap();
    FileWriter fw = new FileWriter(outFile.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);

    // init//from   w w w  .  java  2 s.c  o m
    try {

        Object obj = parser.parse(new FileReader(args[2]));

        JSONArray jsonArray = (JSONArray) obj;

        for (int i = 0; i < jsonArray.size(); i++) {

            Tweet twt = new Tweet();
            JSONObject jObj = (JSONObject) jsonArray.get(i);
            String text = jObj.get("text").toString();

            long sum = 0;
            for (int y = 0; y < text.toCharArray().length; y++) {

                sum += (int) text.toCharArray()[y];
            }

            String[] token = text.split(" ");
            String tID = jObj.get("id").toString();

            Set<String> mySet = new HashSet<String>(Arrays.asList(token));
            twt.setAttributeValue(sum);
            twt.setText(mySet);
            twt.setTweetID(tID);
            tweets.put(tID, twt);

        }

        // preparing initial clusters
        int i = 0;
        while (s.hasNext()) {
            String id = s.next();// id
            Tweet t = tweets.get(id.trim());
            clusterSet.add(new Cluster(i + 1, t, new LinkedList()));
            i++;
        }

        Iterator it = tweets.entrySet().iterator();

        for (int l = 0; l < 2; l++) { // limit to 25 iterations

            while (it.hasNext()) {
                Map.Entry me = (Map.Entry) it.next();

                // calculate distance to each centroid
                Tweet p = (Tweet) me.getValue();
                HashMap<Cluster, Float> distMap = new HashMap();

                for (Cluster clust : clusterSet) {

                    distMap.put(clust, jaccardDistance(p.getText(), clust.getCentroid().getText()));
                }

                HashMap<Cluster, Float> sorted = (HashMap<Cluster, Float>) sortByValue(distMap);

                sorted.keySet().iterator().next().getMembers().add(p);

            }

            // calculate new centroid and update Clusterset
            for (Cluster clust : clusterSet) {

                TreeMap<String, Long> tDistMap = new TreeMap();

                Tweet newCentroid = null;
                Long avgSumDist = new Long(0);
                for (int j = 0; j < clust.getMembers().size(); j++) {

                    avgSumDist += clust.getMembers().get(j).getAttributeValue();
                    tDistMap.put(clust.getMembers().get(j).getTweetID(),
                            clust.getMembers().get(j).getAttributeValue());
                }
                if (clust.getMembers().size() != 0) {
                    avgSumDist /= (clust.getMembers().size());
                }

                ArrayList<Long> listValues = new ArrayList<Long>(tDistMap.values());

                if (tDistMap.containsValue(findClosestNumber(listValues, avgSumDist))) {
                    // found closest
                    newCentroid = tweets
                            .get(getKeyByValue(tDistMap, findClosestNumber(listValues, avgSumDist)));
                    clust.setCentroid(newCentroid);
                }

            }

        }
        // create an iterator
        Iterator iterator = clusterSet.iterator();

        // check values
        while (iterator.hasNext()) {

            Cluster c = (Cluster) iterator.next();
            bw.write(c.getId() + "\t");
            System.out.print(c.getId() + "\t");

            for (Tweet t : c.getMembers()) {
                bw.write(t.getTweetID() + ", ");
                System.out.print(t.getTweetID() + ",");

            }
            bw.write("\n");
            System.out.println("");
        }

        System.out.println("");

        System.out.println("SSE " + sumSquaredErrror(clusterSet));

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        bw.close();
        fw.close();
    }
}

From source file:Finger.java

public static void main(String[] args) {

    String hostname = "";
    String ulist = "";
    if (args.length == 0) {
        System.out.println("usage: finger host [user]");
        System.exit(1);//from  w  w w.ja  v  a  2  s  . co m
    }
    if (args.length >= 2)
        for (int i = 1; i < args.length; i++)
            ulist += args[i] + " ";
    hostname = args[0];
    Finger worker = new Finger();
    try {
        System.out.println(worker.finger(hostname, ulist.trim()));
    } catch (Exception e) {
        System.out.println(e);
    }
}

From source file:com.genentech.chemistry.tool.mm.SDFMMMinimize.java

/**
 * Main function for running on the command line
 * @param args//from  www  .  jav  a2s .co m
 */
public static void main(String... args) throws IOException {
    // Get the available options from the programs
    Map<String, List<String>> allowedProgramsAndForceFields = getAllowedProgramsAndForceFields();
    Map<String, List<String>> allowedProgramsAndSolvents = getAllowedProgramsAndSolvents();

    // create command line Options object
    Options options = new Options();
    Option opt = new Option(OPT_INFILE, true,
            "input file oe-supported Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_OUTFILE, true, "output file oe-supported. Use .sdf|.smi to specify the file type.");
    opt.setRequired(true);
    options.addOption(opt);

    StringBuilder programOptions = new StringBuilder("Program to use for minimization.  Choices are\n");

    for (String program : allowedProgramsAndForceFields.keySet()) {
        programOptions.append("\n***   -program " + program + "   ***\n");
        String forcefields = "";
        for (String option : allowedProgramsAndForceFields.get(program)) {
            forcefields += option + " ";
        }
        programOptions.append("-forcefield " + forcefields + "\n");

        String solvents = "";
        for (String option : allowedProgramsAndSolvents.get(program)) {
            solvents += option + " ";
        }
        programOptions.append("-solvent " + solvents + "\n");
    }

    opt = new Option(OPT_PROGRAM, true, programOptions.toString());
    opt.setRequired(true);
    options.addOption(opt);

    opt = new Option(OPT_FORCEFIELD, true, "Forcefield options.  See -program for choices");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_SOLVENT, true, "Solvent options.  See -program for choices");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_FIXED_ATOM_TAG, true, "SD tag name which contains the atom numbers to be held fixed.");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_FIX_TORSION, true,
            "true/false. if true, the atoms in fixedAtomTag contains 4 indices of atoms defining a torsion angle to be held fixed");
    opt.setRequired(false);
    options.addOption(opt);

    opt = new Option(OPT_WORKING_DIR, true, "Working directory to put files.");
    opt.setRequired(false);
    options.addOption(opt);

    CommandLineParser parser = new PosixParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        exitWithHelp(options);
    }
    args = cmd.getArgs();

    if (args.length != 0) {
        System.err.println("Unknown arguments" + args);
        exitWithHelp(options);
    }

    if (cmd.hasOption("d")) {
        System.err.println("Start debugger and press return:");
        new BufferedReader(new InputStreamReader(System.in)).readLine();
    }

    String inFile = cmd.getOptionValue(OPT_INFILE);
    String outFile = cmd.getOptionValue(OPT_OUTFILE);
    String fixedAtomTag = cmd.getOptionValue(OPT_FIXED_ATOM_TAG);
    boolean fixTorsion = (cmd.getOptionValue(OPT_FIX_TORSION) != null
            && cmd.getOptionValue(OPT_FIX_TORSION).equalsIgnoreCase("true"));
    String programName = cmd.getOptionValue(OPT_PROGRAM);
    String forcefield = cmd.getOptionValue(OPT_FORCEFIELD);
    String solvent = cmd.getOptionValue(OPT_SOLVENT);
    String workDir = cmd.getOptionValue(OPT_WORKING_DIR);

    if (workDir == null || workDir.trim().length() == 0)
        workDir = ".";

    // Create a minimizer 
    SDFMMMinimize minimizer = new SDFMMMinimize();
    minimizer.setMethod(programName, forcefield, solvent);
    minimizer.run(inFile, outFile, fixedAtomTag, fixTorsion, workDir);
    minimizer.close();
    System.err.println("Minimization complete.");
}

From source file:GcmSender.java

public static void main(String[] ar) {
    String message = "<Push message string here>";
    String to = "<Device token here>";
    try {//from   w w  w  . ja v a2s  .co  m
        // Prepare JSON containing the GCM message content. What to send and where to send.
        JSONObject jGcmData = new JSONObject();
        JSONObject jData = new JSONObject();
        try {
            jData.put("message", message.trim());

            // Where to send GCM message.
            if (to.length() != 0) {

                jGcmData.put("to", to.trim());

            } else {
                jGcmData.put("to", "/topics/global");
            }
            // What to send in GCM message.
            jGcmData.put("data", jData);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // Create connection to send GCM Message request.
        URL url = new URL("https://android.googleapis.com/gcm/send");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestProperty("Authorization", "key=" + API_KEY);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestMethod("POST");
        conn.setDoOutput(true);

        // Send GCM message content.
        OutputStream outputStream = conn.getOutputStream();
        outputStream.write(jGcmData.toString().getBytes());

        // Read GCM response.
        InputStream inputStream = conn.getInputStream();
        String resp = IOUtils.toString(inputStream);
        System.out.println(resp);
        System.out.println("Check your device/emulator for notification or logcat for "
                + "confirmation of the receipt of the GCM message.");
    } catch (IOException e) {
        System.out.println("Unable to send GCM message.");
        System.out.println("Please ensure that API_KEY has been replaced by the server "
                + "API key, and that the device's registration token is correct (if specified).");
        e.printStackTrace();
    }
}