Example usage for java.lang String substring

List of usage examples for java.lang String substring

Introduction

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

Prototype

public String substring(int beginIndex, int endIndex) 

Source Link

Document

Returns a string that is a substring of this string.

Usage

From source file:at.treedb.util.SevenZip.java

public static void main(String args[]) throws IOException {
    System.out.println("Extract");
    HashMap<String, byte[]> map = exctact(new File("c:/TreeDBdata/domains/ZooDB.7z"), "info.xml", "classes/");
    for (String s : map.keySet()) {
        if (s.startsWith("classes/")) {
            String className = s.substring("classes/".length(), s.lastIndexOf(".class")).replace("/", ".");
            System.out.println(className);
        }//from  w  ww. j av  a 2  s  .  c  om
    }
}

From source file:hk.hku.cecid.corvus.http.AS2EnvelopQuerySender.java

/**
 * The main method is for CLI mode.//w  w  w . jav  a2  s. c  om
 */
public static void main(String[] args) {
    try {
        java.io.PrintStream out = System.out;

        if (args.length < 2) {
            out.println("Usage: as2-envelop [config-xml] [log-path]");
            out.println();
            out.println("Example: as2-envelop ./config/as2-envelop/as2-request.xml ./logs/as2-envelop.log");
            System.exit(1);
        }

        out.println("------------------------------------------------------");
        out.println("       AS2 Envelop Queryer       ");
        out.println("------------------------------------------------------");

        // Initialize the logger.
        out.println("Initialize logger .. ");
        // The logger path is specified at the last argument.
        FileLogger logger = new FileLogger(new File(args[args.length - 1]));

        // Initialize the query parameter.
        out.println("Importing AS2 administrative sending parameters ... ");
        AS2AdminData acd = DataFactory.getInstance()
                .createAS2AdminDataFromXML(new PropertyTree(new File(args[0]).toURI().toURL()));

        boolean historyQueryNeeded = false;
        AS2MessageHistoryRequestData queryData = new AS2MessageHistoryRequestData();
        if (acd.getMessageIdCriteria() == null || acd.getMessageIdCriteria().trim().equals("")) {

            historyQueryNeeded = true;

            // print command prompt
            out.println("No messageID was specified!");
            out.println("Start querying message repositry ...");

            String endpoint = acd.getEnvelopQueryEndpoint();
            String host = endpoint.substring(0, endpoint.indexOf("/corvus"));
            host += "/corvus/httpd/as2/msg_history";
            queryData.setEndPoint(host);
        } /*
            If the user has entered message id but no messagebox, 
            using the messageid as serach criteria and as 
            user to chose his target message
          */
        else if (acd.getMessageBoxCriteria() == null || acd.getMessageBoxCriteria().trim().equals("")) {

            historyQueryNeeded = true;

            // print command prompt
            out.println("Message Box value haven't specified.");
            out.println("Start query message whcih matched with messageID: " + acd.getMessageIdCriteria());

            String endpoint = acd.getEnvelopQueryEndpoint();
            String host = endpoint.substring(0, endpoint.indexOf("/corvus"));
            host += "/corvus/httpd/as2/msg_history";

            queryData.setEndPoint(host);
            queryData.setMessageId(acd.getMessageIdCriteria());
        }
        //Debug Message
        System.out.println("history Endpoint: " + queryData.getEndPoint());
        System.out.println("Repositry Endpoint: " + acd.getEnvelopQueryEndpoint());

        if (historyQueryNeeded) {
            List msgList = listAvailableMessage(queryData, logger);

            if (msgList == null || msgList.size() == 0) {
                out.println();
                out.println();
                out.println("No stream data found in repositry...");
                out.println("Please view log for details .. ");
                return;
            }

            int selection = promptForSelection(msgList);

            if (selection == -1) {
                return;
            }

            String messageID = (String) ((List) msgList.get(selection)).get(0);
            String messageBox = (String) ((List) msgList.get(selection)).get(1);
            acd.setMessageIdCriteria(messageID);
            acd.setMessageBoxCriteria(messageBox.toUpperCase());
            out.println();
            out.println();
            out.println("Start download targeted message envelop ...");
        }

        // Initialize the sender.
        out.println("Initialize AS2 HTTP data service client... ");
        AS2EnvelopQuerySender sender = new AS2EnvelopQuerySender(logger, acd);

        out.println("Sending    AS2 HTTP Envelop Query request ... ");
        sender.run();

        out.println();
        out.println("                    Sending Done:                   ");
        out.println("----------------------------------------------------");
        out.println("The Message Envelope : ");
        InputStream eins = sender.getEnvelopStream();
        if (eins.available() == 0) {
            out.println("No stream data found.");
            out.println("The message envelop does not exist for message id " + sender.getMessageIdToDownload()
                    + " and message box " + sender.getMessageBoxToDownload());
        } else
            IOHandler.pipe(sender.getEnvelopStream(), out);

        out.println("Please view log for details .. ");
    } catch (Exception e) {
        e.printStackTrace(System.err);
    }
}

