/**
   * Returns the nl expression of a property name
   *
   * @param s property name
   * @return String NL-representation
   */
  public static String getNLExpression(String s) {
    StringBuffer result = new StringBuffer(s);
    if (s.length() < 3)
      return s; // LET'S ASSUME FOR NOW THAT ONLY HAPPENS WITH ABBREVIATIONS, WHICH SHOULD BE
    // CAPITALISED ANYWAY
    String sub = result.substring(result.length() - 2); // get the last two characters
    if (sub.equals("Of") || (result.indexOf("For") == (result.length() - 3))) {
      if (!result.substring(0, 2).toLowerCase().equals("is")) result.insert(0, "Is ");
    } else if ((sub.equals("By") || sub.equals("As"))
        && !result.substring(0, 2).toLowerCase().equals("is")) result.insert(0, "Is ");

    for (int i = 1;
        i < result.length();
        i++) { // replace all capitals with lowercase letters, and add spaces if needed
      char c = result.charAt(i);
      if (Character.isUpperCase(c)) {
        result.setCharAt(i, Character.toLowerCase(c));
        if (!(result.charAt(i - 1) == ' ') && !(result.charAt(i - 1) == '_'))
          result.insert(i, ' '); // insert a space		
      }
    }
    result.setCharAt(
        0, Character.toUpperCase(result.charAt(0))); // set first character to upper case
    return result.toString().replaceAll("_", " "); // replace all underscores with spaces
  }
Example #2
0
 // capital letters in template are macros
 private String getCorrectOpcodeName(
     String oldName, int prefixes, boolean operandSize, boolean addrSize) {
   StringBuffer newName = new StringBuffer(oldName);
   int index = 0;
   for (index = 0; index < oldName.length(); index++) {
     switch (oldName.charAt(index)) {
       case 'C': /* For jcxz/jecxz */
         if (addrSize) newName.setCharAt(index, 'e');
         index++;
         break;
       case 'N':
         if ((prefixes & PREFIX_FWAIT) == 0) newName.setCharAt(index, 'n');
         index++;
         break;
       case 'S':
         /* operand size flag */
         if (operandSize == true) newName.setCharAt(index, 'l');
         else newName.setCharAt(index, 'w');
         index++;
         break;
       default:
         break;
     }
   }
   return newName.toString();
 }
  public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos) {
    StringBuffer s = new StringBuffer(nf.format(number));
    if (sign) {
      if (s.charAt(0) == '+') s.setCharAt(0, ' ');
    } else {
      if (s.charAt(0) == '-') s.setCharAt(0, '*');
      else s.deleteCharAt(0);
    }

    return toAppendTo.append(s);
  }
Example #4
0
 /**
  * Converts a byte array to a hex string.
  *
  * @param data the byte array
  * @param nOfs start index where to get the bytes
  * @param nLen number of bytes to convert
  * @return the hex string
  */
 public static final String bytesToHexStr(byte[] data, int nOfs, int nLen) {
   StringBuffer sbuf;
   sbuf = new StringBuffer();
   sbuf.setLength(nLen << 1);
   int nPos = 0;
   int nC = nOfs + nLen;
   while (nOfs < nC) {
     sbuf.setCharAt(nPos++, HEXTAB[(data[nOfs] >> 4) & 0x0f]);
     sbuf.setCharAt(nPos++, HEXTAB[data[nOfs++] & 0x0f]);
   }
   return sbuf.toString();
 }
Example #5
0
 private UTF8String toTitleCaseSlow() {
   StringBuffer sb = new StringBuffer();
   String s = toString();
   sb.append(s);
   sb.setCharAt(0, Character.toTitleCase(sb.charAt(0)));
   for (int i = 1; i < s.length(); i++) {
     if (sb.charAt(i - 1) == ' ') {
       sb.setCharAt(i, Character.toTitleCase(sb.charAt(i)));
     }
   }
   return fromString(sb.toString());
 }
Example #6
0
 public void mutacao(double chance) {
   int tam = getTamanho();
   StringBuffer gen = getGenotipo();
   for (int i = 0; i < tam; i++) {
     if (Math.random() < chance) {
       if (gen.charAt(i) == '0') {
         gen.setCharAt(i, '1');
       } else {
         gen.setCharAt(i, '0');
       }
     }
   }
 }
