Example usage for java.lang String replaceFirst

List of usage examples for java.lang String replaceFirst

Introduction

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

Prototype

public String replaceFirst(String regex, String replacement) 

Source Link

Document

Replaces the first substring of this string that matches the given regular expression with the given replacement.

Usage

From source file:org.eclipse.lyo.client.oslc.samples.RRCFormSample.java

/**
 * Login to the RRC server and perform some OSLC actions
 * @param args//ww  w. j av a2 s  .  co m
 * @throws ParseException 
 */
public static void main(String[] args) throws ParseException {

    Options options = new Options();

    options.addOption("url", true, "url");
    options.addOption("user", true, "user ID");
    options.addOption("password", true, "password");
    options.addOption("project", true, "project area");

    CommandLineParser cliParser = new GnuParser();

    //Parse the command line
    CommandLine cmd = cliParser.parse(options, args);

    if (!validateOptions(cmd)) {
        logger.severe(
                "Syntax:  java <class_name> -url https://<server>:port/<context>/ -user <user> -password <password> -project \"<project_area>\"");
        logger.severe(
                "Example: java RRCFormSample -url https://exmple.com:9443/rm -user ADMIN -password ADMIN -project \"JKE Banking (Requirements Management)\"");
        return;
    }

    String webContextUrl = cmd.getOptionValue("url");
    String user = cmd.getOptionValue("user");
    String passwd = cmd.getOptionValue("password");
    String projectArea = cmd.getOptionValue("project");

    try {

        //STEP 1: Initialize a Jazz rootservices helper and indicate we're looking for the RequirementManagement catalog
        JazzRootServicesHelper helper = new JazzRootServicesHelper(webContextUrl, OSLCConstants.OSLC_RM_V2);

        //STEP 2: Create a new Form Auth client with the supplied user/password
        //RRC is a fronting server, so need to use the initForm() signature which allows passing of an authentication URL.
        //For RRC, use the JTS for the authorization URL

        //This is a bit of a hack for readability.  It is assuming RRC is at context /rm.  Could use a regex or UriBuilder instead.
        String authUrl = webContextUrl.replaceFirst("/rm", "/jts");
        JazzFormAuthClient client = helper.initFormClient(user, passwd, authUrl);

        //STEP 3: Login in to Jazz Server
        if (client.formLogin() == HttpStatus.SC_OK) {

            //STEP 4: Get the URL of the OSLC ChangeManagement catalog
            String catalogUrl = helper.getCatalogUrl();

            //STEP 5: Find the OSLC Service Provider for the project area we want to work with
            String serviceProviderUrl = client.lookupServiceProviderUrl(catalogUrl, projectArea);

            //STEP 6: Get the Query Capabilities URL so that we can run some OSLC queries
            String queryCapability = client.lookupQueryCapability(serviceProviderUrl, OSLCConstants.OSLC_RM_V2,
                    OSLCConstants.RM_REQUIREMENT_TYPE);
            //STEP 7: Create base requirements
            //Get the Creation Factory URL for change requests so that we can create one
            Requirement requirement = new Requirement();
            String requirementFactory = client.lookupCreationFactory(serviceProviderUrl,
                    OSLCConstants.OSLC_RM_V2, requirement.getRdfTypes()[0].toString());

            //Get Feature Requirement Type URL
            ResourceShape featureInstanceShape = RmUtil.lookupRequirementsInstanceShapes(serviceProviderUrl,
                    OSLCConstants.OSLC_RM_V2, requirement.getRdfTypes()[0].toString(), client, "Feature");

            URI rootFolder = null;
            //Get Collection Type URL
            RequirementCollection collection = new RequirementCollection();
            ResourceShape collectionInstanceShape = RmUtil.lookupRequirementsInstanceShapes(serviceProviderUrl,
                    OSLCConstants.OSLC_RM_V2, collection.getRdfTypes()[0].toString(), client,
                    "Personal Collection");

            String req01URL = null;
            String req02URL = null;
            String req03URL = null;
            String req04URL = null;
            String reqcoll01URL = null;

            String primaryText = null;
            if ((featureInstanceShape != null) && (requirementFactory != null)) {

                // Create REQ01
                requirement.setInstanceShape(featureInstanceShape.getAbout());
                requirement.setTitle("Req01");

                // Decorate the PrimaryText
                primaryText = "My Primary Text";
                org.w3c.dom.Element obj = RmUtil.convertStringToHTML(primaryText);
                requirement.getExtendedProperties().put(RmConstants.PROPERTY_PRIMARY_TEXT, obj);

                requirement.setDescription("Created By EclipseLyo");
                requirement.addImplementedBy(new Link(new URI("http://google.com"), "Link in REQ01"));
                //Create the change request
                ClientResponse creationResponse = client.createResource(requirementFactory, requirement,
                        OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_RDF_XML);
                req01URL = creationResponse.getHeaders().getFirst(HttpHeaders.LOCATION);
                creationResponse.consumeContent();

                // Create REQ02   
                requirement = new Requirement();
                requirement.setInstanceShape(featureInstanceShape.getAbout());
                requirement.setTitle("Req02");
                requirement.setDescription("Created By EclipseLyo");
                requirement.addValidatedBy(new Link(new URI("http://bancomer.com"), "Link in REQ02"));
                //Create the change request
                creationResponse = client.createResource(requirementFactory, requirement,
                        OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_RDF_XML);

                req02URL = creationResponse.getHeaders().getFirst(HttpHeaders.LOCATION);
                creationResponse.consumeContent();

                // Create REQ03   
                requirement = new Requirement();
                requirement.setInstanceShape(featureInstanceShape.getAbout());
                requirement.setTitle("Req03");
                requirement.setDescription("Created By EclipseLyo");
                requirement.addValidatedBy(new Link(new URI("http://outlook.com"), "Link in REQ03"));
                //Create the change request
                creationResponse = client.createResource(requirementFactory, requirement,
                        OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_RDF_XML);
                req03URL = creationResponse.getHeaders().getFirst(HttpHeaders.LOCATION);
                creationResponse.consumeContent();

                // Create REQ04   
                requirement = new Requirement();
                requirement.setInstanceShape(featureInstanceShape.getAbout());
                requirement.setTitle("Req04");
                requirement.setDescription("Created By EclipseLyo");

                //Create the Requirement
                creationResponse = client.createResource(requirementFactory, requirement,
                        OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_RDF_XML);
                req04URL = creationResponse.getHeaders().getFirst(HttpHeaders.LOCATION);
                creationResponse.consumeContent();

                // Now create a collection 
                // Create REQ04   
                collection = new RequirementCollection();

                collection.addUses(new URI(req03URL));
                collection.addUses(new URI(req04URL));

                collection.setInstanceShape(collectionInstanceShape.getAbout());
                collection.setTitle("Collection01");
                collection.setDescription("Created By EclipseLyo");
                //Create the change request
                creationResponse = client.createResource(requirementFactory, collection,
                        OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_RDF_XML);
                reqcoll01URL = creationResponse.getHeaders().getFirst(HttpHeaders.LOCATION);
                creationResponse.consumeContent();

            }

            // Check that everything was properly created
            if (req01URL == null || req02URL == null || req03URL == null || req04URL == null
                    || reqcoll01URL == null) {
                throw new Exception("Failed to create an artifact");
            }

            // GET the root folder based on First requirement created
            ClientResponse getResponse = client.getResource(req01URL, OslcMediaType.APPLICATION_RDF_XML);
            requirement = getResponse.getEntity(Requirement.class);
            String etag1 = getResponse.getHeaders().getFirst(OSLCConstants.ETAG);
            // May not be needed getResponse.consumeContent();
            //Save the URI of the root folder in order to used it easily 
            rootFolder = (URI) requirement.getExtendedProperties().get(RmConstants.PROPERTY_PARENT_FOLDER);

            String changedPrimaryText = (String) requirement.getExtendedProperties()
                    .get(RmConstants.PROPERTY_PRIMARY_TEXT);
            if (changedPrimaryText == null) {
                // Check with the workaround
                changedPrimaryText = (String) requirement.getExtendedProperties()
                        .get(PROPERTY_PRIMARY_TEXT_WORKAROUND);
            }

            if ((changedPrimaryText != null) && (!changedPrimaryText.contains(primaryText))) {
                logger.log(Level.SEVERE, "Error getting primary Text");
            }

            //QUERIES
            // SCENARIO 01  Do a query for type= Requirements
            OslcQueryParameters queryParams = new OslcQueryParameters();
            queryParams.setPrefix("rdf=<http://www.w3.org/1999/02/22-rdf-syntax-ns#>");
            queryParams.setWhere("rdf:type=<http://open-services.net/ns/rm#Requirement>");
            OslcQuery query = new OslcQuery(client, queryCapability, 10, queryParams);
            OslcQueryResult result = query.submit();
            boolean processAsJavaObjects = false;
            int resultsSize = result.getMembersUrls().length;
            processPagedQueryResults(result, client, processAsJavaObjects);
            System.out.println("\n------------------------------\n");
            System.out.println("Number of Results for SCENARIO 01 = " + resultsSize + "\n");

            // SCENARIO 02    Do a query for type= Requirements and for it folder container = rootFolder
            queryParams = new OslcQueryParameters();
            queryParams.setPrefix(
                    "nav=<http://com.ibm.rdm/navigation#>,rdf=<http://www.w3.org/1999/02/22-rdf-syntax-ns#>");
            queryParams.setWhere("rdf:type=<http://open-services.net/ns/rm#Requirement> and nav:parent=<"
                    + rootFolder + ">");
            query = new OslcQuery(client, queryCapability, 10, queryParams);
            result = query.submit();
            processAsJavaObjects = false;
            resultsSize = result.getMembersUrls().length;
            processPagedQueryResults(result, client, processAsJavaObjects);
            System.out.println("\n------------------------------\n");
            System.out.println("Number of Results for SCENARIO 02 = " + resultsSize + "\n");

            // SCENARIO 03   Do a query for title
            queryParams = new OslcQueryParameters();
            queryParams.setPrefix("dcterms=<http://purl.org/dc/terms/>");
            queryParams.setWhere("dcterms:title=\"Req04\"");
            query = new OslcQuery(client, queryCapability, 10, queryParams);
            result = query.submit();
            resultsSize = result.getMembersUrls().length;
            processAsJavaObjects = false;
            processPagedQueryResults(result, client, processAsJavaObjects);
            System.out.println("\n------------------------------\n");
            System.out.println("Number of Results for SCENARIO 03 = " + resultsSize + "\n");

            // SCENARIO 04   Do a query for the link that is implemented
            queryParams = new OslcQueryParameters();
            queryParams.setPrefix("oslc_rm=<http://open-services.net/ns/rm#>");
            queryParams.setWhere("oslc_rm:implementedBy=<http://google.com>");
            query = new OslcQuery(client, queryCapability, 10, queryParams);
            result = query.submit();
            resultsSize = result.getMembersUrls().length;
            processAsJavaObjects = false;
            processPagedQueryResults(result, client, processAsJavaObjects);
            System.out.println("\n------------------------------\n");
            System.out.println("Number of Results for SCENARIO 04 = " + resultsSize + "\n");

            // SCENARIO 05   Do a query for the links that is validated 
            queryParams = new OslcQueryParameters();
            queryParams.setPrefix("oslc_rm=<http://open-services.net/ns/rm#>");
            queryParams.setWhere("oslc_rm:validatedBy in [<http://bancomer.com>,<http://outlook.com>]");
            query = new OslcQuery(client, queryCapability, 10, queryParams);
            result = query.submit();
            resultsSize = result.getMembersUrls().length;
            processAsJavaObjects = false;
            processPagedQueryResults(result, client, processAsJavaObjects);
            System.out.println("\n------------------------------\n");
            System.out.println("Number of Results for SCENARIO 05 = " + resultsSize + "\n");

            // SCENARIO 06 Do a query for it container folder and for the link that is implemented
            queryParams = new OslcQueryParameters();
            queryParams.setPrefix(
                    "nav=<http://com.ibm.rdm/navigation#>,oslc_rm=<http://open-services.net/ns/rm#>");
            queryParams
                    .setWhere("nav:parent=<" + rootFolder + "> and oslc_rm:validatedBy=<http://bancomer.com>");
            query = new OslcQuery(client, queryCapability, 10, queryParams);
            result = query.submit();
            resultsSize = result.getMembersUrls().length;
            processAsJavaObjects = false;
            processPagedQueryResults(result, client, processAsJavaObjects);
            System.out.println("\n------------------------------\n");
            System.out.println("Number of Results for SCENARIO 06 = " + resultsSize + "\n");

            // GET resources from req03 in order edit its values
            getResponse = client.getResource(req03URL, OslcMediaType.APPLICATION_RDF_XML);
            requirement = getResponse.getEntity(Requirement.class);
            // Get the eTAG, we need it to update
            String etag = getResponse.getHeaders().getFirst(OSLCConstants.ETAG);
            getResponse.consumeContent();
            requirement.setTitle("My new Title");
            requirement.addImplementedBy(
                    new Link(new URI("http://google.com"), "Link created by an Eclipse Lyo user"));

            // Update the requirement with the proper etag 
            ClientResponse updateResponse = client.updateResource(req03URL, requirement,
                    OslcMediaType.APPLICATION_RDF_XML, OslcMediaType.APPLICATION_RDF_XML, etag);

            updateResponse.consumeContent();

            /*Do a query in order to see if the requirement have changed*/
            // SCENARIO 07 Do a query for the new title just changed
            queryParams = new OslcQueryParameters();
            queryParams.setPrefix("dcterms=<http://purl.org/dc/terms/>");
            queryParams.setWhere("dcterms:title=\"My new Title\"");
            query = new OslcQuery(client, queryCapability, 10, queryParams);
            result = query.submit();
            resultsSize = result.getMembersUrls().length;
            processAsJavaObjects = false;
            processPagedQueryResults(result, client, processAsJavaObjects);
            System.out.println("\n------------------------------\n");
            System.out.println("Number of Results for SCENARIO 07 = " + resultsSize + "\n");

            // SCENARIO 08   Do a query for implementedBy links
            queryParams = new OslcQueryParameters();
            queryParams.setPrefix("oslc_rm=<http://open-services.net/ns/rm#>");
            queryParams.setWhere("oslc_rm:implementedBy=<http://google.com>");
            query = new OslcQuery(client, queryCapability, 10, queryParams);
            result = query.submit();
            resultsSize = result.getMembersUrls().length;
            processAsJavaObjects = false;
            processPagedQueryResults(result, client, processAsJavaObjects);
            System.out.println("\n------------------------------\n");
            System.out.println("Number of Results for SCENARIO 08 = " + resultsSize + "\n");

        }
    } catch (RootServicesException re) {
        logger.log(Level.SEVERE,
                "Unable to access the Jazz rootservices document at: " + webContextUrl + "/rootservices", re);
    } catch (Exception e) {
        logger.log(Level.SEVERE, e.getMessage(), e);
    }

}

