Example usage for java.util StringTokenizer hasMoreElements

List of usage examples for java.util StringTokenizer hasMoreElements

Introduction

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

Prototype

public boolean hasMoreElements() 

Source Link

Document

Returns the same value as the hasMoreTokens method.

Usage

From source file:org.eclipse.californium.proxy.HttpTranslator.java

public static void getHttpDiscovery(HttpRequest httpRequest, Response coapResponse, HttpResponse httpResponse) {
    // TODO Auto-generated method stub
    String response = coapResponse.getPayloadString();

    int start_index = response.indexOf("rt=\"", 0);
    String substring = response.substring(start_index + 4);
    int end_index = substring.indexOf('"', 0);
    String rt = substring.substring(0, end_index);
    StringTokenizer tokenizer = new StringTokenizer(rt, " ");
    String resources = "";

    while (tokenizer.hasMoreElements()) {
        String resource = "<" + (String) tokenizer.nextElement() + ">; rel=\"type\", ";
        resources = resources + resource;
    }/*from  w ww .  ja  v a2 s .c om*/

    resources = resources.substring(0, resources.length() - 2);
    Header link = new BasicHeader("Link", resources);
    httpResponse.addHeader(link);

}

From source file:ancat.visualizers.EdgeTransformers.java

/**
 * Configuration of the Stroke used for drawing edges. It processes the
 * following values://from   w  w  w.  j  a  v  a2  s.c o  m
 * 
 * <code> edge:style </code> may be set to solid, dashed or dotted. By default
 * the edge style is set to dashed.
 * 
 * <code> edge:stroke-width </code> The width of the stroke used for
 * rendering.
 * 
 * <code> edge:dash-pattern</code> Contains an array of float values
 * describing the dash pattern. See documentation of Java Stroke class to
 * understand the pattern style</code>
 */
protected void setupStroke() {
    String style = "solid";
    float width = 0.5f;
    float dash[] = null;

    Map<String, String> edgeConfig = _renderConfig.edgeConfiguration();

    if (edgeConfig.containsKey("edge:style")) {
        style = edgeConfig.get("edge:style");

        if (!style.equalsIgnoreCase("solid") && !style.equalsIgnoreCase("dashed")
                && !style.equalsIgnoreCase("dotted")) {
            _logger.error("unsupported edge style attribute: " + style + " allowed is solid, dashed, dotted");

            style = "solid";
        }
    }

    if (edgeConfig.containsKey("edge:stroke-width")) {
        try {
            width = Float.parseFloat(edgeConfig.get("edge:stroke-width"));
        } catch (Exception e) {
            _logger.error("unsupported specification of float value for edge width, changing to default");
        }
    }

    if (edgeConfig.containsKey("edge:dash-pattern")) {
        try {
            StringTokenizer tokenizer = new StringTokenizer(edgeConfig.get("edge:dash-pattern"), ",");

            dash = new float[tokenizer.countTokens()];

            int counter = 0;

            while (tokenizer.hasMoreElements()) {
                dash[counter] = Float.parseFloat(tokenizer.nextToken().trim());
                counter += 1;
            }
        } catch (Exception e) {
            _logger.error("Error while parsing dash style, changing to default");

            dash = new float[] { 10.0f };
        }
    }

    if (style.equalsIgnoreCase("dashed")) {
        _edgeStroke = new BasicStroke(width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash, 0.0f);
    } else if (style.equalsIgnoreCase("dotted")) {
        dash = new float[] { 2.0f, 2.0f };
        _edgeStroke = new BasicStroke(width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 10.0f, dash, 0.0f);
    } else if (style.equalsIgnoreCase("solid")) {
        _edgeStroke = new BasicStroke(width, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER);
    }
}

From source file:org.kuali.rice.testtools.selenium.JiraIssueCreation.java