Example #7
0
 public static void main(String args[]) {
   String ch = "la java";
   StringBuffer chBuf = new StringBuffer(ch);
   System.out.println(chBuf);
   chBuf.setCharAt(3, 'J');
   System.out.println(chBuf);
   chBuf.setCharAt(1, 'e');
   System.out.println(chBuf);
   chBuf.append(" 2");
   System.out.println(chBuf);
   chBuf.insert(3, " langage ");
   System.out.println(chBuf);
 }
Example #8
0
  /** Property setter */
  public VelPropertySet getPropertySet(Object obj, String identifier, Object arg, Info i)
      throws Exception {
    Class claz = obj.getClass();

    VelPropertySet vs = null;
    VelMethod vm = null;
    try {
      /*
       *  first, we introspect for the set<identifier> setter method
       */

      Object[] params = {arg};

      try {
        vm = getMethod(obj, "set" + identifier, params, i);

        if (vm == null) {
          throw new NoSuchMethodException();
        }
      } catch (NoSuchMethodException nsme2) {
        StringBuffer sb = new StringBuffer("set");
        sb.append(identifier);

        if (Character.isLowerCase(sb.charAt(3))) {
          sb.setCharAt(3, Character.toUpperCase(sb.charAt(3)));
        } else {
          sb.setCharAt(3, Character.toLowerCase(sb.charAt(3)));
        }

        vm = getMethod(obj, sb.toString(), params, i);

        if (vm == null) {
          throw new NoSuchMethodException();
        }
      }
    } catch (NoSuchMethodException nsme) {
      /*
       *  right now, we only support the Map interface
       */

      if (Map.class.isAssignableFrom(claz)) {
        Object[] params = {new Object(), new Object()};

        vm = getMethod(obj, "put", params, i);

        if (vm != null) return new VelSetterImpl(vm, identifier);
      }
    }

    return (vm != null) ? new VelSetterImpl(vm) : null;
  }
Example #9
0
  public static final String crypt(String salt, String original) {
    while (salt.length() < 2) salt += "A";

    StringBuffer buffer = new StringBuffer("             ");

    char charZero = salt.charAt(0);
    char charOne = salt.charAt(1);

    buffer.setCharAt(0, charZero);
    buffer.setCharAt(1, charOne);

    int Eswap0 = con_salt[(int) charZero];
    int Eswap1 = con_salt[(int) charOne] << 4;

    byte key[] = new byte[8];

    for (int i = 0; i < key.length; i++) key[i] = (byte) 0;

    for (int i = 0; i < key.length && i < original.length(); i++) {
      int iChar = (int) original.charAt(i);

      key[i] = (byte) (iChar << 1);
    }

    int schedule[] = des_set_key(key);
    int out[] = body(schedule, Eswap0, Eswap1);

    byte b[] = new byte[9];

    intToFourBytes(out[0], b, 0);
    intToFourBytes(out[1], b, 4);
    b[8] = 0;

    for (int i = 2, y = 0, u = 0x80; i < 13; i++) {
      for (int j = 0, c = 0; j < 6; j++) {
        c <<= 1;

        if (((int) b[y] & u) != 0) c |= 1;

        u >>>= 1;

        if (u == 0) {
          y++;
          u = 0x80;
        }
        buffer.setCharAt(i, (char) cov_2char[c]);
      }
    }
    return (buffer.toString());
  }
 @Override
 public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition pos) {
   super.format(date, toAppendTo, pos);
   if (escape) {
     for (int i = 5; i < toAppendTo.length(); i++) {
       if (toAppendTo.charAt(i) == '\0') {
         toAppendTo.setCharAt(i, toAppendTo.charAt(i - 1));
         toAppendTo.setCharAt(i - 1, toAppendTo.charAt(i - 2));
         toAppendTo.setCharAt(i - 2, ':');
       }
     }
   }
   return toAppendTo;
 }
