Example usage for java.util StringTokenizer StringTokenizer

List of usage examples for java.util StringTokenizer StringTokenizer

Introduction

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

Prototype

public StringTokenizer(String str, String delim) 

Source Link

Document

Constructs a string tokenizer for the specified string.

Usage

From source file:org.ambraproject.queue.CrossrefResponseConsumer.java

/**
 * Message handler method. Message comes in articleId|result|errorMessage format.
 *
 * @param body Message body./*from   w  w  w .j a  va  2  s.c  om*/
 * @throws org.ambraproject.ApplicationException If operation fails, URISyntaxException if
 *                              <code>updateSyndication</code> method fails to create the Syndication's unique Id.
 * @throws Exception in operation failed.
 */
@Handler
public void handleResponse(@Body String body) throws Exception {

    if (body == null) {
        throw new ApplicationException("Crossref response message is null");
    }

    log.info("Received syndication response: " + body);

    StringTokenizer tokenizer = new StringTokenizer(body, SEPARATOR);

    String doi;
    String result;
    String errorMessage = null;

    if (tokenizer.hasMoreTokens()) {
        doi = tokenizer.nextToken();
    } else {
        throw new ApplicationException("Invalid Crossref response message received: " + body);
    }

    if (tokenizer.hasMoreTokens()) {
        result = tokenizer.nextToken();
    } else {
        throw new ApplicationException("Invalid Crossref response message received: " + body);
    }

    if (tokenizer.hasMoreTokens()) {
        errorMessage = tokenizer.nextToken();
    }

    if (doi == null || doi.equalsIgnoreCase(UNKNOWN)) {
        log.error("Received " + result + " response for unknow DOI. Error message: " + errorMessage);
    } else {
        syndicationService.updateSyndication(doi, "CROSSREF",
                OK.equalsIgnoreCase(result) ? Syndication.STATUS_SUCCESS : Syndication.STATUS_FAILURE,
                errorMessage);
    }
}

From source file:com.jadyounan.Packager.java

/**
 * Servlet handler , should listen on the callback URL (as in webServiceURL)
 * @param requestPath//from   w  w w .  j a va2s .co  m
 * @param req
 * @param servletRequest
 * @param servletResponse
 * @throws Exception
 */
public static void handle(String requestPath, Request req, HttpServletRequest servletRequest,
        HttpServletResponse servletResponse) throws Exception {

    StringTokenizer st = new StringTokenizer(requestPath, "/");
    st.nextToken();
    String companyDomain = st.nextToken();

    String version = st.nextToken();

    byte bytes[] = new byte[] {};

    switch (st.nextToken().toLowerCase()) {
    case "log": {
        bytes = new byte[] {};

        byte r[] = org.eclipse.jetty.util.IO.readBytes(servletRequest.getInputStream());

        System.out.println("LOG " + new String(r));
    }
        break;
    case "devices": {
        String deviceID = st.nextToken();

        String authToken = req.getHeader("Authorization").split(" ")[1];

        // use the authToken to get the userID who started the request

        switch (servletRequest.getMethod().toUpperCase()) {
        case "DELETE":
            //handle deleting the token from your database
            break;
        default: {
            //handle adding the token/deviceID to your database
        }
            break;
        }

        FLUSH.updatePushDevices(userID);

        bytes = new byte[] {};
    }
        break;
    case "pushpackages": {
        /**
         * Safari requests the pacakge
         */
        String id = st.nextToken();

        JSONObject obj = new JSONObject(
                new String(org.eclipse.jetty.util.IO.readBytes(servletRequest.getInputStream())));

        String userID = obj.getString("user_id");

        String authenticationToken = "..a random string so you can later identify the user who started the request";

        bytes = createPackageFile(authenticationToken);
    }
        break;
    default:
        bytes = new byte[] {};
        break;
    }

    servletResponse.setStatus(200);
    servletResponse.setContentLength(bytes.length);
    try (OutputStream out = servletResponse.getOutputStream()) {
        out.write(bytes);
        out.flush();
    }
}

