Example usage for java.util StringTokenizer nextToken

List of usage examples for java.util StringTokenizer nextToken

Introduction

In this page you can find the example usage for java.util StringTokenizer nextToken.

Prototype

public String nextToken() 

Source Link

Document

Returns the next token from this string tokenizer.

Usage

From source file:com.trailmagic.image.ui.WebSupport.java

public static Long extractImageIdFromRequest(HttpServletRequest req)
        throws IllegalArgumentException, NumberFormatException {
    UrlPathHelper pathHelper = new UrlPathHelper();
    String myPath = pathHelper.getLookupPathForRequest(req);
    s_logger.debug("Lookup path: " + pathHelper.getLookupPathForRequest(req));
    StringTokenizer pathTokens = new StringTokenizer(myPath, "/");
    String token = null;//from   www  .  jav  a 2  s.com
    while (pathTokens.hasMoreTokens()) {
        token = pathTokens.nextToken();
    }

    if (s_logger.isDebugEnabled()) {
        s_logger.debug("Last token is: " + token);
    }

    if (token == null || "".equals(token)) {
        throw new IllegalArgumentException("Invalid request");
    }
    return new Long(token);
}

From source file:org.dojotoolkit.zazl.internal.XMLHttpRequestUtils.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static String xhrRequest(String shrDataString) {
    InputStream is = null;/*from   w  ww .ja  v  a2 s.com*/
    String json = null;

    try {
        logger.logp(Level.FINER, XMLHttpRequestUtils.class.getName(), "xhrRequest",
                "shrDataString [" + shrDataString + "]");

        Map<String, Object> xhrData = (Map<String, Object>) JSONParser.parse(new StringReader(shrDataString));
        String url = (String) xhrData.get("url");
        String method = (String) xhrData.get("method");
        List headers = (List) xhrData.get("headers");
        URL requestURL = createURL(url);
        URI uri = new URI(requestURL.toString());

        HashMap httpMethods = new HashMap(7);
        httpMethods.put("DELETE", new HttpDelete(uri));
        httpMethods.put("GET", new HttpGet(uri));
        httpMethods.put("HEAD", new HttpHead(uri));
        httpMethods.put("OPTIONS", new HttpOptions(uri));
        httpMethods.put("POST", new HttpPost(uri));
        httpMethods.put("PUT", new HttpPut(uri));
        httpMethods.put("TRACE", new HttpTrace(uri));
        HttpUriRequest request = (HttpUriRequest) httpMethods.get(method.toUpperCase());

        if (request.equals(null)) {
            throw new Error("SYNTAX_ERR");
        }

        for (Object header : headers) {
            StringTokenizer st = new StringTokenizer((String) header, ":");
            String name = st.nextToken();
            String value = st.nextToken();
            request.addHeader(name, value);
        }

        HttpClient client = new DefaultHttpClient();

        HttpResponse response = client.execute(request);
        Map headerMap = new HashMap();

        HeaderIterator headerIter = response.headerIterator();

        while (headerIter.hasNext()) {
            Header header = headerIter.nextHeader();
            headerMap.put(header.getName(), header.getValue());
        }

        int status = response.getStatusLine().getStatusCode();
        String statusText = response.getStatusLine().toString();

        is = response.getEntity().getContent();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line = null;
        StringBuffer sb = new StringBuffer();

        while ((line = br.readLine()) != null) {
            sb.append(line);
            sb.append('\n');
        }
        Map m = new HashMap();
        m.put("status", new Integer(status));
        m.put("statusText", statusText);
        m.put("responseText", sb.toString());
        m.put("headers", headerMap.toString());
        StringWriter w = new StringWriter();
        JSONSerializer.serialize(w, m);
        json = w.toString();
        logger.logp(Level.FINER, XMLHttpRequestUtils.class.getName(), "xhrRequest", "json [" + json + "]");
    } catch (Throwable e) {
        logger.logp(Level.SEVERE, XMLHttpRequestUtils.class.getName(), "xhrRequest",
                "Failed request for [" + shrDataString + "]", e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
    }
    return json;
}

From source file:keel.Algorithms.MIL.G3PMI.Main.java

/**
 * <p>/*from   ww  w. j a  v a  2  s  .  c  om*/
 * Configure the execution of the algorithm.
 * 
 * @param jobFilename Name of the KEEL file with properties of the execution
 *  </p>                  
 */

private static void configureJob(String jobFilename) {

    Properties props = new Properties();

    try {
        InputStream paramsFile = new FileInputStream(jobFilename);
        props.load(paramsFile);
        paramsFile.close();
    } catch (IOException ioe) {
        ioe.printStackTrace();
        System.exit(0);
    }

    // Files training and test
    String trainFile;
    String testFile;
    StringTokenizer tokenizer = new StringTokenizer(props.getProperty("inputData"));
    tokenizer.nextToken();
    trainFile = tokenizer.nextToken();
    trainFile = trainFile.substring(1, trainFile.length() - 1);
    testFile = tokenizer.nextToken();
    testFile = testFile.substring(1, testFile.length() - 1);

    tokenizer = new StringTokenizer(props.getProperty("outputData"));
    String reportTrainFile = tokenizer.nextToken();
    reportTrainFile = reportTrainFile.substring(1, reportTrainFile.length() - 1);
    String reportTestFile = tokenizer.nextToken();
    reportTestFile = reportTestFile.substring(1, reportTestFile.length() - 1);
    //System.out.println("SALIDA: " + reportTestFile);
    //String reportRulesFile = tokenizer.nextToken();
    //reportRulesFile = reportRulesFile.substring(1, reportRulesFile.length()-1);            

    // Algorithm auxiliar configuration
    XMLConfiguration algConf = new XMLConfiguration();
    algConf.setRootElementName("experiment");
    algConf.addProperty("process.algorithm[@type]",
            "org.ayrna.jclec.problem.classification.syntaxtree.multiinstance.G3PMIKeel.G3PMIAlgorithm");
    algConf.addProperty("process.algorithm.rand-gen-factory[@type]",
            "org.ayrna.jclec.util.random.RanecuFactory");
    algConf.addProperty("process.algorithm.rand-gen-factory[@seed]",
            Integer.parseInt(props.getProperty("seed")));
    algConf.addProperty("process.algorithm.population-size",
            Integer.parseInt(props.getProperty("population-size")));
    algConf.addProperty("process.algorithm.max-of-generations",
            Integer.parseInt(props.getProperty("max-generations")));
    algConf.addProperty("process.algorithm.max-deriv-size",
            Integer.parseInt(props.getProperty("max-deriv-size")));
    algConf.addProperty("process.algorithm.species[@type]",
            "org.ayrna.jclec.problem.classification.syntaxtree.multiinstance.G3PMIKeel.G3PMISyntaxTreeSpecies");
    algConf.addProperty("process.algorithm.species.max-deriv-size",
            Integer.parseInt(props.getProperty("max-deriv-size")));
    algConf.addProperty("process.algorithm.species.dataset[@type]",
            "org.ayrna.jclec.util.dataset.KeelMultiInstanceDataSet");
    algConf.addProperty("process.algorithm.species.dataset.file-name", trainFile);
    algConf.addProperty("process.algorithm.species.rand-gen-factory[@type]",
            "org.ayrna.jclec.util.random.RanecuFactory");
    algConf.addProperty("process.algorithm.species.rand-gen-factory[@seed]",
            Integer.parseInt(props.getProperty("seed")));
    algConf.addProperty("process.algorithm.evaluator[@type]",
            "org.ayrna.jclec.problem.classification.syntaxtree.multiinstance.G3PMIKeel.G3PMIEvaluator");
    algConf.addProperty("process.algorithm.evaluator.rand-gen-factory[@type]",
            "org.ayrna.jclec.util.random.RanecuFactory");
    algConf.addProperty("process.algorithm.evaluator.rand-gen-factory[@seed]",
            Integer.parseInt(props.getProperty("seed")));
    algConf.addProperty("process.algorithm.evaluator.dataset[@type]",
            "org.ayrna.jclec.util.dataset.KeelMultiInstanceDataSet");
    algConf.addProperty("process.algorithm.evaluator.dataset.file-name", trainFile);
    algConf.addProperty("process.algorithm.evaluator.max-deriv-size",
            Integer.parseInt(props.getProperty("max-deriv-size")));
    algConf.addProperty("process.algorithm.provider[@type]", "org.ayrna.jclec.syntaxtree.SyntaxTreeCreator");
    algConf.addProperty("process.algorithm.parents-selector[@type]",
            "org.ayrna.jclec.selector.RouletteSelector");
    algConf.addProperty("process.algorithm.recombinator.decorated[@type]",
            "org.ayrna.jclec.problem.classification.syntaxtree.multiinstance.G3PMIKeel.G3PMICrossover");
    algConf.addProperty("process.algorithm.recombinator.recombination-prob",
            Double.parseDouble(props.getProperty("rec-prob")));
    algConf.addProperty("process.algorithm.mutator.decorated[@type]",
            "org.ayrna.jclec.problem.classification.syntaxtree.multiinstance.G3PMIKeel.G3PMIMutator");
    algConf.addProperty("process.algorithm.mutator.mutation-prob",
            Double.parseDouble(props.getProperty("mut-prob")));
    algConf.addProperty("process.listeners.listener[@type]",
            "org.ayrna.jclec.problem.classification.syntaxtree.multiinstance.G3PMIKeel.G3PMIPopulationReport");
    algConf.addProperty("process.listeners.listener.report-dir-name", "./");
    algConf.addProperty("process.listeners.listener.train-report-file", reportTrainFile);
    algConf.addProperty("process.listeners.listener.test-report-file", reportTestFile);
    algConf.addProperty("process.listeners.listener.global-report-name", "resumen");
    algConf.addProperty("process.listeners.listener.report-frequency", 50);
    algConf.addProperty("process.listeners.listener.test-dataset[@type]",
            "org.ayrna.jclec.util.dataset.KeelMultiInstanceDataSet");
    algConf.addProperty("process.listeners.listener.test-dataset.file-name", testFile);

    try {
        algConf.save(new File("configure.txt"));
    } catch (ConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    org.ayrna.jclec.genlab.GenLab.main(new String[] { "configure.txt" });
}

From source file:com.vmware.identity.idm.STSSpnValidator.java

public static boolean validate(String spn) {
    // validate spn format, and service principal name and domain name are
    // valid strings.
    Validate.notNull(spn, "Service Princiapal Name cannot be null");
    Validate.notEmpty(spn, "Service Principal Name cannot be empty");
    StringTokenizer st = new StringTokenizer(spn, VALID_SPN_SEPARATORS);
    if (st.countTokens() != 2) {
        logAndThrow("Invalid service principal name format: " + spn);
    } else {//from   www .  j  a  v a2 s.  c o m
        String servicePrincipalName = st.nextToken();
        String domainName = st.nextToken();
        if (null == servicePrincipalName) {
            logAndThrow(String.format("Service Name must be specfied before [%s]" + VALID_SPN_SEPARATORS));
        }
        if (!servicePrincipalName.equalsIgnoreCase(SERVICE_PRINCIPAL_NAME)) {
            logAndThrow("Service name must be STS (case insensitive)");
        }
        if (null == domainName || domainName.trim().isEmpty()) {
            logAndThrow(String.format("Domain Name must be specfied after [%s]" + VALID_SPN_SEPARATORS));
        }
    }
    return true;
}

From source file:Main.java

/**
 * Find an element using XPath-quotation expressions. Path must not including
 * the context element, path elements can be separated by / or .,
 * and namespace is NOT supported.//from  www.j a v a  2  s. c  om
 * @param context Element to start the search from, cannot be null.
 * @param path XPath-quotation expression, cannot be null.
 * @param create if true, new elements are created if necessary.
 * @return the first matched element if there are matches, otherwise
 * return null.
 */
public static Element getElementByPath(Element context, String path, boolean create) {
    Element cur = context;
    StringTokenizer tokens = new StringTokenizer(path, "/");

    while (tokens.hasMoreTokens()) {
        String name = tokens.nextToken();
        Element parent = cur;
        cur = getChildElement(cur, name);
        if (cur == null) {
            if (create) {
                // create the element
                Element newElement = context.getOwnerDocument().createElement(name);
                //context.appendChild(newElement);
                parent.appendChild(newElement);
                cur = newElement;
            } else {
                return null;
            }
        }
    }
    return cur;
}

From source file:com.joliciel.talismane.utils.DaoUtils.java

public static List<String> getSelectArray(String selectString, String alias) {
    List<String> selectArray = new ArrayList<String>();
    StringTokenizer st = new StringTokenizer(selectString, ",", false);
    boolean haveAlias = alias != null && alias.length() > 0;
    while (st.hasMoreTokens()) {
        String column = st.nextToken().trim();
        if (haveAlias)
            selectArray.add(alias + "." + column + " as " + alias + "_" + column);
        else/* www .  ja v a2s. c o m*/
            selectArray.add(column);

    }
    return selectArray;
}

From source file:de.iteratec.iteraplan.db.SqlScriptExecutor.java

public static List<String> readSqlScript(InputStream in) {
    InputStream setupSqlInputStream = in;
    String sqlString = null;/*  ww w.  j a  va2s . c  o  m*/
    try {
        sqlString = IOUtils.toString(setupSqlInputStream);
    } catch (IOException fnfe) {
        LOGGER.error("unable to read data.");
    } finally {
        if (setupSqlInputStream != null) {
            try {
                setupSqlInputStream.close();
            } catch (IOException e) {
                LOGGER.error("Cannot close stream for setupSqlFile", e);
            }
        }
    }
    List<String> sqlStatements = Lists.newArrayList();

    StringTokenizer tokenizer = new StringTokenizer(sqlString, ";");
    while (tokenizer.hasMoreTokens()) {
        String nextToken = tokenizer.nextToken();
        sqlStatements.add(nextToken);
    }

    return sqlStatements;
}

From source file:com.codedx.burp.security.InvalidCertificateDialogStrategy.java

private static String getCN(X509Certificate cert) {
    String principal = cert.getSubjectX500Principal().toString();
    StringTokenizer tokenizer = new StringTokenizer(principal, ",");
    while (tokenizer.hasMoreTokens()) {
        String token = tokenizer.nextToken();
        int i = token.indexOf("CN=");
        if (i >= 0) {
            return token.substring(i + 3);
        }/*  w w w  . j a  v a2  s.  c  o  m*/
    }
    return null;
}

From source file:de.otto.mongodb.profiler.web.ConnectionController.java

private static void parseHosts(final String input, final ProfiledConnectionConfiguration.Builder configBuilder)
        throws ParseException, InvalidHostException {

    final String raw = input.replace("\r", "").replace("\n", ",").replace(" ", "");

    final StringTokenizer tokenizer = new StringTokenizer(raw, ",");
    while (tokenizer.hasMoreTokens()) {
        parseHost(tokenizer.nextToken(), configBuilder);
    }//w w  w  .jav a  2 s .  c om
}

From source file:org.jberet.support.io.NoMappingJsonFactoryObjectFactory.java

static void configureJsonFactoryFeatures(final JsonFactory jsonFactory, final String jsonFactoryFeatures) {
    final StringTokenizer st = new StringTokenizer(jsonFactoryFeatures, ",");
    while (st.hasMoreTokens()) {
        final String[] pair = parseSingleFeatureValue(st.nextToken().trim());
        final String key = pair[0];
        final String value = pair[1];
        final JsonFactory.Feature feature;
        try {//  w ww  . j  a  v a2 s .  c  om
            feature = JsonFactory.Feature.valueOf(key);
        } catch (final Exception e1) {
            throw SupportMessages.MESSAGES.unrecognizedReaderWriterProperty(key, value);
        }
        if ("true".equals(value)) {
            if (!feature.enabledByDefault()) {
                jsonFactory.configure(feature, true);
            }
        } else if ("false".equals(value)) {
            if (feature.enabledByDefault()) {
                jsonFactory.configure(feature, false);
            }
        } else {
            throw SupportMessages.MESSAGES.invalidReaderWriterProperty(null, value, key);
        }
    }
}