@Test
public void testCreateJira() throws InterruptedException, IOException {
    for (Map<String, String> jiraMap : jiraMaps.values()) {

        // Jira/*  ww  w .  j  av  a  2  s. co  m*/
        WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.id("create_link"),
                this.getClass().toString());
        driver.get(jiraBase + "/secure/CreateIssue!default.jspa");

        // Project
        WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.id("project-field"),
                this.getClass().toString()).sendKeys(jiraMap.get("jira.project"));

        // Issue type
        WebElement issue = WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(),
                By.id("issuetype-field"), this.getClass().toString());
        issue.click();
        issue.sendKeys(Keys.BACK_SPACE);
        issue.sendKeys(jiraMap.get("jira.issuetype"));
        //            issue.sendKeys(Keys.ARROW_DOWN);
        issue.sendKeys(Keys.TAB);

        WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.id("issue-create-submit"),
                this.getClass().toString()).click();

        // Summary // TODO remove things that look like java object references
        // TODO if the error messages are the same for all jiras then include it in the summary
        WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.id("summary"),
                this.getClass().toString()).sendKeys(jiraMap.get("jira.summary"));

        // Components
        WebElement component = WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(),
                By.id("components-textarea"), this.getClass().toString());
        String components = jiraMap.get("jira.component");
        StringTokenizer tokens = new StringTokenizer(components);
        while (tokens.hasMoreElements()) {
            component.click();
            component.sendKeys(tokens.nextToken());
            //                component.sendKeys(Keys.ARROW_DOWN);
            component.sendKeys(Keys.TAB);
        }

        // Description
        WebElement descriptionElement = WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(),
                By.id("description"), this.getClass().toString());
        descriptionElement.click();
        descriptionElement.sendKeys(jiraMap.get("jira.description"));

        // Priority
        WebElement priority = WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(),
                By.id("priority-field"), this.getClass().toString());
        priority.click();
        priority.sendKeys(Keys.BACK_SPACE);
        priority.sendKeys(jiraMap.get("jira.priority"));
        //            priority.sendKeys(Keys.ARROW_DOWN);
        priority.sendKeys(Keys.TAB);

        // Version
        WebElement version = WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(),
                By.id("versions-textarea"), this.getClass().toString());
        version.click();
        version.sendKeys(jiraMap.get("jira.versions"));
        //            version.sendKeys(Keys.ARROW_DOWN);
        version.sendKeys(Keys.TAB);

        // Fix version
        WebElement fixVersion = WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(),
                By.id("fixVersions-textarea"), this.getClass().toString());
        fixVersion.click();
        fixVersion.sendKeys(jiraMap.get("jira.fixVersions"));
        //            fixVersion.sendKeys(Keys.ARROW_DOWN);
        fixVersion.sendKeys(Keys.TAB);

        // Release notes unchecked
        WebDriverUtils.waitFor(driver, WebDriverUtils.configuredImplicityWait(), By.id("customfield_11621-1"),
                this.getClass().toString()).click();

        WebDriverUtils.waitFor(driver, 8, By.id("issue-create-submit"), this.getClass().toString());

        //            WebDriverUtils.acceptAlertIfPresent(driver); // Dialog present when running Se.....
    }
}

From source file:eu.europa.esig.dss.DSSUtils.java

/**
 * This method return the unique message id which can be used for translation purpose.
 *
 * @param message/*from  ww  w.  j  a v  a 2 s .com*/
 *            the {@code String} message on which the unique id is calculated.
 * @return the unique id
 */
public static String getMessageId(final String message) {

    final String message_ = message./*replace('\'', '_').*/toLowerCase().replaceAll("[^a-z_]", " ");
    StringBuilder nameId = new StringBuilder();
    final StringTokenizer stringTokenizer = new StringTokenizer(message_);
    while (stringTokenizer.hasMoreElements()) {

        final String word = (String) stringTokenizer.nextElement();
        nameId.append(word.charAt(0));
    }
    final String nameIdString = nameId.toString();
    return nameIdString.toUpperCase();
}

From source file:nl.nn.adapterframework.pipes.CompressPipe.java

