Java Code Examples for java.util.StringTokenizer

The following are top voted examples for showing how to use java.util.StringTokenizer. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: rskj   File: WorldDslProcessor.java   Source Code and License 6 votes vote down vote up
private void processBlockChainCommand(DslCommand cmd) {
    Block parent = world.getBlockByName(cmd.getArgument(0));

    int k = 1;

    while (cmd.getArgument(k) != null) {
        String name = cmd.getArgument(k);
        int difficulty = k;
        if (name != null) {
            StringTokenizer difficultyTokenizer = new StringTokenizer(name,":");
            name = difficultyTokenizer.nextToken();
            difficulty = difficultyTokenizer.hasMoreTokens()?parseDifficulty(difficultyTokenizer.nextToken(),k):k;
        }
        Block block = new BlockBuilder().difficulty(difficulty).parent(parent).build();
        BlockExecutor executor = new BlockExecutor(ConfigHelper.CONFIG, world.getRepository(),
                world.getBlockChain(), world.getBlockChain().getBlockStore(), null);
        executor.executeAndFill(block, parent);
        world.saveBlock(name, block);
        parent = block;
        k++;
    }
}
 
Example 2
Project: incubator-netbeans   File: ExtKit.java   Source Code and License 6 votes vote down vote up
protected JPopupMenu buildPopupMenu(JTextComponent target) {
    JPopupMenu pm = createPopupMenu(target);

    EditorUI ui = Utilities.getEditorUI(target);
    String settingName = ui == null || ui.hasExtComponent()
            ? "popup-menu-action-name-list" //NOI18N
            : "dialog-popup-menu-action-name-list"; //NOI18N
    
    Preferences prefs = MimeLookup.getLookup(DocumentUtilities.getMimeType(target)).lookup(Preferences.class);
    String actionNames = prefs.get(settingName, null);

    if (actionNames != null) {
        for(StringTokenizer t = new StringTokenizer(actionNames, ","); t.hasMoreTokens(); ) {
            String action = t.nextToken().trim();
            addAction(target, pm, action);
        }
    }
    
    return pm;
}
 
Example 3
Project: applecommander   File: CpmFormatDisk.java   Source Code and License 6 votes vote down vote up
/**
 * Returns a valid filename for the given filename.  The assumed rules
 * are that the name must be 8 characters long (padded on the end with
 * spaces) and alphanumeric, starting with a character.
 * @see com.webcodepro.applecommander.storage.FormattedDisk#getSuggestedFilename(java.lang.String)
 */
public String getSuggestedFilename(String filename) {
	StringTokenizer tokenizer = new StringTokenizer(filename, "."); //$NON-NLS-1$
	filename = tokenizer.nextToken();	// grab just the first part of the name..
	StringBuffer newName = new StringBuffer();
	if (!Character.isLetter(filename.charAt(0))) {
		newName.append('A');
	}
	int i=0;
	while (newName.length() < 8 && i<filename.length()) {
		char ch = filename.charAt(i);
		if (Character.isLetterOrDigit(ch) || ch == '.') {
			newName.append(ch);
		}
		i++;
	}
	while (newName.length() < 8) newName.append(' ');
	return newName.toString().toUpperCase().trim();
}
 
Example 4
Project: AppleCommander   File: CpmFormatDisk.java   Source Code and License 6 votes vote down vote up
/**
 * Returns a valid filetype for the given filename.  Rules are very
 * similar to the filename, but trim to 3 characters.
 * @see com.webcodepro.applecommander.storage.FormattedDisk#getSuggestedFiletype(java.lang.String)
 */
public String getSuggestedFiletype(String filetype) {
	StringTokenizer tokenizer = new StringTokenizer(filetype, "."); //$NON-NLS-1$
	tokenizer.nextToken();
	filetype = ""; //$NON-NLS-1$
	while (tokenizer.hasMoreTokens()) {
		filetype = tokenizer.nextToken();	// grab just the last part of the name...
	}
	StringBuffer newType = new StringBuffer();
	if (filetype.length() > 0 && !Character.isLetter(filetype.charAt(0))) {
		newType.append('A');
	}
	int i=0;
	while (newType.length() < 3 && i<filetype.length()) {
		char ch = filetype.charAt(i);
		if (Character.isLetterOrDigit(ch) || ch == '.') {
			newType.append(ch);
		}
		i++;
	}
	while (newType.length() < 3) newType.append(' ');
	return newType.toString().toUpperCase().trim();
}
 
Example 5
Project: BaseClient   File: Util.java   Source Code and License 6 votes vote down vote up
/**
 * Extract the style value from a Inkscape encoded string
 * 
 * @param style The style string to be decoded 
 * @param attribute The style attribute to retrieve 
 * @return The value for the given attribute
 */
static String extractStyle(String style, String attribute) {
	if (style == null) {
		return "";
	}
	
	StringTokenizer tokens = new StringTokenizer(style,";");
	
	while (tokens.hasMoreTokens()) {
		String token = tokens.nextToken();
		String key = token.substring(0,token.indexOf(':'));
		if (key.equals(attribute)) {
			return token.substring(token.indexOf(':')+1);
		}
	}
	
	return "";
}
 
Example 6
Project: hacker-rank   File: Jim_and_The_Others.java   Source Code and License 6 votes vote down vote up
public static void main(String ... ags)throws IOException
{
	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	int n = Integer.parseInt(in.readLine());
	int [][] arr = new int[n][2];
	for(int i=0;i<n;i++)
	{
		StringTokenizer tk = new StringTokenizer(in.readLine());
		int val = Integer.parseInt(tk.nextToken()) + Integer.parseInt(tk.nextToken());
		arr[i][0] = val;
		arr[i][1] = i+1;
	}
	Arrays.sort(arr, new Comparator<int[]>(){
		@Override
		public int compare(int[] ob1, int[] ob2)
		{
			if(ob1[0] != ob2[0])
				return ob1[0] - ob2[0];

			return ob1[1] - ob2[1];
		}
	});
	for(int[] ob : arr)
		System.out.print(ob[1]+" ");
}
 