Example #11
0
  /**
   * Create switch assembly code for to route one item from
   *
   * <pre>fire</pre>
   *
   * to the dests.
   *
   * <pre>previous</pre>
   *
   * is a hashmap from ComputeNode -> ComputeNode that maps a node to its previous hop,
   *
   * <pre>next</pre>
   *
   * is similiar...
   */
  protected void asm(
      ComputeNode fire,
      HashMap<ComputeNode, ComputeNode> previous,
      HashMap<ComputeNode, HashSet> next) {
    assert fire != null;
    // System.out.println("asm: " + fire);
    // generate the sends
    if (!switchSchedules.containsKey(fire)) switchSchedules.put(fire, new StringBuffer());
    StringBuffer buf = switchSchedules.get(fire);
    Iterator it = next.get(fire).iterator();
    buf.append("route ");
    while (it.hasNext()) {
      ComputeNode dest = (ComputeNode) it.next();
      buf.append("$csto->" + "$c" + rawChip.getDirection(fire, dest) + "o,");
    }
    // erase the trailing ,
    buf.setCharAt(buf.length() - 1, '\n');

    // generate all the other
    Iterator<ComputeNode> tiles = next.keySet().iterator();
    while (tiles.hasNext()) {
      ComputeNode tile = tiles.next();
      assert tile != null;
      if (tile == fire) continue;
      if (!switchSchedules.containsKey(tile)) switchSchedules.put(tile, new StringBuffer());
      buf = switchSchedules.get(tile);
      ComputeNode prevTile = previous.get(tile);
      buf.append("route ");
      Iterator nexts = next.get(tile).iterator();
      while (nexts.hasNext()) {
        ComputeNode nextTile = (ComputeNode) nexts.next();
        if (!nextTile.equals(tile))
          buf.append(
              "$c"
                  + rawChip.getDirection(tile, prevTile)
                  + "i->$c"
                  + rawChip.getDirection(tile, nextTile)
                  + "o,");
        else
          buf.append(
              "$c"
                  + rawChip.getDirection(tile, prevTile)
                  + "i->$c"
                  + rawChip.getDirection(tile, nextTile)
                  + "i,");
      }
      buf.setCharAt(buf.length() - 1, '\n');
    }
  }
  /**
   * Loads mock data from the "glossary-type.csv" file.
   *
   * @throws Exception error loading file
   */
  private void loadGlossaryTypes() throws Exception {
    InputStream in = null;
    BufferedReader reader = null;

    glossaryTypeData = new ArrayList<String[]>();

    try {

      ClassLoader loader = Thread.currentThread().getContextClassLoader();
      if (loader == null) {
        loader = this.getClass().getClassLoader();
      }

      in = loader.getResourceAsStream("mockdata/glossary-type.csv");
      if (in == null) throw new FileNotFoundException("Unable to open mockdata/glossary-type.csv");

      reader = new BufferedReader(new InputStreamReader(in));

      String line = null;
      do {
        line = reader.readLine();
        if (line == null || line.length() == 0) {
          break;
        }

        String[] columns = line.split("\t");
        if (2 != columns.length)
          throw new Exception("Invalid number of columns in glossary-type.csv");

        // fix some bad data
        StringBuffer buff = new StringBuffer(columns[0].toLowerCase().trim());
        for (int i = buff.length() - 1; i > 0; i--) {
          if (buff.charAt(i) == ' ') {
            buff.setCharAt(i + 1, Character.toUpperCase(buff.charAt(i + 1)));
          }
        }
        buff.setCharAt(0, Character.toUpperCase(buff.charAt(0)));

        columns[0] = buff.toString();
        glossaryTypeData.add(columns);

      } while (true);

    } finally {
      reader.close();
      in.close();
    }
  }
Example #13
0
  /**
   * Note this method will <strong>not </strong> handle references to higher directories ("..").
   *
   * @param rrd a {@link java.lang.String} object.
   * @return a {@link java.lang.String} object.
   */
  public static String convertToValidRrdName(final String rrd) {
    if (rrd == null) {
      throw new IllegalArgumentException("Cannot take null parameters.");
    }

    final StringBuffer buffer = new StringBuffer(rrd);

    // truncate after the max length
    if (rrd.length() > MAX_RRD_FILENAME_LENGTH) {
      buffer.setLength(MAX_RRD_FILENAME_LENGTH - 1);
    }

    final int length = buffer.length();

    for (int i = 0; i < length; i++) {
      char c = buffer.charAt(i);

      if (!(('A' <= c && c <= 'Z')
          || ('a' <= c && c <= 'z')
          || ('0' <= c && c <= '9')
          || (c == '_')
          || (c == '.')
          || (c == '-')
          || (c == '/'))) {
        buffer.setCharAt(i, '_');
      }
    }

    return buffer.toString();
  }