From source file:com.twitter.hbc.example.FilterStreamExample.java

public static String classifyText(String msg) {

    //Delimeters need to be further extended.
    StringTokenizer st = new StringTokenizer(msg, "[,. #]+");
    int positive = 0, negative = 0, neutral = 0;
    while (st.hasMoreTokens()) {
        String next = st.nextToken().toLowerCase();
        //System.out.println(next);
        positive += (positiveList.contains(next) ? 1 : 0);
        negative += (negativeList.contains(next) ? 1 : 0);

        //See whether neutral adds any value, TODO -
        if (!positiveList.contains(next) && !negativeList.contains(next))
            neutral += (positiveList.contains(next) ? 1 : 0);
    }/*from w w  w. j a v a  2 s  .co  m*/
    return (positive == negative) ? "Neutral" : ((positive > negative) ? "Positive" : "Negative");
}

From source file:com.dosport.system.utils.ServletUtils.java

/**
 * ?? If-None-Match Header, Etag?./*from w w w  .  j  a va  2 s  . c  o m*/
 * 
 * Etag, checkIfNoneMatchfalse, 304 not modify status.
 * 
 * @param etag
 *            ETag.
 */
public static boolean checkIfNoneMatchEtag(HttpServletRequest request, HttpServletResponse response,
        String etag) {
    String headerValue = request.getHeader("If-None-Match");
    if (headerValue != null) {
        boolean conditionSatisfied = false;
        if (!"*".equals(headerValue)) {
            StringTokenizer commaTokenizer = new StringTokenizer(headerValue, ",");

            while (!conditionSatisfied && commaTokenizer.hasMoreTokens()) {
                String currentToken = commaTokenizer.nextToken();
                if (currentToken.trim().equals(etag)) {
                    conditionSatisfied = true;
                }
            }
        } else {
            conditionSatisfied = true;
        }

        if (conditionSatisfied) {
            response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            response.setHeader("ETag", etag);
            return false;
        }
    }
    return true;
}

From source file:com.cisco.ca.cstg.pdi.services.license.LicenseKeyServiceImpl.java