Example 7
Project: ProyectoPacientes   File: StringUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Splits stringToSplit into a list, using the given delimiter
 * 
 * @param stringToSplit
 *            the string to split
 * @param delimiter
 *            the string to split on
 * @param trim
 *            should the split strings be whitespace trimmed?
 * 
 * @return the list of strings, split by delimiter
 * 
 * @throws IllegalArgumentException
 */
public static List<String> split(String stringToSplit, String delimiter, boolean trim) {
    if (stringToSplit == null) {
        return new ArrayList<String>();
    }

    if (delimiter == null) {
        throw new IllegalArgumentException();
    }

    StringTokenizer tokenizer = new StringTokenizer(stringToSplit, delimiter, false);

    List<String> splitTokens = new ArrayList<String>(tokenizer.countTokens());

    while (tokenizer.hasMoreTokens()) {
        String token = tokenizer.nextToken();

        if (trim) {
            token = token.trim();
        }

        splitTokens.add(token);
    }

    return splitTokens;
}
 
Example 8
Project: incubator-netbeans   File: NativeDiff.java   Source Code and License 6 votes vote down vote up
private String[] prepareCommand(String firstFile, String secondFile) {
    StringTokenizer tok = new StringTokenizer(diffcmd);
    int tokensCount = tok.countTokens();
    String[] cmdarray = new String[tokensCount];
    for(int i=0;i<tokensCount;i++) {
        String token = tok.nextToken();
        if (token.equals("%TESTFILE%")) {
            cmdarray[i] = firstFile;
        } else if (token.equals("%PASSFILE%")) {
            cmdarray[i] = secondFile;
        } else {
            cmdarray[i] = token;
        }
    }
    return cmdarray;
}
 