From source file:com.admc.jcreole.JCreole.java

/**
 * Run this method with no parameters to see syntax requirements and the
 * available parameters./*from w ww.j  a v  a 2 s . c  o m*/
 *
 * N.b. do not call this method from a persistent program, because it
 * may call System.exit!
 * <p>
 * Any long-running program should use the lower-level methods in this
 * class instead (or directly use CreoleParser and CreoleScanner
 * instances).
 * </p> <p>
 * This method executes with all JCreole privileges.
 * </p> <p>
 * This method sets up the following htmlExpander mappings (therefore you
 * can reference these in both Creole and boilerplate text).<p>
 * <ul>
 *   <li>sys|*: mappings for Java system properties
 *   <li>isoDateTime
 *   <li>isoDate
 *   <li>pageTitle: Value derived from the specified Creole file name.
 * </ul>
 *
 * @throws IOException for any I/O problem that makes it impossible to
 *         satisfy the request.
 * @throws CreoleParseException
 *         if can not generate output, or if the run generates 0 output.
 *         If the problem is due to input formatting, in most cases you
 *         will get a CreoleParseException, which is a RuntimException, and
 *         CreoleParseException has getters for locations in the source
 *         data (though they will be offset for \r's in the provided
 *         Creole source, if any).
 */
public static void main(String[] sa) throws IOException {
    String bpResPath = null;
    String bpFsPath = null;
    String outPath = null;
    String inPath = null;
    boolean debugs = false;
    boolean troubleshoot = false;
    boolean noBp = false;
    int param = -1;
    try {
        while (++param < sa.length) {
            if (sa[param].equals("-d")) {
                debugs = true;
                continue;
            }
            if (sa[param].equals("-t")) {
                troubleshoot = true;
                continue;
            }
            if (sa[param].equals("-r") && param + 1 < sa.length) {
                if (bpFsPath != null || bpResPath != null || noBp)
                    throw new IllegalArgumentException();
                bpResPath = sa[++param];
                continue;
            }
            if (sa[param].equals("-f") && param + 1 < sa.length) {
                if (bpResPath != null || bpFsPath != null || noBp)
                    throw new IllegalArgumentException();
                bpFsPath = sa[++param];
                continue;
            }
            if (sa[param].equals("-")) {
                if (noBp || bpFsPath != null || bpResPath != null)
                    throw new IllegalArgumentException();
                noBp = true;
                continue;
            }
            if (sa[param].equals("-o") && param + 1 < sa.length) {
                if (outPath != null)
                    throw new IllegalArgumentException();
                outPath = sa[++param];
                continue;
            }
            if (inPath != null)
                throw new IllegalArgumentException();
            inPath = sa[param];
        }
        if (inPath == null)
            throw new IllegalArgumentException();
    } catch (IllegalArgumentException iae) {
        System.err.println(SYNTAX_MSG);
        System.exit(1);
    }
    if (!noBp && bpResPath == null && bpFsPath == null)
        bpResPath = DEFAULT_BP_RES_PATH;
    String rawBoilerPlate = null;
    if (bpResPath != null) {
        if (bpResPath.length() > 0 && bpResPath.charAt(0) == '/')
            // Classloader lookups are ALWAYS relative to CLASSPATH roots,
            // and will abort if you specify a beginning "/".
            bpResPath = bpResPath.substring(1);
        InputStream iStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(bpResPath);
        if (iStream == null)
            throw new IOException("Boilerplate inaccessible: " + bpResPath);
        rawBoilerPlate = IOUtil.toString(iStream);
    } else if (bpFsPath != null) {
        rawBoilerPlate = IOUtil.toString(new File(bpFsPath));
    }
    String creoleResPath = (inPath.length() > 0 && inPath.charAt(0) == '/') ? inPath.substring(1) : inPath;
    // Classloader lookups are ALWAYS relative to CLASSPATH roots,
    // and will abort if you specify a beginning "/".
    InputStream creoleStream = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream(creoleResPath);
    File inFile = (creoleStream == null) ? new File(inPath) : null;
    JCreole jCreole = (rawBoilerPlate == null) ? (new JCreole()) : (new JCreole(rawBoilerPlate));
    if (debugs) {
        jCreole.setInterWikiMapper(new InterWikiMapper() {
            // This InterWikiMapper is just for prototyping.
            // Use wiki name of "nil" to force lookup failure for path.
            // Use wiki page of "nil" to force lookup failure for label.
            public String toPath(String wikiName, String wikiPage) {
                if (wikiName != null && wikiName.equals("nil"))
                    return null;
                return "{WIKI-LINK to: " + wikiName + '|' + wikiPage + '}';
            }

            public String toLabel(String wikiName, String wikiPage) {
                if (wikiPage == null)
                    throw new RuntimeException("Null page name sent to InterWikiMapper");
                if (wikiPage.equals("nil"))
                    return null;
                return "{LABEL for: " + wikiName + '|' + wikiPage + '}';
            }
        });
        Expander creoleExpander = new Expander(Expander.PairedDelims.RECTANGULAR);
        creoleExpander.put("testMacro",
                "\n\n<<prettyPrint>>\n{{{\n" + "!/bin/bash -p\n\ncp /etc/inittab /tmp\n}}}\n");
        jCreole.setCreoleExpander(creoleExpander);
    }
    jCreole.setPrivileges(EnumSet.allOf(JCreolePrivilege.class));
    Expander exp = jCreole.getHtmlExpander();
    Date now = new Date();
    exp.putAll("sys", System.getProperties(), false);
    exp.put("isoDateTime", isoDateTimeFormatter.format(now), false);
    exp.put("isoDate", isoDateFormatter.format(now), false);
    exp.put("pageTitle",
            (inFile == null) ? creoleResPath.replaceFirst("[.][^.]*$", "").replaceFirst(".*[/\\\\.]", "")
                    : inFile.getName().replaceFirst("[.][^.]*$", ""));
    if (troubleshoot) {
        // We don't write any HMTL output here.
        // Goal is just to output diagnostics.
        StringBuilder builder = (creoleStream == null) ? IOUtil.toStringBuilder(inFile)
                : IOUtil.toStringBuilder(creoleStream);
        int newlineCount = 0;
        int lastOffset = -1;
        int offset = builder.indexOf("\n");
        for (; offset >= 0; offset = builder.indexOf("\n", offset + 1)) {
            lastOffset = offset;
            newlineCount++;
        }
        // Accommodate input files with no terminating newline:
        if (builder.length() > lastOffset + 1)
            newlineCount++;
        System.out.println("Input lines:  " + newlineCount);
        Exception lastException = null;
        while (true) {
            try {
                jCreole.parseCreole(builder);
                break;
            } catch (Exception e) {
                lastException = e;
            }
            if (builder.charAt(builder.length() - 1) == '\n')
                builder.setLength(builder.length() - 1);
            offset = builder.lastIndexOf("\n");
            if (offset < 1)
                break;
            newlineCount--;
            builder.setLength(builder.lastIndexOf("\n"));
        }
        System.out.println((lastException == null) ? "Input validates"
                : String.format("Error around input line %d:  %s", newlineCount, lastException.getMessage()));
        return;
    }
    String generatedHtml = (creoleStream == null) ? jCreole.parseCreole(inFile)
            : jCreole.parseCreole(IOUtil.toStringBuilder(creoleStream));
    String html = jCreole.postProcess(generatedHtml, SystemUtils.LINE_SEPARATOR);
    if (outPath == null) {
        System.out.print(html);
    } else {
        FileUtils.writeStringToFile(new File(outPath), html, "UTF-8");
    }
}

