Java Code Examples for java.util.StringTokenizer#nextToken()
The following examples show how to use
java.util.StringTokenizer#nextToken() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Main.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
/** * Grab a resource string and parse it into an array of strings. Assumes * comma separated list. * @param name The resource name. * @param mustExist If true, throws error if resource does not exist. If * false and resource does not exist, returns zero element array. */ protected String[] getArray(String name, boolean mustExist) { String[] result = null; String value = getString(name); if (value == null) { if (mustExist) { error("rmic.resource.not.found",name); return null; } else { return new String[0]; } } StringTokenizer parser = new StringTokenizer(value,", \t\n\r", false); int count = parser.countTokens(); result = new String[count]; for (int i = 0; i < count; i++) { result[i] = parser.nextToken(); } return result; }
Example 2
Source File: JAXBContextFactory.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
/** * The JAXB API will invoke this method via reflection */ public static JAXBContext createContext( String contextPath, ClassLoader classLoader, Map properties ) throws JAXBException { List<Class> classes = new ArrayList<Class>(); StringTokenizer tokens = new StringTokenizer(contextPath,":"); // each package should be pointing to a JAXB RI generated // content interface package. // // translate them into a list of private ObjectFactories. try { while(tokens.hasMoreTokens()) { String pkg = tokens.nextToken(); classes.add(classLoader.loadClass(pkg+IMPL_DOT_OBJECT_FACTORY)); } } catch (ClassNotFoundException e) { throw new JAXBException(e); } // delegate to the JAXB provider in the system return JAXBContext.newInstance(classes.toArray(new Class[classes.size()]),properties); }
Example 3
Source File: TimeUnit.java From netcdf-java with BSD 3-Clause "New" or "Revised" License | 6 votes |
/** * Constructor from a String. * * @param text [value] <time unit> eg "hours" or "13 hours". Time unit is from udunits. * @throws UnitException is bad format */ public TimeUnit(String text) throws UnitException { if (text == null) { this.value = 1.0; this.unitString = "secs"; this.uu = SimpleUnit.makeUnit(unitString); // always a base unit return; } StringTokenizer stoker = new StringTokenizer(text); int ntoke = stoker.countTokens(); if (ntoke == 1) { this.value = 1.0; this.unitString = stoker.nextToken(); } else if (ntoke == 2) { this.value = Double.parseDouble(stoker.nextToken()); this.unitString = stoker.nextToken(); } else throw new IllegalArgumentException("Not TimeUnit = " + text); uu = SimpleUnit.makeUnit(unitString); // always a base unit factor = uu.convertTo(1.0, SimpleUnit.secsUnit); }
Example 4
Source File: SourceMapper.java From openjdk-jdk8u with GNU General Public License v2.0 | 6 votes |
SourceMapper(String sourcepath) { /* * sourcepath can also arrive from the command line * as a String. (via "-sourcepath") * * Using File.pathSeparator as delimiter below is OK * because we are on the same machine as the command * line originiated. */ StringTokenizer st = new StringTokenizer(sourcepath, File.pathSeparator); List<String> dirList = new ArrayList<String>(); while (st.hasMoreTokens()) { String s = st.nextToken(); //XXX remove .jar and .zip files; we want only directories on //the source path. (Bug ID 4186582) if ( ! (s.endsWith(".jar") || s.endsWith(".zip"))) { dirList.add(s); } } dirs = dirList.toArray(new String[0]); }
Example 5
Source File: UnixUserGroupInformation.java From hadoop-gpu with Apache License 2.0 | 5 votes |
private static String[] executeShellCommand(String[] command) throws IOException { String groups = Shell.execCommand(command); StringTokenizer tokenizer = new StringTokenizer(groups); int numOfTokens = tokenizer.countTokens(); String[] tokens = new String[numOfTokens]; for (int i=0; tokenizer.hasMoreTokens(); i++) { tokens[i] = tokenizer.nextToken(); } return tokens; }
Example 6
Source File: AdminClan.java From L2jOrg with GNU General Public License v3.0 | 5 votes |
/** * @param activeChar * @param st * @return */ private Player getPlayer(Player activeChar, StringTokenizer st) { String val; Player player = null; if (st.hasMoreTokens()) { val = st.nextToken(); // From the HTML we receive player's object Id. if (Util.isInteger(val)) { player = World.getInstance().findPlayer(Integer.parseInt(val)); if (player == null) { activeChar.sendPacket(SystemMessageId.THAT_PLAYER_IS_NOT_ONLINE); return null; } } else { player = World.getInstance().findPlayer(val); if (player == null) { activeChar.sendPacket(SystemMessageId.NAME_IS_NOT_ALLOWED_PLEASE_CHOOSE_ANOTHER_NAME); return null; } } } else { final WorldObject targetObj = activeChar.getTarget(); if (!isPlayer(targetObj)) { activeChar.sendPacket(SystemMessageId.INVALID_TARGET); return null; } player = targetObj.getActingPlayer(); } return player; }
Example 7
Source File: PunctuationSeparator.java From djl with Apache License 2.0 | 5 votes |
/** {@inheritDoc} */ @Override public List<String> preprocess(List<String> tokens) { List<String> list = new ArrayList<>(); for (String token : tokens) { StringTokenizer tokenizer = new StringTokenizer(token, punctuations, true); while (tokenizer.hasMoreElements()) { String element = tokenizer.nextToken(); if (!element.isEmpty()) { list.add(element); } } } return list; }
Example 8
Source File: ProcessConfig.java From KEEL with GNU General Public License v3.0 | 5 votes |
/** * <p> * Sets the class member Iman with true if the next tokens in configuration file is 1; false otherwise. * parNivelSignifica is update with value 1. * </p> * @param tokens tokens recover class connected to the configuration file. * @throws SyntaxError */ void doImanDavenport(StringTokenizer tokens) throws SyntaxError { this.parSignificanceLevel = 0; if (!tokens.hasMoreTokens()) { throw new SyntaxError( "No value selected for 'Apply Iman-Davenport Derivation'"); } String tmp = tokens.nextToken(); Iman = false; if (tmp.equalsIgnoreCase("YES")) { Iman = true; parSignificanceLevel = 1; } }
Example 9
Source File: LdapReferralContext.java From jdk8u-jdk with GNU General Public License v2.0 | 5 votes |
private SearchControls overrideAttributesAndScope(SearchControls cons) { SearchControls urlCons; if ((urlScope != null) || (urlAttrs != null)) { urlCons = new SearchControls(cons.getSearchScope(), cons.getCountLimit(), cons.getTimeLimit(), cons.getReturningAttributes(), cons.getReturningObjFlag(), cons.getDerefLinkFlag()); if (urlScope != null) { if (urlScope.equals("base")) { urlCons.setSearchScope(SearchControls.OBJECT_SCOPE); } else if (urlScope.equals("one")) { urlCons.setSearchScope(SearchControls.ONELEVEL_SCOPE); } else if (urlScope.equals("sub")) { urlCons.setSearchScope(SearchControls.SUBTREE_SCOPE); } } if (urlAttrs != null) { StringTokenizer tokens = new StringTokenizer(urlAttrs, ","); int count = tokens.countTokens(); String[] attrs = new String[count]; for (int i = 0; i < count; i ++) { attrs[i] = tokens.nextToken(); } urlCons.setReturningAttributes(attrs); } return urlCons; } else { return cons; } }
Example 10
Source File: Sudoku.java From hadoop-book with Apache License 2.0 | 5 votes |
/** * Set up a puzzle board to the given size. Boards may be asymmetric, but * the squares will always be divided to be more cells wide than they are * tall. For example, a 6x6 puzzle will make sub-squares that are 3x2 (3 * cells wide, 2 cells tall). Clearly that means the board is made up of 2x3 * sub-squares. * * @param stream The input stream to read the data from */ public Sudoku(InputStream stream) throws IOException { BufferedReader file = new BufferedReader(new InputStreamReader(stream)); String line = file.readLine(); List<int[]> result = new ArrayList<int[]>(); while (line != null) { StringTokenizer tokenizer = new StringTokenizer(line); int size = tokenizer.countTokens(); int[] col = new int[size]; int y = 0; while (tokenizer.hasMoreElements()) { String word = tokenizer.nextToken(); if ("?".equals(word)) { col[y] = - 1; } else { col[y] = Integer.parseInt(word); } y += 1; } result.add(col); line = file.readLine(); } size = result.size(); board = (int[][]) result.toArray(new int[size][]); squareYSize = (int) Math.sqrt(size); squareXSize = size / squareYSize; file.close(); }
Example 11
Source File: WmsProxyController.java From geomajas-project-server with GNU Affero General Public License v3.0 | 5 votes |
/** Get the layer ID out of the request URL. * * @param request servlet request * @return layer id */ private String parseLayerId(HttpServletRequest request) { StringTokenizer tokenizer = new StringTokenizer(request.getRequestURI(), "/"); String token = ""; while (tokenizer.hasMoreTokens()) { token = tokenizer.nextToken(); } return token; }
Example 12
Source File: PhoenixEmbeddedDriver.java From phoenix with Apache License 2.0 | 4 votes |
protected static ConnectionInfo create(String url) throws SQLException { StringTokenizer tokenizer = new StringTokenizer(url == null ? "" : url.substring(PhoenixRuntime.JDBC_PROTOCOL.length()),DELIMITERS, true); int nTokens = 0; String[] tokens = new String[5]; String token = null; while (tokenizer.hasMoreTokens() && !(token=tokenizer.nextToken()).equals(TERMINATOR) && tokenizer.hasMoreTokens() && nTokens < tokens.length) { token = tokenizer.nextToken(); // This would mean we have an empty string for a token which is illegal if (DELIMITERS.contains(token)) { throw getMalFormedUrlException(url); } tokens[nTokens++] = token; } if (tokenizer.hasMoreTokens() && !TERMINATOR.equals(token)) { throw getMalFormedUrlException(url); } String quorum = null; Integer port = null; String rootNode = null; String principal = null; String keytabFile = null; int tokenIndex = 0; if (nTokens > tokenIndex) { quorum = tokens[tokenIndex++]; // Found quorum if (nTokens > tokenIndex) { try { port = Integer.parseInt(tokens[tokenIndex]); if (port < 0) { throw getMalFormedUrlException(url); } tokenIndex++; // Found port } catch (NumberFormatException e) { // No port information if (isMultiPortUrl(tokens[tokenIndex])) { throw getMalFormedUrlException(url); } } if (nTokens > tokenIndex) { if (tokens[tokenIndex].startsWith("/")) { rootNode = tokens[tokenIndex++]; // Found rootNode } if (nTokens > tokenIndex) { principal = tokens[tokenIndex++]; // Found principal if (nTokens > tokenIndex) { keytabFile = tokens[tokenIndex++]; // Found keytabFile } } } } } return new ConnectionInfo(quorum,port,rootNode, principal, keytabFile); }
Example 13
Source File: DeityweapToken.java From pcgen with GNU Lesser General Public License v2.1 | 4 votes |
@Override protected ParseResult parseTokenWithSeparator(LoadContext context, Deity deity, String value) { boolean first = true; boolean foundAny = false; boolean foundOther = false; StringTokenizer tok = new StringTokenizer(value, Constants.PIPE); while (tok.hasMoreTokens()) { String token = tok.nextToken(); CDOMReference<WeaponProf> ref; if (Constants.LST_DOT_CLEAR.equals(token)) { if (!first) { return new ParseResult.Fail( " Non-sensical " + getTokenName() + ": .CLEAR was not the first list item"); } context.getObjectContext().removeList(deity, ListKey.DEITYWEAPON); } else { if (Constants.LST_ALL.equalsIgnoreCase(token) || Constants.LST_ANY.equalsIgnoreCase(token)) { foundAny = true; ref = context.getReferenceContext().getCDOMAllReference(WEAPONPROF_CLASS); } else { foundOther = true; ref = context.getReferenceContext().getCDOMReference(WEAPONPROF_CLASS, token); } context.getObjectContext().addToList(deity, ListKey.DEITYWEAPON, ref); } first = false; } if (foundAny && foundOther) { return new ParseResult.Fail( "Non-sensical " + getTokenName() + ": Contains ANY and a specific reference: " + value); } return ParseResult.SUCCESS; }
Example 14
Source File: AbstractLauncher.java From hottub with GNU General Public License v2.0 | 4 votes |
String[] tokenizeCommand(String command, char quote) { String quoteStr = String.valueOf(quote); // easier to deal with /* * Tokenize the command, respecting the given quote character. */ StringTokenizer tokenizer = new StringTokenizer(command, quote + " \t\r\n\f", true); String quoted = null; String pending = null; List<String> tokenList = new ArrayList<String>(); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); if (quoted != null) { if (token.equals(quoteStr)) { tokenList.add(quoted); quoted = null; } else { quoted += token; } } else if (pending != null) { if (token.equals(quoteStr)) { quoted = pending; } else if ((token.length() == 1) && Character.isWhitespace(token.charAt(0))) { tokenList.add(pending); } else { throw new InternalException("Unexpected token: " + token); } pending = null; } else { if (token.equals(quoteStr)) { quoted = ""; } else if ((token.length() == 1) && Character.isWhitespace(token.charAt(0))) { // continue } else { pending = token; } } } /* * Add final token. */ if (pending != null) { tokenList.add(pending); } /* * An unclosed quote at the end of the command. Do an * implicit end quote. */ if (quoted != null) { tokenList.add(quoted); } String[] tokenArray = new String[tokenList.size()]; for (int i = 0; i < tokenList.size(); i++) { tokenArray[i] = tokenList.get(i); } return tokenArray; }
Example 15
Source File: FileMetadataRepository.java From archiva with Apache License 2.0 | 4 votes |
@Override public List<ArtifactMetadata> getArtifacts( RepositorySession session, String repoId, String namespace, String projectId, String projectVersion) throws MetadataResolutionException { try { Map<String, ArtifactMetadata> artifacts = new HashMap<>(); Path directory = getDirectory(repoId).resolve(namespace + "/" + projectId + "/" + projectVersion); Properties properties = readOrCreateProperties(directory, PROJECT_VERSION_METADATA_KEY); for (Map.Entry entry : properties.entrySet()) { String name = (String) entry.getKey(); StringTokenizer tok = new StringTokenizer(name, ":"); if (tok.hasMoreTokens() && "artifact".equals(tok.nextToken())) { String field = tok.nextToken(); String id = tok.nextToken(); ArtifactMetadata artifact = artifacts.get(id); if (artifact == null) { artifact = new ArtifactMetadata(); artifact.setRepositoryId(repoId); artifact.setNamespace(namespace); artifact.setProject(projectId); artifact.setProjectVersion(projectVersion); artifact.setVersion(projectVersion); artifact.setId(id); artifacts.put(id, artifact); } String value = (String) entry.getValue(); if ("updated".equals(field)) { artifact.setFileLastModified(Long.parseLong(value)); } else if ("size".equals(field)) { artifact.setSize(Long.valueOf(value)); } else if ("whenGathered".equals(field)) { artifact.setWhenGathered(ZonedDateTime.ofInstant(Instant.ofEpochMilli(Long.parseLong(value)), ZoneId.of("GMT"))); } else if ("version".equals(field)) { artifact.setVersion(value); } else if (field.startsWith("checksum")) { String algorithmStr = StringUtils.removeStart( name, "artifact:checksum:"+id+":"); artifact.setChecksum( ChecksumAlgorithm.valueOf( algorithmStr ), value ); } else if ("facetIds".equals(field)) { if (value.length() > 0) { String propertyPrefix = "artifact:facet:" + id + ":"; for (String facetId : value.split(",")) { MetadataFacetFactory factory = getFacetFactory(facetId); if (factory == null) { log.error("Attempted to load unknown artifact metadata facet: {}", facetId); } else { MetadataFacet facet = factory.createMetadataFacet(); String prefix = propertyPrefix + facet.getFacetId(); Map<String, String> map = new HashMap<>(); for (Object key : new ArrayList<>(properties.keySet())) { String property = (String) key; if (property.startsWith(prefix)) { map.put(property.substring(prefix.length() + 1), properties.getProperty(property)); } } facet.fromProperties(map); artifact.addFacet(facet); } } } updateArtifactFacets(artifact, properties); } } } return new ArrayList<>(artifacts.values()); } catch (IOException e) { throw new MetadataResolutionException(e.getMessage(), e); } }
Example 16
Source File: ProcessConfig.java From KEEL with GNU General Public License v3.0 | 4 votes |
/** * <p> * Output data are extracted from configuration file. * </p> * @param tokens tokens recover class connected to the configuration file. * @throws SyntaxError */ void doOutputData(StringTokenizer tokens) throws SyntaxError { if (!tokens.hasMoreTokens()) { throw new SyntaxError("OutputData no especificado"); } String linea = new String(); while (tokens.hasMoreTokens()) { linea = linea + tokens.nextToken(); } System.out.println("Procesando argumento[" + linea + "]"); String tmp; StringTokenizer tk = new StringTokenizer(linea, "\""); while (tk.hasMoreTokens()) { tmp = tk.nextToken(); tmp = tmp.trim(); if (tmp.length() > 0) { System.out.println("Nombre resultados train [" + tmp + "]"); parResultTrainName = tmp; tmp = new String(""); if (tk.hasMoreTokens()) { tmp = tk.nextToken(); tmp = tmp.trim(); } if (tmp.length() == 0) { tmp = new String("result.log"); } System.out.println("Nombre resultados test [" + tmp + "]"); parResultName = tmp; break; } } createResultFile = true; //Nuevo: Para leer mas ficheros de salida: while (tk.hasMoreTokens()) { tmp = tk.nextToken(); tmp = tmp.trim(); if (tmp.length() > 0) { outputData.add(tmp); //Anado la ruta del fichero de salida } } }
Example 17
Source File: CoordinationDemo.java From Tomcat7.0.67 with Apache License 2.0 | 4 votes |
public String[] tokenize(String line) { StringTokenizer tz = new StringTokenizer(line," "); String[] result = new String[tz.countTokens()]; for (int i=0; i<result.length; i++ ) result[i] = tz.nextToken(); return result; }
Example 18
Source File: 10528 Major Scales.java From UVA with GNU General Public License v3.0 | 4 votes |
public static void main(String[] args) throws IOException { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); String [] notes={"C","C#","D","D#","E","F","F#","G","G#","A","A#","B"}; int [] addition={2,2,1,2,2,2,1}; HashMap<String,HashMap<String,Boolean>> map=new HashMap<>(); for (int i=0;i<notes.length;i++) { map.put(notes[i],new HashMap<>()); } for (int i=0;i<notes.length;i++) { int currIndex=i; map.get(notes[i]).put(notes[i],true); for (int i2=0;i2<addition.length;i2++) { currIndex=(currIndex+addition[i2])%notes.length; map.get(notes[currIndex]).put(notes[i], true); } } String s; while (!(s=br.readLine()).equals("END")) { StringTokenizer st=new StringTokenizer(s); String [] currNodes=new String[st.countTokens()]; for (int i=0;i<currNodes.length;i++) { currNodes[i]=st.nextToken(); } Arrays.sort(currNodes); StringBuilder sb=new StringBuilder(); for (int i=0;i<notes.length;i++) { boolean allIn=true; for (int i2=0;i2<currNodes.length && allIn;i2++) { if (i2==0 || !currNodes[i2].equals(currNodes[i2-1])) { allIn=map.get(currNodes[i2]).get(notes[i])!=null; } } if (allIn) { sb.append(notes[i]); sb.append(" "); } } String disp=sb.toString(); if (disp.length()>0) { disp=disp.substring(0,disp.length()-1); } System.out.println(disp); } }
Example 19
Source File: SkillToken.java From pcgen with GNU Lesser General Public License v2.1 | 3 votes |
/** * Process the Armour Check Penalty tag. * Syntax: SKILL.%.ACPfoo,bar,baz,bot * where foo, bar, baz, and bot are strings of unfixed length. * Behavior: tests for armor check penalty interaction with this skill. * foo is printed if the skill is not affected by ACP. * bar is printed if the skill is affected by ACP. * baz is printed if the skill is only affected by ACP if the user * is untrained * bot is printed if the skill has the special weight penalty * (like Swim) * * @param aSkill The skill instance to be processed * @param property The output property supplied. * @return The ACP tag output. */ public static String getAcpOutput(Skill aSkill, String property) { final StringTokenizer aTok = new StringTokenizer(property.substring(3), ","); int numArgs = aTok.countTokens(); int acp = aSkill.getSafe(ObjectKey.ARMOR_CHECK).ordinal(); String[] acpText = new String[numArgs]; for (int i = 0; aTok.hasMoreTokens(); i++) { acpText[i] = aTok.nextToken(); } return acp < numArgs ? acpText[acp] : ""; }
Example 20
Source File: Runtime.java From openjdk-jdk9 with GNU General Public License v2.0 | 3 votes |
/** * Executes the specified string command in a separate process with the * specified environment and working directory. * * <p>This is a convenience method. An invocation of the form * {@code exec(command, envp, dir)} * behaves in exactly the same way as the invocation * {@link #exec(String[], String[], File) exec}{@code (cmdarray, envp, dir)}, * where {@code cmdarray} is an array of all the tokens in * {@code command}. * * <p>More precisely, the {@code command} string is broken * into tokens using a {@link StringTokenizer} created by the call * {@code new {@link StringTokenizer}(command)} with no * further modification of the character categories. The tokens * produced by the tokenizer are then placed in the new string * array {@code cmdarray}, in the same order. * * @param command a specified system command. * * @param envp array of strings, each element of which * has environment variable settings in the format * <i>name</i>=<i>value</i>, or * {@code null} if the subprocess should inherit * the environment of the current process. * * @param dir the working directory of the subprocess, or * {@code null} if the subprocess should inherit * the working directory of the current process. * * @return A new {@link Process} object for managing the subprocess * * @throws SecurityException * If a security manager exists and its * {@link SecurityManager#checkExec checkExec} * method doesn't allow creation of the subprocess * * @throws IOException * If an I/O error occurs * * @throws NullPointerException * If {@code command} is {@code null}, * or one of the elements of {@code envp} is {@code null} * * @throws IllegalArgumentException * If {@code command} is empty * * @see ProcessBuilder * @since 1.3 */ public Process exec(String command, String[] envp, File dir) throws IOException { if (command.length() == 0) throw new IllegalArgumentException("Empty command"); StringTokenizer st = new StringTokenizer(command); String[] cmdarray = new String[st.countTokens()]; for (int i = 0; st.hasMoreTokens(); i++) cmdarray[i] = st.nextToken(); return exec(cmdarray, envp, dir); }