From source file:com.gson.util.HttpKit.java

public static void main(String[] args) {
    String fname = "dsasdas.mp4";
    String s = fname.substring(0, fname.lastIndexOf("."));
    String f = fname.substring(s.length() + 1);
    System.out.println(f);/*from   w  w w. ja va 2 s  .  c om*/
}

From source file:com.cyberway.issue.util.SurtPrefixSet.java

/**
 * Allow class to be used as a command-line tool for converting 
 * URL lists (or naked host or host/path fragments implied
 * to be HTTP URLs) to implied SURT prefix form. 
 * /*from w  ww . j a va  2 s. co m*/
 * Read from stdin or first file argument. Writes to stdout. 
 *
 * @param args cmd-line arguments: may include input file
 * @throws IOException
 */
public static void main(String[] args) throws IOException {
    InputStream in = args.length > 0 ? new BufferedInputStream(new FileInputStream(args[0])) : System.in;
    PrintStream out = args.length > 1 ? new PrintStream(new BufferedOutputStream(new FileOutputStream(args[1])))
            : System.out;
    BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String line;
    while ((line = br.readLine()) != null) {
        if (line.indexOf("#") > 0)
            line = line.substring(0, line.indexOf("#"));
        line = line.trim();
        if (line.length() == 0)
            continue;
        out.println(prefixFromPlain(line));
    }
    br.close();
    out.close();
}

From source file:jhc.redsniff.generation.PackageScanningGenerator.java

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

    if (args.length != 5) {
        System.err.println("Args: source-dir package-class-filter parent-class generated-class output-dir");
        System.err.println("");
        System.err.println("    source-dir  : Path to Java source containing matchers to generate sugar for.");
        System.err.println("                  May contain multiple paths, separated by commas.");
        System.err.println("                  e.g. src/java,src/more-java");
        System.err.println(//from w  w w.jav  a  2s .  c  om
                "    package-class-filter  : base of package to look for classes with methods, eg jhc.selenium.matchers");

        System.err.println("");
        System.err.println(
                "parent-class : Full name of parent class type to examine - eg org.hamcrest.Matcher, jhc.selenium.seeker.Seeker");
        System.err.println("                  e.g. org.myproject.MyMatchers");
        System.err.println("generated-class : Full name of class to generate.");
        System.err.println("                  e.g. org.myproject.MyMatchers");
        System.err.println("");
        System.err.println("     output-dir : Where to output generated code (package subdirs will be");
        System.err.println("                  automatically created).");
        System.err.println("                  e.g. build/generated-code");
        System.exit(-1);
    }

    String srcDirs = args[0];
    String package_name_prefix = args[1];
    String parentClassName = args[2];
    String fullClassName = args[3];
    File outputDir = new File(args[4]);

    String fileName = fullClassName.replace('.', File.separatorChar) + ".java";
    int dotIndex = fullClassName.lastIndexOf(".");
    String packageName = dotIndex == -1 ? "" : fullClassName.substring(0, dotIndex);
    String shortClassName = fullClassName.substring(dotIndex + 1);

    if (!outputDir.isDirectory()) {
        System.err.println("Output directory not found : " + outputDir.getAbsolutePath());
        System.exit(-1);
    }

    Class<?> parentClass = Class.forName(parentClassName);

    File outputFile = new File(outputDir, fileName);
    outputFile.getParentFile().mkdirs();
    File tmpFile = new File(outputDir, fileName + ".tmp");

    SugarGenerator sugarGenerator = new SugarGenerator();
    try {
        sugarGenerator
                .addWriter(new SeleniumFactoryWriter(packageName, shortClassName, new FileWriter(tmpFile)));
        sugarGenerator.addWriter(new QuickReferenceWriter(System.out));

        PackageScanningGenerator pkgScanningGenerator = new PackageScanningGenerator(sugarGenerator,
                PackageScanningGenerator.class.getClassLoader(), parentClass);

        if (srcDirs.trim().length() > 0) {
            for (String srcDir : srcDirs.split(",")) {
                pkgScanningGenerator.addSourceDir(new File(srcDir));
            }
        }
        // could add use of xml just to list filter expressions
        // pkgScanningGenerator.load(new InputSource(configFile));
        pkgScanningGenerator.addClasses(package_name_prefix);

        System.out.println("Generating " + fullClassName);
        sugarGenerator.generate();
        sugarGenerator.close();
        outputFile.delete();
        FileUtils.moveFile(tmpFile, outputFile);

    } finally {
        tmpFile.delete();
        sugarGenerator.close();
    }
}