Example #14
0
  public static void main(String[] args) {
    String station = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    Scanner sc = new Scanner(System.in);

    while (true) {
      int n = sc.nextInt();
      if (n == 0) {
        break;
      }

      int[] k = new int[n];
      for (int i = 0; i < n; i++) {
        k[i] = sc.nextInt();
      }
      StringBuffer s = new StringBuffer(sc.next());

      for (int i = 0; i < s.length(); i++) {
        char tmp = s.charAt(i);
        int pos = station.indexOf(tmp);
        char newStation = station.charAt((pos + (52 - k[i % k.length])) % 52);
        s.setCharAt(i, newStation);
      }
      System.out.println(s);
    }
  }
  public static void decry() {
    try {
      BufferedReader bf = new BufferedReader(new FileReader("ciphertext.txt"));
      BufferedWriter wr = new BufferedWriter(new FileWriter("plaintext.txt"));
      char rkey[] = new char[26];
      for (char i = 'a'; i <= 'z'; i++) {
        if (key.charAt(i - 'a') > 'z' || key.charAt(i - 'a') < 'a') continue;
        rkey[key.charAt(i - 'a') - 'a'] = i;
      }
      System.out.println(rkey);
      StringBuffer strb;
      String str;
      while (((str = bf.readLine())) != null) {
        strb = new StringBuffer(str);
        // System.out.println(strb);
        // String ans;
        for (int i = 0; i < strb.length(); i++) {
          if (strb.charAt(i) >= 'a' && strb.charAt(i) <= 'z') {
            strb.setCharAt(i, rkey[strb.charAt(i) - 'a']);
          }
        }
        System.out.println(strb.toString());
        wr.write(strb.toString());
        wr.newLine();
      }
      // keyf.close();
      wr.close();
      bf.close();

    } catch (IOException e) {

    }
  }
Example #16
0
 private static void uppercaseFirstLetter(final StringBuffer buf) {
   if (buf.length() > 1) {
     char[] firstLetter = new char[1];
     buf.getChars(0, 1, firstLetter, 0);
     buf.setCharAt(0, Character.toUpperCase(firstLetter[0]));
   }
 }
Example #17
0
 /**
  * Translates occurrences at a position of / or \ to correct separator of the current platform and
  * returns whether it had to do a replacement.
  *
  * @param buffer a buffer containing a string
  * @param pos the position in the string buffer to convert
  * @return true if the character was a / or \
  */
 protected static boolean translateFileSep(StringBuffer buffer, int pos) {
   if (buffer.charAt(pos) == '/' || buffer.charAt(pos) == '\\') {
     buffer.setCharAt(pos, File.separatorChar);
     return true;
   }
   return false;
 }
Example #18
0
 /** replaces all characters oldC in a String s with character newC */
 public static String replaceChar(String s, char oldC, char newC) {
   StringBuffer sb = new StringBuffer(s);
   for (int i = 0; i < s.length(); i++) {
     if (s.charAt(i) == oldC) sb.setCharAt(i, newC);
   }
   return sb.toString();
 }