Example 9
Project: GitHub   File: NanoHTTPD.java   Source Code and License 6 votes vote down vote up
protected Map<String, List<String>> decodeParameters(String queryString) {
    Map<String, List<String>> parms = new HashMap<String, List<String>>();
    if (queryString != null) {
        StringTokenizer st = new StringTokenizer(queryString, "&");
        while (st.hasMoreTokens()) {
            String e = st.nextToken();
            int sep = e.indexOf('=');
            try {
                String propertyName = (sep >= 0) ? decodePercent(
                        e.substring(0, sep)).trim() : decodePercent(e)
                        .trim();
                if (!parms.containsKey(propertyName)) {
                    parms.put(propertyName, new ArrayList<String>());
                }
                String propertyValue = (sep >= 0) ? decodePercent(e
                        .substring(sep + 1)) : null;
                if (propertyValue != null) {
                    parms.get(propertyName).add(propertyValue);
                }
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        }
    }
    return parms;
}
 
Example 10
Project: incubator-netbeans   File: TopLogging.java   Source Code and License 6 votes vote down vote up
/** Scans path list for something that can be added to classpath.
 * @param extensions null or path list
 * @param sb buffer to put results to
 */
private static void findBootJars(final String extensions, final StringBuffer sb) {
    if (extensions != null) {
        for (StringTokenizer st = new StringTokenizer(extensions, File.pathSeparator); st.hasMoreTokens();) {
            File dir = new File(st.nextToken());
            File[] entries = dir.listFiles();
            if (entries != null) {
                for (int i = 0; i < entries.length; i++) {
                    String name = entries[i].getName().toLowerCase(Locale.US);
                    if (name.endsWith(".zip") || name.endsWith(".jar")) { // NOI18N
                        if (sb.length() > 0) {
                            sb.append(File.pathSeparatorChar);
                        }
                        sb.append(entries[i].getPath());
                    }
                }
            }
        }
    }
}
 
Example 11
Project: OpenVertretung   File: StringUtils.java   Source Code and License 6 votes vote down vote up
/**
 * Splits stringToSplit into a list, using the given delimiter
 * 
 * @param stringToSplit
 *            the string to split
 * @param delimiter
 *            the string to split on
 * @param trim
 *            should the split strings be whitespace trimmed?
 * 
 * @return the list of strings, split by delimiter
 * 
 * @throws IllegalArgumentException
 */
public static List<String> split(String stringToSplit, String delimiter, boolean trim) {
    if (stringToSplit == null) {
        return new ArrayList<String>();
    }

    if (delimiter == null) {
        throw new IllegalArgumentException();
    }

    StringTokenizer tokenizer = new StringTokenizer(stringToSplit, delimiter, false);

    List<String> splitTokens = new ArrayList<String>(tokenizer.countTokens());

    while (tokenizer.hasMoreTokens()) {
        String token = tokenizer.nextToken();

        if (trim) {
            token = token.trim();
        }

        splitTokens.add(token);
    }

    return splitTokens;
}
 
Example 12
Project: incubator-netbeans   File: ToolTipManagerEx.java   Source Code and License 6 votes vote down vote up
private static Dimension parseDimension(String s) {
    StringTokenizer st = new StringTokenizer(s, ","); // NOI18N

    int arr[] = new int[2];
    int i = 0;
    while (st.hasMoreElements()) {
        if (i > 1) {
            return null;
        }
        try {
            arr[i] = Integer.parseInt(st.nextToken());
        } catch (NumberFormatException nfe) {
            LOG.log(Level.WARNING, null, nfe);
            return null;
        }
        i++;
    }
    if (i != 2) {
        return null;
    } else {
        return new Dimension(arr[0], arr[1]);
    }
}
 
Example 13
Project: doctemplate   File: PropertyUtils.java   Source Code and License 6 votes vote down vote up
public static Class<?> getNestedPropertyType(Class<?> clazz, String nestedProperty)
		throws IllegalArgumentException, SecurityException, IntrospectionException,
		NoSuchMethodException {
	Class<?> propertyType = null;
	StringTokenizer st = new StringTokenizer(nestedProperty, ".", false);
	while (st.hasMoreElements() && clazz != null) {
		String nam = (String) st.nextElement();
		Method readMethod = getReadMethod(clazz, nam);
		if (readMethod != null) {
			if (st.hasMoreElements()) {
				clazz = readMethod.getReturnType();
			}
			else {
				propertyType = readMethod.getReturnType();
			}
		}
		else {
			while (st.hasMoreElements()) {
				st.nextElement(); // use remaining tokens
			}
		}
	}
	return propertyType;
}
 
Example 14
Project: MetadataEditor   File: AbstractFrameBodyPairs.java   Source Code and License 6 votes vote down vote up
/**
 * Set the text, decoded as pairs of involvee - involvement
 *
 * @param text
 */
public void setText(String text)
{
    PairedTextEncodedStringNullTerminated.ValuePairs value = new PairedTextEncodedStringNullTerminated.ValuePairs();
    StringTokenizer stz = new StringTokenizer(text, "\0");

    while (stz.hasMoreTokens())
    {
        String key =stz.nextToken();
        if(stz.hasMoreTokens())
        {
            value.add(key, stz.nextToken());
        }
        
    }
    setObjectValue(DataTypes.OBJ_TEXT, value);
}
 
Example 15
Project: doctemplate   File: PropertyUtils.java   Source Code and License 6 votes vote down vote up
public static Object getNestedProperty(Object bean, String nestedProperty)
		throws IllegalArgumentException, SecurityException, IllegalAccessException,
		InvocationTargetException, IntrospectionException, NoSuchMethodException {
	Object object = null;
	StringTokenizer st = new StringTokenizer(nestedProperty, ".", false);
	while (st.hasMoreElements() && bean != null) {
		String nam = (String) st.nextElement();
		if (st.hasMoreElements()) {
			bean = getProperty(bean, nam);
		}
		else {
			object = getProperty(bean, nam);
		}
	}
	return object;
}
 
Example 16
Project: ActiveMQ-JWT-Authentication-Plugin   File: JWTAuthenticationPlugin.java   Source Code and License 6 votes vote down vote up
@Override
public Broker installPlugin(Broker parent) throws Exception {

    logger.info("Initialize JWTAuthenticationPlugin");

    Set<Principal> groups = new HashSet();
    StringTokenizer iter = new StringTokenizer(this.defaultUserGroups, ",");
    while (iter.hasMoreTokens()) {
        String name = iter.nextToken().trim();
        groups.add(new GroupPrincipal(name));
    }
    JaasAuthenticationPlugin jaasAuthenticationPlugin = new JaasAuthenticationPlugin();
    jaasAuthenticationPlugin.setConfiguration(this.jaasConfiguration);
    jaasAuthenticationPlugin.setDiscoverLoginConfig(this.discoverLoginConfig);
    Broker jaasAuthenticationFallbackBroker = jaasAuthenticationPlugin.installPlugin(parent);
    return new JWTAuthenticationBroker(
            parent, jaasAuthenticationFallbackBroker, this.defaultUser,
            groups, this.masterSecretKey, this.tokenHeader);
}
 
Example 17
Project: openjdk-jdk10   File: MimeTable.java   Source Code and License 6 votes vote down vote up
void parse(String pair, MimeEntry entry) {
    // REMIND add exception handling...
    String name = null;
    String value = null;

    boolean gotName = false;
    StringTokenizer tokenizer = new StringTokenizer(pair, "=");
    while (tokenizer.hasMoreTokens()) {
        if (gotName) {
            value = tokenizer.nextToken().trim();
        }
        else {
            name = tokenizer.nextToken().trim();
            gotName = true;
        }
    }

    fill(entry, name, value);
}
 
Example 18
Project: hacker-rank   File: Fair_Rations.java   Source Code and License 6 votes vote down vote up
public static void main(String ... ags)throws IOException
{
	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	int n = Integer.parseInt(in.readLine());
	StringTokenizer tk = new StringTokenizer(in.readLine());
	TreeSet<Integer> ts = new TreeSet<>();
	for(int i=0;i<n;i++)
	{
		int val = Integer.parseInt(tk.nextToken());
		if(val%2 != 0)
			ts.add(i);
	}
	if(ts.size()%2 != 0)
		System.out.println("NO");
	else
	{
		int res = 0;
		while(ts.size() != 0)
		{
			int a = ts.pollFirst();
			int b = ts.pollFirst();
			res += (b-a-1)*2 + 2;
		}
		System.out.println(res);
	}
}
 
Example 19
Project: openNaEF   File: SuperHubTelnetUtil.java   Source Code and License 6 votes vote down vote up
public String[] getTrapReceiverAddresses(ConsoleAccess telnet)
        throws IOException, AbortedException {
    StringTokenizer st = this.getResults(telnet, "show snmp-server traps");
    Matcher matcher;
    LinkedList<String> list = new LinkedList<String>();

    while (st.hasMoreTokens()) {
        matcher = trapReceiverPattern.matcher(st.nextToken());
        if (matcher.matches()) {
            list.add(matcher.group(1));
        }
    }
    if (list.size() == 0)
        return (new String[0]);
    return list.toArray(new String[0]);
}
 
Example 20
Project: neoscada   File: InfrastructureActionBarContributor.java   Source Code and License 6 votes vote down vote up
/**
 * This extracts those actions in the <code>submenuActions</code> collection whose text is qualified and returns
 * a map of these actions, keyed by submenu text.
 * <!-- begin-user-doc -->
 * <!-- end-user-doc -->
 * @generated
 */
protected Map<String, Collection<IAction>> extractSubmenuActions ( Collection<IAction> createActions )
{
    Map<String, Collection<IAction>> createSubmenuActions = new LinkedHashMap<String, Collection<IAction>> ();
    if ( createActions != null )
    {
        for ( Iterator<IAction> actions = createActions.iterator (); actions.hasNext (); )
        {
            IAction action = actions.next ();
            StringTokenizer st = new StringTokenizer ( action.getText (), "|" ); //$NON-NLS-1$
            if ( st.countTokens () == 2 )
            {
                String text = st.nextToken ().trim ();
                Collection<IAction> submenuActions = createSubmenuActions.get ( text );
                if ( submenuActions == null )
                {
                    createSubmenuActions.put ( text, submenuActions = new ArrayList<IAction> () );
                }
                action.setText ( st.nextToken ().trim () );
                submenuActions.add ( action );
                actions.remove ();
            }
        }
    }
    return createSubmenuActions;
}
 
Example 21
Project: OpenCV   File: StaticHelper.java   Source Code and License 6 votes vote down vote up
private static boolean initOpenCVLibs(String Libs)
{
    Log.d(TAG, "Trying to init OpenCV libs");

    boolean result = true;

    if ((null != Libs) && (Libs.length() != 0))
    {
        Log.d(TAG, "Trying to load libs by dependency list");
        StringTokenizer splitter = new StringTokenizer(Libs, ";");
        while(splitter.hasMoreTokens())
        {
            result &= loadLibrary(splitter.nextToken());
        }
    }
    else
    {
        // If dependencies list is not defined or empty.
        result &= loadLibrary("opencv_java3");
    }

    return result;
}
 
Example 22
Project: incubator-netbeans   File: BinaryFS.java   Source Code and License 6 votes vote down vote up
/** Finds a file given its full resource path.
 * @param name the resource path, e.g. "dir/subdir/file.ext" or "dir/subdir" or "dir"
 * @return a file object with the given path or
 *   <CODE>null</CODE> if no such file exists
 *
 */
@Override
public FileObject findResource(String name) {
    if (name.length () == 0) {
        return root;
    }

    StringTokenizer st = new StringTokenizer(name, "/");
    FileObject fo = root;
    while (fo != null && st.hasMoreTokens()) {
        String next = st.nextToken();
        fo = fo.getFileObject(next, null); // XXX ??
    }

    return fo;
}
 
Example 23
Project: OpenJSharp   File: RuntimeModeler.java   Source Code and License 6 votes vote down vote up
/**
 * gets the namespace <code>String</code> for a given <code>packageName</code>
 * @param packageName the name of the package used to find a namespace.
 *      can be empty.
 * @return the namespace for the specified <code>packageName</code>
 */
public static String getNamespace(@NotNull String packageName) {
    if (packageName.length() == 0)
        return null;

    StringTokenizer tokenizer = new StringTokenizer(packageName, ".");
    String[] tokens;
    if (tokenizer.countTokens() == 0) {
        tokens = new String[0];
    } else {
        tokens = new String[tokenizer.countTokens()];
        for (int i=tokenizer.countTokens()-1; i >= 0; i--) {
            tokens[i] = tokenizer.nextToken();
        }
    }
    StringBuilder namespace = new StringBuilder("http://");
    for (int i=0; i<tokens.length; i++) {
        if (i!=0)
            namespace.append('.');
        namespace.append(tokens[i]);
    }
    namespace.append('/');
    return namespace.toString();
}
 
Example 24
Project: jDialects   File: DDLFormatter.java   Source Code and License 6 votes vote down vote up
private String formatAlterTable(String sql) {
	final StringBuilder result = new StringBuilder(60).append(INITIAL_LINE);
	final StringTokenizer tokens = new StringTokenizer(sql, " (,)'[]\"", true);

	boolean quoted = false;
	while (tokens.hasMoreTokens()) {
		final String token = tokens.nextToken();
		if (isQuote(token)) {
			quoted = !quoted;
		} else if (!quoted) {
			if (isBreak(token)) {
				result.append(OTHER_LINES);
			}
		}
		result.append(token);
	}

	return result.toString();
}
 
Example 25
Project: incubator-netbeans   File: NativeProcessBuilderTest.java   Source Code and License 6 votes vote down vote up
private String findComand(String command) {
    ArrayList<String> list = new ArrayList<>();
    String path = System.getenv("PATH"); // NOI18N
    if (path != null) {
        StringTokenizer st = new StringTokenizer(path, File.pathSeparator); // NOI18N
        while (st.hasMoreTokens()) {
            String dir = st.nextToken();
            list.add(dir);
        }
    } else {
        list.add("C:/WINDOWS/System32"); // NOI18N
        list.add("C:/WINDOWS"); // NOI18N
        list.add("C:/cygwin/bin"); // NOI18N
    }
    for (String p : list) {
        String task = p + File.separatorChar + command;
        File tool = new File(task);
        if (tool.exists() && tool.isFile()) {
            return tool.getAbsolutePath();
        }
    }
    return null;
}
 
Example 26
Project: hadoop   File: WordStandardDeviation.java   Source Code and License 6 votes vote down vote up
/**
 * Emits 3 key-value pairs for counting the word, its length, and the
 * squares of its length. Outputs are (Text, LongWritable).
 * 
 * @param value
 *          This will be a line of text coming in from our input file.
 */
public void map(Object key, Text value, Context context)
    throws IOException, InterruptedException {
  StringTokenizer itr = new StringTokenizer(value.toString());
  while (itr.hasMoreTokens()) {
    String string = itr.nextToken();

    this.wordLen.set(string.length());

    // the square of an integer is an integer...
    this.wordLenSq.set((long) Math.pow(string.length(), 2.0));

    context.write(LENGTH, this.wordLen);
    context.write(SQUARE, this.wordLenSq);
    context.write(COUNT, ONE);
  }
}
 
Example 27
Project: unitimes   File: ExternalUidLookup.java   Source Code and License 6 votes vote down vote up
public String getMiddleName() {
	if (iMiddleName != null) return iMiddleName;
	if (iName != null) {
        StringTokenizer s = new StringTokenizer(iName);
        if (s.countTokens() > 2) {
        	s.nextToken();
        	String m = "";
        	while (true) {
        		String n = s.nextToken();
        		if (!s.hasMoreTokens()) break;
        		m += (m.isEmpty() ? "" : " ") + n;
        	}
        	return m;
        }
	}
	return "";
}
 
Example 28
Project: incubator-netbeans   File: ActionMappings.java   Source Code and License 6 votes vote down vote up
@Override
protected MappingWrapper doUpdate() {
    MappingWrapper wr = super.doUpdate();
    if (wr != null) {
        String text = txtGoals.getText();
        StringTokenizer tok = new StringTokenizer(text, " "); //NOI18N
        NetbeansActionMapping mapp = wr.getMapping();
        List<String> goals = new ArrayList<String>();
        while (tok.hasMoreTokens()) {
            String token = tok.nextToken();
            goals.add(token);
        }
        mapp.setGoals(goals);
        if (handle != null) {
            handle.markAsModified(getActionMappings());
        }
    }
    return wr;
}
 
Example 29
Project: MOAAP   File: StaticHelper.java   Source Code and License 6 votes vote down vote up
private static boolean initOpenCVLibs(String Libs)
{
    Log.d(TAG, "Trying to init OpenCV libs");

    boolean result = true;

    if ((null != Libs) && (Libs.length() != 0))
    {
        Log.d(TAG, "Trying to load libs by dependency list");
        StringTokenizer splitter = new StringTokenizer(Libs, ";");
        while(splitter.hasMoreTokens())
        {
            result &= loadLibrary(splitter.nextToken());
        }
    }
    else
    {
        // If dependencies list is not defined or empty.
        result &= loadLibrary("opencv_java3");
    }

    return result;
}
 
Example 30
Project: gate-core   File: OptionsMap.java   Source Code and License 6 votes vote down vote up
/**
 * If the object stored under key is a Font then returns its value
 * otherwise returns null.
 * @param key key associated to the value to retrieve
 * @return the associated font
 */
public Font getFont(Object key) {
  try {
    String stringValue = (String) get(key);
    if (stringValue == null) { return null; }
    StringTokenizer strTok = new StringTokenizer(stringValue, "#", false);
    String family = strTok.nextToken();
    int size = Integer.parseInt(strTok.nextToken());
    boolean italic = Boolean.valueOf(strTok.nextToken());
    boolean bold = Boolean.valueOf(strTok.nextToken());
    HashMap<TextAttribute, Serializable> fontAttrs =
      new HashMap<TextAttribute, Serializable>();
    fontAttrs.put(TextAttribute.FAMILY, family);
    fontAttrs.put(TextAttribute.SIZE, (float) size);
    if(bold) fontAttrs.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_BOLD);
    else fontAttrs.put(TextAttribute.WEIGHT, TextAttribute.WEIGHT_REGULAR);
    if(italic) fontAttrs.put(
      TextAttribute.POSTURE, TextAttribute.POSTURE_OBLIQUE);
    else fontAttrs.put(TextAttribute.POSTURE, TextAttribute.POSTURE_REGULAR);
    return new Font(fontAttrs);
  } catch (Exception e) {
    return null;
  }
}
 
