Search in sources :

Example 91 with StringTokenizer

use of java.util.StringTokenizer in project pcgen by PCGen.

the class ExportHandler method replaceTokenForDfor.

/**
	 * Helper method to deal with DFOR token, e.g.
	 * 
	 * DFOR.0,(COUNT[SKILLS]+1)/2,1,COUNT[SKILLS],(COUNT[SKILLS]+1)/2,<td>\SKILL%\</td>
	 * <td>\SKILL%.TOTAL\</td><td>\SKILL%.RANK\</td>
	 * <td>\SKILL%.ABILITY\</td><td>\SKILL%.MOD\,<tr align="center">,</tr>,0
	 * 
	 * Produces a 2 column row table of all skills.
	 * 
	 * @param aString String to process
	 * @param output Output we are writing to
	 * @param aPC PC we are exporting
	 */
private void replaceTokenForDfor(String aString, BufferedWriter output, PlayerCharacter aPC) {
    StringTokenizer aTok;
    // Split after DFOR. or DFOR by the ',' delimiter
    if (aString.startsWith("DFOR.")) {
        aTok = new StringTokenizer(aString.substring(5), ",", false);
    } else {
        aTok = new StringTokenizer(aString.substring(4), ",", false);
    }
    int cMin = 0;
    int cMax = 100;
    int cStep = 1;
    int cStepLine = 1;
    int cStepLineMax = 0;
    String cString = "";
    String cStartLineString = "";
    String cEndLineString = "";
    boolean isDFor = false;
    int i = 0;
    // While there are more tokens
    while (aTok.hasMoreTokens()) {
        String tokA = aTok.nextToken();
        switch(i) {
            case 0:
                cMin = getVarValue(tokA, aPC);
                break;
            case 1:
                cMax = getVarValue(tokA, aPC);
                break;
            case 2:
                cStep = getVarValue(tokA, aPC);
                if (aString.startsWith("DFOR.")) {
                    isDFor = true;
                    cStepLineMax = getVarValue(aTok.nextToken(), aPC);
                    cStepLine = getVarValue(aTok.nextToken(), aPC);
                }
                break;
            case 3:
                cString = tokA;
                break;
            case 4:
                cStartLineString = tokA;
                break;
            case 5:
                cEndLineString = tokA;
                break;
            case 6:
                existsOnly = (!"0".equals(tokA));
                if ("2".equals(tokA)) {
                    checkBefore = true;
                }
                break;
            default:
                Logging.errorPrint("ExportHandler.replaceTokenForDfor can't handle token number " + i + " this probably means you've passed in too many parameters.");
                break;
        }
        i++;
    }
    if ("COMMA".equals(cStartLineString)) {
        cStartLineString = ",";
    }
    if ("COMMA".equals(cEndLineString)) {
        cEndLineString = ",";
    }
    if ("NONE".equals(cStartLineString)) {
        cStartLineString = "";
    }
    if ("NONE".equals(cEndLineString)) {
        cEndLineString = "";
    }
    if ("CRLF".equals(cStartLineString)) {
        cStartLineString = Constants.LINE_SEPARATOR;
    }
    if ("CRLF".equals(cEndLineString)) {
        cEndLineString = Constants.LINE_SEPARATOR;
    }
    int iStart = cMin;
    int x = 0;
    while (iStart < cMax) {
        if (x == 0) {
            FileAccess.write(output, cStartLineString);
        }
        x++;
        int iNow = iStart;
        if (!isDFor) {
            cStepLineMax = iNow + cStep;
        }
        if ((cStepLineMax > cMax) && !isDFor) {
            cStepLineMax = cMax;
        }
        while ((iNow < cStepLineMax) || (isDFor && (iNow < cMax))) {
            boolean insideToken = false;
            if (cString.startsWith(csheetTag2)) {
                insideToken = true;
            }
            aTok = new StringTokenizer(cString, csheetTag2, false);
            int j = 0;
            while (aTok.hasMoreTokens()) {
                String eString = aTok.nextToken();
                String gString = "";
                String hString = eString;
                int index = 0;
                while (hString.indexOf('%', index) > 0) {
                    index = hString.indexOf('%', index);
                    if (index == -1) {
                        break;
                    }
                    if ((index < (hString.length() - 1)) && (hString.charAt(index + 1) != '.')) {
                        index++;
                        continue;
                    }
                    String fString = hString.substring(0, index);
                    if ((index + 1) < eString.length()) {
                        gString = hString.substring(index + 1);
                    }
                    hString = fString + Integer.toString(iNow) + gString;
                }
                if ("%0".equals(eString) || "%1".equals(eString)) {
                    final int cInt = iNow + Integer.parseInt(eString.substring(1));
                    FileAccess.write(output, Integer.toString(cInt));
                } else {
                    if (insideToken) {
                        replaceToken(hString, output, aPC);
                    } else {
                        boolean oldSkipMath = skipMath;
                        skipMath = true;
                        replaceToken(hString, output, aPC);
                        skipMath = oldSkipMath;
                    }
                }
                if (checkBefore && noMoreItems) {
                    iNow = cMax;
                    iStart = cMax;
                    if (j == 0) {
                        existsOnly = false;
                    }
                    break;
                }
                ++j;
                insideToken = !insideToken;
            }
            iNow += cStepLine;
            if (cStepLine == 0) {
                break;
            }
        }
        if ((cStepLine > 0) || ((cStepLine == 0) && (x == cStep)) || (existsOnly == noMoreItems)) {
            FileAccess.write(output, cEndLineString);
            x = 0;
            if (existsOnly && noMoreItems) {
                return;
            }
        }
        iStart += cStep;
    }
}
Also used : StringTokenizer(java.util.StringTokenizer)

