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:jfs.sync.meta.MetaFileStorageAccess.java

/**
 *
 * Extract one file from encrypted repository.
 *
 * TODO: list directories//from  w  w w. j av a2 s  .c  om
 *
 */
public static void main(String[] args) throws Exception {
    final String password = args[0];
    MetaFileStorageAccess storage = new MetaFileStorageAccess("Twofish", false) {

        protected String getPassword(String relativePath) {
            String result = "";

            String pwd = password;

            int i = 0;
            int j = relativePath.length() - 1;
            while ((i < pwd.length()) || (j >= 0)) {
                if (i < pwd.length()) {
                    result += pwd.charAt(i++);
                } // if
                if (j >= 0) {
                    result += relativePath.charAt(j--);
                } // if
            } // while

            return result;
        } // getPassword()
    };
    String encryptedPath = args[2];
    String[] elements = encryptedPath.split("\\\\");
    String path = "";
    for (int i = 0; i < elements.length; i++) {
        String encryptedName = elements[i];
        String plain = storage.getDecryptedFileName(path, encryptedName);
        path += storage.getSeparator();
        path += plain;
        System.out.println(path);
    } // for

    String cipherSpec = storage.getCipherSpec();
    byte[] credentials = storage.getFileCredentials(path);
    Cipher cipher = SecurityUtils.getCipher(cipherSpec, Cipher.DECRYPT_MODE, credentials);

    InputStream is = storage.getInputStream(args[1], path);
    is = JFSEncryptedStream.createInputStream(is, JFSEncryptedStream.DONT_CHECK_LENGTH, cipher);
    int b = 0;
    while (b >= 0) {
        b = is.read();
        System.out.print((char) b);
    } // while
    is.close();
}

From source file:LengthOf.java

public static void main(String[] argv) {
    int ints[] = new int[3];
    Object objs[] = new Object[7];

    String stra = "Hello World";
    String strb = new String();

    // Length of any array - use its length attribute
    System.out.println("Length of argv is " + argv.length);
    System.out.println("Length of ints is " + ints.length);
    System.out.println("Length of objs is " + objs.length);

    // Length of any string - call its length() method.
    System.out.println("Length of stra is " + stra.length());
    System.out.println("Length of strb is " + strb.length());
}

From source file:RegExTest.java

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    System.out.println("Enter pattern: ");
    String patternString = in.nextLine();

    Pattern pattern = null;//ww w .j  ava2s.c o  m
    try {
        pattern = Pattern.compile(patternString);
    } catch (PatternSyntaxException e) {
        System.out.println("Pattern syntax error");
        System.exit(1);
    }

    while (true) {
        System.out.println("Enter string to match: ");
        String input = in.nextLine();
        if (input == null || input.equals(""))
            return;
        Matcher matcher = pattern.matcher(input);
        if (matcher.matches()) {
            System.out.println("Match");
            int g = matcher.groupCount();
            if (g > 0) {
                for (int i = 0; i < input.length(); i++) {
                    for (int j = 1; j <= g; j++)
                        if (i == matcher.start(j))
                            System.out.print('(');
                    System.out.print(input.charAt(i));
                    for (int j = 1; j <= g; j++)
                        if (i + 1 == matcher.end(j))
                            System.out.print(')');
                }
                System.out.println();
            }
        } else
            System.out.println("No match");
    }
}

From source file:JALPTest.java

/**
 * The main method that gets called to test JALoP.
 *
 * @param args   the command line arguments
 *//* w ww  .ja  v  a  2 s.  co  m*/
public static void main(String[] args) {
    Producer producer = null;
    try {
        Options options = createOptions();
        CommandLineParser parser = new PosixParser();
        CommandLine cmd = parser.parse(options, args);

        String pathToXML = null;
        String type = null;
        String input = null;
        String privateKeyPath = null;
        String publicKeyPath = null;
        String certPath = null;
        String socketPath = null;
        Boolean hasDigest = false;
        File file = null;
        ApplicationMetadataXML xml = null;

        if (cmd.hasOption("h")) {
            System.out.println(usage);
            return;
        }
        if (cmd.hasOption("a")) {
            pathToXML = cmd.getOptionValue("a");
        }
        if (cmd.hasOption("t")) {
            type = cmd.getOptionValue("t");
        }
        if (cmd.hasOption("p")) {
            file = new File(cmd.getOptionValue("p"));
        }
        if (cmd.hasOption("s")) {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            StringBuilder sb = new StringBuilder();
            String s;
            while ((s = in.readLine()) != null && s.length() != 0) {
                sb.append(s);
                sb.append("\n");
            }
            input = sb.toString();
        }
        if (cmd.hasOption("j")) {
            socketPath = cmd.getOptionValue("j");
        }
        if (cmd.hasOption("k")) {
            privateKeyPath = cmd.getOptionValue("k");
        }
        if (cmd.hasOption("b")) {
            publicKeyPath = cmd.getOptionValue("b");
        }
        if (cmd.hasOption("c")) {
            certPath = cmd.getOptionValue("c");
        }
        if (cmd.hasOption("d")) {
            hasDigest = true;
        }

        if (pathToXML != null) {
            xml = createXML(readXML(pathToXML));
        }

        producer = createProducer(xml, socketPath, privateKeyPath, publicKeyPath, certPath, hasDigest);
        callSend(producer, type, input, file);

    } catch (IOException e) {
        if (producer != null) {
            System.out.println("Failed to open socket: " + producer.getSocketFile());
        } else {
            System.out.println("Failed to create Producer");
        }
    } catch (Exception e) {
        error(e.toString());
        return;
    }
}