Example 31
Project: openNaEF   File: SuperHubTelnetUtil.java   Source Code and License 6 votes vote down vote up
public String getOSVersion(ConsoleAccess telnet) throws IOException,
        AbortedException {
    StringTokenizer st = this.getResults(telnet, "show version");
    Matcher matcher;
    String version = null;
    String edition = null;

    while (st.hasMoreTokens()) {
        matcher = versionPattern.matcher(st.nextToken());
        if (matcher.matches()) {
            version = matcher.group(1);
            break;
        }
    }
    if (version == null)
        throw new IOException("parse failed");

    while (st.hasMoreTokens()) {
        matcher = editionPattern.matcher(st.nextToken());
        if (matcher.matches()) {
            edition = matcher.group(1);
            return version + " Ed" + edition;
        }
    }
    throw new IOException("parse failed");
}
 
Example 32
Project: non-dominated-sorting   File: IdUtils.java   Source Code and License 6 votes vote down vote up
public static String factorize(String s, String factor) {
    StringBuilder rv = new StringBuilder();
    boolean first = true;
    StringTokenizer st = new StringTokenizer(s, ".");
    while (st.hasMoreTokens()) {
        String token = st.nextToken();
        if (!token.startsWith(factor) || (token.length() != factor.length() && !Character.isDigit(token.charAt(factor.length())))) {
            if (first) {
                first = false;
            } else {
                rv.append('.');
            }
            rv.append(token);
        }
    }
    return rv.toString();
}
 