Example 92 with StringTokenizer

use of java.util.StringTokenizer in project pcgen by PCGen.

the class ExportHandler method mathMode.

/**
	 * Math Mode - Most of the code logic was copied from PlayerCharacter.getVariableValue
	 * included a treatment for math with attack routines (for example +6/+1 - 2 = +4/-1)
	 *
	 * @param aString The string to be converted
	 * @param aPC the PC being exported
	 * @return String
	 */
private String mathMode(String aString, PlayerCharacter aPC) {
    String str = aString;
    // Deal with Knowledge () type tokens
    str = processBracketedTokens(str, aPC);
    // Replace all square brackets with curved ones
    str = str.replaceAll(Pattern.quote("["), "(");
    str = str.replaceAll(Pattern.quote("]"), ")");
    // A list of mathematical delimiters
    final String delimiter = "+-/*";
    String valString = "";
    final int ADDITION_MODE = 0;
    final int SUBTRACTION_MODE = 1;
    final int MULTIPLICATION_MODE = 2;
    final int DIVISION_MODE = 3;
    // Mode is addition mode by default
    int mode = ADDITION_MODE;
    int nextMode = 0;
    final int REGULAR_MODE = 0;
    final int INTVAL_MODE = 1;
    final int SIGN_MODE = 2;
    final int NO_ZERO_MODE = 3;
    int endMode = REGULAR_MODE;
    boolean attackRoutine = false;
    String attackData = "";
    Float total = 0.0f;
    for (int i = 0; i < str.length(); ++i) {
        valString += str.substring(i, i + 1);
        if ((i == (str.length() - 1)) || ((delimiter.lastIndexOf(str.charAt(i)) > -1) && (i > 0) && (str.charAt(i - 1) != '.'))) {
            if (delimiter.lastIndexOf(str.charAt(i)) > -1) {
                valString = valString.substring(0, valString.length() - 1);
            }
            if (i < str.length()) {
                // Deal with .TRUNC
                if (valString.endsWith(".TRUNC")) {
                    if (attackRoutine) {
                        Logging.errorPrint("Math Mode Error: Not allowed to use .TRUNC in Attack Mode.");
                    } else {
                        valString = String.valueOf(Float.valueOf(mathMode(valString.substring(0, valString.length() - 6), aPC)).intValue());
                    }
                }
                // Deal with .INTVAL
                if (valString.endsWith(".INTVAL")) {
                    if (attackRoutine) {
                        Logging.errorPrint("Math Mode Error: Using .INTVAL in Attack Mode.");
                    } else {
                        valString = mathMode(valString.substring(0, valString.length() - 7), aPC);
                    }
                    endMode = INTVAL_MODE;
                }
                // Deal with .SIGN
                if (valString.endsWith(".SIGN")) {
                    valString = mathMode(valString.substring(0, valString.length() - 5), aPC);
                    endMode = SIGN_MODE;
                }
                // Deal with .NOZERO
                if (valString.endsWith(".NOZERO")) {
                    valString = mathMode(valString.substring(0, valString.length() - 7), aPC);
                    endMode = NO_ZERO_MODE;
                }
                // Set the next mode based on the mathematical sign
                if ((!str.isEmpty()) && (str.charAt(i) == '+')) {
                    nextMode = ADDITION_MODE;
                } else if ((!str.isEmpty()) && (str.charAt(i) == '-')) {
                    nextMode = SUBTRACTION_MODE;
                } else if ((!str.isEmpty()) && (str.charAt(i) == '*')) {
                    nextMode = MULTIPLICATION_MODE;
                } else if ((!str.isEmpty()) && (str.charAt(i) == '/')) {
                    nextMode = DIVISION_MODE;
                }
                StringWriter sWriter = new StringWriter();
                BufferedWriter aWriter = new BufferedWriter(sWriter);
                replaceTokenSkipMath(aPC, valString, aWriter);
                sWriter.flush();
                try {
                    aWriter.flush();
                } catch (IOException e) {
                    Logging.errorPrint("Failed to flush oputput in MathMode.", e);
                }
                final String bString = sWriter.toString();
                try {
                    // Float values
                    DecimalFormatSymbols decimalFormatSymbols = new DecimalFormatSymbols(Locale.US);
                    DecimalFormat decimalFormat = new DecimalFormat("#,##0.##", decimalFormatSymbols);
                    valString = String.valueOf(decimalFormat.parse(bString));
                } catch (ParseException e) {
                    // String values
                    valString = bString;
                }
                if ((!attackRoutine) && Pattern.matches("^([-+]\\d+/)*[-+]\\d+$", valString)) {
                    attackRoutine = true;
                    attackData = valString;
                    valString = "";
                }
            }
            try {
                if (!valString.isEmpty()) {
                    if (attackRoutine) {
                        StringTokenizer bTok = new StringTokenizer(attackData, "/");
                        if (bTok.countTokens() > 0) {
                            String newAttackData = "";
                            while (bTok.hasMoreTokens()) {
                                final String bString = bTok.nextToken();
                                float bf = Float.parseFloat(bString);
                                float vf = Float.parseFloat(valString);
                                switch(mode) {
                                    case ADDITION_MODE:
                                        float addf = bf + vf;
                                        newAttackData += ("/+" + Integer.toString((int) addf));
                                        break;
                                    case SUBTRACTION_MODE:
                                        float subf = bf - vf;
                                        newAttackData += ("/+" + Integer.toString((int) subf));
                                        break;
                                    case MULTIPLICATION_MODE:
                                        float multf = bf * vf;
                                        newAttackData += ("/+" + Integer.toString((int) multf));
                                        break;
                                    case DIVISION_MODE:
                                        float divf = bf / vf;
                                        newAttackData += ("/+" + Integer.toString((int) divf));
                                        break;
                                    default:
                                        Logging.errorPrint("In mathMode the mode " + mode + " is unsupported.");
                                        break;
                                }
                            }
                            attackData = newAttackData.substring(1).replaceAll(Pattern.quote("+-"), "-");
                        }
                    } else {
                        switch(mode) {
                            case ADDITION_MODE:
                                total = (float) (total.doubleValue() + Double.parseDouble(valString));
                                break;
                            case SUBTRACTION_MODE:
                                total = (float) (total.doubleValue() - Double.parseDouble(valString));
                                break;
                            case MULTIPLICATION_MODE:
                                total = (float) (total.doubleValue() * Double.parseDouble(valString));
                                break;
                            case DIVISION_MODE:
                                total = (float) (total.doubleValue() / Double.parseDouble(valString));
                                break;
                            default:
                                Logging.errorPrint("In mathMode the mode " + mode + " is unsupported.");
                                break;
                        }
                    }
                }
            } catch (NumberFormatException exc) {
                StringWriter sWriter = new StringWriter();
                BufferedWriter aWriter = new BufferedWriter(sWriter);
                replaceTokenSkipMath(aPC, str, aWriter);
                sWriter.flush();
                try {
                    aWriter.flush();
                } catch (IOException e) {
                    Logging.errorPrint("Math Mode Error: Could not flush output.");
                }
                return sWriter.toString();
            }
            mode = nextMode;
            // Set the nextMode back to the default
            nextMode = ADDITION_MODE;
            valString = "";
        }
    }
    if (attackRoutine) {
        return attackData;
    }
    if (endMode == INTVAL_MODE) {
        return Integer.toString(total.intValue());
    }
    if (endMode == SIGN_MODE) {
        return Delta.toString(total.intValue());
    }
    if (endMode == NO_ZERO_MODE) {
        final int totalIntValue = total.intValue();
        if (totalIntValue == 0) {
            return "";
        }
        return Delta.toString(totalIntValue);
    }
    return total.toString();
}
Also used : DecimalFormatSymbols(java.text.DecimalFormatSymbols) DecimalFormat(java.text.DecimalFormat) IOException(java.io.IOException) BufferedWriter(java.io.BufferedWriter) StringTokenizer(java.util.StringTokenizer) StringWriter(java.io.StringWriter) ParseException(java.text.ParseException)

