Example usage for java.lang String length

List of usage examples for java.lang String length

Introduction

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

Prototype

public int length() 

Source Link

Document

Returns the length of this string.

Usage

From source file:httpclient.client.ClientInteractiveAuthentication.java

public static void main(String[] args) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();

    // Create local execution context
    HttpContext localContext = new BasicHttpContext();

    HttpGet httpget = new HttpGet("http://localhost/test");

    boolean trying = true;
    while (trying) {
        System.out.println("executing request " + httpget.getRequestLine());
        HttpResponse response = httpclient.execute(httpget, localContext);

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());

        // Consume response content
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            entity.consumeContent();/*from  w  w w  .ja v a2s  . c  om*/
        }

        int sc = response.getStatusLine().getStatusCode();

        AuthState authState = null;
        if (sc == HttpStatus.SC_UNAUTHORIZED) {
            // Target host authentication required
            authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
        }
        if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
            // Proxy authentication required
            authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
        }

        if (authState != null) {
            System.out.println("----------------------------------------");
            AuthScope authScope = authState.getAuthScope();
            System.out.println("Please provide credentials");
            System.out.println(" Host: " + authScope.getHost() + ":" + authScope.getPort());
            System.out.println(" Realm: " + authScope.getRealm());

            BufferedReader console = new BufferedReader(new InputStreamReader(System.in));

            System.out.print("Enter username: ");
            String user = console.readLine();
            System.out.print("Enter password: ");
            String password = console.readLine();

            if (user != null && user.length() > 0) {
                Credentials creds = new UsernamePasswordCredentials(user, password);
                httpclient.getCredentialsProvider().setCredentials(authScope, creds);
                trying = true;
            } else {
                trying = false;
            }
        } else {
            trying = false;
        }
    }

    // When HttpClient instance is no longer needed, 
    // shut down the connection manager to ensure
    // immediate deallocation of all system resources
    httpclient.getConnectionManager().shutdown();
}

From source file:example.wildcard.Client.java

public static void main(String[] args) {
    String url = BROKER_URL;
    if (args.length > 0) {
        url = args[0].trim();//from  w ww. jav  a 2s.  co m
    }
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "password", url);
    Connection connection = null;

    try {
        Topic senderTopic = new ActiveMQTopic(System.getProperty("topicName"));

        connection = connectionFactory.createConnection("admin", "password");

        Session senderSession = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
        MessageProducer sender = senderSession.createProducer(senderTopic);

        Session receiverSession = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);

        String policyType = System.getProperty("wildcard", ".*");
        String receiverTopicName = senderTopic.getTopicName() + policyType;
        Topic receiverTopic = receiverSession.createTopic(receiverTopicName);

        MessageConsumer receiver = receiverSession.createConsumer(receiverTopic);
        receiver.setMessageListener(new MessageListener() {
            public void onMessage(Message message) {
                try {
                    if (message instanceof TextMessage) {
                        String text = ((TextMessage) message).getText();
                        System.out.println("We received a new message: " + text);
                    }
                } catch (JMSException e) {
                    System.out.println("Could not read the receiver's topic because of a JMSException");
                }
            }
        });

        connection.start();
        System.out.println("Listening on '" + receiverTopicName + "'");
        System.out.println("Enter a message to send: ");

        Scanner inputReader = new Scanner(System.in);

        while (true) {
            String line = inputReader.nextLine();
            if (line == null) {
                System.out.println("Done!");
                break;
            } else if (line.length() > 0) {
                try {
                    TextMessage message = senderSession.createTextMessage();
                    message.setText(line);
                    System.out.println("Sending a message: " + message.getText());
                    sender.send(message);
                } catch (JMSException e) {
                    System.out.println("Exception during publishing a message: ");
                }
            }
        }

        receiver.close();
        receiverSession.close();
        sender.close();
        senderSession.close();

    } catch (Exception e) {
        System.out.println("Caught exception!");
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                System.out.println("When trying to close connection: ");
            }
        }
    }

}

From source file:com.data2semantics.yasgui.server.db.ConnectionFactory.java

public static void main(String[] args) {
    String basename = "delta_10.sql";
    basename = basename.substring("delta_".length());
    basename = basename.substring(0, basename.length() - ".sql".length());
}

From source file:edu.ksu.cis.indus.xmlizer.JimpleXMLizerCLI.java