public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException {
    try {// w w w  . ja  va 2s .c o m
        Object result;
        InputStream in;
        OutputStream out;
        boolean zipMultipleFiles = false;
        if (messageIsContent) {
            if (input instanceof byte[]) {
                in = new ByteArrayInputStream((byte[]) input);
            } else {
                in = new ByteArrayInputStream(input.toString().getBytes());
            }
        } else {
            if (compress && StringUtils.contains((String) input, ";")) {
                zipMultipleFiles = true;
                in = null;
            } else {
                in = new FileInputStream((String) input);
            }
        }
        if (resultIsContent) {
            out = new ByteArrayOutputStream();
            result = out;
        } else {
            String outFilename = null;
            if (messageIsContent) {
                outFilename = FileUtils.getFilename(getParameterList(), session, (File) null, filenamePattern);
            } else {
                outFilename = FileUtils.getFilename(getParameterList(), session, new File((String) input),
                        filenamePattern);
            }
            File outFile = new File(outputDirectory, outFilename);
            result = outFile.getAbsolutePath();
            out = new FileOutputStream(outFile);
        }
        if (zipMultipleFiles) {
            ZipOutputStream zipper = new ZipOutputStream(out);
            StringTokenizer st = new StringTokenizer((String) input, ";");
            while (st.hasMoreElements()) {
                String fn = st.nextToken();
                String zipEntryName = getZipEntryName(fn, session);
                zipper.putNextEntry(new ZipEntry(zipEntryName));
                in = new FileInputStream(fn);
                try {
                    int readLength = 0;
                    byte[] block = new byte[4096];
                    while ((readLength = in.read(block)) > 0) {
                        zipper.write(block, 0, readLength);
                    }
                } finally {
                    in.close();
                    zipper.closeEntry();
                }
            }
            zipper.close();
            out = zipper;
        } else {
            if (compress) {
                if ("gz".equals(fileFormat) || fileFormat == null && resultIsContent) {
                    out = new GZIPOutputStream(out);
                } else {
                    ZipOutputStream zipper = new ZipOutputStream(out);
                    String zipEntryName = getZipEntryName(input, session);
                    zipper.putNextEntry(new ZipEntry(zipEntryName));
                    out = zipper;
                }
            } else {
                if ("gz".equals(fileFormat) || fileFormat == null && messageIsContent) {
                    in = new GZIPInputStream(in);
                } else {
                    ZipInputStream zipper = new ZipInputStream(in);
                    String zipEntryName = getZipEntryName(input, session);
                    if (zipEntryName.equals("")) {
                        // Use first entry found
                        zipper.getNextEntry();
                    } else {
                        // Position the stream at the specified entry
                        ZipEntry zipEntry = zipper.getNextEntry();
                        while (zipEntry != null && !zipEntry.getName().equals(zipEntryName)) {
                            zipEntry = zipper.getNextEntry();
                        }
                    }
                    in = zipper;
                }
            }
            try {
                int readLength = 0;
                byte[] block = new byte[4096];
                while ((readLength = in.read(block)) > 0) {
                    out.write(block, 0, readLength);
                }
            } finally {
                out.close();
                in.close();
            }
        }
        return new PipeRunResult(getForward(), getResultMsg(result));
    } catch (Exception e) {
        PipeForward exceptionForward = findForward(EXCEPTIONFORWARD);
        if (exceptionForward != null) {
            log.warn(getLogPrefix(session) + "exception occured, forwarded to [" + exceptionForward.getPath()
                    + "]", e);
            String originalMessage;
            if (input instanceof String) {
                originalMessage = (String) input;
            } else {
                originalMessage = "Object of type " + input.getClass().getName();
            }
            String resultmsg = new ErrorMessageFormatter().format(getLogPrefix(session), e, this,
                    originalMessage, session.getMessageId(), 0);
            return new PipeRunResult(exceptionForward, resultmsg);
        }
        throw new PipeRunException(this, "Unexpected exception during compression", e);
    }
}

From source file:org.wso2.carbon.andes.authorization.andes.AndesAuthorizationHandler.java