Example 93 with StringTokenizer

use of java.util.StringTokenizer in project pcgen by PCGen.

the class ExportHandler method replaceToken.

/**
	 * Replace the token with the value it represents
	 * 
	 * @param aString The string containing the token to be replaced
	 * @param output The object that will capture the output
	 * @param aPC The PC currently being exported
	 * @return value
	 */
public int replaceToken(String aString, BufferedWriter output, PlayerCharacter aPC) {
    try {
        // If it is plain text then there's no replacement necessary
        if (isPlainText(aString)) {
            return 0;
        }
        // then there is nothing to replace so return 0
        if ("%".equals(aString)) {
            inLabel = false;
            canWrite = true;
            return 0;
        }
        // and return the length of the line (minus any whitespace)
        if (aString.startsWith("${") && aString.endsWith("}")) {
            String jepString = aString.substring(2, aString.length() - 1);
            String variableValue = aPC.getVariableValue(jepString, "").toString();
            FileAccess.write(output, variableValue);
            return aString.trim().length();
        }
        // TODO Why?
        FileAccess.maxLength(-1);
        // If the string is a non empty filter and does not have a '<' or a '>' in it then replace the token
        if (isFilterToken(aString)) {
            return dealWithFilteredTokens(aString, aPC);
        }
        String tokenString = aString;
        // e.g: |SUB10.ARMOR.AC|
        if (isValidSubToken(tokenString)) {
            tokenString = replaceSubToken(tokenString);
        }
        // Now check for the rest of the tokens
        populateTokenMap();
        StringTokenizer tok = new StringTokenizer(tokenString, ".,", false);
        String firstToken = tok.nextToken();
        // Get the remaining token/test string 
        // TODO Understand this
        String testString = tokenString;
        if (testString.indexOf(',') > -1) {
            testString = testString.substring(0, testString.indexOf(','));
        }
        if (testString.indexOf('~') > -1) {
            testString = testString.substring(0, testString.indexOf('~'));
        }
        int len = 1;
        // Deal with FOR/DFOR token
        if (isForOrDForToken(tokenString)) {
            processLoopToken(tokenString, output, aPC);
            return 0;
        } else // Deal with OIF token
        if (tokenString.startsWith("OIF(")) {
            replaceTokenOIF(tokenString, output, aPC);
        } else // Deal with mathematical tokenLeave
        if (containsMathematicalToken(testString) && (!skipMath)) {
            FileAccess.maxLength(-1);
            FileAccess.write(output, mathMode(tokenString, aPC));
            return 0;
        } else // Deal with CSHEETTAG2.
        if (tokenString.startsWith("CSHEETTAG2.")) {
            csheetTag2 = tokenString.substring(11, 12);
            FileAccess.maxLength(-1);
            return 0;
        } else // Else if the token is in the list of valid output tokens
        if (tokenMap.get(firstToken) != null) {
            Token token = tokenMap.get(firstToken);
            if (token.isEncoded()) {
                FileAccess.encodeWrite(output, token.getToken(tokenString, aPC, this));
            } else {
                FileAccess.write(output, token.getToken(tokenString, aPC, this));
            }
        } else // Default case
        {
            len = tokenString.trim().length();
            if (manualWhitespace) {
                tokenString = tokenString.replaceAll("[ \\t]", "");
                if (len > 0) {
                    FileAccess.write(output, tokenString);
                }
            } else {
                FileAccess.write(output, tokenString);
            }
        }
        FileAccess.maxLength(-1);
        return len;
    } catch (Exception exc) {
        Logging.errorPrint("Error replacing " + aString, exc);
        return 0;
    }
}
Also used : StringTokenizer(java.util.StringTokenizer) SkillToken(pcgen.io.exporttoken.SkillToken) Token(pcgen.io.exporttoken.Token) MovementToken(pcgen.io.exporttoken.MovementToken) EqToken(pcgen.io.exporttoken.EqToken) StatToken(pcgen.io.exporttoken.StatToken) GameModeToken(pcgen.io.exporttoken.GameModeToken) EqTypeToken(pcgen.io.exporttoken.EqTypeToken) WeaponhToken(pcgen.io.exporttoken.WeaponhToken) SkillpointsToken(pcgen.io.exporttoken.SkillpointsToken) BonusToken(pcgen.io.exporttoken.BonusToken) TotalToken(pcgen.io.exporttoken.TotalToken) AbilityListToken(pcgen.io.exporttoken.AbilityListToken) WeaponToken(pcgen.io.exporttoken.WeaponToken) AbilityToken(pcgen.io.exporttoken.AbilityToken) ParseException(java.text.ParseException) TemplateException(freemarker.template.TemplateException) IOException(java.io.IOException)