Example #19
0
File: Name.java Project: srnsw/xena
  public Name(FontFile2 currentFontFile) {

    // LogWriter.writeMethod("{readMapxTable}", 0);

    // move to start and check exists
    int startPointer = currentFontFile.selectTable(FontFile2.NAME);

    // read 'head' table
    if (startPointer != 0) {

      // read global details
      currentFontFile.getNextUint16(); // format
      int count = currentFontFile.getNextUint16();
      int offset = currentFontFile.getNextUint16();

      /** read strings */
      for (int i = 0; i < count; i++) {

        // get table values
        int platformID = currentFontFile.getNextUint16();
        int platformSpecificID = currentFontFile.getNextUint16();
        int langID = currentFontFile.getNextUint16();
        int nameID = currentFontFile.getNextUint16();
        int length = currentFontFile.getNextUint16();
        int offset2 = currentFontFile.getNextUint16();

        // only these 2 variations at present
        if ((platformID == 1 && platformSpecificID == 0 && langID == 0)
            || (platformID == 3 && platformSpecificID == 0 && langID == 1033)
            || (platformID == 3 && platformSpecificID == 1 && langID == 1033)) {

          // read actual string for location, altering/restoring pointers
          int oldP = currentFontFile.getPointer();

          currentFontFile.setPointer(startPointer + offset + offset2);

          int nextChar;

          // allow for 2 bytes in char
          if (platformID == 0 || platformID == 3) length = length / 2;

          StringBuffer s = new StringBuffer();
          s.setLength(length);

          for (int ii = 0; ii < length; ii++) {
            if (platformID == 0 || platformID == 3) nextChar = currentFontFile.getNextUint16();
            else nextChar = currentFontFile.getNextUint8();

            s.setCharAt(ii, (char) nextChar);
          }

          String str = s.toString();

          if (str != null) strings.put(new Integer(nameID), str);

          currentFontFile.setPointer(oldP);
        }
      }
    }
  }
 private static void decodeAlphanumericSegment(
     BitSource bits, StringBuffer result, int count, boolean fc1InEffect) throws FormatException {
   // Read two characters at a time
   int start = result.length();
   while (count > 1) {
     int nextTwoCharsBits = bits.readBits(11);
     result.append(toAlphaNumericChar(nextTwoCharsBits / 45));
     result.append(toAlphaNumericChar(nextTwoCharsBits % 45));
     count -= 2;
   }
   if (count == 1) {
     // special case: one character left
     result.append(toAlphaNumericChar(bits.readBits(6)));
   }
   // See section 6.4.8.1, 6.4.8.2
   if (fc1InEffect) {
     // We need to massage the result a bit if in an FNC1 mode:
     for (int i = start; i < result.length(); i++) {
       if (result.charAt(i) == '%') {
         if (i < result.length() - 1 && result.charAt(i + 1) == '%') {
           // %% is rendered as %
           result.deleteCharAt(i + 1);
         } else {
           // In alpha mode, % should be converted to FNC1 separator 0x1D
           result.setCharAt(i, (char) 0x1D);
         }
       }
     }
   }
 }