From source file:com.datazuul.iiif.presentation.api.ManifestGenerator.java

public static void main(String[] args)
        throws ParseException, JsonProcessingException, IOException, URISyntaxException {
    Options options = new Options();
    options.addOption("d", true, "Absolute file path to the directory containing the image files.");

    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = parser.parse(options, args);

    if (cmd.hasOption("d")) {
        String imageDirectoryPath = cmd.getOptionValue("d");
        Path imageDirectory = Paths.get(imageDirectoryPath);
        final List<Path> files = new ArrayList<>();
        try {// w w  w.  j a v  a  2 s.c  o m
            Files.walkFileTree(imageDirectory, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (!attrs.isDirectory()) {
                        // TODO there must be a more elegant solution for filtering jpeg files...
                        if (file.getFileName().toString().endsWith("jpg")) {
                            files.add(file);
                        }
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        Collections.sort(files, new Comparator() {
            @Override
            public int compare(Object fileOne, Object fileTwo) {
                String filename1 = ((Path) fileOne).getFileName().toString();
                String filename2 = ((Path) fileTwo).getFileName().toString();

                try {
                    // numerical sorting
                    Integer number1 = Integer.parseInt(filename1.substring(0, filename1.lastIndexOf(".")));
                    Integer number2 = Integer.parseInt(filename2.substring(0, filename2.lastIndexOf(".")));
                    return number1.compareTo(number2);
                } catch (NumberFormatException nfe) {
                    // alpha-numerical sorting
                    return filename1.compareToIgnoreCase(filename2);
                }
            }
        });

        generateManifest(imageDirectory.getFileName().toString(), files);
    } else {
        // automatically generate the help statement
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("ManifestGenerator", options);
    }
}

From source file:com.qpark.maven.plugin.servletconfig.WsServletXmlGenerator.java

public static void main(final String[] args) {
    final String s = "<bean id=\"\neins\" lkajsdfid=\"zwei\"kljadf";
    final String[] ss = s.split("id=\\\"");
    for (final String string : ss) {
        if (string.indexOf('"') > 0) {
            System.out.println(/*from  ww  w  .  ja  v  a2 s  .c  om*/
                    string.substring(0, string.indexOf('"')).replaceAll("\\\n", "").replaceAll("\\\r", ""));
        }
    }
}

From source file:net.ontopia.topicmaps.db2tm.CSVImport.java

public static void main(String[] argv) throws Exception {

    // Initialize logging
    CmdlineUtils.initializeLogging();//from ww  w.  ja va  2  s . c o  m

    // Initialize command line option parser and listeners
    CmdlineOptions options = new CmdlineOptions("CSVImport", argv);
    OptionsListener ohandler = new OptionsListener();

    // Register local options
    options.addLong(ohandler, "separator", 's', true);
    options.addLong(ohandler, "stripquotes", 'q');
    options.addLong(ohandler, "ignorelines", 'i', true);

    // Register logging options
    CmdlineUtils.registerLoggingOptions(options);

    // Parse command line options
    try {
        options.parse();
    } catch (CmdlineOptions.OptionsException e) {
        System.err.println("Error: " + e.getMessage());
        System.exit(1);
    }

    // Get command line arguments
    String[] args = options.getArguments();
    if (args.length < 2) {
        System.err.println("Error: wrong number of arguments.");
        usage();
        System.exit(1);
    }

    String dbprops = args[0];
    String csvfile = args[1];
    String table = (args.length >= 3 ? args[2] : null);
    if (table == null) {
        if (csvfile.endsWith(".csv"))
            table = csvfile.substring(0, csvfile.length() - 4);
        else
            table = csvfile;
    }
    String[] columns = (args.length >= 4 ? StringUtils.split(args[3], ",") : null);

    // Load property file
    Properties props = new Properties();
    props.load(new FileInputStream(dbprops));

    // Create database connection
    DefaultConnectionFactory cfactory = new DefaultConnectionFactory(props, false);
    Connection conn = cfactory.requestConnection();

    CSVImport ci = new CSVImport(conn);
    ci.setTable(table);
    ci.setColumns(columns);
    ci.setSeparator(ohandler.separator);
    ci.setClearTable(true);
    ci.setStripQuotes(ohandler.stripquotes);
    ci.setIgnoreColumns(true);
    ci.setIgnoreLines(ohandler.ignorelines);

    ci.importCSV(new FileInputStream(csvfile));
}

From source file:importer.handler.post.stages.Splitter.java

/** test and commandline utility */
public static void main(String[] args) {
    if (args.length >= 1) {
        try {//w  w  w .  j a va  2 s .c o  m
            int i = 0;
            int fileIndex = 0;
            // see if the user supplied a conf file
            String textConf = Discriminator.defaultConf;
            while (i < args.length) {
                if (args[i].equals("-c") && i < args.length - 1) {
                    textConf = readConfig(args[i + 1]);
                    i += 2;
                } else {
                    fileIndex = i;
                    i++;
                }
            }
            File f = new File(args[fileIndex]);
            char[] data = new char[(int) f.length()];
            FileReader fr = new FileReader(f);
            fr.read(data);
            JSONObject config = (JSONObject) JSONValue.parse(textConf);
            Splitter split = new Splitter(config);
            Map<String, String> map = split.split(new String(data));
            Set<String> keys = map.keySet();
            String rawFileName = args[fileIndex];
            int pos = rawFileName.lastIndexOf(".");
            if (pos != -1)
                rawFileName = rawFileName.substring(0, pos);
            Iterator<String> iter = keys.iterator();
            while (iter.hasNext()) {
                String key = iter.next();
                String fName = rawFileName + "-" + key + ".xml";
                File g = new File(fName);
                if (g.exists())
                    g.delete();
                FileOutputStream fos = new FileOutputStream(g);
                fos.write(map.get(key).getBytes("UTF-8"));
                fos.close();
            }
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
    } else
        System.out.println("usage: java -jar split.jar [-c json-config] <tei-xml>\n");
}

From source file:com.joliciel.lefff.Lefff.java

/**
 * @param args/*from w ww  .  j a v  a  2  s. c  o  m*/
 */
public static void main(String[] args) throws Exception {
    long startTime = (new Date()).getTime();
    String command = args[0];

    String memoryBaseFilePath = "";
    String lefffFilePath = "";
    String posTagSetPath = "";
    String posTagMapPath = "";
    String word = null;
    List<String> categories = null;
    int startLine = -1;
    int stopLine = -1;

    boolean firstArg = true;
    for (String arg : args) {
        if (firstArg) {
            firstArg = false;
            continue;
        }
        int equalsPos = arg.indexOf('=');
        String argName = arg.substring(0, equalsPos);
        String argValue = arg.substring(equalsPos + 1);
        if (argName.equals("memoryBase"))
            memoryBaseFilePath = argValue;
        else if (argName.equals("lefffFile"))
            lefffFilePath = argValue;
        else if (argName.equals("startLine"))
            startLine = Integer.parseInt(argValue);
        else if (argName.equals("stopLine"))
            stopLine = Integer.parseInt(argValue);
        else if (argName.equals("posTagSet"))
            posTagSetPath = argValue;
        else if (argName.equals("posTagMap"))
            posTagMapPath = argValue;
        else if (argName.equals("word"))
            word = argValue;
        else if (argName.equals("categories")) {
            String[] parts = argValue.split(",");
            categories = new ArrayList<String>();
            for (String part : parts) {
                categories.add(part);
            }
        } else
            throw new RuntimeException("Unknown argument: " + argName);
    }

    final LefffServiceLocator locator = new LefffServiceLocator();
    locator.setDataSourcePropertiesFile("jdbc-live.properties");

    TalismaneServiceLocator talismaneServiceLocator = TalismaneServiceLocator.getInstance();

    final LefffService lefffService = locator.getLefffService();
    if (command.equals("load")) {
        if (lefffFilePath.length() == 0)
            throw new RuntimeException("Required argument: lefffFile");
        final LefffLoader loader = lefffService.getLefffLoader();
        File file = new File(lefffFilePath);
        if (startLine > 0)
            loader.setStartLine(startLine);
        if (stopLine > 0)
            loader.setStopLine(stopLine);

        loader.LoadFile(file);
    } else if (command.equals("serialiseBase")) {
        if (memoryBaseFilePath.length() == 0)
            throw new RuntimeException("Required argument: memoryBase");
        if (posTagSetPath.length() == 0)
            throw new RuntimeException("Required argument: posTagSet");
        if (posTagMapPath.length() == 0)
            throw new RuntimeException("Required argument: posTagMap");

        PosTaggerServiceLocator posTaggerServiceLocator = talismaneServiceLocator.getPosTaggerServiceLocator();
        PosTaggerService posTaggerService = posTaggerServiceLocator.getPosTaggerService();
        File posTagSetFile = new File(posTagSetPath);
        PosTagSet posTagSet = posTaggerService.getPosTagSet(posTagSetFile);

        File posTagMapFile = new File(posTagMapPath);
        LefffPosTagMapper posTagMapper = lefffService.getPosTagMapper(posTagMapFile, posTagSet);

        Map<PosTagSet, LefffPosTagMapper> posTagMappers = new HashMap<PosTagSet, LefffPosTagMapper>();
        posTagMappers.put(posTagSet, posTagMapper);

        LefffMemoryLoader loader = new LefffMemoryLoader();
        LefffMemoryBase memoryBase = loader.loadMemoryBaseFromDatabase(lefffService, posTagMappers, categories);
        File memoryBaseFile = new File(memoryBaseFilePath);
        memoryBaseFile.delete();
        loader.serializeMemoryBase(memoryBase, memoryBaseFile);
    } else if (command.equals("deserialiseBase")) {
        if (memoryBaseFilePath.length() == 0)
            throw new RuntimeException("Required argument: memoryBase");

        LefffMemoryLoader loader = new LefffMemoryLoader();
        File memoryBaseFile = new File(memoryBaseFilePath);
        LefffMemoryBase memoryBase = loader.deserializeMemoryBase(memoryBaseFile);

        String[] testWords = new String[] { "avoir" };
        if (word != null) {
            testWords = word.split(",");
        }

        for (String testWord : testWords) {
            Set<PosTag> possiblePosTags = memoryBase.findPossiblePosTags(testWord);
            LOG.debug("##### PosTags for '" + testWord + "': " + possiblePosTags.size());
            int i = 1;
            for (PosTag posTag : possiblePosTags) {
                LOG.debug("### PosTag " + (i++) + ":" + posTag);
            }

            List<? extends LexicalEntry> entriesForWord = memoryBase.getEntries(testWord);
            LOG.debug("##### Entries for '" + testWord + "': " + entriesForWord.size());
            i = 1;
            for (LexicalEntry entry : entriesForWord) {
                LOG.debug("### Entry " + (i++) + ":" + entry.getWord());
                LOG.debug("Category " + entry.getCategory());
                LOG.debug("Predicate " + entry.getPredicate());
                LOG.debug("Lemma " + entry.getLemma());
                LOG.debug("Morphology " + entry.getMorphology());
            }

            List<? extends LexicalEntry> entriesForLemma = memoryBase.getEntriesForLemma(testWord, "");
            LOG.debug("##### Entries for '" + testWord + "' lemma: " + entriesForLemma.size());
            for (LexicalEntry entry : entriesForLemma) {
                LOG.debug("### Entry " + entry.getWord());
                LOG.debug("Category " + entry.getCategory());
                LOG.debug("Predicate " + entry.getPredicate());
                LOG.debug("Lemma " + entry.getLemma());
                LOG.debug("Morphology " + entry.getMorphology());
                for (PredicateArgument argument : entry.getPredicateArguments()) {
                    LOG.debug("Argument: " + argument.getFunction() + ",Optional? " + argument.isOptional());
                    for (String realisation : argument.getRealisations()) {
                        LOG.debug("Realisation: " + realisation);
                    }
                }
            }
        }

    } else {
        System.out.println("Usage : Lefff load filepath");
    }
    long endTime = (new Date()).getTime() - startTime;
    LOG.debug("Total runtime: " + ((double) endTime / 1000) + " seconds");
}