List of usage examples for java.util StringTokenizer hasMoreElements
public boolean hasMoreElements()
From source file:org.owasp.dependencycheck.analyzer.CPEAnalyzer.java
/** * This method constructs a Lucene query for a given field. The searchText * is split into separate words and if the word is within the list of * weighted words then an additional weighting is applied to the term as it * is appended into the query.//from ww w . jav a 2 s.c o m * * @param sb a StringBuilder that the query text will be appended to. * @param field the field within the Lucene index that the query is * searching. * @param searchText text used to construct the query. * @param weightedText a list of terms that will be considered higher * importance when searching. * @return if the append was successful. */ private boolean appendWeightedSearch(StringBuilder sb, String field, String searchText, Set<String> weightedText) { sb.append(field).append(":("); final String cleanText = cleanseText(searchText); if (cleanText.isEmpty()) { return false; } if (weightedText == null || weightedText.isEmpty()) { LuceneUtils.appendEscapedLuceneQuery(sb, cleanText); } else { boolean addSpace = false; final StringTokenizer tokens = new StringTokenizer(cleanText); while (tokens.hasMoreElements()) { final String word = tokens.nextToken(); StringBuilder temp = null; for (String weighted : weightedText) { final String weightedStr = cleanseText(weighted); if (equalsIgnoreCaseAndNonAlpha(word, weightedStr)) { temp = new StringBuilder(word.length() + 2); LuceneUtils.appendEscapedLuceneQuery(temp, word); temp.append(WEIGHTING_BOOST); if (!word.equalsIgnoreCase(weightedStr)) { if (temp.length() > 0) { temp.append(' '); } LuceneUtils.appendEscapedLuceneQuery(temp, weightedStr); temp.append(WEIGHTING_BOOST); } break; } } if (addSpace) { sb.append(' '); } else { addSpace = true; } if (temp == null) { LuceneUtils.appendEscapedLuceneQuery(sb, word); } else { sb.append(temp); } } } sb.append(")"); return true; }
From source file:com.sfs.dao.GadgetPreferencesDAOImpl.java
/** * Rebuild the gadget preferences array order based on the string of gadget * ids./*from w w w. j a va2s . co m*/ * * @param gadgetsPreferences the gadgets preferences * @param orderVal the order string * * @return the gadgets preferences bean */ public final GadgetsPreferencesBean reorderGadgets(final GadgetsPreferencesBean gadgetsPreferences, final String orderVal) { String orderString = ""; if (orderVal != null) { orderString = orderVal; } // Tokenize string based on ',' character StringTokenizer tokenizer = new StringTokenizer(orderString, ","); int orderId = 0; // Refresh the GadgetsPreferencesBean order gadgetsPreferences.voidOrder(); while (tokenizer.hasMoreElements()) { String strGadgetId = tokenizer.nextToken(); int gadgetId = 0; try { gadgetId = Integer.parseInt(strGadgetId); } catch (Exception e) { // Error parsing gadget preference id gadgetId = 0; } if (gadgetId > 0) { // Check that the gadget preference exists if (gadgetsPreferences.hasGadgetPreference(gadgetId)) { // Gadget exists, set gadgetId/order gadgetsPreferences.addGadgetPreferenceRef(gadgetId, orderId); orderId++; } } } // Persist the GadgetsPreferencesBean order to the datastore try { final boolean success = this.persistOrder(gadgetsPreferences); if (success) { dataLogger.debug("The GadgetsPreferencesBean order was persisted"); } else { dataLogger.debug("The GadgetsPreferencesBean order could not be persisted"); } } catch (Exception e) { dataLogger.error("Error persisting GadgetsPreferencesBean order: " + e.getMessage()); } return gadgetsPreferences; }
From source file:org.gytheio.util.exec.RuntimeExec.java
/** * A comma or space separated list of values that, if returned by the executed command, * indicate an error value. This defaults to <b>"1, 2"</b>. * //from ww w . j a v a 2 s . c o m * @param errCodesStr the error codes for the execution */ public void setErrorCodes(String errCodesStr) { errCodes.clear(); StringTokenizer tokenizer = new StringTokenizer(errCodesStr, " ,"); while (tokenizer.hasMoreElements()) { String errCodeStr = tokenizer.nextToken(); // attempt to convert it to an integer try { int errCode = Integer.parseInt(errCodeStr); this.errCodes.add(errCode); } catch (NumberFormatException e) { throw new GytheioRuntimeException( "Property 'errorCodes' must be comma-separated list of integers: " + errCodesStr); } } }
From source file:henplus.commands.SQLCommand.java
/** * parses 'tablename ((AS)? alias)? [,...]' and returns a map, that maps the names (or aliases) to the tablenames. *//*from ww w .j av a 2 s. c o m*/ private Map<String, String> tableDeclParser(final String tableDecl) { final StringTokenizer tokenizer = new StringTokenizer(tableDecl, " \t\n\r\f,", true); final Map<String, String> result = new HashMap<String, String>(); String tok; String table = null; String alias = null; int state = 0; while (tokenizer.hasMoreElements()) { tok = tokenizer.nextToken(); if (tok.length() == 1 && Character.isWhitespace(tok.charAt(0))) { continue; } switch (state) { case 0: { // initial/endstate table = tok; alias = tok; state = 1; break; } case 1: { // table seen, waiting for potential alias. if ("AS".equals(tok.toUpperCase())) { state = 2; } else if (",".equals(tok)) { state = 0; // we are done. } else { alias = tok; state = 3; } break; } case 2: { // 'AS' seen, waiting definitly for alias. if (",".equals(tok)) { // error: alias missing for $table. state = 0; } else { alias = tok; state = 3; } break; } case 3: { // waiting for ',' at end of 'table (as)? alias' if (!",".equals(tok)) { // error: ',' expected. } state = 0; break; } } if (state == 0) { result.put(alias, table); } } // store any unfinished state.. if (state == 1 || state == 3) { result.put(alias, table); } else if (state == 2) { // error: alias expected for $table. } return result; }
From source file:org.springframework.security.oauth.consumer.client.CoreOAuthConsumerSupport.java
/** * Loads the OAuth parameters for the given resource at the given URL and the given token. These parameters include * any query parameters on the URL since they are included in the signature. The oauth parameters are NOT encoded. * * @param details The resource details. * @param requestURL The request URL.//from w w w . j a va 2 s. co m * @param requestToken The request token. * @param httpMethod The http method. * @param additionalParameters Additional oauth parameters (outside of the core oauth spec). * @return The parameters. */ protected Map<String, Set<CharSequence>> loadOAuthParameters(ProtectedResourceDetails details, URL requestURL, OAuthConsumerToken requestToken, String httpMethod, Map<String, String> additionalParameters) { Map<String, Set<CharSequence>> oauthParams = new TreeMap<String, Set<CharSequence>>(); if (additionalParameters != null) { for (Map.Entry<String, String> additionalParam : additionalParameters.entrySet()) { Set<CharSequence> values = oauthParams.get(additionalParam.getKey()); if (values == null) { values = new HashSet<CharSequence>(); oauthParams.put(additionalParam.getKey(), values); } if (additionalParam.getValue() != null) { values.add(additionalParam.getValue()); } } } String query = requestURL.getQuery(); if (query != null) { StringTokenizer queryTokenizer = new StringTokenizer(query, "&"); while (queryTokenizer.hasMoreElements()) { String token = (String) queryTokenizer.nextElement(); CharSequence value = null; int equalsIndex = token.indexOf('='); if (equalsIndex < 0) { token = urlDecode(token); } else { value = new QueryParameterValue(urlDecode(token.substring(equalsIndex + 1))); token = urlDecode(token.substring(0, equalsIndex)); } Set<CharSequence> values = oauthParams.get(token); if (values == null) { values = new HashSet<CharSequence>(); oauthParams.put(token, values); } if (value != null) { values.add(value); } } } String tokenSecret = requestToken == null ? null : requestToken.getSecret(); String nonce = getNonceFactory().generateNonce(); oauthParams.put(OAuthConsumerParameter.oauth_consumer_key.toString(), Collections.singleton((CharSequence) details.getConsumerKey())); if ((requestToken != null) && (requestToken.getValue() != null)) { oauthParams.put(OAuthConsumerParameter.oauth_token.toString(), Collections.singleton((CharSequence) requestToken.getValue())); } oauthParams.put(OAuthConsumerParameter.oauth_nonce.toString(), Collections.singleton((CharSequence) nonce)); oauthParams.put(OAuthConsumerParameter.oauth_signature_method.toString(), Collections.singleton((CharSequence) details.getSignatureMethod())); oauthParams.put(OAuthConsumerParameter.oauth_timestamp.toString(), Collections.singleton((CharSequence) String.valueOf(System.currentTimeMillis() / 1000))); oauthParams.put(OAuthConsumerParameter.oauth_version.toString(), Collections.singleton((CharSequence) "1.0")); String signatureBaseString = getSignatureBaseString(oauthParams, requestURL, httpMethod); OAuthSignatureMethod signatureMethod; try { signatureMethod = getSignatureFactory().getSignatureMethod(details.getSignatureMethod(), details.getSharedSecret(), tokenSecret); } catch (UnsupportedSignatureMethodException e) { throw new OAuthRequestFailedException(e.getMessage(), e); } String signature = signatureMethod.sign(signatureBaseString); oauthParams.put(OAuthConsumerParameter.oauth_signature.toString(), Collections.singleton((CharSequence) signature)); return oauthParams; }
From source file:org.jahia.data.viewhelper.principal.PrincipalViewHelper.java
/** * Create the view helper with a given string format given by the following * syntax :/*from w ww. j a v a 2s . c o m*/ * textFormat ::= (principal)? (permissions)? (provider)? (name)? (properties)? * principal ::= "Principal" * permissions ::= "Permissions" * provider ::= "Provider," size * name ::= "Name," size * properties ::= "Properties," size * size ::= number{2..n} * * @param textFormat The string format given by the above syntax. */ public PrincipalViewHelper(String[] textFormat) { for (int i = 0; i < textFormat.length; i++) { final StringTokenizer st = new StringTokenizer(textFormat[i], ","); final String fieldToDisplay = (String) st.nextElement(); if (selectBoxFieldsHeading.contains(fieldToDisplay)) { if (st.hasMoreElements()) { selectBoxFieldsSize.add(Integer.valueOf(((String) st.nextElement()).trim())); } else { selectBoxFieldsSize.add(new Integer(-1)); } try { selectBoxFieldsMethod.add(PrincipalViewHelper.class.getMethod("get" + fieldToDisplay, new Class[] { JCRNodeWrapper.class, Integer.class })); } catch (java.lang.NoSuchMethodException nsme) { logger.error("Internal class error ! Please check Jahia code", nsme); } } } }
From source file:com.sshtools.j2ssh.sftp.SftpSubsystemClient.java
/** * * * @param path/* w w w . jav a 2 s .c om*/ * * @throws IOException */ public void recurseMakeDirectory(String path) throws IOException { SftpFile file; if (path.trim().length() > 0) { try { file = openDirectory(path); file.close(); } catch (IOException ioe) { StringTokenizer tokenizer = new StringTokenizer(path, "/", true); String dir = ""; while (tokenizer.hasMoreElements()) { dir += tokenizer.nextElement(); try { file = openDirectory(dir); file.close(); } catch (IOException ioe2) { log.info("Creating " + dir); makeDirectory(dir); } } } } }
From source file:gate.creole.tokeniser.SimpleTokeniser.java
/** Parses from the given string tokeniser until it finds a specific * delimiter.// w w w . ja va 2s. c o m * One use for this method is to read everything until the first quote. * * @param st a {@link java.util.StringTokenizer StringTokenizer} that * provides the input * @param until a String representing the end delimiter. */ String parseQuotedString(StringTokenizer st, String until) throws TokeniserException { String token; if (st.hasMoreElements()) token = st.nextToken(); else return null; ///String type = ""; StringBuffer type = new StringBuffer(Gate.STRINGBUFFER_SIZE); while (!token.equals(until)) { //type += token; type.append(token); if (st.hasMoreElements()) token = st.nextToken(); else throw new InvalidRuleException("Tokeniser rule ended too soon!"); } return type.toString(); }
From source file:org.codehaus.enunciate.modules.csharp.CSharpDeploymentModule.java
@Override protected void doCompile() throws EnunciateException, IOException { File compileDir = getCompileDir(); Enunciate enunciate = getEnunciate(); String compileExecutable = getCompileExecutable(); if (getCompileExecutable() != null) { if (!enunciate.isUpToDateWithSources(compileDir)) { compileDir.mkdirs();//from ww w. j a v a 2 s. co m String compileCommand = getCompileCommand(); if (compileCommand == null) { throw new IllegalStateException( "Somehow the \"compile\" step was invoked on the C# module without a valid compile command."); } compileCommand = compileCommand.replace(' ', '\0'); //replace all spaces with the null character, so the command can be tokenized later. File dll = new File(compileDir, getDLLFileName()); File docXml = new File(compileDir, getDocXmlFileName()); File sourceFile = new File(getGenerateDir(), getSourceFileName()); compileCommand = String.format(compileCommand, compileExecutable, dll.getAbsolutePath(), docXml.getAbsolutePath(), sourceFile.getAbsolutePath()); StringTokenizer tokenizer = new StringTokenizer(compileCommand, "\0"); //tokenize on the null character to preserve the spaces in the command. List<String> command = new ArrayList<String>(); while (tokenizer.hasMoreElements()) { command.add((String) tokenizer.nextElement()); } Process process = new ProcessBuilder(command).redirectErrorStream(true).directory(compileDir) .start(); BufferedReader procReader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line = procReader.readLine(); while (line != null) { info(line); line = procReader.readLine(); } int procCode; try { procCode = process.waitFor(); } catch (InterruptedException e1) { throw new EnunciateException("Unexpected inturruption of the C# compile process."); } if (procCode != 0) { throw new EnunciateException("C# compile failed."); } enunciate.addArtifact(new FileArtifact(getName(), "csharp.assembly", dll)); if (docXml.exists()) { enunciate.addArtifact(new FileArtifact(getName(), "csharp.docs.xml", docXml)); } } else { info("Skipping C# compile because everything appears up-to-date."); } } else { debug("Skipping C# compile because a compile executale was neither found nor provided. The C# bundle will only include the sources."); } }
From source file:org.wso2.carbon.identity.provider.OpenIDProviderService.java
/** * @param openId//from w w w. j a va2 s . c o m * @param profileId * @param claimList * @return * @throws IdentityProviderException */ private OpenIDClaimDTO[] getOpenIDClaimValues(String openId, String profileId, List<String> claimList) throws IdentityProviderException { UserStoreManager userStore = null; Map<String, String> claimValues = null; OpenIDClaimDTO[] claims = null; OpenIDClaimDTO dto = null; IdentityClaimManager claimManager = null; Claim[] claimData = null; String[] claimArray = new String[claimList.size()]; String userName = null; String domainName = null; String tenantUser; UserRealm realm = null; try { userName = OpenIDUtil.getUserName(openId); } catch (MalformedURLException e) { throw new IdentityProviderException("Failed to get username from OpenID " + openId, e); } domainName = MultitenantUtils.getDomainNameFromOpenId(openId); tenantUser = MultitenantUtils.getTenantAwareUsername(userName); try { realm = IdentityTenantUtil.getRealm(domainName, userName); userStore = realm.getUserStoreManager(); claimValues = userStore.getUserClaimValues(tenantUser, claimList.toArray(claimArray), profileId); } catch (IdentityException | UserStoreException e) { throw new IdentityProviderException("Failed to get claims of user " + tenantUser, e); } String claimSeparator = claimValues.get(IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR); if (StringUtils.isNotBlank(claimSeparator)) { userAttributeSeparator = claimSeparator; } claimValues.remove(IdentityCoreConstants.MULTI_ATTRIBUTE_SEPARATOR); int i = 0; JSONArray values; claims = new OpenIDClaimDTO[claimValues.size()]; try { claimManager = IdentityClaimManager.getInstance(); claimData = claimManager.getAllSupportedClaims(realm); } catch (IdentityException e) { throw new IdentityProviderException("Failed load all supported claims", e); } for (Claim element : claimData) { if (claimValues.containsKey(element.getClaimUri())) { dto = new OpenIDClaimDTO(); values = new JSONArray(); dto.setClaimUri(element.getClaimUri()); String value = claimValues.get(element.getClaimUri()); if (userAttributeSeparator != null && value.contains(userAttributeSeparator)) { StringTokenizer st = new StringTokenizer(value, userAttributeSeparator); while (st.hasMoreElements()) { String attValue = st.nextElement().toString(); if (StringUtils.isNotBlank(attValue)) { values.add(attValue); } } } else { values.add(value); } dto.setClaimValue(values.toJSONString()); dto.setDisplayTag(element.getDisplayTag()); dto.setDescription(element.getDescription()); claims[i++] = dto; } } return claims; }