Example 94 with StringTokenizer

use of java.util.StringTokenizer in project OpenAM by OpenRock.

the class ResourceNameSplitter method splitPath.

private static Set<String> splitPath(String path) {
    Set<String> results = new HashSet<String>();
    results.add("/");
    path = path.toLowerCase();
    if ((path.length() > 0) && !path.equals("/")) {
        String prefix = "";
        StringTokenizer st = new StringTokenizer(path, "/");
        while (st.hasMoreTokens()) {
            String s = st.nextToken();
            prefix += "/" + s;
            results.add(prefix);
        }
    }
    return results;
}
Also used : StringTokenizer(java.util.StringTokenizer) HashSet(java.util.HashSet)

Example 95 with StringTokenizer

use of java.util.StringTokenizer in project OpenAM by OpenRock.

the class SuffixResourceName method split.

/* Splits the given resource name
     * @param res the resource name to be split
     * @return an array of (String) split resource names
     */
public String[] split(String res) {
    StringTokenizer st = new StringTokenizer(res, delimiter);
    int n = st.countTokens();
    String[] retVal = new String[n];
    for (int i = 0; i < n; i++) {
        retVal[n - i - 1] = st.nextToken();
    }
    return retVal;
}
Also used : StringTokenizer(java.util.StringTokenizer)

Aggregations

StringTokenizer (java.util.StringTokenizer)4881 ArrayList (java.util.ArrayList)1083 IOException (java.io.IOException)506 File (java.io.File)392 BufferedReader (java.io.BufferedReader)380 HashMap (java.util.HashMap)375 HashSet (java.util.HashSet)263 FileReader (java.io.FileReader)224 List (java.util.List)200 InputStreamReader (java.io.InputStreamReader)191 Map (java.util.Map)152 FileInputStream (java.io.FileInputStream)135 Iterator (java.util.Iterator)114 Set (java.util.Set)114 URL (java.net.URL)108 NoSuchElementException (java.util.NoSuchElementException)90 Properties (java.util.Properties)84 InputStream (java.io.InputStream)83 BufferedWriter (java.io.BufferedWriter)80 FileNotFoundException (java.io.FileNotFoundException)78