Example 33
Project: javaide   File: PrintingProcessor.java   Source Code and License 6 votes vote down vote up
private void printDocComment(Element e) {
    String docComment = elementUtils.getDocComment(e);

    if (docComment != null) {
        // Break comment into lines
        StringTokenizer st = new StringTokenizer(docComment,
                                                          "\n\r");
        indent();
        writer.println("/**");

        while(st.hasMoreTokens()) {
            indent();
            writer.print(" *");
            writer.println(st.nextToken());
        }

        indent();
        writer.println(" */");
    }
}
 
Example 34
Project: alfresco-remote-api   File: WebDAVHelper.java   Source Code and License 6 votes vote down vote up
/**
 * Split the path into all the component directories and filename
 * 
 * @param path          the string to split
 * @return              an array of all the path components
 */
public List<String> splitAllPaths(String path)
{
    if (path == null || path.length() == 0)
    {
        return Collections.emptyList();
    }

    // split the path
    StringTokenizer token = new StringTokenizer(path, PathSeperator);
    List<String> results = new ArrayList<String>(10);
    while (token.hasMoreTokens())
    {
        results.add(token.nextToken());
    }
    return results;
}
 
Example 35
Project: Computer-Science-1   File: DataHandler.java   Source Code and License 6 votes vote down vote up
/**
 * Calculates all data required.
 */
void calculate() {
    // Break user input into the three variables
    StringTokenizer st = new StringTokenizer(this.userInput, " ");
    try {
        this.grossPay = Double.parseDouble(st.nextToken());
        this.savingsRate = Double.parseDouble(st.nextToken());
        this.iraRate = Double.parseDouble(st.nextToken());
    } catch (NumberFormatException | NoSuchElementException e) {
        // In case the user enters gibberish or nothing at all
        System.exit(-1);
    }

    // Calculate savings and IRA investment
    this.savingsAmount = grossPay * (savingsRate / 100.0);
    this.iraAmount = grossPay * (iraRate / 100.0);
    this.totalAmount = this.savingsAmount + this.iraAmount;
}
 