Example #21
0
 /**
  * Clean string.
  *
  * @param str the str
  * @return the string
  */
 public static String cleanString(String str) {
   Transliterator accentsconverter =
       Transliterator.getInstance("Latin; NFD; [:Nonspacing Mark:] Remove; NFC;");
   str = accentsconverter.transliterate(str);
   // the character ? seems to not be changed to d by the transliterate
   // function
   StringBuffer cleanedStr = new StringBuffer(str.trim());
   // delete special character
   for (int i = 0; i < cleanedStr.length(); i++) {
     char c = cleanedStr.charAt(i);
     if (c == ' ') {
       if (i > 0 && cleanedStr.charAt(i - 1) == '-') {
         cleanedStr.deleteCharAt(i--);
       } else {
         c = '-';
         cleanedStr.setCharAt(i, c);
       }
       continue;
     }
     if (i > 0 && !(Character.isLetterOrDigit(c) || c == '-')) {
       cleanedStr.deleteCharAt(i--);
       continue;
     }
     if (i > 0 && c == '-' && cleanedStr.charAt(i - 1) == '-') cleanedStr.deleteCharAt(i--);
   }
   return cleanedStr.toString().toLowerCase();
 }
 /**
  * Initialize the taglet manager. The strings to initialize the simple custom tags should be in
  * the following format: "[tag name]:[location str]:[heading]".
  *
  * @param customTagStrs the set two dimentional arrays of strings. These arrays contain either
  *     -tag or -taglet arguments.
  */
 private void initTagletManager(Set customTagStrs) {
   tagletManager =
       tagletManager == null
           ? new TagletManager(nosince, showversion, showauthor, message)
           : tagletManager;
   String[] args;
   for (Iterator it = customTagStrs.iterator(); it.hasNext(); ) {
     args = (String[]) it.next();
     if (args[0].equals("-taglet")) {
       tagletManager.addCustomTag(args[1], tagletpath);
       continue;
     }
     String[] tokens = Util.tokenize(args[1], TagletManager.SIMPLE_TAGLET_OPT_SEPERATOR, 3);
     if (tokens.length == 1) {
       String tagName = args[1];
       if (tagletManager.isKnownCustomTag(tagName)) {
         // reorder a standard tag
         tagletManager.addNewSimpleCustomTag(tagName, null, "");
       } else {
         // Create a simple tag with the heading that has the same name as the tag.
         StringBuffer heading = new StringBuffer(tagName + ":");
         heading.setCharAt(0, Character.toUpperCase(tagName.charAt(0)));
         tagletManager.addNewSimpleCustomTag(tagName, heading.toString(), "a");
       }
     } else if (tokens.length == 2) {
       // Add simple taglet without heading, probably to excluding it in the output.
       tagletManager.addNewSimpleCustomTag(tokens[0], tokens[1], "");
     } else if (tokens.length >= 3) {
       tagletManager.addNewSimpleCustomTag(tokens[0], tokens[2], tokens[1]);
     } else {
       message.error("doclet.Error_invalid_custom_tag_argument", args[1]);
     }
   }
 }
  /**
   * This function creates a directive record and adds it to the list, the value will be added later
   * after it is parsed.
   *
   * @param name Name
   * @param haveQuotedPair true if quoted pair is there else false
   */
  @DSGenerator(
      tool_name = "Doppelganger",
      tool_version = "2.0",
      generated_on = "2014-09-03 15:02:38.406 -0400",
      hash_original_method = "266E87F8A828CDA30627CAA7433FF646",
      hash_generated_method = "CE03EAF7EDFB05F294B401E410CDC667")
  void addDirective(String name, boolean haveQuotedPair) {
    String value;
    int inputIndex;
    int valueIndex;
    char valueChar;
    int type;

    if (!haveQuotedPair) {
      value = m_directives.substring(m_scanStart, m_curPos);
    } else { // copy one character at a time skipping backslash excapes.
      StringBuffer valueBuf = new StringBuffer(m_curPos - m_scanStart);
      valueIndex = 0;
      inputIndex = m_scanStart;
      while (inputIndex < m_curPos) {
        if ('\\' == (valueChar = m_directives.charAt(inputIndex))) inputIndex++;
        valueBuf.setCharAt(valueIndex, m_directives.charAt(inputIndex));
        valueIndex++;
        inputIndex++;
      }
      value = new String(valueBuf);
    }

    if (m_state == STATE_SCANNING_QUOTED_STRING_VALUE) type = ParsedDirective.QUOTED_STRING_VALUE;
    else type = ParsedDirective.TOKEN_VALUE;
    m_directiveList.add(new ParsedDirective(name, value, type));
  }
Example #24
0
 /** Overwrites a string s at a given position with newString */
 public static String replaceString(String s, int pos, String newString) {
   StringBuffer sb = new StringBuffer(s);
   for (int i = 0; i < newString.length(); i++) {
     sb.setCharAt(pos + i, newString.charAt(i));
   }
   return sb.toString();
 }
Example #25
0
 private static boolean fixSlash(StringBuffer buffer, int pos) {
     if (buffer.charAt(pos) == '/' || buffer.charAt(pos) == '\\') {
         buffer.setCharAt(pos, File.separatorChar);
         return true;
     }
     return false;
 }