/**
 * We want to check user is authorize for parent topic in case of hierarchical topic
 * i.e. Let's say there is topic hierarchical topic country.province.city1
 * user who has permission to either country or province should be able to subscribe or
 * publish to city1 as well.//from ww w  .j av  a  2  s.  co m
 *
 * @param username username of logged user
 * @param userRealm User's Realm
 * @param topicId topic id
 * @param permission The permission type to check for
 *
 * @return is user authorize
 * @throws UserStoreException
 */
private static boolean isAuthorizeToParentInHierarchy(String username, UserRealm userRealm, String topicId,
        TreeNode.Permission permission) throws UserStoreException, RegistryClientException {

    //check given resource path exist before check permission in parent hierarchy
    if (!RegistryClient.isResourceExist(topicId)) {
        return false;
    }
    //tokenize resource path
    StringTokenizer tokenizer = new StringTokenizer(topicId, "/");
    StringBuilder resourcePathBuilder = new StringBuilder();
    //get token count
    int tokenCount = tokenizer.countTokens();
    int count = 0;
    boolean userAuthorized = false;
    Pattern pattern = Pattern.compile(PARENT_RESOURCE_PATH);

    while (tokenizer.hasMoreElements()) {
        //get each element in topicId resource path
        String resource = tokenizer.nextElement().toString();
        //build resource path again
        resourcePathBuilder.append(resource);
        //we want to check that build resource path has permission to any resource
        // after event/topics/
        Matcher matcher = pattern.matcher(resourcePathBuilder.toString());
        if (matcher.find()) {
            if (userRealm.getAuthorizationManager().isUserAuthorized(username, resourcePathBuilder.toString(),
                    permission.toString().toLowerCase())) {
                userAuthorized = true;
                break;
            }

        }
        count++;
        if (count < tokenCount) {
            resourcePathBuilder.append("/");
        }

    }
    return userAuthorized;
}

From source file:org.openmrs.module.muzima.web.resource.openmrs.ConceptResource.java

/**
 * Gets the delegate object with the given unique id. Implementations may decide whether
 * "unique id" means a uuid, or if they also want to retrieve delegates based on a unique
 * human-readable property./*from w w  w . j  a v a 2 s. c om*/
 *
 * @param uniqueId
 * @return the delegate for the given uniqueId
 */
@Override
public Object retrieve(String uniqueId, RequestContext context) throws ResponseException {
    //TODO: this is an overkill of a very simple method that would be solved simply by ConceptService.getConceptByUuid(uuid, locales)
    //TODO: Observe for OpenMRS to implement such method
    Concept concept = Context.getConceptService().getConceptByUuid(uniqueId);
    if (concept == null && StringUtils.isNumeric(uniqueId))
        concept = Context.getConceptService().getConcept(Integer.parseInt(uniqueId));

    Concept localizedConcept = concept;
    if (concept != null) {
        String acceptedLanguages = context.getRequest().getHeader("Accept-Language");
        if (StringUtils.isNotBlank(acceptedLanguages)) {
            StringTokenizer localeTokens = new StringTokenizer(acceptedLanguages, ",");
            if (localeTokens.hasMoreElements()) {
                String strLocale = localeTokens.nextToken();
                StringTokenizer countrySplitter = new StringTokenizer(strLocale, "_-");
                if (countrySplitter.hasMoreElements()) {
                    Locale parsedLocale = new Locale(countrySplitter.nextToken());
                    if (concept.getNames(parsedLocale) != null && concept.getNames(parsedLocale).size() > 0) {
                        localizedConcept.setNames(concept.getNames(parsedLocale));
                        if (concept.getShortNameInLocale(parsedLocale) != null)
                            localizedConcept.setShortName(concept.getShortNameInLocale(parsedLocale));
                        if (concept.getPreferredName(parsedLocale) != null)
                            localizedConcept.setPreferredName(concept.getPreferredName(parsedLocale));
                        if (concept.getFullySpecifiedName(parsedLocale) != null)
                            localizedConcept.setFullySpecifiedName(concept.getFullySpecifiedName(parsedLocale));
                        if (concept.getDescription(parsedLocale) != null) {
                            Collection<ConceptDescription> descriptions = new ArrayList<ConceptDescription>();
                            descriptions.add(concept.getDescription(parsedLocale));
                            localizedConcept.setDescriptions(descriptions);
                        } else
                            localizedConcept.setDescriptions(null);
                    } else
                        localizedConcept = null;
                }
            }
        }
    }

    return ConversionUtil.convertToRepresentation(FakeConcept.copyConcept(localizedConcept),
            context.getRepresentation());
}