From source file:com.github.codingtogenomic.CodingToGenomic.java

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

    //parse commandline
    Options options = new Options();
    CommandLineParser parser = new PosixParser();
    String gene = new String();
    String transcript = new String();
    String species = "human";
    boolean mapCdna = false;
    String coordinate = new String();
    StringBuilder errorMsg = new StringBuilder();
    try {//from  w  w  w .  j av a  2  s. c  o m
        options = getOptions(args);
    } catch (org.apache.commons.cli.ParseException ex) {
        System.err.println("Parsing failed.  Reason: " + ex.getMessage());
        System.exit(1);
    }
    CommandLine line = parser.parse(options, args);
    if (line.hasOption("help")) {
        showHelp(options);
    }
    if (line.hasOption("gene")) {
        gene = line.getOptionValue("gene");
    } else {
        if (!line.hasOption("transcript")) {
            errorMsg.append("Either --gene or --transcript argument is required\n");
        }
    }
    if (line.hasOption("transcript")) {
        if (line.hasOption("gene")) {
            errorMsg.append("Please specify only one of " + "--gene or --transcript arguments, not both\n");
        } else {
            transcript = line.getOptionValue("transcript");
            if (line.hasOption("species")) {
                System.out.println("Ignoring --species option when using --transcript argument");
            }
        }
    }
    if (line.hasOption("coordinate")) {
        coordinate = line.getOptionValue("coordinate");
    } else {
        errorMsg.append("--coordinate argument is required\n");
    }
    if (line.hasOption("species")) {
        species = line.getOptionValue("species").replaceAll("\\s+", "_");
    }
    if (line.hasOption("b37")) {
        if (species.equalsIgnoreCase("human") || species.equalsIgnoreCase("homo sapiens")) {
            SERVER = GRCh37Server;
        } else {
            System.out.println("--b37 argument will be ignored - it can only be "
                    + "used when human is the species of interest. Current species" + " is " + species + ".\n");
        }
    }
    if (line.hasOption("noncoding")) {
        mapCdna = true;
    }

    if (errorMsg.length() > 0) {
        showHelp(options, errorMsg.toString(), 2);
    }
    int c = 0;
    boolean threePrimeUtr = false;
    String prefix = "c.";
    if (mapCdna) {
        prefix = "n.";
        try {
            c = Integer.parseInt(coordinate);
        } catch (NumberFormatException ex) {
            showHelp(options,
                    "--coordinate argument '" + coordinate + "' could not " + "be parsed as an integer", 2);
        }
    } else if (coordinate.startsWith("*")) {
        threePrimeUtr = true;
        prefix = "c.*";
        String coord = coordinate.replaceFirst("\\*", "");
        try {
            c = Integer.parseInt(coord);
        } catch (NumberFormatException ex) {
            showHelp(options, "--coordinate argument '" + coordinate + "' could not "
                    + "be parsed as an integer or UTR coordinate", 2);
        }
    } else {
        try {
            c = Integer.parseInt(coordinate);
        } catch (NumberFormatException ex) {
            showHelp(options,
                    "--coordinate argument '" + coordinate + "' could not " + "be parsed as an integer", 2);
        }
    }
    //got arguments
    String result;
    String header = "Input\tSymbol\tEnsemblGene\tEnsemblTranscript\tGenomicCoordinate";
    if (!gene.isEmpty()) {
        IdParser idParser = new IdParser(gene);
        System.out.println("Interpretting " + gene + " as of type " + idParser.getIdentifierType());
        if (idParser.isEnsemblId()) {
            if (line.hasOption("species")) {
                System.out.println("Ignoring --species option when searching Ensembl ID.");
            }
            if (idParser.isTranscript()) {
                result = codingToGenomicTranscript(gene, c, threePrimeUtr, mapCdna);
            } else if (idParser.isEnsp()) {
                result = codingToGenomicEnsp(gene, c, threePrimeUtr, mapCdna);
            } else {
                result = codingToGenomicId(gene, c, threePrimeUtr, mapCdna);
            }
        } else {
            if (idParser.isTranscript()) {
                //append user input to beginning
                result = codingToGenomicXrefTranscript(species, gene, c, threePrimeUtr, mapCdna);
            } else {
                result = codingToGenomicXref(species, gene, c, threePrimeUtr, mapCdna);
            }
        }
        if (idParser.isTranscript() || idParser.isEnsp()) {

            result = gene + ":" + prefix + c + "\t" + result;
        } else {
            result = convertGeneResult(result, gene, c, prefix);
        }

    } else {
        System.out.println("Searching for " + transcript + " as Ensembl transcript ID");
        result = codingToGenomicTranscript(transcript, c, threePrimeUtr, mapCdna);
        //append user input to beginning
        result = transcript + ":" + prefix + c + "\t" + result;
    }

    System.out.println(header);
    System.out.println(result);

}