Example 36
Project: incubator-netbeans   File: ModuleTargetChooserPanel.java   Source Code and License 6 votes vote down vote up
private boolean isValidModule (FileObject root, final String path) {
    //May be null when nothing selected in the GUI.
    if (root == null) {
        return false;
    }
    if (path == null) {
        return false;
    }
    final StringTokenizer st = new StringTokenizer(path,".");   //NOI18N
    while (st.hasMoreTokens()) {
        root = root.getFileObject(st.nextToken());
        if (root == null) {
            return true;
        }
        else if (root.isData()) {
            return false;
        }
    }
    return true;
}
 
Example 37
Project: aliyun-maxcompute-data-collectors   File: SQLServerUpdateDBExecThread.java   Source Code and License 6 votes vote down vote up
/**
 * Initialize the writer thread with Job Configuration
 */
@Override
public void initialize(Configuration conf) throws IOException {
  super.initialize(conf);

  // Get the update columns
  String updateKeyColumns =
    conf.get(ExportJobBase.SQOOP_EXPORT_UPDATE_COL_KEY);

  Set<String> updateKeys = new LinkedHashSet<String>();
  StringTokenizer stok = new StringTokenizer(updateKeyColumns, ",");
  while (stok.hasMoreTokens()) {
    String nextUpdateKey = stok.nextToken().trim();
    if (nextUpdateKey.length() > 0) {
      updateKeys.add(nextUpdateKey);
    } else {
      throw new RuntimeException("Invalid update key column value specified"
          + ": '" + updateKeyColumns + "'");
    }
  }

  updateCols = updateKeys.toArray(new String[updateKeys.size()]);
}
 
Example 38
Project: sentry   File: MessageSplitter.java   Source Code and License 5 votes vote down vote up
private List<String> splitString(String str, int maxLength) {
    List<String> splits = new ArrayList<>();
    String codeBlock = "```";
    StringTokenizer tokenizer = new StringTokenizer(str, "\n", true);
    StringBuilder builder = new StringBuilder();
    boolean hasUnmatchedCodeBlock = false;
    while (tokenizer.hasMoreTokens()) {
        String line = tokenizer.nextToken();
        if (builder.length() > 0 && builder.length() + line.length() > maxLength - (hasUnmatchedCodeBlock ? codeBlock.length() : 0)) {
            if (hasUnmatchedCodeBlock) {
                builder.append(codeBlock);
            }
            splits.add(builder.toString());
            builder = new StringBuilder();
            if (hasUnmatchedCodeBlock) {
                builder.append(codeBlock).append('\n');
            }
        }
        if (line.contains(codeBlock)) {
            hasUnmatchedCodeBlock = !hasUnmatchedCodeBlock;
        }
        builder.append(line);
    }
    if (builder.length() > maxLength) {
        splits.addAll(splitString(WordUtils.wrap(builder.toString(), maxLength), maxLength));
    } else {
        splits.add(builder.toString());
    }
    return splits;
}
 
Example 39
Project: incubator-netbeans   File: NbInstaller.java   Source Code and License 5 votes vote down vote up
private static void createBootClassPath(List<String> l) {
    // boot
    String boot = System.getProperty("sun.boot.class.path"); // NOI18N
    if (boot != null) {
        StringTokenizer tok = new StringTokenizer(boot, File.pathSeparator);
        while (tok.hasMoreTokens()) {
            l.add(tok.nextToken());
        }
    }
    
    // std extensions
    String extensions = System.getProperty("java.ext.dirs"); // NOI18N
    if (extensions != null) {
        for (StringTokenizer st = new StringTokenizer(extensions, File.pathSeparator); st.hasMoreTokens();) {
            File dir = new File(st.nextToken());
            File[] entries = dir.listFiles();
            if (entries != null) {
                for (File f : entries) {
                    String name = f.getName().toLowerCase(Locale.US);
                    if (name.endsWith(".zip") || name.endsWith(".jar")) { // NOI18N
                        l.add(f.getAbsolutePath());
                    }
                }
            }
        }
    }
}
 
Example 40
Project: parabuild-ci   File: ZaurusEditor.java   Source Code and License 5 votes vote down vote up
private String[] getWords() {

        StringTokenizer tokenizer =
            new StringTokenizer(fSearchWords.getText());
        String[] result = new String[tokenizer.countTokens()];
        int      i      = 0;

        while (tokenizer.hasMoreTokens()) {
            result[i++] = tokenizer.nextToken();
        }    // end of while ((tokenizer.hasMoreTokens()))

        return result;
    }
 
Example 41
Project: headb   File: HSQLFormatter.java   Source Code and License 5 votes vote down vote up
public FormatProcess(String sql) {
  tokens = new StringTokenizer(
      sql,
      "()+*/-=<>'`\"[]," + WHITESPACE,
      true
  );
}
 
Example 42
Project: incubator-netbeans   File: PropertyType_Dimension.java   Source Code and License 5 votes vote down vote up
public void setCustomizerValue() {
    DimensionCustomEditorOperator customizer = new DimensionCustomEditorOperator(propertyCustomizer);

    StringTokenizer st = new StringTokenizer(propertyValue_L, ", ");
    int x = st.countTokens();
    
    if(x>2)
        throw new JemmyException("ERROR: DimensionPointCustomizer.setValue(\""+propertyValue_L+"\") - {number values="+x+"}.");
    
    customizer.setDimensionValue(st.nextToken(), st.nextToken());
}
 
Example 43
Project: gw4e.project   File: EdgeFigure.java   Source Code and License 5 votes vote down vote up
private String stripSource (String source) {
	if (source==null) return null;
	String ret  =  "";
	StringTokenizer st = new StringTokenizer(source,"\r\n");
	int max = PreferenceManager.getMaxRowInTooltip();
	int index = 1;
	while (st.hasMoreTokens()) {
		ret = ret + st.nextToken();
		if (index>=max) return ret;
		ret = ret+"\r\n";
		index++;
	}
	return ret;
}
 
