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:com.afis.jx.ckfinder.connector.utils.FileUtils.java

/**
 * rename file with double extension.//  w  w  w  .  j av a  2 s  .c  o  m
 *
 * @param type a {@code ResourceType} object holding list of allowed and denied extensions against which file extension will be tested.
 * @param fileName file name
 * @return new file name with . replaced with _ (but not last)
 */
public static String renameFileWithBadExt(final ResourceType type, final String fileName) {
    if (type == null || fileName == null) {
        return null;
    }

    if (fileName.indexOf('.') == -1) {
        return fileName;
    }

    StringTokenizer tokens = new StringTokenizer(fileName, ".");
    String cfileName = tokens.nextToken();
    String currToken;
    while (tokens.hasMoreTokens()) {
        currToken = tokens.nextToken();
        if (tokens.hasMoreElements()) {
            cfileName = cfileName.concat(checkSingleExtension(currToken, type) ? "." : "_");
            cfileName = cfileName.concat(currToken);
        } else {
            cfileName = cfileName.concat(".".concat(currToken));
        }
    }
    return cfileName;
}

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

public License setKey(String key) throws LicenseParsingException {
    License license = null;//  w ww  .  j a v  a  2 s  . co  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:org.inbio.ait.model.SystemUser.java

@Override
public GrantedAuthority[] getAuthorities() {

    StringTokenizer st = new StringTokenizer(this.getRoles(), ROLE_DELIMITER);
    GrantedAuthorityImpl[] grantedAuthorityImplArray = new GrantedAuthorityImpl[st.countTokens()];

    for (int i = 0; st.hasMoreElements(); i++)
        grantedAuthorityImplArray[i] = new GrantedAuthorityImpl(st.nextToken());

    return grantedAuthorityImplArray;
}

From source file:org.apache.jcs.auxiliary.lateral.socket.tcp.LateralTCPCacheFactory.java

public AuxiliaryCache createCache(AuxiliaryCacheAttributes iaca, ICompositeCacheManager cacheMgr) {
    ITCPLateralCacheAttributes lac = (ITCPLateralCacheAttributes) iaca;
    ArrayList noWaits = new ArrayList();

    // pars up the tcp servers and set the tcpServer value and
    // get the manager and then get the cache
    // no servers are required.
    if (lac.getTcpServers() != null) {
        StringTokenizer it = new StringTokenizer(lac.getTcpServers(), ",");
        if (log.isDebugEnabled()) {
            log.debug("Configured for [" + it.countTokens() + "]  servers.");
        }/*  w w  w  . j av  a  2  s. c  om*/
        while (it.hasMoreElements()) {
            String server = (String) it.nextElement();
            if (log.isDebugEnabled()) {
                log.debug("tcp server = " + server);
            }
            ITCPLateralCacheAttributes lacC = (ITCPLateralCacheAttributes) lac.copy();
            lacC.setTcpServer(server);
            LateralTCPCacheManager lcm = LateralTCPCacheManager.getInstance(lacC, cacheMgr);
            ICache ic = lcm.getCache(lacC.getCacheName());
            if (ic != null) {
                noWaits.add(ic);
            } else {
                if (log.isDebugEnabled()) {
                    log.debug("noWait is null, no lateral connection made");
                }
            }
        }
    }

    createListener((ILateralCacheAttributes) iaca, cacheMgr);

    // create the no wait facade.
    LateralCacheNoWaitFacade lcnwf = new LateralCacheNoWaitFacade(
            (LateralCacheNoWait[]) noWaits.toArray(new LateralCacheNoWait[0]), (ILateralCacheAttributes) iaca);

    // create udp discovery if available.
    createDiscoveryService(lac, lcnwf, cacheMgr);

    return lcnwf;
}

From source file:com.telefonica.euro_iaas.sdc.rest.validation.ProductInstanceResourceValidatorImpl.java

private void validateAttributesType(List<Attribute> attributes) throws InvalidProductException {
    String msg = "Attribute type is incorrect.";
    for (Attribute att : attributes) {
        if (att.getType() == null) {
            att.setType("Plain");
        }/* w  w w  .  j a v a  2s  .  c o  m*/

        String availableTypes = systemPropertiesProvider
                .getProperty(SystemPropertiesProvider.AVAILABLE_ATTRIBUTE_TYPES);

        StringTokenizer st2 = new StringTokenizer(availableTypes, "|");
        boolean error = true;
        while (st2.hasMoreElements()) {
            if (att.getType().equals(st2.nextElement())) {
                error = false;
                break;
            }
        }
        if (error) {
            throw new InvalidProductException(msg);
        }
    }
}

From source file:com.emcopentechnologies.viprcloudstorage.WAStorageClient.java

/**
 * Uploads files to ViPR Cloud Storage./*from  ww  w  .j a va 2  s. c om*/
 * 
 * @param listener
 * @param build
 * @param StorageAccountInfo
 *            storage account information.
 * @param expContainerName
 *            container name.
 * @param cntPubAccess
 *            denotes if container is publicly accessible.
 * @param expFP
 *            File Path in ant glob syntax relative to CI tool workspace.
 * @param expVP
 *            Virtual Path of blob container.
 * @return filesUploaded number of files that are uploaded.
 * @throws WAStorageException
 * @throws Exception
 */
public static int upload(AbstractBuild<?, ?> build, BuildListener listener, StorageAccountInfo strAcc,
        String expContainerName, boolean cntPubAccess, boolean cleanUpContainer, String expFP, String expVP,
        List<CloudBlob> blobs) throws WAStorageException {

    CloudBlockBlob blob = null;
    int filesUploaded = 0; // Counter to track no. of files that are uploaded

    try {
        FilePath workspacePath = build.getWorkspace();
        if (workspacePath == null) {
            listener.getLogger().println(Messages.CloudStorageBuilder_ws_na());
            return filesUploaded;
        }
        StringTokenizer strTokens = new StringTokenizer(expFP, fpSeparator);
        FilePath[] paths = null;

        listener.getLogger().println(Messages.WAStoragePublisher_uploading());

        CloudBlobContainer container = WAStorageClient.getBlobContainerReference(strAcc.getStorageAccName(),
                strAcc.getStorageAccountKey(), strAcc.getBlobEndPointURL(), expContainerName, true, true,
                cntPubAccess);

        // Delete previous contents if cleanup is needed
        if (cleanUpContainer) {
            deleteContents(container);
        }

        while (strTokens.hasMoreElements()) {
            String fileName = strTokens.nextToken();

            String embeddedVP = null;

            if (fileName != null) {
                int embVPSepIndex = fileName.indexOf("::");

                // Separate fileName and Virtual directory name
                if (embVPSepIndex != -1) {
                    if (fileName.length() > embVPSepIndex + 1) {
                        embeddedVP = fileName.substring(embVPSepIndex + 2, fileName.length());

                        if (Utils.isNullOrEmpty(embeddedVP)) {
                            embeddedVP = null;
                        }

                        if (embeddedVP != null && !embeddedVP.endsWith(Utils.FWD_SLASH)) {
                            embeddedVP = embeddedVP + Utils.FWD_SLASH;
                        }
                    }
                    fileName = fileName.substring(0, embVPSepIndex);
                }
            }

            if (Utils.isNullOrEmpty(fileName)) {
                return filesUploaded;
            }

            FilePath fp = new FilePath(workspacePath, fileName);

            if (fp.exists() && !fp.isDirectory()) {
                paths = new FilePath[1];
                paths[0] = fp;
            } else {
                paths = workspacePath.list(fileName);
            }

            if (paths.length != 0) {
                for (FilePath src : paths) {
                    if (Utils.isNullOrEmpty(expVP) && Utils.isNullOrEmpty(embeddedVP)) {
                        blob = container.getBlockBlobReference(src.getName());
                    } else {
                        String prefix = expVP;

                        if (!Utils.isNullOrEmpty(embeddedVP)) {
                            if (Utils.isNullOrEmpty(expVP)) {
                                prefix = embeddedVP;
                            } else {
                                prefix = expVP + embeddedVP;
                            }
                        }
                        blob = container.getBlockBlobReference(prefix + src.getName());
                    }

                    long startTime = System.currentTimeMillis();
                    InputStream inputStream = src.read();
                    try {
                        blob.upload(inputStream, src.length(), null, getBlobRequestOptions(), null);
                    } finally {
                        try {
                            inputStream.close();
                        } catch (IOException e) {

                        }
                    }
                    long endTime = System.currentTimeMillis();
                    listener.getLogger().println(
                            "Uploaded blob with uri " + blob.getUri() + " in " + getTime(endTime - startTime));
                    blobs.add(new CloudBlob(blob.getName(),
                            blob.getUri().toString().replace("http://", "https://")));
                    filesUploaded++;
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new WAStorageException(e.getMessage(), e.getCause());
    }
    return filesUploaded;
}

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

/**
 * Admin user and user who had add topic permission create the hierarchy topic get permission to all level by default
 *
 * @param userRealm User's Realm//from w  w  w.  j  ava2 s  .c  o  m
 * @param topicId topic id
 * @param role admin role
 * @throws UserStoreException
 */
private static void grantPermissionToHierarchyLevel(UserRealm userRealm, String topicId, String role)
        throws UserStoreException {
    //tokenize resource path
    StringTokenizer tokenizer = new StringTokenizer(topicId, "/");
    StringBuilder resourcePathBuilder = new StringBuilder();
    //get token count
    int tokenCount = tokenizer.countTokens();
    int count = 0;
    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 give permission to any resource after event/topics/ in build resource path
        Matcher matcher = pattern.matcher(resourcePathBuilder.toString());
        if (matcher.find()) {
            userRealm.getAuthorizationManager().authorizeRole(role, resourcePathBuilder.toString(),
                    TreeNode.Permission.SUBSCRIBE.toString().toLowerCase());
            userRealm.getAuthorizationManager().authorizeRole(role, resourcePathBuilder.toString(),
                    TreeNode.Permission.PUBLISH.toString().toLowerCase());
            userRealm.getAuthorizationManager().authorizeRole(role, resourcePathBuilder.toString(),
                    PERMISSION_CHANGE_PERMISSION);
        }
        count++;
        if (count < tokenCount) {
            resourcePathBuilder.append("/");
        }

    }
}

From source file:org.apache.james.protocols.smtp.core.RcptCmdHandler.java

/**
 * @param session//from  w  ww  .j  a  va 2 s  .  c om
 *            SMTP session object
 * @param argument
 *            the argument passed in with the command by the SMTP client
 */
protected Response doFilterChecks(SMTPSession session, String command, String argument) {
    String recipient = null;
    if ((argument != null) && (argument.indexOf(":") > 0)) {
        int colonIndex = argument.indexOf(":");
        recipient = argument.substring(colonIndex + 1);
        argument = argument.substring(0, colonIndex);
    }
    if (session.getAttachment(SMTPSession.SENDER, State.Transaction) == null) {
        return MAIL_NEEDED;
    } else if (argument == null || !argument.toUpperCase(Locale.US).equals("TO") || recipient == null) {
        return SYNTAX_ERROR_ARGS;
    }

    recipient = recipient.trim();
    int lastChar = recipient.lastIndexOf('>');
    // Check to see if any options are present and, if so, whether they
    // are correctly formatted
    // (separated from the closing angle bracket by a ' ').
    String rcptOptionString = null;
    if ((lastChar > 0) && (recipient.length() > lastChar + 2) && (recipient.charAt(lastChar + 1) == ' ')) {
        rcptOptionString = recipient.substring(lastChar + 2);

        // Remove the options from the recipient
        recipient = recipient.substring(0, lastChar + 1);
    }
    if (session.getConfiguration().useAddressBracketsEnforcement()
            && (!recipient.startsWith("<") || !recipient.endsWith(">"))) {
        if (session.getLogger().isInfoEnabled()) {
            StringBuilder errorBuffer = new StringBuilder(192).append("Error parsing recipient address: ")
                    .append("Address did not start and end with < >")
                    .append(getContext(session, null, recipient));
            session.getLogger().info(errorBuffer.toString());
        }
        return SYNTAX_ERROR_DELIVERY;
    }
    MailAddress recipientAddress = null;
    // Remove < and >
    if (session.getConfiguration().useAddressBracketsEnforcement()
            || (recipient.startsWith("<") && recipient.endsWith(">"))) {
        recipient = recipient.substring(1, recipient.length() - 1);
    }

    if (!recipient.contains("@")) {
        // set the default domain
        recipient = recipient + "@" + getDefaultDomain();
    }

    try {
        recipientAddress = new MailAddress(recipient);
    } catch (Exception pe) {
        if (session.getLogger().isInfoEnabled()) {
            StringBuilder errorBuffer = new StringBuilder(192).append("Error parsing recipient address: ")
                    .append(getContext(session, recipientAddress, recipient)).append(pe.getMessage());
            session.getLogger().info(errorBuffer.toString());
        }
        /*
         * from RFC2822; 553 Requested action not taken: mailbox name
         * not allowed (e.g., mailbox syntax incorrect)
         */
        return SYNTAX_ERROR_ADDRESS;
    }

    if (rcptOptionString != null) {

        StringTokenizer optionTokenizer = new StringTokenizer(rcptOptionString, " ");
        while (optionTokenizer.hasMoreElements()) {
            String rcptOption = optionTokenizer.nextToken();
            int equalIndex = rcptOption.indexOf('=');
            String rcptOptionName = rcptOption;
            String rcptOptionValue = "";
            if (equalIndex > 0) {
                rcptOptionName = rcptOption.substring(0, equalIndex).toUpperCase(Locale.US);
                rcptOptionValue = rcptOption.substring(equalIndex + 1);
            }
            // Unexpected option attached to the RCPT command
            if (session.getLogger().isDebugEnabled()) {
                StringBuilder debugBuffer = new StringBuilder(128)
                        .append("RCPT command had unrecognized/unexpected option ").append(rcptOptionName)
                        .append(" with value ").append(rcptOptionValue)
                        .append(getContext(session, recipientAddress, recipient));
                session.getLogger().debug(debugBuffer.toString());
            }

            return new SMTPResponse(SMTPRetCode.PARAMETER_NOT_IMPLEMENTED,
                    "Unrecognized or unsupported option: " + rcptOptionName);
        }
        optionTokenizer = null;
    }

    session.setAttachment(CURRENT_RECIPIENT, recipientAddress, State.Transaction);

    return null;
}

From source file:com.sp.keyword_generator.UnitexParser.java

public KeywordSet parseKeywords(String s, Book ABook) {

    boolean Normier = Boolean.parseBoolean(conf.getProperty("advance.keyword.generation"));

    String line;//from w w  w.  j a v  a 2  s.  com

    if (s.compareTo("") == 0) {
        return new KeywordSet();
    }
    StringTokenizer st = new StringTokenizer(s, "\n");
    KeywordSet KeywordList = new KeywordSet();

    for (int i = 0; i < 59 && st.hasMoreElements(); i++, st.hasMoreTokens()) {

        try {
            line = st.nextToken();
        } catch (java.util.NoSuchElementException e) {
            LOG.info("No more elements");
            break;
        }

        String[] temp = line.split("\t");
        String keywordLemma = StringEscapeUtils.escapeSql(temp[1].trim());

        String weight = temp[0].trim();

        String[] ArrayStopWords = { "pre", "livre", "dit", "ISBN", "isbn", "mre", "fille", "fils",
                "famille", "homme", "femme", "histoire", "an", "anne", "premier", "dernier", "histoire",
                "vie", "jours", "fin", "jeune", "vieux", "bon", "critique.N", "mai.N", "critiques.N",
                "critiques.N", "page.N", "pages.N", "critique.A", "critiques.A", "maison d'dition", "tome",
                "commentaire", "grand", "petit", "premier", "nouveau", "certain", "dition", "tome",
                "commentaire", "diteur", "babelio", "LiliGalipette", "chose", "choses", "titre",
                "livre de poche", "BVIALLET", "Vienlivre", "nom", "lecture", "mis", "brigetoun",
                "brigittelascombe", "Evene", "null", "vincentf", "premire", "br", "diffrent", "monde",
                "diffrents", "http", "Livr" };

        ArrayList<String> Stopwords = new ArrayList<>(Arrays.asList(ArrayStopWords));

        temp = keywordLemma.split("\\.");
        String lemma = null;

        if (temp.length > 1) {
            lemma = temp[1];
        }

        String keyword = temp[0];

        if ("N".equals(lemma) || "A".equals(lemma) || (keyword.matches("^[A-Z].*") && "".equals(lemma))) {

            if (/*!Stopwords.contains(keywordLemma) && !Stopwords.contains(keyword) && */keyword != null
                    && keyword.length() > 1) {
                if (lemma.isEmpty() || "".equals(lemma)) {
                    lemma = "NP";
                }

                Keyword new_kw = new Keyword(keyword, lemma, Double.parseDouble(weight));

                if (Normier) {
                    Main.NormierKeywords.put(new_kw);
                }

                KeywordList.put(new_kw);
            }
        }
    }
    return KeywordList;
}

From source file:org.yoceflab.hybris.mailpreview.MailPreviewEmailContextFactory.java

protected void parseVariablesIntoEmailContext(final AbstractEmailContext<BusinessProcessModel> emailContext) {
    final Map<String, String> variables = getEmailContextVariables();
    if (variables != null) {
        for (final Entry<String, String> entry : variables.entrySet()) {
            final StringBuilder buffer = new StringBuilder();

            final StringTokenizer tokenizer = new StringTokenizer(entry.getValue(), "{}");
            while (tokenizer.hasMoreElements()) {
                final String token = tokenizer.nextToken();
                if (emailContext.containsKey(token)) {
                    final Object tokenValue = emailContext.get(token);
                    if (tokenValue != null) {
                        buffer.append(tokenValue.toString());
                    }//from   w ww  .  j av a 2 s.c o  m
                } else {
                    buffer.append(token);
                }
            }

            emailContext.put(entry.getKey(), buffer.toString());
        }
    }
}