From source file:com.google.api.services.samples.youtube.cmdline.data.Topics.java

/**
 * Execute a search request that starts by calling the Freebase API to
 * retrieve a topic ID matching a user-provided term. Then initialize a
 * YouTube object to search for YouTube videos and call the YouTube Data
 * API's youtube.search.list method to retrieve a list of videos associated
 * with the selected Freebase topic and with another search query term,
 * which the user also enters. Finally, display the titles, video IDs, and
 * thumbnail images for the first five videos in the YouTube Data API
 * response.// w  ww .  j av a 2s  .  c o  m
 *
 * @param args This application does not use command line arguments.
 */
public static void main(String[] args) {
    // Read the developer key from the properties file.
    Properties properties = new Properties();
    try {
        InputStream in = Topics.class.getResourceAsStream("/" + PROPERTIES_FILENAME);
        properties.load(in);

    } catch (IOException e) {
        System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause() + " : "
                + e.getMessage());
        System.exit(1);
    }

    try {
        // Retrieve a Freebase topic ID based on a user-entered query term.
        String topicsId = getTopicId();
        if (topicsId.length() < 1) {
            System.out.println("No topic id will be applied to your search.");
        }

        // Prompt the user to enter a search query term. This term will be
        // used to retrieve YouTube search results related to the topic
        // selected above.
        String queryTerm = getInputQuery("search");

        // This object is used to make YouTube Data API requests. The last
        // argument is required, but since we don't need anything
        // initialized when the HttpRequest is initialized, we override
        // the interface and provide a no-op function.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
            public void initialize(HttpRequest request) throws IOException {
            }
        }).setApplicationName("youtube-cmdline-search-sample").build();

        YouTube.Search.List search = youtube.search().list("id,snippet");

        // Set your developer key from the {{ Google Cloud Console }} for
        // non-authenticated requests. See:
        // {{ https://cloud.google.com/console }}
        String apiKey = properties.getProperty("youtube.apikey");
        search.setKey(apiKey);
        search.setQ(queryTerm);
        if (topicsId.length() > 0) {
            search.setTopicId(topicsId);
        }

        // Restrict the search results to only include videos. See:
        // https://developers.google.com/youtube/v3/docs/search/list#type
        search.setType("video");

        // To increase efficiency, only retrieve the fields that the
        // application uses.
        search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
        search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
        SearchListResponse searchResponse = search.execute();

        List<SearchResult> searchResultList = searchResponse.getItems();

        if (searchResultList != null) {
            prettyPrint(searchResultList.iterator(), queryTerm, topicsId);
        } else {
            System.out.println("There were no results for your query.");
        }
    } catch (GoogleJsonResponseException e) {
        System.err.println(
                "There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.google.api.services.samples.youtube.cmdline.Topics.java

/**
 * Execute a search request that starts by calling the Freebase API to
 * retrieve a topic ID matching a user-provided term. Then initialize a
 * YouTube object to search for YouTube videos and call the YouTube Data
 * API's youtube.search.list method to retrieve a list of videos associated
 * with the selected Freebase topic and with another search query term,
 * which the user also enters. Finally, display the titles, video IDs, and
 * thumbnail images for the first five videos in the YouTube Data API
 * response./*  w  w w .  j  a v a2s  . c om*/
 *
 * @param args This application does not use command line arguments.
 */
public static void main(String[] args) {
    // Read the developer key from the properties file.
    Properties properties = new Properties();
    try {
        InputStream in = Topics.class.getResourceAsStream("/" + PROPERTIES_FILENAME);
        properties.load(in);

    } catch (IOException e) {
        System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause() + " : "
                + e.getMessage());
        System.exit(1);
    }

    try {
        // Retrieve a Freebase topic ID based on a user-entered query term.
        String topicsId = getTopicId();
        if (topicsId.length() < 1) {
            System.out.println("No topic id will be applied to your search.");
        }

        // Prompt the user to enter a search query term. This term will be
        // used to retrieve YouTube search results related to the topic
        // selected above.
        String queryTerm = getInputQuery("search");

        // This object is used to make YouTube Data API requests. The last
        // argument is required, but since we don't need anything
        // initialized when the HttpRequest is initialized, we override
        // the interface and provide a no-op function.
        youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
            public void initialize(HttpRequest request) throws IOException {
            }
        }).setApplicationName("youtube-cmdline-search-sample").build();

        YouTube.Search.List search = youtube.search().list("id,snippet");

        // Set your developer key from the Google Developers Console for
        // non-authenticated requests. See:
        // https://cloud.google.com/console
        String apiKey = properties.getProperty("youtube.apikey");
        search.setKey(apiKey);
        search.setQ(queryTerm);
        if (topicsId.length() > 0) {
            search.setTopicId(topicsId);
        }

        // Restrict the search results to only include videos. See:
        // https://developers.google.com/youtube/v3/docs/search/list#type
        search.setType("video");

        // To increase efficiency, only retrieve the fields that the
        // application uses.
        search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
        search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
        SearchListResponse searchResponse = search.execute();

        List<SearchResult> searchResultList = searchResponse.getItems();

        if (searchResultList != null) {
            prettyPrint(searchResultList.iterator(), queryTerm, topicsId);
        } else {
            System.out.println("There were no results for your query.");
        }
    } catch (GoogleJsonResponseException e) {
        System.err.println(
                "There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.tmo.swagger.main.GenrateSwaggerJson.java

public static void main(String[] args)
        throws JsonGenerationException, JsonMappingException, IOException, EmptyXlsRows {

    PropertyReader pr = new PropertyReader();

    Properties prop = pr.readPropertiesFile(args[0]);
    //Properties prop =pr.readClassPathPropertyFile("common.properties");
    String swaggerFile = prop.getProperty("swagger.json");
    String sw = "";
    if (swaggerFile != null && swaggerFile.length() > 0) {
        Swagger swagger = populatePropertiesOnlyPaths(prop, new SwaggerParser().read(swaggerFile));
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL);
        sw = mapper.writeValueAsString(swagger);
    } else {/*from w  ww .j a  v  a 2  s . c  o  m*/
        ObjectMapper mapper = new ObjectMapper();
        mapper.setSerializationInclusion(Include.NON_NULL);
        Swagger swagger = populateProperties(prop);
        sw = mapper.writeValueAsString(swagger);
    }
    try {
        File file = new File(args[1] + prop.getProperty("path.operation.tags") + ".json");
        //File file = new File("src/main/resources/"+prop.getProperty("path.operation.tags")+".json");
        if (!file.exists()) {
            file.createNewFile();
        }
        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(sw);
        logger.info("Swagger Genration Done!");
        bw.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:mujava.cli.testnew.java

public static void main(String[] args) throws IOException {
    testnewCom jct = new testnewCom();
    String[] argv = { "Flower", "/Users/dmark/mujava/src/Flower" };
    new JCommander(jct, args);

    muJavaHomePath = Util.loadConfig();
    // muJavaHomePath= "/Users/dmark/mujava";

    // check if debug mode
    if (jct.isDebug() || jct.isDebugMode()) {
        Util.debug = true;/*from   w  ww  .j ava  2s. co  m*/
    }
    System.out.println(jct.getParameters().size());
    sessionName = jct.getParameters().get(0); // set first parameter as the
    // session name

    ArrayList<String> srcFiles = new ArrayList<>();

    for (int i = 1; i < jct.getParameters().size(); i++) {
        srcFiles.add(jct.getParameters().get(i)); // retrieve all src file
        // names from parameters
    }

    // get all existing session name
    File folder = new File(muJavaHomePath);
    if (!folder.isDirectory()) {
        Util.Error("ERROR: cannot locate the folder specified in mujava.config");
        return;
    }
    File[] listOfFiles = folder.listFiles();
    // null checking
    // check the specified folder has files or not
    if (listOfFiles == null) {
        Util.Error("ERROR: no files in the muJava home folder " + muJavaHomePath);
        return;
    }
    List<String> fileNameList = new ArrayList<>();
    for (File file : listOfFiles) {
        fileNameList.add(file.getName());
    }

    // check if the session is new or not
    if (fileNameList.contains(sessionName)) {
        Util.Error("Session already exists.");
    } else {
        // create sub-directory for the session
        setupSessionDirectory(sessionName);

        // move src files into session folder
        for (String srcFile : srcFiles) {
            // new (dir, name)
            // check abs path or not

            // need to check if srcFile has .java at the end or not
            if (srcFile.length() > 5) {
                if (srcFile.substring(srcFile.length() - 5).equals(".java")) // name has .java at the end, e.g. cal.java
                {
                    // delete .java, e.g. make it cal
                    srcFile = srcFile.substring(0, srcFile.length() - 5);
                }
            }

            File source = new File(srcFile + ".java");

            if (!source.isAbsolute()) // relative path, attach path, e.g. cal.java, make it c:\mujava\cal.java
            {
                source = new File(muJavaHomePath + "/src" + java.io.File.separator + srcFile + ".java");

            }

            File desc = new File(muJavaHomePath + "/" + sessionName + "/src");
            FileUtils.copyFileToDirectory(source, desc);

            // compile src files
            // String srcName = "t";
            boolean result = compileSrc(srcFile);
            if (result)
                Util.Print("Session is built successfully.");
        }

    }

    // System.exit(0);
}

From source file:com.google.api.services.samples.youtube.cmdline.youtube_cmdline_topics_sample.Topics.java

/**
 * Method kicks off a search via the Freebase API for a topics id.  It initializes a YouTube
 * object to search for videos on YouTube (Youtube.Search.List) using that topics id to make the
 * search more specific.  The program then prints the names and thumbnails of each of the videos
 * (only first 5 videos).  Please note, user input is taken for both search on Freebase and on
 * YouTube.//from  w  w  w  .j  a  v  a2s  .co  m
 *
 * @param args command line args not used.
*/
public static void main(String[] args) {
    // Read the developer key from youtube.properties
    Properties properties = new Properties();
    try {
        InputStream in = Topics.class.getResourceAsStream("/" + PROPERTIES_FILENAME);
        properties.load(in);

    } catch (IOException e) {
        System.err.println("There was an error reading " + PROPERTIES_FILENAME + ": " + e.getCause() + " : "
                + e.getMessage());
        System.exit(1);
    }

    try {
        // Gets a topic id via the Freebase API based on user input.
        String topicsId = getTopicId();
        if (topicsId.length() < 1) {
            System.out.println("No topic id will be applied to your search.");
        }

        /*
         * Get query term from user.  The "search" parameter is just used as output to clarify that
         * we want a "search" term (vs. a "topics" term).
         */
        String queryTerm = getInputQuery("search");

        /*
         * The YouTube object is used to make all API requests.  The last argument is required, but
         * because we don't need anything initialized when the HttpRequest is initialized, we
         * override the interface and provide a no-op function.
         */
        youtube = new YouTube.Builder(HTTP_TRANSPORT, JSON_FACTORY, new HttpRequestInitializer() {
            public void initialize(HttpRequest request) throws IOException {
            }
        }).setApplicationName("youtube-cmdline-search-sample").build();

        YouTube.Search.List search = youtube.search().list("id,snippet");
        /*
         * It is important to set your developer key from the Google Developer Console for
         * non-authenticated requests (found under the API Access tab at this link:
         * code.google.com/apis/). This is good practice and increases your quota.
         */
        String apiKey = properties.getProperty("youtube.apikey");
        search.setKey(apiKey);
        search.setQ(queryTerm);
        if (topicsId.length() > 0) {
            search.setTopicId(topicsId);
        }

        /*
         * We are only searching for videos (not playlists or channels).  If we were searching for
         * more, we would add them as a string like this: "video,playlist,channel".
         */
        search.setType("video");
        /*
         * This method reduces the info returned to only the fields we need.  It makes things more
         * efficient, because we are transmitting less data.
         */
        search.setFields("items(id/kind,id/videoId,snippet/title,snippet/thumbnails/default/url)");
        search.setMaxResults(NUMBER_OF_VIDEOS_RETURNED);
        SearchListResponse searchResponse = search.execute();

        List<SearchResult> searchResultList = searchResponse.getItems();

        if (searchResultList != null) {
            prettyPrint(searchResultList.iterator(), queryTerm, topicsId);
        } else {
            System.out.println("There were no results for your query.");
        }
    } catch (GoogleJsonResponseException e) {
        System.err.println(
                "There was a service error: " + e.getDetails().getCode() + " : " + e.getDetails().getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.networknt.light.server.handler.loader.PageLoader.java

public static void main(String[] args) {
    try {//from   www. j  av a  2  s .  c o  m
        String host = null;
        String userId = null;
        String password = null;
        if (args != null && args.length == 3) {
            host = args[0];
            userId = args[1];
            password = args[2];
            if (host.length() == 0 || userId.length() == 0 || password.length() == 0) {
                System.out.println("host, userId and password are required");
                System.exit(1);
            }
        } else {
            System.out.println("Usage: PageLoader host userId password");
            System.exit(1);
        }

        File folder = getFileFromResourceFolder(pageFolder);
        if (folder != null) {
            httpclient = HttpClients.createDefault();
            // login as owner here
            login(host, userId, password);
            getPageMap(host);

            File[] listOfFiles = folder.listFiles();
            for (int i = 0; i < listOfFiles.length; i++) {
                loadPageFile(host, listOfFiles[i]);
            }
            httpclient.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
    }
}