Example 44
Project: parabuild-ci   File: URLClassPathRepository.java   Source Code and License 5 votes vote down vote up
/**
 * Add components of system classpath.
 * @throws IOException
 */
public void addSystemClasspathComponents() throws IOException {
	String systemClassPath = ClassPath.getClassPath();
	StringTokenizer tok = new StringTokenizer(systemClassPath, File.pathSeparator);
	while (tok.hasMoreTokens()) {
		String entryName = tok.nextToken();
		try {
			urlClassPath.addURL(entryName);
		}
		catch (IOException e) {
			System.err.println("Warning: couldn't add path to classpath: " + entryName);
		}
	}
}
 
Example 45
Project: OpenJSharp   File: SymbolTable.java   Source Code and License 5 votes vote down vote up
/**
 * Exclude a series of namespaces given by a list of whitespace
 * separated namespace prefixes.
 */
public void excludeNamespaces(String prefixes) {
    if (prefixes != null) {
        StringTokenizer tokens = new StringTokenizer(prefixes);
        while (tokens.hasMoreTokens()) {
            final String prefix = tokens.nextToken();
            final String uri;
            if (prefix.equals("#default"))
                uri = lookupNamespace(Constants.EMPTYSTRING);
            else
                uri = lookupNamespace(prefix);
            if (uri != null) excludeURI(uri);
        }
    }
}
 
Example 46
Project: geomapapp   File: GridderZW.java   Source Code and License 5 votes vote down vote up
public XGrid_ZW getGrid(String name) throws IOException {
	StringTokenizer st = new StringTokenizer(name, "WESN_.", true);
	int x0 = (st.nextToken().equals("E")) ? 1 : -1;
	x0 *= Integer.parseInt(st.nextToken());
	int y0 = (st.nextToken().equals("N")) ? 1 : -1;
	y0 *= Integer.parseInt(st.nextToken());
	st.nextToken();
	return getGrid(x0*gridSize, y0*gridSize);
}
 
Example 47
Project: Krine   File: StringUtil.java   Source Code and License 5 votes vote down vote up
public static String[] split(String s, String delim) {
    List<String> v = new ArrayList<>();
    StringTokenizer st = new StringTokenizer(s, delim);
    while (st.hasMoreTokens())
        v.add(st.nextToken());
    return v.toArray(new String[0]);
}
 
Example 48
Project: Yass   File: YassHyphenator.java   Source Code and License 5 votes vote down vote up
/**
 * Description of the Method
 *
 * @param txt Description of the Parameter
 * @return Description of the Return Value
 */
public String hyphenateText(String txt) {
    StringTokenizer st = new StringTokenizer(txt, "\n");
    StringBuilder sb = new StringBuilder();
    while (st.hasMoreTokens()) {
        String line = st.nextToken();
        StringTokenizer st2 = new StringTokenizer(line, " ");
        boolean first = true;
        while (st2.hasMoreTokens()) {
            String word = st2.nextToken();
            word = word.replaceAll("-", "");
            word = word.replace(YassRow.SPACE, ' ');
            word = word.replace(YassRow.HYPHEN, '-');

            //System.out.print("word "+word+" ");
            word = hyphenator.hyphenate(word, 2, 2);
            //System.out.println(word);
            word = word.replace('-', YassRow.HYPHEN);
            word = word.replace(' ', YassRow.SPACE);
            word = word.replace('\u00ad', '-');
            word = word.replaceAll("\u200b", "");

            if (first) {
                first = false;
            } else {
                sb.append(" ");
            }
            sb.append(word);
        }
        sb.append("\n");
    }
    return sb.toString();
}
 
Example 49
Project: VASSAL-src   File: VisibilityOption.java   Source Code and License 5 votes vote down vote up
public void setValue(String in) {
  StringTokenizer st = new StringTokenizer(in,"\t");
  super.setValue(st.nextToken());
  if (st.hasMoreTokens()) {
    isVisible = "true".equals(st.nextToken());
  }
  else {
    isVisible = true;
  }
  theFrame.setVisible(isVisible);
}
 
Example 50
Project: ramus   File: IDLImporter.java   Source Code and License 5 votes vote down vote up
private String getLastWord(String string) {
    String res = null;
    StringTokenizer st = new StringTokenizer(string);
    while (st.hasMoreTokens())
        res = st.nextToken();
    return res;
}
 
Example 51
Project: alfresco-remote-api   File: WebDAVHelper.java   Source Code and License 5 votes vote down vote up
public String getURLForPath(HttpServletRequest request, String path, boolean isCollection, String userAgent)
{
    String urlPathPrefix = getUrlPathPrefix(request);
    StringBuilder urlStr = new StringBuilder(urlPathPrefix);
    
    if (path.equals(WebDAV.RootPath) == false)
    {
        // split the path and URL encode each path element
        for (StringTokenizer t = new StringTokenizer(path, PathSeperator); t.hasMoreTokens(); /**/)
        {
            urlStr.append( WebDAVHelper.encodeURL(t.nextToken(), userAgent) );
            if (t.hasMoreTokens())
            {
                urlStr.append(PathSeperator);
            }
        }
    }
    
    // If the URL is to a collection add a trailing slash
    if (isCollection && urlStr.charAt( urlStr.length() - 1) != PathSeperatorChar)
    {
        urlStr.append( PathSeperator);
    }
    
    logger.debug("getURLForPath() path:" + path + " => url:" + urlStr);
    
    // Return the URL string
    return urlStr.toString();
}
 
Example 52
Project: hacker-rank   File: Introduction_to_Nim.java   Source Code and License 5 votes vote down vote up
public static void main(String ... ags)throws IOException
{
	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
	int test = Integer.parseInt(in.readLine());
	for(int t=0;t<test;t++)
	{
		in.readLine();
		StringTokenizer tk = new StringTokenizer(in.readLine());
		int res = Integer.parseInt(tk.nextToken());
		while(tk.hasMoreTokens())
			res = res ^ Integer.parseInt(tk.nextToken());
		String ans = (res == 0) ? "First" : "Second";
		System.out.println(ans);
	}	
}
 