From source file:au.org.ands.vocabs.toolkit.db.PopulateAccessPoints.java

/**
 * Main program.//from   www  .  j a va 2  s  .  c  om
 * @param args Command-line arguments
 */
public static void main(final String[] args) {
    // Create prefixes that both end with a slash, so that
    // they can be substituted for each other.
    String sparqlPrefix = sparqlPrefixProperty;
    if (!sparqlPrefix.endsWith("/")) {
        sparqlPrefix += "/";
    }
    String sesamePrefix = sesamePrefixProperty;
    if (!sesamePrefix.endsWith("/")) {
        sesamePrefix += "/";
    }
    sesamePrefix += "repositories/";
    System.out.println("sparqlPrefix: " + sparqlPrefix);
    System.out.println("sesamePrefix: " + sesamePrefix);
    List<Version> versions = VersionUtils.getAllVersions();
    for (Version version : versions) {
        System.out.println(version.getId());
        System.out.println(version.getTitle());
        String data = version.getData();
        System.out.println(data);
        JsonNode dataJson = TaskUtils.jsonStringToTree(data);
        JsonNode accessPoints = dataJson.get("access_points");
        if (accessPoints != null) {
            System.out.println(accessPoints);
            System.out.println(accessPoints.size());
            for (JsonNode accessPoint : accessPoints) {
                System.out.println(accessPoint);
                AccessPoint ap = new AccessPoint();
                ap.setVersionId(version.getId());
                String type = accessPoint.get("type").asText();
                JsonObjectBuilder jobPortal = Json.createObjectBuilder();
                JsonObjectBuilder jobToolkit = Json.createObjectBuilder();
                String uri;
                switch (type) {
                case AccessPoint.FILE_TYPE:
                    ap.setType(type);
                    // Get the path from the original access point.
                    String filePath = accessPoint.get("uri").asText();
                    // Save the last component of the path to use
                    // in the portal URI.
                    String downloadFilename = Paths.get(filePath).getFileName().toString();
                    if (!filePath.startsWith("/")) {
                        // Relative path that we need to fix up manually.
                        filePath = "FIXME " + filePath;
                    }
                    jobToolkit.add("path", filePath);
                    ap.setPortalData("");
                    ap.setToolkitData(jobToolkit.build().toString());
                    // Persist what we have ...
                    AccessPointUtils.saveAccessPoint(ap);
                    // ... so that now we can get access to the
                    // ID of the persisted object with ap2.getId().
                    String format;
                    if (downloadFilename.endsWith(".trig")) {
                        // Force TriG. This is needed for some legacy
                        // cases where the filename is ".trig" but
                        // the format has been incorrectly recorded
                        // as RDF/XML.
                        format = "TriG";
                    } else {
                        format = accessPoint.get("format").asText();
                    }
                    jobPortal.add("format", format);
                    jobPortal.add("uri", downloadPrefixProperty + ap.getId() + "/" + downloadFilename);
                    ap.setPortalData(jobPortal.build().toString());
                    AccessPointUtils.updateAccessPoint(ap);
                    break;
                case AccessPoint.API_SPARQL_TYPE:
                    ap.setType(type);
                    uri = accessPoint.get("uri").asText();
                    jobPortal.add("uri", uri);
                    if (uri.startsWith(sparqlPrefix)) {
                        // One of ours, so also add a sesameDownload
                        // endpoint.
                        AccessPoint ap2 = new AccessPoint();
                        ap2.setVersionId(version.getId());
                        ap2.setType(AccessPoint.SESAME_DOWNLOAD_TYPE);
                        ap2.setPortalData("");
                        ap2.setToolkitData("");
                        // Persist what we have ...
                        AccessPointUtils.saveAccessPoint(ap2);
                        // ... so that now we can get access to the
                        // ID of the persisted object with ap2.getId().
                        JsonObjectBuilder job2Portal = Json.createObjectBuilder();
                        JsonObjectBuilder job2Toolkit = Json.createObjectBuilder();
                        job2Portal.add("uri", downloadPrefixProperty + ap2.getId() + "/"
                                + Download.downloadFilename(ap2, ""));
                        job2Toolkit.add("uri", uri.replaceFirst(sparqlPrefix, sesamePrefix));
                        ap2.setPortalData(job2Portal.build().toString());
                        ap2.setToolkitData(job2Toolkit.build().toString());
                        AccessPointUtils.updateAccessPoint(ap2);
                        jobPortal.add("source", AccessPoint.SYSTEM_SOURCE);
                    } else {
                        jobPortal.add("source", AccessPoint.USER_SOURCE);
                    }
                    ap.setPortalData(jobPortal.build().toString());
                    ap.setToolkitData(jobToolkit.build().toString());
                    AccessPointUtils.saveAccessPoint(ap);
                    break;
                case AccessPoint.WEBPAGE_TYPE:
                    uri = accessPoint.get("uri").asText();
                    if (uri.endsWith("concept/topConcepts")) {
                        ap.setType(AccessPoint.SISSVOC_TYPE);
                        jobPortal.add("source", AccessPoint.SYSTEM_SOURCE);
                        jobPortal.add("uri", uri.replaceFirst("/concept/topConcepts$", ""));
                    } else {
                        ap.setType(type);
                        jobPortal.add("uri", uri);
                    }
                    ap.setPortalData(jobPortal.build().toString());
                    ap.setToolkitData(jobToolkit.build().toString());
                    AccessPointUtils.saveAccessPoint(ap);
                    break;
                default:
                }
                System.out.println("type is: " + ap.getType());
                System.out.println("portal_data: " + ap.getPortalData());
                System.out.println("toolkit_data: " + ap.getToolkitData());
            }
        }
    }
}