public License setKey(String key) throws LicenseParsingException {
    License license = null;//w  w w .  j a  va  2 s . c o m
    String licenseValues = null;
    String licenseParseMessageString = "Invalid license file";

    try {
        licenseValues = licenseCryptoService.decrypt(key);
    } catch (NoSuchAlgorithmException nsae) {
        LOGGER.info("NoSuchAlgorithmException exception in setKey method.", nsae);
    } catch (BadPaddingException bpe) {
        LOGGER.info("BadPaddingException exception in setKey method.", bpe);
    } catch (IllegalBlockSizeException ibse) {
        LOGGER.info("IllegalBlockSizeException exception in setKey method.", ibse);
    } catch (InvalidKeyException ike) {
        LOGGER.info("InvalidKeyException exception in setKey method.", ike);
    } catch (NoSuchPaddingException nspe) {
        LOGGER.info("NoSuchPaddingException exception in setKey method.", nspe);
    } catch (NumberFormatException nfe) {
        LOGGER.info("NumberFormatException exception in setKey method.", nfe);
    }

    if (licenseValues != null) {
        license = (License) findById(License.class, 1);
        if (license == null) {
            license = new License();
        }

        String licenseValueString = licenseValues;
        StringTokenizer licenseValueTokenizer = new StringTokenizer(licenseValueString, ",");

        Map<String, String> licenseValuesMap = new HashMap<>();
        while (licenseValueTokenizer.hasMoreElements()) {
            String token = licenseValueTokenizer.nextToken();
            String[] tokenValues = token.split(":");
            if (tokenValues.length == 2) {
                licenseValuesMap.put(tokenValues[0], tokenValues[1]);
            }
        }

        if (licenseValuesMap.containsKey(Constants.LICENSE_KEY_PROJECT_NAME)) {
            license.setName(licenseValuesMap.get(Constants.LICENSE_KEY_PROJECT_NAME));
        }

        if (licenseValuesMap.containsKey(Constants.LICENSE_KEY_CUSTOMER_NAME)) {
            license.setCustomerName(licenseValuesMap.get(Constants.LICENSE_KEY_CUSTOMER_NAME));
        }

        if (licenseValuesMap.containsKey(Constants.LICENSE_KEY_CUSTOMER_DESCRIPTION)) {
            license.setDescription(licenseValuesMap.get(Constants.LICENSE_KEY_CUSTOMER_DESCRIPTION));

        }

        if (licenseValuesMap.containsKey(Constants.LICENSE_KEY_CUSTOMER_BUSINESS)) {
            license.setCustomerBusiness(licenseValuesMap.get(Constants.LICENSE_KEY_CUSTOMER_BUSINESS));
        }

        if (licenseValuesMap.containsKey(Constants.LICENSE_KEY_THEATRE)) {
            license.setTheatre(licenseValuesMap.get(Constants.LICENSE_KEY_THEATRE));
        }

        if (licenseValuesMap.containsKey(Constants.LICENSE_KEY_CUSTOMER_VERTICALS)) {
            license.setCustomerVertical(licenseValuesMap.get(Constants.LICENSE_KEY_CUSTOMER_VERTICALS));
        }
        if (licenseValuesMap.containsKey(Constants.LICENSE_KEY_ASPID)) {
            license.setAsPid(licenseValuesMap.get(Constants.LICENSE_KEY_ASPID));
        }

        if (licenseValuesMap.containsKey(Constants.LICENSE_KEY_SITEID)) {
            license.setSiteId(licenseValuesMap.get(Constants.LICENSE_KEY_SITEID));
        }

        if (licenseValuesMap.containsKey(Constants.LICENSE_KEY_CREATED_BY)) {
            license.setCreatedby(licenseValuesMap.get(Constants.LICENSE_KEY_CREATED_BY));
        }

        if (licenseValuesMap.containsKey(Constants.LICENSE_KEY_SITENAME)) {
            license.setSite(licenseValuesMap.get(Constants.LICENSE_KEY_SITENAME));
        }

        String serviceTypeValue = null;
        if (licenseValuesMap.containsKey(Constants.LICENSE_KEY_SERVICE_TYPE)) {
            serviceTypeValue = licenseValuesMap.get(Constants.LICENSE_KEY_SERVICE_TYPE);
        }

        if (serviceTypeValue != null && serviceTypeValue.matches("UCSPDI")) {
            license.setServiceType(serviceTypeValue);
            saveOrUpdate(license);
        } else {
            license = null;
            licenseParseMessageString = "The License file is invalid. Kindly upload the valid License file.";
        }
    }

    if (license == null) {
        throw new LicenseParsingException(licenseParseMessageString);
    }
    return license;
}

From source file:com.benfante.minimark.blo.ImporterBo.java

