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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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   View source code 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;
    }