/**
 * The entry point to execute this xmlizer from command prompt.
 * /*w  w w.j a  v a  2s  . co m*/
 * @param s is the command-line arguments.
 * @throws RuntimeException when jimple xmlization fails.
 * @pre s != null
 */
public static void main(final String[] s) {
    final Scene _scene = Scene.v();

    final Options _options = new Options();
    Option _o = new Option("d", "dump directory", true, "The directory in which to write the xml files.  "
            + "If unspecified, the xml output will be directed standard out.");
    _o.setArgs(1);
    _o.setArgName("path");
    _o.setOptionalArg(false);
    _options.addOption(_o);
    _o = new Option("h", "help", false, "Display message.");
    _options.addOption(_o);
    _o = new Option("p", "soot-classpath", true, "Prepend this to soot class path.");
    _o.setArgs(1);
    _o.setArgName("classpath");
    _o.setOptionalArg(false);
    _options.addOption(_o);

    final HelpFormatter _help = new HelpFormatter();

    try {
        final CommandLine _cl = (new BasicParser()).parse(_options, s);
        final String[] _args = _cl.getArgs();

        if (_cl.hasOption('h')) {
            final String _cmdLineSyn = "java " + JimpleXMLizerCLI.class.getName() + "<options> <class names>";
            _help.printHelp(_cmdLineSyn.length(), _cmdLineSyn, "", _options, "", true);
        } else {
            if (_args.length > 0) {
                if (_cl.hasOption('p')) {
                    _scene.setSootClassPath(
                            _cl.getOptionValue('p') + File.pathSeparator + _scene.getSootClassPath());
                }

                final NamedTag _tag = new NamedTag("JimpleXMLizer");

                for (int _i = 0; _i < _args.length; _i++) {
                    final SootClass _sc = _scene.loadClassAndSupport(_args[_i]);
                    _sc.addTag(_tag);
                }
                final IProcessingFilter _filter = new TagBasedProcessingFilter(_tag.getName());
                writeJimpleAsXML(new Environment(_scene), _cl.getOptionValue('d'), null,
                        new UniqueJimpleIDGenerator(), _filter);
            } else {
                System.out.println("No classes were specified.");
            }
        }
    } catch (final ParseException _e) {
        LOGGER.error("Error while parsing command line.", _e);
        printUsage(_options);
    } catch (final Throwable _e) {
        LOGGER.error("Beyond our control. May day! May day!", _e);
        throw new RuntimeException(_e);
    }
}

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

public static void main(String[] args) {
    final Display display = new Display();
    final Color black = display.getSystemColor(SWT.COLOR_BLACK);
    Shell shell = new Shell(display);
    shell.setText("Snippet 111");
    shell.setLayout(new FillLayout());
    final Tree tree = new Tree(shell, SWT.BORDER);
    for (int i = 0; i < 16; i++) {
        TreeItem itemI = new TreeItem(tree, SWT.NONE);
        itemI.setText("Item " + i);
        for (int j = 0; j < 16; j++) {
            TreeItem itemJ = new TreeItem(itemI, SWT.NONE);
            itemJ.setText("Item " + j);
        }//  w  w  w  .j ava2s.  c om
    }
    final TreeItem[] lastItem = new TreeItem[1];
    final TreeEditor editor = new TreeEditor(tree);
    tree.addListener(SWT.Selection, event -> {
        final TreeItem item = (TreeItem) event.item;
        if (item != null && item == lastItem[0]) {
            boolean showBorder = true;
            final Composite composite = new Composite(tree, SWT.NONE);
            if (showBorder)
                composite.setBackground(black);
            final Text text = new Text(composite, SWT.NONE);
            final int inset = showBorder ? 1 : 0;
            composite.addListener(SWT.Resize, e1 -> {
                Rectangle rect1 = composite.getClientArea();
                text.setBounds(rect1.x + inset, rect1.y + inset, rect1.width - inset * 2,
                        rect1.height - inset * 2);
            });
            Listener textListener = e2 -> {
                switch (e2.type) {
                case SWT.FocusOut:
                    item.setText(text.getText());
                    composite.dispose();
                    break;
                case SWT.Verify:
                    String newText = text.getText();
                    String leftText = newText.substring(0, e2.start);
                    String rightText = newText.substring(e2.end, newText.length());
                    GC gc = new GC(text);
                    Point size = gc.textExtent(leftText + e2.text + rightText);
                    gc.dispose();
                    size = text.computeSize(size.x, SWT.DEFAULT);
                    editor.horizontalAlignment = SWT.LEFT;
                    Rectangle itemRect = item.getBounds(), rect2 = tree.getClientArea();
                    editor.minimumWidth = Math.max(size.x, itemRect.width) + inset * 2;
                    int left = itemRect.x, right = rect2.x + rect2.width;
                    editor.minimumWidth = Math.min(editor.minimumWidth, right - left);
                    editor.minimumHeight = size.y + inset * 2;
                    editor.layout();
                    break;
                case SWT.Traverse:
                    switch (e2.detail) {
                    case SWT.TRAVERSE_RETURN:
                        item.setText(text.getText());
                        //FALL THROUGH
                    case SWT.TRAVERSE_ESCAPE:
                        composite.dispose();
                        e2.doit = false;
                    }
                    break;
                }
            };
            text.addListener(SWT.FocusOut, textListener);
            text.addListener(SWT.Traverse, textListener);
            text.addListener(SWT.Verify, textListener);
            editor.setEditor(composite, item);
            text.setText(item.getText());
            text.selectAll();
            text.setFocus();
        }
        lastItem[0] = item;
    });
    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    display.dispose();
}