Example 53
Project: camunda-bpm-swagger   File: StringHelper.java   Source Code and License 5 votes vote down vote up
public static String camelize(final String value) {
  if (value == null || !value.contains("-")) {
    return value;
  }
  final StringTokenizer token = new StringTokenizer(value, "-");
  final StringBuilder str = new StringBuilder(token.nextToken());
  while (token.hasMoreTokens()) {
    final String s = token.nextToken();
    str.append(Character.toUpperCase(s.charAt(0))).append(s.substring(1));
  }
  return str.toString();
}
 
Example 54
Project: L2jBrasil   File: AdminPolymorph.java   Source Code and License 5 votes vote down vote up
public boolean useAdminCommand(String command, L2PcInstance activeChar)
{
	if (!Config.ALT_PRIVILEGES_ADMIN)
		if (!(checkLevel(activeChar.getAccessLevel()) && activeChar.isGM()))
			return false;

	if (command.startsWith("admin_polymorph"))
	{
		StringTokenizer st = new StringTokenizer(command);
		L2Object target = activeChar.getTarget();
		try
		{
			st.nextToken();
			String p1 = st.nextToken();
			if (st.hasMoreTokens())
			{
				String p2 = st.nextToken();
				doPolymorph(activeChar, target, p2, p1);
			}
			else
				doPolymorph(activeChar, target, p1, "npc");
		}
		catch(Exception e)
		{
			activeChar.sendMessage("Usage: //polymorph [type] <id>");
		}
	}
	else if (command.equals("admin_unpolymorph"))
	{
		doUnpoly(activeChar,activeChar.getTarget());
	}
	if (command.contains("menu"))
		showMainPage(activeChar);
	return true;
}
 
Example 55
Project: TestDemo1-github   File: DealString.java   Source Code and License 5 votes vote down vote up
private String delSQlString(String sql){
    String delSql = "in(";
    StringTokenizer Tokenizer = new StringTokenizer(sql,"|");

    // 标记本身等于分隔符的特殊情况
    delSql += Tokenizer.nextToken().toString();
    while (Tokenizer.hasMoreTokens()) {
    	delSql += Tokenizer.nextToken() + ",";
    }
    delSql = delSql.substring(0,delSql.length()-1) + ")";
    return delSql;
}
 
Example 56
Project: nifi-nars   File: StandardMongoClientService.java   Source Code and License 5 votes vote down vote up
List<ServerAddress> parseServerAddresses(String hostlist) {
    List<ServerAddress> addresses = new ArrayList<>();
    StringTokenizer tokenizer = new StringTokenizer(hostlist, ",; ");
    while (tokenizer.hasMoreTokens()) {
        String host = tokenizer.nextToken();
        String[] split = host.split(":");
        int port = DEFAULT_PORT;
        if (split.length == 2) {
            port = Integer.parseInt(split[1]);
        }
        addresses.add(new ServerAddress(split[0], port));
    }
    return addresses;
}
 
Example 57
Project: openjdk-jdk10   File: LdapURL.java   Source Code and License 5 votes vote down vote up
/**
 * Given a space-separated list of LDAP URLs, returns an array of strings.
 */
public static String[] fromList(String urlList) throws NamingException {

    String[] urls = new String[(urlList.length() + 1) / 2];
    int i = 0;              // next available index in urls
    StringTokenizer st = new StringTokenizer(urlList, " ");

    while (st.hasMoreTokens()) {
        urls[i++] = st.nextToken();
    }
    String[] trimmed = new String[i];
    System.arraycopy(urls, 0, trimmed, 0, i);
    return trimmed;
}
 
Example 58
Project: unitimes   File: ListSolutionsForm.java   Source Code and License 5 votes vote down vote up
public void setSolutionId(String solutionId) throws Exception {
	iSolutionBeans.clear();
	if (solutionId==null || solutionId.length()==0) return;
	for (StringTokenizer s=new StringTokenizer(solutionId,",");s.hasMoreTokens();) {
		Long id = Long.valueOf(s.nextToken());
		Solution solution = (new SolutionDAO()).get(id);
		if (solution!=null)
			iSolutionBeans.addElement(new SolutionBean(solution));
	}
}
 
Example 59
Project: AceptaElReto   File: Problema291.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws IOException {
	while ((line = in.readLine()) != null) {
		c = Integer.parseInt(line);
		if (c == 0)
			break;
		data = new TreeMap<String, LinkedList<Integer>>();
		for (int i = 1; i <= c; i++) {
			st = new StringTokenizer(in.readLine(), " ");
			while (st.hasMoreTokens()) {
				word = st.nextToken().toLowerCase();
				if (word.length() > 2) {
					if (data.containsKey(word)) {
						if (data.get(word).getLast() != i)
							data.get(word).add(i);
					} else {
						tree = new LinkedList<Integer>();
						tree.add(i);
						data.put(word, tree);
					}
				}
			}
		}
		for (Entry<String, LinkedList<Integer>> entry : data.entrySet()) {
			sb.append(entry.getKey()).append(ESPACIO);
			itr = entry.getValue().iterator();
			l = entry.getValue().size();
			c2 = 0;
			while (itr.hasNext()) {
				c2++;
				sb.append(itr.next());
				if (c2 != l)
					sb.append(ESPACIO);
				else
					sb.append(SALTO);
			}
		}
		sb.append(FINAL);
	}
	System.out.print(sb.toString());
}
 
Example 60
Project: jdk8u-jdk   File: MouseModifiersUnitTest_Standard.java   Source Code and License 5 votes vote down vote up
public static Vector<String> tokenizeModifiers(String modifierList){
    Vector<String> modifiers = new Vector<String>();
    StringTokenizer st = new StringTokenizer(modifierList, "+");
    while (st.hasMoreTokens()){
        String tmp = st.nextToken();
        modifiers.addElement(tmp);
        System.out.println("MODIFIER PARSER : "+tmp);
    }
    return modifiers;
}