From source file:org.kchine.rpf.db.DBLayer.java

public static String[] getPrefixes(String prefixes) {
    StringTokenizer st = new StringTokenizer(prefixes, ",");
    Vector<String> pv = new Vector<String>();
    while (st.hasMoreElements())
        pv.add((String) st.nextElement());
    return pv.toArray(new String[0]);
}

From source file:org.opentestsystem.delivery.testreg.upload.FileUploadUtils.java

public int getDomainObject(final Object[] cellData) {

    //getting each row data during file-upload process and construct LinkedHashMap assign data to its corresponding key

    int counter = 0;
    List<String> headersList = masterResourceAccommodationService.getAllOptionsCodes();
    HashMap<String, String> headerResourceTypes = masterResourceAccommodationService.getAllResourceTypes();
    headerResourceTypes.put("StudentId", "SingleSelectResource");
    headerResourceTypes.put("StateAbbreviation", "SingleSelectResource");
    headerResourceTypes.put("Subject", "SingleSelectResource");
    Map<String, String> accommodationMap = new LinkedHashMap<String, String>();
    Map<String, Object> accommoMap = new LinkedHashMap<String, Object>();
    if (cellData.length == 4) {
        accommoMap = convertDataToMap(cellData, headersList, headerResourceTypes);
    } else {/*from  w  w w . j a v  a2  s.c  o  m*/
        for (int i = 0; i < headersList.size(); i++) {
            String key = ARTHelpers.convertCodeToUpperCase(headersList.get(i));
            if (headerResourceTypes.containsKey(key) && headerResourceTypes.get(key)
                    .equals(AccommodationResourceType.MultiSelectResource.name())) {
                List<String> al = new ArrayList<String>();
                StringTokenizer tokenizer = new StringTokenizer(cellData[i].toString(), ";");
                while (tokenizer.hasMoreElements()) {
                    String token = (String) tokenizer.nextElement();
                    al.add(token.trim());
                }
                accommodationMap.put(headersList.get(i), al.toString());
                accommoMap.put(headersList.get(i), al);
            } else if (headerResourceTypes.containsKey(key)
                    && headerResourceTypes.get(key)
                            .equals(AccommodationResourceType.SingleSelectResource.name())
                    || headerResourceTypes.get(key).equals(AccommodationResourceType.EditResource.name())) {
                if (headersList.get(i).equalsIgnoreCase("subject")
                        || headersList.get(i).equalsIgnoreCase("stateAbbreviation")) {
                    accommodationMap.put(headersList.get(i), cellData[i].toString().toUpperCase());
                    accommoMap.put(headersList.get(i), cellData[i].toString().toUpperCase());
                } else {
                    accommodationMap.put(headersList.get(i), cellData[i].toString());
                    accommoMap.put(headersList.get(i), cellData[i].toString());
                }
            }
        }
    }

    String studentId = (String) accommoMap.get("studentId");
    String stateAbbreviation = (String) accommoMap.get("stateAbbreviation");

    //saving accommodationMap we constructed into it's corresponding student based on studentId,stateAbbreviation
    Student student = studentService.saveAccommodation(studentId, stateAbbreviation, accommoMap);
    if (student != null) {
        counter++;
    }
    return counter;
}

From source file:org.wso2.carbon.repository.core.jdbc.dataaccess.TenantAwareSQLTransformer.java

/**
 * Construct the TenantAwareSQLTransformer for a given query
 *
 * @param sqlQuery the query to transform to tenant aware sql
 *
 * @throws RepositoryException throws if the transformation failed.
 *//* ww  w  . jav  a2s  .c  o m*/