From source file:com.meli.client.controller.AppController.java

public static void main(String[] args) {
        String query = "";
        String fileName = "";
        String countryCode = "";
        String option = "";

        for (int i = 0; i < args.length - 1; i++) {
            option = args[i];//from   w  w  w . j  a  va 2s. co m

            if (option.length() >= 2) {
                String argVal = option.substring(0, 2);

                if (!args[i + 1].isEmpty() && !args[i + 1].matches("-[qfc]")) {
                    if ("-q".equals(argVal)) {
                        query = args[i + 1];
                        continue;
                    }
                    if ("-f".equals(argVal)) {
                        fileName = args[i + 1];
                        continue;
                    }
                    if ("-c".equals(argVal))
                        countryCode = args[i + 1];

                }
            }
        }

        if (!fileName.isEmpty())
            processQueryFile(fileName, countryCode);

        if (!query.isEmpty())
            doApiCalls(query, countryCode);

    }

From source file:net.kolola.msgparsercli.MsgParseCLI.java

public static void main(String[] args) {

    // Parse options

    OptionParser parser = new OptionParser("f:a:bi?*");
    OptionSet options = parser.parse(args);

    // Get the filename
    if (!options.has("f")) {
        System.err.print("Specify a msg file with the -f option");
        System.exit(0);/*from  w  ww .j av a  2s . co m*/
    }

    File file = new File((String) options.valueOf("f"));

    MsgParser msgp = new MsgParser();
    Message msg = null;

    try {
        msg = msgp.parseMsg(file);
    } catch (UnsupportedOperationException | IOException e) {
        System.err.print("File does not exist or is not a valid msg file");
        //e.printStackTrace();
        System.exit(1);
    }

    // Show info (as JSON)
    if (options.has("i")) {
        Map<String, Object> data = new HashMap<String, Object>();

        String date;

        try {
            Date st = msg.getClientSubmitTime();
            date = st.toString();
        } catch (Exception g) {
            try {
                date = msg.getDate().toString();
            } catch (Exception e) {
                date = "[UNAVAILABLE]";
            }
        }

        data.put("date", date);
        data.put("subject", msg.getSubject());
        data.put("from", "\"" + msg.getFromName() + "\" <" + msg.getFromEmail() + ">");
        data.put("to", "\"" + msg.getToRecipient().toString());

        String cc = "";
        for (RecipientEntry r : msg.getCcRecipients()) {
            if (cc.length() > 0)
                cc.concat("; ");

            cc.concat(r.toString());
        }

        data.put("cc", cc);

        data.put("body_html", msg.getBodyHTML());
        data.put("body_rtf", msg.getBodyRTF());
        data.put("body_text", msg.getBodyText());

        // Attachments
        List<Map<String, String>> atts = new ArrayList<Map<String, String>>();
        for (Attachment a : msg.getAttachments()) {
            HashMap<String, String> info = new HashMap<String, String>();

            if (a instanceof FileAttachment) {
                FileAttachment fa = (FileAttachment) a;

                info.put("type", "file");
                info.put("filename", fa.getFilename());
                info.put("size", Long.toString(fa.getSize()));
            } else {
                info.put("type", "message");
            }

            atts.add(info);
        }

        data.put("attachments", atts);

        JSONObject json = new JSONObject(data);

        try {
            System.out.print(json.toString(4));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    // OR return an attachment in BASE64
    else if (options.has("a")) {
        Integer anum = Integer.parseInt((String) options.valueOf("a"));

        Encoder b64 = Base64.getEncoder();

        List<Attachment> atts = msg.getAttachments();

        if (atts.size() <= anum) {
            System.out.print("Attachment " + anum.toString() + " does not exist");
        }

        Attachment att = atts.get(anum);

        if (att instanceof FileAttachment) {
            FileAttachment fatt = (FileAttachment) att;
            System.out.print(b64.encodeToString(fatt.getData()));
        } else {
            System.err.print("Attachment " + anum.toString() + " is a message - That's not implemented yet :(");
        }
    }
    // OR print the message body
    else if (options.has("b")) {
        System.out.print(msg.getConvertedBodyHTML());
    } else {
        System.err.print(
                "Specify either -i to return msg information or -a <num> to print an attachment as a BASE64 string");
    }

}

From source file:CompRcv.java

public static void main(String[] args) throws Exception {
    Socket sock = new Socket(args[0], Integer.parseInt(args[1]));
    GZIPOutputStream zip = new GZIPOutputStream(sock.getOutputStream());
    String line;
    BufferedReader bis = new BufferedReader(new FileReader(args[2]));
    while (true) {
        try {//from   www . jav a  2 s. c  o  m
            line = bis.readLine();
            if (line == null)
                break;
            line = line + "\n";
            zip.write(line.getBytes(), 0, line.length());
        } catch (Exception e) {
            break;
        }
    }
    zip.finish();
    zip.close();
    sock.close();
}

From source file:org.hyperic.hq.hqapi1.tools.PasswordEncryptor.java

public static void main(String[] args) throws Exception {
    String password1 = String.valueOf(PasswordField.getPassword(System.in, "Enter password: "));
    String password2 = String.valueOf(PasswordField.getPassword(System.in, "Re-Enter password: "));
    String encryptionKey = "defaultkey";
    if (password1.equals(password2)) {
        System.out.print("Encryption Key: ");
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        encryptionKey = in.readLine();/*w  ww .  jav  a2 s . co m*/
        if (encryptionKey.length() < 8) {
            System.out.println("Encryption key too short. Please use at least 8 characters");
            System.exit(-1);
        }
    } else {
        System.out.println("Passwords don't match");
        System.exit(-1);
    }

    System.out.println("The encrypted password is " + encryptPassword(password1, encryptionKey));
}

From source file:com.dlmu.heipacker.crawler.client.ClientInteractiveAuthentication.java

public static void main(String[] args) throws Exception {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {//from  w  ww .  ja  v a 2s  . com
        // Create local execution context
        HttpContext localContext = new BasicHttpContext();

        HttpGet httpget = new HttpGet("http://localhost/test");

        boolean trying = true;
        while (trying) {
            System.out.println("executing request " + httpget.getRequestLine());
            HttpResponse response = httpclient.execute(httpget, localContext);

            System.out.println("----------------------------------------");
            System.out.println(response.getStatusLine());

            // Consume response content
            HttpEntity entity = response.getEntity();
            EntityUtils.consume(entity);

            int sc = response.getStatusLine().getStatusCode();

            AuthState authState = null;
            HttpHost authhost = null;
            if (sc == HttpStatus.SC_UNAUTHORIZED) {
                // Target host authentication required
                authState = (AuthState) localContext.getAttribute(ClientContext.TARGET_AUTH_STATE);
                authhost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
            }
            if (sc == HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED) {
                // Proxy authentication required
                authState = (AuthState) localContext.getAttribute(ClientContext.PROXY_AUTH_STATE);
                authhost = (HttpHost) localContext.getAttribute(ExecutionContext.HTTP_PROXY_HOST);
            }

            if (authState != null) {
                System.out.println("----------------------------------------");
                AuthScheme authscheme = authState.getAuthScheme();
                System.out.println("Please provide credentials for " + authscheme.getRealm() + "@"
                        + authhost.toHostString());

                BufferedReader console = new BufferedReader(new InputStreamReader(System.in));

                System.out.print("Enter username: ");
                String user = console.readLine();
                System.out.print("Enter password: ");
                String password = console.readLine();

                if (user != null && user.length() > 0) {
                    Credentials creds = new UsernamePasswordCredentials(user, password);
                    httpclient.getCredentialsProvider().setCredentials(new AuthScope(authhost), creds);
                    trying = true;
                } else {
                    trying = false;
                }
            } else {
                trying = false;
            }
        }

    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
}