public List<Question> readQuestionSet(Reader r) throws ParseException, IOException {
    List<Question> result = new LinkedList<Question>();
    int lineCount = 0;
    String line = null;// w  ww  .j  av  a  2 s . co m
    BufferedReader br = null;
    if (r instanceof BufferedReader) {
        br = (BufferedReader) r;
    } else {
        br = new BufferedReader(r);
    }
    endstream: while ((line = br.readLine()) != null) {
        lineCount++;
        // skip empty and comment lines
        if (StringUtils.isBlank(line) || line.charAt(0) == 'c') {
            continue;
        }
        char questionType = 0;
        String questionId = "";
        StringBuffer questionText = new StringBuffer();
        List<FixedAnswer> answers = new LinkedList<FixedAnswer>();
        String tmp;
        if (line.charAt(0) != 'd') {
            throw new ParseException("Start of question not found", lineCount);
        }
        StringTokenizer tk = new StringTokenizer(line, "|");
        tk.nextToken(); // skip the initial 'd'
        // question id
        tmp = tk.nextToken();
        if (tmp != null) {
            questionId = tmp;
        } else {
            throw new ParseException("Question id not found", lineCount);
        }
        // question type
        tmp = tk.nextToken();
        if ((tmp != null) && (tmp.length() > 0)) {
            questionType = Character.toUpperCase(tmp.charAt(0));
            if ((questionType != 'A') && (questionType != 'R') && (questionType != 'C')
                    && (questionType != 'T')) {
                throw new ParseException("Question type unknown", lineCount);
            }
        } else {
            throw new ParseException("Question type not found", lineCount);
        }
        // answer scrambling flag
        tmp = tk.nextToken();
        if ((tmp != null) && (tmp.length() > 0)) {
            //                char acf = tmp.charAt(0);
            //                switch (acf) {
            //                    case 'u':
            //                        answerScrambling = false;
            //                        break;
            //                    case 's':
            //                        answerScrambling = true;
            //                        break;
            //                    default:
            //                        throw new ParseException("Answer scrambling flag unknown", lineCount);
            //                }
        } else {
            throw new ParseException("Answer scrambling flag not found", lineCount);
        }
        // question text
        tmp = tk.nextToken();
        if ((tmp != null) && (tmp.length() > 0)) {
            questionText.append(tmp);
            if ((questionType == 'A') || (questionType == 'T')) { // multiline questions
                while ((line = br.readLine()) != null) {
                    lineCount++;
                    if (StringUtils.isBlank(line)) {
                        break;
                    }
                    questionText.append('\n').append(line);
                }
            }
        } else {
            throw new ParseException("Question text not found", lineCount);
        }
        // suggested answers
        if ((questionType == 'R') || (questionType == 'C')) {
            while ((line = br.readLine()) != null) {
                lineCount++;
                if (StringUtils.isBlank(line)) {
                    break;
                }
                tk = new StringTokenizer(line, "|");
                // correct char
                tmp = tk.nextToken();
                boolean correct = false;
                if ((tmp != null) && (tmp.length() > 0)) {
                    char correctChar = line.charAt(0);
                    if (correctChar == 'y') {
                        correct = true;
                    } else if (correctChar == 'n') {
                        correct = false;
                    } else {
                        throw new ParseException("Correct char unknown", lineCount);
                    }
                } else {
                    throw new ParseException("Correct char not found (" + tmp + ")", lineCount);
                }
                tmp = tk.nextToken();
                String answerText = null;
                if ((tmp != null) && (tmp.length() > 0)) {
                    answerText = tmp;
                } else {
                    throw new ParseException("Answer text not found", lineCount);
                }
                FixedAnswer fixedAnswer = new FixedAnswer();
                fixedAnswer.setContent(answerText);
                fixedAnswer.setContentFilter(TextFilterUtils.HTML_FILTER_CODE);
                fixedAnswer.setCorrect(correct);
                fixedAnswer.setWeight(BigDecimal.ONE);
                answers.add(fixedAnswer);
            }
        }
        Question newQuestion = makeQuestion(questionType, questionId, questionText.toString(), answers);
        result.add(newQuestion);
    }
    return result;
}

From source file:de.tudarmstadt.ukp.uby.ubycreate.MainController.java

/**
 * This method dumps Germanet, Framenet, WordNet and XML into DB by instantiating the
 * appropriate classes and calling their methods
 */// w w  w.java  2 s  . com