public TenantAwareSQLTransformer(String sqlQuery) throws RepositoryException {
    //parse SQL for possible injected SQLs
    try {
        sanityCheckSQL(sqlQuery);
    } catch (RepositoryException e) {
        throw new RepositoryDBException("SQL query provided failed validity check. Reason for failure is : "
                + e.getMessage() + ".SQL Query received is : " + sqlQuery);
    }

    String sqlQueryUCase = sqlQuery.toUpperCase();
    parameterCount = 0;

    int endOfFromIndex = sqlQueryUCase.indexOf("FROM");

    if (endOfFromIndex == -1) {
        String msg = "Error in parsing the query. You should have a 'FROM' token in your custom query";
        log.error(msg);
        throw new RepositoryDBException(msg);
    }

    endOfFromIndex += 4;
    int startOfWhereIndex = sqlQueryUCase.indexOf("WHERE");
    int startOfThirdClauseIndex = -1;

    for (String s : new String[] { "GROUP BY", "HAVING", "ORDER BY", "LIMIT" }) {
        int index = sqlQueryUCase.indexOf(s);
        if (index > 0 && (startOfThirdClauseIndex == -1 || index < startOfThirdClauseIndex)) {
            startOfThirdClauseIndex = index;
        }
    }

    boolean whereNotFound = false;

    if (startOfWhereIndex == -1) {
        whereNotFound = true;
        startOfWhereIndex = sqlQueryUCase.length();
        if (startOfThirdClauseIndex != -1) {
            startOfWhereIndex = startOfThirdClauseIndex;
        }
    }

    String fromPart = sqlQuery.substring(endOfFromIndex + 1, startOfWhereIndex);
    StringTokenizer tokenizer = new StringTokenizer(fromPart, ",");

    String additionalWherePart;
    StringBuilder sb = new StringBuilder();

    while (tokenizer.hasMoreElements()) {
        String token = tokenizer.nextToken();
        token = token.trim();
        token = token.replaceAll("[\t\r\n]+", " ");
        int separator = token.indexOf(' ');
        String firstPart;
        String secondPart;

        if (separator == -1) {
            firstPart = token;
            secondPart = null;
        } else {
            firstPart = token.substring(0, separator);
            secondPart = token.substring(separator + 1);
            firstPart = firstPart.trim();
            secondPart = secondPart.trim();
        }

        // now the first part contains the table name
        if (secondPart == null) {
            if (sb.length() < 1) {
                sb.append(firstPart).append(".REG_TENANT_ID=?");
            } else {
                sb.append(" AND ").append(firstPart).append(".REG_TENANT_ID=?");
            }
        } else {
            if (sb.length() < 1) {
                sb.append(secondPart).append(".REG_TENANT_ID=?");
            } else {
                sb.append(" AND ").append(secondPart).append(".REG_TENANT_ID=?");
            }
        }
        parameterCount++;
    }

    additionalWherePart = sb.toString();

    if (whereNotFound) {
        if (startOfThirdClauseIndex == -1) {
            transformedQuery = sqlQuery + " WHERE " + additionalWherePart;
        } else {
            String[] parts = sqlQuery.substring(startOfThirdClauseIndex).split("[?]");
            if (parts != null && parts.length > 1) {
                trailingParameterCount += parts.length - 1;
                if (sqlQuery.substring(startOfThirdClauseIndex).endsWith("?")) {
                    trailingParameterCount += 1;
                }
            }
            transformedQuery = sqlQuery.substring(0, startOfThirdClauseIndex) + " WHERE " + additionalWherePart
                    + " " + sqlQuery.substring(startOfThirdClauseIndex);
        }
    } else {
        int endOfWhereIndex = startOfWhereIndex + 5;
        transformedQuery = sqlQuery.substring(0, endOfWhereIndex) + " (" + additionalWherePart + ") AND "
                + sqlQuery.substring(endOfWhereIndex);
    }
}