Example #26
0
  public static final String crypt(String s, String s1) {
    for (; s.length() < 2; s = s + "A") {}
    StringBuffer stringbuffer = new StringBuffer("             ");
    char c = s.charAt(0);
    char c1 = s.charAt(1);
    stringbuffer.setCharAt(0, c);
    stringbuffer.setCharAt(1, c1);
    int i = con_salt[c];
    int j = con_salt[c1] << 4;
    byte abyte0[] = new byte[8];
    for (int k = 0; k < abyte0.length; k++) {
      abyte0[k] = 0;
    }

    for (int l = 0; l < abyte0.length && l < s1.length(); l++) {
      char c2 = s1.charAt(l);
      abyte0[l] = (byte) (c2 << 1);
    }

    int ai[] = COM.dragonflow.Utils.jcrypt.des_set_key(abyte0);
    int ai1[] = COM.dragonflow.Utils.jcrypt.body(ai, i, j);
    byte abyte1[] = new byte[9];
    COM.dragonflow.Utils.jcrypt.intToFourBytes(ai1[0], abyte1, 0);
    COM.dragonflow.Utils.jcrypt.intToFourBytes(ai1[1], abyte1, 4);
    abyte1[8] = 0;
    int i1 = 2;
    int j1 = 0;
    int k1 = 128;
    for (; i1 < 13; i1++) {
      int l1 = 0;
      int i2 = 0;
      for (; l1 < 6; l1++) {
        i2 <<= 1;
        if ((abyte1[j1] & k1) != 0) {
          i2 |= 1;
        }
        k1 >>>= 1;
        if (k1 == 0) {
          j1++;
          k1 = 128;
        }
        stringbuffer.setCharAt(i1, (char) cov_2char[i2]);
      }
    }

    return stringbuffer.toString();
  }
  /**
   * This is a complement to the normal webwork execution which allows for a command-based execution
   * of actions.
   */
  private String invokeCommand() throws Exception {
    Timer t = new Timer();

    final StringBuffer methodName = new StringBuffer("do" + this.commandName);
    methodName.setCharAt(2, Character.toUpperCase(methodName.charAt(2)));

    String result = "";

    try {
      final Method method = getClass().getMethod(methodName.toString(), new Class[0]);
      result = (String) method.invoke(this, new Object[0]);
      setStandardResponseHeaders();
    } catch (NoSuchMethodException e) {
      logger.warn("No such method in:" + getRequest().getRequestURI() + ":" + e.getMessage());
    } catch (Exception ie) {
      if (ie.getMessage() != null) logger.error("Exception in top action:" + ie.getMessage(), ie);

      try {
        throw ie.getCause();
      } catch (ResultException e) {
        logger.error("ResultException " + e, e);
        result = e.getResult();
      } catch (AccessConstraintException e) {
        logger.info("AccessConstraintException " + e, e);
        setErrors(e);
        result = ACCESS_DENIED;
      } catch (ConstraintException e) {
        logger.info("ConstraintException " + e, e);
        setErrors(e);
        if (e.getResult() != null && !e.getResult().equals("")) result = e.getResult();
        else result = INPUT;
      } catch (Bug e) {
        logger.error("Bug " + e.getMessage(), e);
        setError(e, e.getCause());
        result = ERROR;
      } catch (ConfigurationError e) {
        logger.error("ConfigurationError " + e);
        setError(e, e.getCause());
        result = ERROR;
      } catch (SystemException e) {
        logger.error("SystemException " + e, e);
        setError(e, e.getCause());
        result = ERROR;
      } catch (Throwable e) {
        logger.error("Throwable " + e.getMessage(), e);
        final Bug bug = new Bug("Uncaught exception!", e);
        setError(bug, bug.getCause());
        result = ERROR;
      }
    }

    try {
      ChangeNotificationController.notifyListeners();
    } catch (Exception e) {
      e.printStackTrace();
    }

    return result;
  }
Example #28
0
 /**
  * Undoes the changes made by substitute(). That are character pairs and character combinations.
  * Umlauts will remain as their corresponding vowel, as "ß" remains as "ss".
  */
 private void resubstitute(StringBuffer buffer) {
   for (int c = 0; c < buffer.length(); c++) {
     if (buffer.charAt(c) == '*') {
       char x = buffer.charAt(c - 1);
       buffer.setCharAt(c, x);
     } else if (buffer.charAt(c) == '$') {
       buffer.setCharAt(c, 's');
       buffer.insert(c + 1, new char[] {'c', 'h'}, 0, 2);
     } else if (buffer.charAt(c) == '§') {
       buffer.setCharAt(c, 'c');
       buffer.insert(c + 1, 'h');
     } else if (buffer.charAt(c) == '%') {
       buffer.setCharAt(c, 'e');
       buffer.insert(c + 1, 'i');
     } else if (buffer.charAt(c) == '&') {
       buffer.setCharAt(c, 'i');
       buffer.insert(c + 1, 'e');
     } else if (buffer.charAt(c) == '#') {
       buffer.setCharAt(c, 'i');
       buffer.insert(c + 1, 'g');
     } else if (buffer.charAt(c) == '!') {
       buffer.setCharAt(c, 's');
       buffer.insert(c + 1, 't');
     }
   }
 }