From source file:com.samsung.sjs.Compiler.java

@SuppressWarnings("static-access")
public static void main(String[] args) throws IOException, SolverException, InterruptedException {
    boolean debug = false;
    boolean use_gc = true;
    CompilerOptions.Platform p = CompilerOptions.Platform.Native;
    CompilerOptions opts = null;/*from   www.j  av a 2s  .  com*/
    boolean field_opts = false;
    boolean typecheckonly = false;
    boolean showconstraints = false;
    boolean showconstraintsolution = false;
    String[] decls = null;
    String[] links = null;
    String[] objs = null;
    boolean guest = false;
    boolean stop_at_c = false;
    String external_compiler = null;
    boolean encode_vals = false;
    boolean x32 = false;
    boolean validate = true;
    boolean interop = false;
    boolean boot_interop = false;
    boolean oldExpl = false;
    String explanationStrategy = null;
    boolean efl = false;

    Options options = new Options();
    options.addOption("debugcompiler", false, "Enable compiler debug spew");
    //options.addOption("o", true, "Set compiler output file (must be .c)");
    options.addOption(OptionBuilder //.withArgName("o")
            .withLongOpt("output-file").withDescription("Output file (must be .c)").hasArg().withArgName("file")
            .create("o"));
    options.addOption(OptionBuilder.withLongOpt("target")
            .withDescription("Select target platform: 'native' or 'web'").hasArg().create());
    options.addOption(OptionBuilder.withLongOpt("gc")
            .withDescription("Disable GC: param is 'on' (default) or 'off'").hasArg().create());

    options.addOption(OptionBuilder
            .withDescription("Enable field access optimizations: param is 'true' (default) or 'false'").hasArg()
            .create("Xfields"));

    options.addOption(OptionBuilder
            .withDescription("Compile for encoded values.  TEMPORARY.  For testing interop codegen").hasArg()
            .create("XEncodedValues"));

    options.addOption(OptionBuilder.withLongOpt("typecheck-only")
            .withDescription("Only typecheck the file, don't compile").create());
    options.addOption(OptionBuilder.withLongOpt("show-constraints")
            .withDescription("Show constraints generated during type inference").create());
    options.addOption(OptionBuilder.withLongOpt("show-constraint-solution")
            .withDescription("Show solution to type inference constraints").create());
    options.addOption(OptionBuilder.withLongOpt("extra-decls")
            .withDescription("Specify extra declaration files, comma-separated").hasArg()
            .withValueSeparator(',').create());
    options.addOption(OptionBuilder.withLongOpt("native-libs")
            .withDescription("Specify extra linkage files, comma-separated").hasArg().withValueSeparator(',')
            .create());
    Option extraobjs = OptionBuilder.withLongOpt("extra-objs")
            .withDescription("Specify extra .c/.cpp files, comma-separated").hasArg().withValueSeparator(',')
            .create();
    extraobjs.setArgs(Option.UNLIMITED_VALUES);
    options.addOption(extraobjs);
    options.addOption(OptionBuilder.withLongOpt("guest-runtime")
            .withDescription(
                    "Emit code to be called by another runtime (i.e., main() is written in another language).")
            .create());
    options.addOption(OptionBuilder.withLongOpt("only-c")
            .withDescription("Generate C code, but do not attempt to compile it").create());
    options.addOption(OptionBuilder.withLongOpt("c-compiler")
            .withDescription("Disable GC: param is 'on' (default) or 'off'").hasArg().create("cc"));
    options.addOption(OptionBuilder.withLongOpt("runtime-src")
            .withDescription("Specify path to runtime system source").hasArg().create());
    options.addOption(OptionBuilder.withLongOpt("ext-path")
            .withDescription("Specify path to external dependency dir (GC, etc.)").hasArg().create());
    options.addOption(OptionBuilder.withLongOpt("skip-validation")
            .withDescription("Run the backend without validating the results of type inference").create());

    options.addOption(OptionBuilder.withLongOpt("m32").withDescription("Force 32-bit compilation").create());
    options.addOption(OptionBuilder.withLongOpt("Xbootinterop")
            .withDescription("Programs start with global interop dirty flag set (experimental)").create());
    options.addOption(OptionBuilder.withLongOpt("Xinterop")
            .withDescription("Enable (experimental) interoperability backend").create());

    options.addOption(OptionBuilder.withDescription("C compiler default optimization level").create("O"));
    options.addOption(OptionBuilder.withDescription("C compiler optimization level 0").create("O0"));
    options.addOption(OptionBuilder.withDescription("C compiler optimization level 1").create("O1"));
    options.addOption(OptionBuilder.withDescription("C compiler optimization level 2").create("O2"));
    options.addOption(OptionBuilder.withDescription("C compiler optimization level 3").create("O3"));

    options.addOption(
            OptionBuilder.withLongOpt("oldExpl").withDescription("Use old error explanations").create());

    String explanationStrategyHelp = "default: " + FixingSetFinder.defaultStrategy() + "; other choices: "
            + FixingSetFinder.strategyNames().stream().filter(s -> !s.equals(FixingSetFinder.defaultStrategy()))
                    .collect(Collectors.joining(", "));

    options.addOption(OptionBuilder.withLongOpt("explanation-strategy")
            .withDescription("Error explanation strategy to use (" + explanationStrategyHelp + ')').hasArg()
            .create());

    options.addOption(
            OptionBuilder.withLongOpt("efl").withDescription("Set up efl environment in main()").create());

    try {
        CommandLineParser parser = new BasicParser();
        CommandLine cmd = parser.parse(options, args);

        String[] newargs = cmd.getArgs();
        if (newargs.length != 1) {
            throw new ParseException("Invalid number of arguments");
        }

        String sourcefile = newargs[0];
        if (!sourcefile.endsWith(".js")) {
            throw new ParseException("Invalid file extension on input file: " + sourcefile);
        }

        String gc = cmd.getOptionValue("gc", "on");
        if (gc.equals("on")) {
            use_gc = true;
        } else if (gc.equals("off")) {
            use_gc = false;
        } else {
            throw new ParseException("Invalid GC option: " + gc);
        }
        String fields = cmd.getOptionValue("Xfields", "true");
        if (fields.equals("true")) {
            field_opts = true;
        } else if (fields.equals("false")) {
            field_opts = false;
        } else {
            throw new ParseException("Invalid field optimization option: " + fields);
        }
        String encoding = cmd.getOptionValue("XEncodedValues", "false");
        if (encoding.equals("true")) {
            encode_vals = true;
        } else if (encoding.equals("false")) {
            encode_vals = false;
        } else {
            throw new ParseException("Invalid value encoding option: " + encode_vals);
        }
        String plat = cmd.getOptionValue("target", "native");
        if (plat.equals("native")) {
            p = CompilerOptions.Platform.Native;
        } else if (plat.equals("web")) {
            p = CompilerOptions.Platform.Web;
        } else {
            throw new ParseException("Invalid target platform: " + plat);
        }
        if (cmd.hasOption("cc")) {
            external_compiler = cmd.getOptionValue("cc");
        }
        if (cmd.hasOption("skip-validation")) {
            validate = false;
        }
        if (cmd.hasOption("typecheck-only")) {
            typecheckonly = true;
        }
        if (cmd.hasOption("show-constraints")) {
            showconstraints = true;
        }
        if (cmd.hasOption("show-constraint-solution")) {
            showconstraintsolution = true;
        }
        if (cmd.hasOption("debugcompiler")) {
            debug = true;
        }
        if (cmd.hasOption("m32")) {
            x32 = true;
        }
        if (cmd.hasOption("Xinterop")) {
            interop = true;
        }
        if (cmd.hasOption("Xbootinterop")) {
            boot_interop = true;
            if (!interop) {
                System.err.println("WARNING: --Xbootinterop enabled without --Xinterop (no effect)");
            }
        }
        if (cmd.hasOption("oldExpl")) {
            oldExpl = true;
        }
        if (cmd.hasOption("explanation-strategy")) {
            explanationStrategy = cmd.getOptionValue("explanation-strategy");
        }
        String output = cmd.getOptionValue("o");
        if (output == null) {
            output = sourcefile.replaceFirst(".js$", ".c");
        } else {
            if (!output.endsWith(".c")) {
                throw new ParseException("Invalid file extension on output file: " + output);
            }
        }
        String runtime_src = cmd.getOptionValue("runtime-src");
        String ext_path = cmd.getOptionValue("ext-path");
        if (ext_path == null) {
            ext_path = new File(".").getCanonicalPath() + "/external";
        }

        if (cmd.hasOption("extra-decls")) {
            decls = cmd.getOptionValues("extra-decls");
        }
        if (cmd.hasOption("native-libs")) {
            links = cmd.getOptionValues("native-libs");
        }
        if (cmd.hasOption("extra-objs")) {
            objs = cmd.getOptionValues("extra-objs");
        }
        if (cmd.hasOption("guest-runtime")) {
            guest = true;
        }
        if (cmd.hasOption("only-c")) {
            stop_at_c = true;
        }
        if (cmd.hasOption("efl")) {
            efl = true;
        }

        int coptlevel = -1; // default optimization
        if (cmd.hasOption("O3")) {
            coptlevel = 3;
        } else if (cmd.hasOption("O2")) {
            coptlevel = 2;
        } else if (cmd.hasOption("O1")) {
            coptlevel = 1;
        } else if (cmd.hasOption("O0")) {
            coptlevel = 0;
        } else if (cmd.hasOption("O")) {
            coptlevel = -1;
        } else {
            coptlevel = 3;
        }

        if (!Files.exists(Paths.get(sourcefile))) {
            System.err.println("File " + sourcefile + " was not found.");
            throw new FileNotFoundException(sourcefile);
        }

        String cwd = new java.io.File(".").getCanonicalPath();

        opts = new CompilerOptions(p, sourcefile, debug, output, use_gc,
                external_compiler == null ? "clang" : external_compiler,
                external_compiler == null ? "emcc" : external_compiler, cwd + "/a.out", // emcc automatically adds .js
                new File(".").getCanonicalPath(), true, field_opts, showconstraints, showconstraintsolution,
                runtime_src, encode_vals, x32, oldExpl, explanationStrategy, efl, coptlevel);
        if (guest) {
            opts.setGuestRuntime();
        }
        if (interop) {
            opts.enableInteropMode();
        }
        if (boot_interop) {
            opts.startInInteropMode();
        }
        opts.setExternalDeps(ext_path);
        if (decls != null) {
            for (String s : decls) {
                Path fname = FileSystems.getDefault().getPath(s);
                opts.addDeclarationFile(fname);
            }
        }
        if (links != null) {
            for (String s : links) {
                Path fname = FileSystems.getDefault().getPath(s);
                opts.addLinkageFile(fname);
            }
        }
        if (objs == null) {
            objs = new String[0];
        }

    } catch (Exception e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp("sjsc", options);
    }

    if (opts != null) {
        // This typechecks, and depending on flags, also generates C
        compile(opts, typecheckonly, validate); // don't worry about type validation on command line for now
        if (!typecheckonly && !stop_at_c) {
            int ret = 0;
            // Kept around for debugging 32-bit...
            if (p == CompilerOptions.Platform.Native) {
                if (opts.m32()) {
                    String[] x = new String[2];
                    x[0] = "-m32";
                    x[1] = opts.getExternalDeps() + "/gc/x86/lib/libgc.a";
                    ret = clang_compile(opts, objs, x);
                } else {
                    ret = clang_compile(opts, objs, new String[0]);
                }
            } else {
                ret = emcc_compile(opts, objs, new String[0]);
            }
            // If clang failed, propagate the failure outwards
            if (ret != 0) {
                System.exit(ret);
            }
        }
    }
}