private void run(String args[]) throws XMLStreamException, SAXException, DocumentException {

    CmdLineParser parser = new CmdLineParser(this);

    try {

        Map<String, Class<? extends Creator>> creatorMap = createMap();

        parser.parseArgument(args);

        /* Breaking the parameter value into lexicon and source path */
        StringTokenizer tokSource = new StringTokenizer(source, ":");

        String lexicon = tokSource.nextToken();

        Creator creatorObj = creatorMap.get(lexicon).newInstance();

        source = "";

        while (tokSource.hasMoreTokens()) {
            source = source + tokSource.nextToken();
            if (tokSource.hasMoreElements()) {
                source = source + ":";
            }
        }

        StringTokenizer tokTarget = new StringTokenizer(target, ":");
        String targetType = tokTarget.nextToken();

        /* If block is run when target is uby xml */
        if (targetType.equals("xml")) {

            String ubyXMLName = "";

            while (tokTarget.hasMoreTokens()) {
                ubyXMLName = ubyXMLName + tokTarget.nextToken();
                if (tokTarget.hasMoreElements()) {
                    ubyXMLName = ubyXMLName + ":";
                }
            }

            File lmfXML = new File(ubyXMLName);

            creatorObj.lexicon2XML(source, lmfXML);

        } else {

            DBConfig dbConfig = makeDBConfig(target);

            if (dbConfig == null) {
                return;
            }

            /*
             * the following has been commented as it throws exception when there is no table in
             * DB schema to drop
             */
            // LMFDBUtils.dropTables(dbConfig);

            LMFDBUtils.createTables(dbConfig);

            creatorObj.lexicon2DB(dbConfig, source);

        }
    } catch (JWNLException e) {

        printHelpMessage(parser, e);

    } catch (IOException e) {

        printHelpMessage(parser, e);

    } catch (CmdLineException e) {

        printHelpMessage(parser, e);

    } catch (NullPointerException e) {

        printHelpMessage(parser, e);

    } catch (ClassNotFoundException e) {

        printHelpMessage(parser, e);

    } catch (NoSuchElementException e) {

        printHelpMessage(parser, e);

    } catch (IllegalAccessException e) {

        printHelpMessage(parser, e);

    } catch (InstantiationException e) {

        printHelpMessage(parser, e);

    } catch (Exception e) {

        printHelpMessage(parser, e);

    }

}

From source file:com.glaf.oa.reimbursement.web.springmvc.RitemController.java

@ResponseBody
@RequestMapping("/delete")
public void delete(HttpServletRequest request, ModelMap modelMap) {
    String ritemids = request.getParameter("ritemids");
    String reimbursementid = request.getParameter("reimbursementid");
    if (StringUtils.isNotEmpty(ritemids)) {
        StringTokenizer token = new StringTokenizer(ritemids, ",");
        while (token.hasMoreTokens()) {
            String x = token.nextToken();
            if (StringUtils.isNotEmpty(x)) {
                ritemService.deleteById(Long.valueOf(x), Long.valueOf(reimbursementid));
            }/*from ww w . j a v a  2  s  . c  o  m*/
        }
    }
}

From source file:com.appunite.socketio.SocketIOBase.java

private ImmutableSet<String> getTypesFromString(String str) throws WrongSocketIOResponse {
    StringTokenizer st = new StringTokenizer(str, ",");
    HashSet<String> types = new HashSet<String>();
    while (st.hasMoreTokens()) {
        types.add(st.nextToken());/*from  w  w w.j av  a 2s  . c  o m*/
    }
    if (types.isEmpty())
        throw new WrongSocketIOResponse("No transport types in socket response");
    return ImmutableSet.copyOf(types);
}

From source file:com.abhinav.alfresco.publishing.utils.MimeTypesProvider.java

/**
 * Loads the mime types from the alfresco-global.properties.
 *//*from  w  ww.j  ava 2s .  com*/
private void init() {
    final Properties props = new Properties();
    try (InputStream inStream = Thread.currentThread().getContextClassLoader()
            .getResourceAsStream(S3PublishingModel.S3_MODULE_PROPERTIESFILE)) {
        props.load(inStream);
    } catch (IOException ioex) {
        if (LOG.isErrorEnabled()) {
            LOG.error("Exception getting the mimetypes from alfresco-global.properties: ", ioex);
        }
    }
    // Get the supported mimetypes from alfresco-global.properties file
    if (props.getProperty(S3PublishingModel.SUPPORTD_MIME_KEY) != null) {
        final StringTokenizer tokens = new StringTokenizer(
                props.getProperty(S3PublishingModel.SUPPORTD_MIME_KEY), ",");
        while (tokens.hasMoreTokens()) {
            supportedMimeTypes.add(tokens.nextToken().trim());
        }
        LOG.info("SupportedMimeTypes by s3 publishing channel: " + supportedMimeTypes);
    }
}