Example #29
0
  /**
   * Rounds a double and converts it into String.
   *
   * @param value the double value
   * @param afterDecimalPoint the (maximum) number of digits permitted after the decimal point
   * @return the double as a formatted string
   */
  public static String doubleToString(double value, int afterDecimalPoint) {

    StringBuffer stringBuffer;
    double temp;
    int i, dotPosition;
    long precisionValue;

    temp = value * Math.pow(10.0, afterDecimalPoint);
    if (Math.abs(temp) < Long.MAX_VALUE) {
      precisionValue = (temp > 0) ? (long) (temp + 0.5) : -(long) (Math.abs(temp) + 0.5);
      if (precisionValue == 0) {
        stringBuffer = new StringBuffer(String.valueOf(0));
      } else {
        stringBuffer = new StringBuffer(String.valueOf(precisionValue));
      }
      if (afterDecimalPoint == 0) {
        return stringBuffer.toString();
      }
      dotPosition = stringBuffer.length() - afterDecimalPoint;
      while (((precisionValue < 0) && (dotPosition < 1)) || (dotPosition < 0)) {
        if (precisionValue < 0) {
          stringBuffer.insert(1, 0);
        } else {
          stringBuffer.insert(0, 0);
        }
        dotPosition++;
      }
      stringBuffer.insert(dotPosition, '.');
      if ((precisionValue < 0) && (stringBuffer.charAt(1) == '.')) {
        stringBuffer.insert(1, 0);
      } else if (stringBuffer.charAt(0) == '.') {
        stringBuffer.insert(0, 0);
      }
      int currentPos = stringBuffer.length() - 1;
      while ((currentPos > dotPosition) && (stringBuffer.charAt(currentPos) == '0')) {
        stringBuffer.setCharAt(currentPos--, ' ');
      }
      if (stringBuffer.charAt(currentPos) == '.') {
        stringBuffer.setCharAt(currentPos, ' ');
      }

      return stringBuffer.toString().trim();
    }
    return new String("" + value);
  }
  /**
   * Some String can be too long to be correctly displayed on the screen. Mainly when it is a path
   * to a file. This method truncate a String.
   *
   * @param longString The <code>String</code> to be truncated
   * @param maxLength The maximum length of the <code>String</code>
   * @return The truncated string
   */
  public static String getShortStringOf(String longString, int maxLength) {
    int len = longString.length();

    if (len <= maxLength) return longString;
    else if (longString.indexOf('\\') == -1 && longString.indexOf('/') == -1) {
      StringBuffer buff = new StringBuffer(longString.substring(longString.length() - maxLength));
      for (int i = 0; i < 3; i++) buff.setCharAt(i, '.');
      return buff.toString();
    } else {
      int first = len / 2;
      int second = first;

      for (int i = first - 1; i >= 0; i--) {
        if (longString.charAt(i) == '\\' || longString.charAt(i) == '/') {
          first = i;
          break;
        }
      }

      for (int i = second + 1; i < len; i++) {
        if (longString.charAt(i) == '\\' || longString.charAt(i) == '/') {
          second = i;
          break;
        }
      }

      loop:
      while ((len - (second - first)) > maxLength) {
        out:
        for (int i = first - 1; i >= 0; i--) {
          switch (longString.charAt(i)) {
            case '\\':
            case '/':
              first = i;
              break out;
          }
        }

        if ((len - (second - first)) < maxLength) break loop;

        out2:
        for (int i = second + 1; i < len; i++) {
          switch (longString.charAt(i)) {
            case '\\':
            case '/':
              second = i;
              break out2;
          }
        }
      }

      return longString.substring(0, first + 1) + "..." + longString.substring(second);

      // return longString.substring(0, maxLength / 2) + "..." +
      //       longString.substring(len - (maxLength / 2));
    }
  }