From source file:mamo.vanillaVotifier.VanillaVotifier.java

public static void main(String[] args) {
    String[] javaVersion = System.getProperty("java.version").split("\\.");
    if (!(javaVersion.length >= 1 && Integer.parseInt(javaVersion[0]) >= 1 && javaVersion.length >= 2
            && Integer.parseInt(javaVersion[1]) >= 6)) {
        System.out.println(("You need at least Java 1.6 to run this program! Current version: "
                + System.getProperty("java.version") + "."));
        return;/*from ww w . j  a v  a 2s. c om*/
    }

    VanillaVotifier votifier = new VanillaVotifier();
    for (String arg : args) {
        if (arg.equalsIgnoreCase("-report-exceptions")) {
            votifier.reportExceptions = true;
        } else if (arg.equalsIgnoreCase("-help")) {
            votifier.getLogger().printlnTranslation("s58");
            return;
        } else {
            votifier.getLogger().printlnTranslation("s55",
                    new AbstractMap.SimpleEntry<String, Object>("option", arg));
            return;
        }
    }
    votifier.getLogger().printlnTranslation("s42");
    if (!(loadConfig(votifier) && startServer(votifier))) {
        return;
    }
    Scanner in = new Scanner(System.in);

    while (true) {
        String command;
        try {
            command = in.nextLine();
        } catch (NoSuchElementException e) {
            // NoSuchElementException: Can only happen at unexpected program interruption (i. e. CTRL+C). Ignoring.
            continue;
        } catch (Exception e) {
            votifier.getLogger().printlnTranslation("s57",
                    new AbstractMap.SimpleEntry<String, Object>("exception", e));
            if (!stopServer(votifier)) {
                System.exit(0); // "return" somehow isn't enough.
            }
            return;
        }
        if (command.equalsIgnoreCase("stop") || command.toLowerCase().startsWith("stop ")) {
            if (command.split(" ").length == 1) {
                stopServer(votifier);
                break;
            } else {
                votifier.getLogger().printlnTranslation("s17");
            }
        } else if (command.equalsIgnoreCase("restart") || command.toLowerCase().startsWith("restart ")) {
            if (command.split(" ").length == 1) {
                Listener listener = new Listener() {
                    @Override
                    public void onEvent(Event event, VanillaVotifier votifier) {
                        if (event instanceof ServerStoppedEvent) {
                            if (loadConfig((VanillaVotifier) votifier)
                                    && startServer((VanillaVotifier) votifier)) {
                                votifier.getServer().getListeners().remove(this);
                            } else {
                                System.exit(0);
                            }
                        }
                    }
                };
                votifier.getServer().getListeners().add(listener);
                if (!stopServer(votifier)) { // Kill the process if the server doesn't stop
                    System.exit(0); // "return" somehow isn't enough.
                    return;
                }
            } else {
                votifier.getLogger().printlnTranslation("s56");
            }
        } else if (command.equalsIgnoreCase("gen-key-pair") || command.startsWith("gen-key-pair ")) {
            String[] commandArgs = command.split(" ");
            int keySize;
            if (commandArgs.length == 1) {
                keySize = 2048;
            } else if (commandArgs.length == 2) {
                try {
                    keySize = Integer.parseInt(commandArgs[1]);
                } catch (NumberFormatException e) {
                    votifier.getLogger().printlnTranslation("s19");
                    continue;
                }
                if (keySize < 512) {
                    votifier.getLogger().printlnTranslation("s51");
                    continue;
                }
                if (keySize > 16384) {
                    votifier.getLogger().printlnTranslation("s52");
                    continue;
                }
            } else {
                votifier.getLogger().printlnTranslation("s20");
                continue;
            }
            votifier.getLogger().printlnTranslation("s16");
            votifier.getConfig().genKeyPair(keySize);
            try {
                votifier.getConfig().save();
            } catch (Exception e) {
                votifier.getLogger().printlnTranslation("s21",
                        new AbstractMap.SimpleEntry<String, Object>("exception", e));
            }
            votifier.getLogger().printlnTranslation("s23");
        } else if (command.equalsIgnoreCase("test-vote") || command.toLowerCase().startsWith("test-vote ")) {
            String[] commandArgs = command.split(" ");
            if (commandArgs.length == 2) {
                try {
                    votifier.getTester().testVote(new Vote("TesterService", commandArgs[1],
                            votifier.getConfig().getInetSocketAddress().getAddress().getHostName()));
                } catch (Exception e) { // GeneralSecurityException, IOException
                    votifier.getLogger().printlnTranslation("s27",
                            new AbstractMap.SimpleEntry<String, Object>("exception", e));
                }
            } else {
                votifier.getLogger().printlnTranslation("s26");
            }
        } else if (command.equalsIgnoreCase("test-query") || command.toLowerCase().startsWith("test-query ")) {
            if (command.split(" ").length >= 2) {
                try {
                    votifier.getTester()
                            .testQuery(command.replaceFirst("test-query ", "").replaceAll("---", "\n"));
                } catch (Exception e) { // GeneralSecurityException, IOException
                    votifier.getLogger().printlnTranslation("s35",
                            new AbstractMap.SimpleEntry<String, Object>("exception", e));
                }
            } else {
                votifier.getLogger().printlnTranslation("s34");
            }
        } else if (command.equalsIgnoreCase("help") || command.toLowerCase().startsWith("help ")) {
            if (command.split(" ").length == 1) {
                votifier.getLogger().printlnTranslation("s31");
            } else {
                votifier.getLogger().printlnTranslation("s32");
            }
        } else if (command.equalsIgnoreCase("manual") || command.toLowerCase().startsWith("manual ")) {
            if (command.split(" ").length == 1) {
                votifier.getLogger().printlnTranslation("s36");
            } else {
                votifier.getLogger().printlnTranslation("s37");
            }
        } else if (command.equalsIgnoreCase("info") || command.toLowerCase().startsWith("info ")) {
            if (command.split(" ").length == 1) {
                votifier.getLogger().printlnTranslation("s40");
            } else {
                votifier.getLogger().printlnTranslation("s41");
            }
        } else if (command.equalsIgnoreCase("license") || command.toLowerCase().startsWith("license ")) {
            if (command.split(" ").length == 1) {
                votifier.getLogger().printlnTranslation("s43");
            } else {
                votifier.getLogger().printlnTranslation("s44");
            }
        } else {
            votifier.getLogger().printlnTranslation("s33");
        }
    }
}

From source file:Main.java

public static String listFormat(String list) {
    return list.replaceFirst("\\[", "").replaceFirst("\\]", "").replaceAll("\\,", "_");
}

From source file:Main.java

public static String filenameWithoutExtension(String filename) {
    return filename.replaceFirst("[.][^.]+$", "");
}

From source file:Main.java

public static String delFirst(String regex, String content) {
    return content.replaceFirst(regex, "");
}

From source file:Main.java

/**
 * /*w  w  w.  j a va 2s .  c o  m*/
 * @param val
 * @return
 */
public static String removeLeadingZeros(String val) {
    return val.replaceFirst("^0+(?!$)", "");
}