Esempio n. 1
1
 /**
  * This is for debug only: print out training matrices in a CSV type format so that the matrices
  * can be examined in a spreadsheet program for debugging purposes.
  */
 private void WriteCSVfile(
     List<String> rowNames, List<String> colNames, float[][] buf, String fileName) {
   p("tagList.size()=" + tagList.size());
   try {
     FileWriter fw = new FileWriter(fileName + ".txt");
     PrintWriter bw = new PrintWriter(new BufferedWriter(fw));
     // write the first title row:
     StringBuffer sb = new StringBuffer(500);
     for (int i = 0, size = colNames.size(); i < size; i++) {
       sb.append("," + colNames.get(i));
     }
     bw.println(sb.toString());
     // loop on remaining rows:
     for (int i = 0, size = buf.length; i < size; i++) {
       sb.delete(0, sb.length());
       sb.append(rowNames.get(i));
       for (int j = 0, size2 = buf[i].length; j < size2; j++) {
         sb.append("," + buf[i][j]);
       }
       bw.println(sb.toString());
     }
     bw.close();
   } catch (IOException ioe) {
     ioe.printStackTrace();
   }
 }
 /**
  * Build a string representing a sequence of method calls needed to reach a particular child
  * method.
  *
  * @param allMethods previous method call sequence
  * @param newMethods names of each of the methods in callingMethods
  * @param callingMethods MethodEntry objects for each method
  * @param currentMethod current method being handled
  * @param rms contains setting determining if depth-first or breadth-first traversal has taken
  *     place.
  * @return
  */
 private String appendMN(
     String allMethods,
     String[] newMethods,
     List callingMethods,
     MethodEntry currentMethod,
     RelatedMethodsSettings rms) {
   StringBuffer result = new StringBuffer(allMethods.length() + 80);
   result.append(allMethods);
   if (rms.isDepthFirstOrdering()) {
     if (newMethods.length > 0) {
       if (result.length() > 0) result.append('.');
     }
     int index = callingMethods.indexOf(currentMethod);
     result.append(newMethods[index]);
     result.append("()");
   } else {
     if (newMethods.length > 0) {
       if (result.length() > 0) result.append('.');
       if (newMethods.length > 1) {
         result.append('[');
       }
       for (int i = 0; i < newMethods.length; i++) {
         if (i > 0) result.append(',');
         result.append(newMethods[i]);
         result.append("()");
       }
       if (newMethods.length > 1) {
         result.append(']');
       }
     }
   }
   return result.toString();
 }
 // 从页面中读取参数的设置值,按一定的规则设定好形成一个字符串并返回此字符串
 public static String getParametersFromRequest(HttpServletRequest request) {
   StringBuffer re = new StringBuffer();
   Integer type = Integer.parseInt(request.getParameter("processType"));
   if (type == MRBAYESTYPE) {
     return getParametersFromRequestMrBayes(request);
   }
   Enumeration parameterNames = request.getParameterNames();
   List paraList = new MultipleAlignmentDefaultDAO().getParameterList(type);
   if (paraList == null) {
     return "";
   }
   while (parameterNames.hasMoreElements()) {
     String paraName = (String) parameterNames.nextElement();
     if (paraList.contains(paraName)) {
       String paraValue = (String) request.getParameter(paraName);
       if (!"".equals(paraValue) && null != paraValue) {
         re.append(paraName + SEPERATEPARAMETERANDVALUE + paraValue + SEPERATEPARAMETERS);
       }
     }
   }
   if (re.length() > 0) {
     re.deleteCharAt(re.length() - 1);
   }
   return re.toString();
 }
    private Pair<MutableTextRange, StringBuffer> getFragmentByRange(int start, final int length) {
      final StringBuffer fragmentBuffer = new StringBuffer();
      int end = start + length;

      // restoring buffer and remove all subfragments from the list
      int documentOffset = 0;
      int effectiveOffset = 0;

      Iterator<Pair<MutableTextRange, StringBuffer>> iterator = myAffectedFragments.iterator();
      while (iterator.hasNext() && effectiveOffset <= end) {
        final Pair<MutableTextRange, StringBuffer> pair = iterator.next();
        final MutableTextRange range = pair.getFirst();
        final StringBuffer buffer = pair.getSecond();
        int effectiveFragmentEnd = range.getStartOffset() + buffer.length();

        if (range.getStartOffset() <= start && effectiveFragmentEnd >= end) return pair;

        if (effectiveFragmentEnd >= start) {
          final int effectiveStart = Math.max(effectiveOffset, start);
          if (range.getStartOffset() > start) {
            fragmentBuffer.append(
                myDocument.getCharsSequence(),
                effectiveStart - effectiveOffset + documentOffset,
                Math.min(range.getStartOffset(), end) - effectiveOffset + documentOffset);
          }
          if (end >= range.getStartOffset()) {
            fragmentBuffer.append(buffer);
            end =
                end > effectiveFragmentEnd
                    ? end - (buffer.length() - range.getLength())
                    : range.getEndOffset();
            effectiveFragmentEnd = range.getEndOffset();
            start = Math.min(start, range.getStartOffset());
            iterator.remove();
          }
        }

        documentOffset += range.getEndOffset() - effectiveOffset;
        effectiveOffset = effectiveFragmentEnd;
      }

      if (effectiveOffset < end) {
        final int effectiveStart = Math.max(effectiveOffset, start);
        fragmentBuffer.append(
            myDocument.getCharsSequence(),
            effectiveStart - effectiveOffset + documentOffset,
            end - effectiveOffset + documentOffset);
      }

      MutableTextRange newRange = new MutableTextRange(start, end);
      final Pair<MutableTextRange, StringBuffer> pair =
          new Pair<MutableTextRange, StringBuffer>(newRange, fragmentBuffer);
      for (Pair<MutableTextRange, StringBuffer> affectedFragment : myAffectedFragments) {
        MutableTextRange range = affectedFragment.getFirst();
        assert end <= range.getStartOffset() || range.getEndOffset() <= start
            : "Range :" + range + "; Added: " + newRange;
      }
      myAffectedFragments.add(pair);
      return pair;
    }
Esempio n. 5
0
  private static String[] getSuggestionsByValue(final String stringValue) {
    List<String> result = new ArrayList<String>();
    StringBuffer currentWord = new StringBuffer();

    boolean prevIsUpperCase = false;

    for (int i = 0; i < stringValue.length(); i++) {
      final char c = stringValue.charAt(i);
      if (Character.isUpperCase(c)) {
        if (currentWord.length() > 0 && !prevIsUpperCase) {
          result.add(currentWord.toString());
          currentWord = new StringBuffer();
        }
        currentWord.append(c);
      } else if (Character.isLowerCase(c)) {
        currentWord.append(Character.toUpperCase(c));
      } else if (Character.isJavaIdentifierPart(c) && c != '_') {
        if (Character.isJavaIdentifierStart(c) || currentWord.length() > 0 || !result.isEmpty()) {
          currentWord.append(c);
        }
      } else {
        if (currentWord.length() > 0) {
          result.add(currentWord.toString());
          currentWord = new StringBuffer();
        }
      }

      prevIsUpperCase = Character.isUpperCase(c);
    }

    if (currentWord.length() > 0) {
      result.add(currentWord.toString());
    }
    return ArrayUtil.toStringArray(result);
  }
Esempio n. 6
0
 // Serialize the bean using the specified namespace prefix & uri
 public String serialize(Object bean) throws IntrospectionException, IllegalAccessException {
   // Use the class name as the name of the root element
   String className = bean.getClass().getName();
   String rootElementName = null;
   if (bean.getClass().isAnnotationPresent(ObjectXmlAlias.class)) {
     AnnotatedElement annotatedElement = bean.getClass();
     ObjectXmlAlias aliasAnnotation = annotatedElement.getAnnotation(ObjectXmlAlias.class);
     rootElementName = aliasAnnotation.value();
   }
   // Use the package name as the namespace URI
   Package pkg = bean.getClass().getPackage();
   nsURI = pkg.getName();
   // Remove a trailing semi-colon (;) if present (i.e. if the bean is an array)
   className = StringUtils.deleteTrailingChar(className, ';');
   StringBuffer sb = new StringBuffer(className);
   String objectName = sb.delete(0, sb.lastIndexOf(".") + 1).toString();
   domDocument = createDomDocument(objectName);
   document = domDocument.getDocument();
   Element root = document.getDocumentElement();
   // Parse the bean elements
   getBeanElements(root, rootElementName, className, bean);
   StringBuffer xml = new StringBuffer();
   if (prettyPrint)
     xml.append(domDocument.serialize(lineSeperator, indentChars, includeXmlProlog));
   else xml.append(domDocument.serialize(includeXmlProlog));
   if (!includeTypeInfo) {
     int index = xml.indexOf(root.getNodeName());
     xml.delete(index - 1, index + root.getNodeName().length() + 2);
     xml.delete(xml.length() - root.getNodeName().length() - 4, xml.length());
   }
   return xml.toString();
 }
Esempio n. 7
0
  @Override
  public String toString() {
    StringBuffer sb = new StringBuffer();

    if (this.getId() != null) {
      sb.append(String.format("ID = %d", this.getId()));
    }
    if (StringUtil.isVazia(this.getNome())) {
      if (sb.length() > 0) {
        sb.append(", ");
      }
      sb.append(String.format("nome = '%s'", this.getNome()));
    }
    if (this.getTipo() != null) {
      if (sb.length() > 0) {
        sb.append(", ");
      }
      sb.append(String.format("tipo = '%s'", this.getTipo()));
    }
    try {
      PessoaIdentificacao cpfCnpj = PessoaUtils.recuperarCpfCnpj(this);
      if (cpfCnpj != null) {
        if (sb.length() > 0) {
          sb.append(", ");
        }
        sb.append(String.format("CPF/CNPJ = %s", cpfCnpj.getIdentificacao()));
      }
    } catch (PessoaIdentificacaoNaoEncontradaException e) {
    }
    return sb.toString();
  }
  /**
   * Constructs a new path from current user path. This is an easy way to get a path if the user
   * specified, for example, "..\Java" as new path. This method will return the argument if this one
   * is a path to a root (i.e, if <code>change</code> is equal to C:\Jdk, constructPath will return
   * C:\Jdk).
   *
   * @param change The modification to apply to the path
   */
  public static String constructPath(String change) {
    if (beginsWithRoot(change)) return change;

    StringBuffer newPath = new StringBuffer(getUserDirectory());

    char current;
    char lastChar = '\0';
    boolean toAdd = false;
    change = change.trim();
    StringBuffer buf = new StringBuffer(change.length());

    for (int i = 0; i < change.length(); i++) {
      switch ((current = change.charAt(i))) {
        case '.':
          if (lastChar == '.') {
            String parent = (new File(newPath.toString())).getParent();
            if (parent != null) newPath = new StringBuffer(parent);
          } else if ((lastChar != '\0' && lastChar != '\\' && lastChar != '/')
              || (i < change.length() - 1 && change.charAt(i + 1) != '.')) buf.append('.');
          lastChar = '.';
          break;
        case '\\':
        case '/':
          if (lastChar == '\0') {
            newPath = new StringBuffer(getRoot(newPath.toString()));
          } else {
            char c = newPath.charAt(newPath.length() - 1);
            if (c != '\\' && c != '/') newPath.append(File.separator).append(buf.toString());
            else newPath.append(buf.toString());
            buf = new StringBuffer();
            toAdd = false;
          }
          lastChar = '\\';
          break;
        case '~':
          if (i < change.length() - 1) {
            if (change.charAt(i + 1) == '\\' || change.charAt(i + 1) == '/')
              newPath = new StringBuffer(getHomeDirectory());
            else buf.append('~');
          } else if (i == 0) newPath = new StringBuffer(getHomeDirectory());
          else buf.append('~');
          lastChar = '~';
          break;
        default:
          lastChar = current;
          buf.append(current);
          toAdd = true;
          break;
      }
    }

    if (toAdd) {
      char c = newPath.charAt(newPath.length() - 1);
      if (c != '\\' && c != '/') newPath.append(File.separator).append(buf.toString());
      else newPath.append(buf.toString());
    }

    return newPath.toString();
  }
Esempio n. 9
0
 public TextState copyAll() {
   TextState tmp = copyState();
   if (s.length() == 0) return tmp;
   for (int i = 0; i < s.length(); i++) {
     tmp.s.append(s.charAt(i));
   }
   return tmp;
 }
  /**
   * Creates a new <code>DictionaryNameFactory</code>.
   *
   * @param file the file from which the names can be read.
   * @param nameFactory the name factory from which names will be retrieved if the list of read
   *     names has been exhausted.
   */
  public DictionaryNameFactory(File file, NameFactory nameFactory) throws IOException {
    this.names = new ArrayList();
    this.nameFactory = nameFactory;

    Reader reader = new FileReader(file);

    try {
      StringBuffer buffer = new StringBuffer();

      while (true) {
        // Read the next character.
        int c = reader.read();

        // Is it a valid identifier character?
        if (c != -1
            && (buffer.length() == 0
                ? Character.isJavaIdentifierStart((char) c)
                : Character.isJavaIdentifierPart((char) c))) {
          // Append it to the current identifier.
          buffer.append((char) c);
        } else {
          // Did we collect a new identifier?
          if (buffer.length() > 0) {
            // Add the completed name to the list of names, if it's
            // not in it yet.
            String name = buffer.toString();
            if (!names.contains(name)) {
              names.add(name);
            }

            // Clear the buffer.
            buffer.setLength(0);
          }

          // Is this the beginning of a comment line?
          if (c == COMMENT_CHARACTER) {
            // Skip all characters till the end of the line.
            do {
              c = reader.read();
            } while (c != -1 && c != '\n' && c != '\r');
          }

          // Is this the end of the file?
          if (c == -1) {
            // Just return.
            return;
          }
        }
      }
    } finally {
      reader.close();
    }
  }
Esempio n. 11
0
 public String next() {
   ListEntry listEntry = entries.next();
   StringBuffer line = new StringBuffer();
   for (String tag : listEntry.getCustomElements().getTags()) {
     line.append("\"").append(listEntry.getCustomElements().getValue(tag)).append("\"");
     line.append(",");
   }
   if (line.length() > 0) {
     line.deleteCharAt(line.length() - 1);
   }
   return line.toString();
 }
Esempio n. 12
0
 public static <T> String collectionToCommaString(Collection<T> list) {
   if (CollectionUtils.isEmpty(list)) return "";
   StringBuffer result = new StringBuffer();
   for (T item : list) {
     if (item != null) {
       result.append(item.toString() + ",");
     }
   }
   if (result.length() >= 1) {
     result.setLength(result.length() - 1);
   }
   return result.toString();
 }
 // return all grantees: thr_0, thr_1, thr_2 ..., excluding itself
 private static String getAllGrantees() {
   StringBuffer aStr = new StringBuffer("  ");
   Map<String, String> userPasswd =
       (Map<String, String>) SQLBB.getBB().getSharedMap().get(SQLSecurityTest.userPasswdMap);
   for (Map.Entry<String, String> e : userPasswd.entrySet()) {
     if (!e.getKey().equalsIgnoreCase("thr_" + RemoteTestModule.getCurrentThread().getThreadId()))
       aStr.append(e.getKey() + ", ");
   }
   if (aStr.charAt(aStr.length() - 2) == ',') {
     aStr.deleteCharAt(aStr.length() - 2);
   }
   aStr.deleteCharAt(0); // delete the leading space
   return aStr.toString();
 }
  protected void updateStatusLabel(JLabel label) {
    //		System.out.println("M="+move+",F="+fight+",G="+magic+",currentCount="+currentCount+"
    // NeedsToFatigue="+needsToFatigue()+",NeedsToMakeChange="+needsToMakeChange());
    StringBuffer restrictions = new StringBuffer();
    if (move < 0 || makeChangeType == TYPE_MOVE || (move > 0 && fight == 0)) {
      restrictions.append("MOVE");
    }
    if (fight < 0 || makeChangeType == TYPE_FIGHT || (fight > 0 && move == 0)) {
      if (restrictions.length() > 0) {
        restrictions.append(",");
      }
      restrictions.append("FIGHT");
    }
    if (restrictions.length() > 0) {
      restrictions.append(" only");
    }
    String warning = restrictions.length() == 0 ? "" : (" (" + restrictions.toString() + ")");
    String lostAsteriskWarning =
        lostAsterisks == 0
            ? ""
            : " (lost " + lostAsterisks + " asterisk" + (lostAsterisks == 1 ? "" : "s") + ")";
    warning += lostAsteriskWarning;

    if (!needsToFatigue() && !needsToMakeChange()) {
      label.setText(lostAsteriskWarning);
    } else if (needsToFatigue()) {
      label.setText(
          "Fatigue " + currentCount + " asterisk" + (currentCount == 1 ? "" : "s") + warning);
      label.setForeground(Color.black);
    } else if (needsToMakeChange()) {
      if (canMakeChange()) {
        int changeCount = 0;
        if (move < 0) changeCount = move;
        if (fight < 0) changeCount = fight;
        if (magic < 0) changeCount = magic;
        if (changeCount == 0) changeCount = currentCount;
        label.setText(
            "Make change for "
                + (-changeCount)
                + " asterisk"
                + (changeCount == -1 ? "" : "s")
                + warning);
        label.setForeground(Color.red);
      } else {
        label.setText("Can't make change, so the extra asterisk will be lost!");
        label.setForeground(Color.red);
      }
    }
  }
  /**
   * Output the specified {@link Collection} in proper columns.
   *
   * @param stuff the stuff to print
   */
  public void printColumns(final Collection stuff) throws IOException {
    if ((stuff == null) || (stuff.size() == 0)) {
      return;
    }

    int width = getTermwidth();
    int maxwidth = 0;

    for (Iterator i = stuff.iterator();
        i.hasNext();
        maxwidth = Math.max(maxwidth, i.next().toString().length())) {;
    }

    StringBuffer line = new StringBuffer();

    int showLines;

    if (usePagination) showLines = getTermheight() - 1; // page limit
    else showLines = Integer.MAX_VALUE;

    for (Iterator i = stuff.iterator(); i.hasNext(); ) {
      String cur = (String) i.next();

      if ((line.length() + maxwidth) > width) {
        printString(line.toString().trim());
        printNewline();
        line.setLength(0);
        if (--showLines == 0) { // Overflow
          printString(loc.getString("display-more"));
          flushConsole();
          int c = readVirtualKey();
          if (c == '\r' || c == '\n') showLines = 1; // one step forward
          else if (c != 'q') showLines = getTermheight() - 1; // page forward

          back(loc.getString("display-more").length());
          if (c == 'q') break; // cancel
        }
      }

      pad(cur, maxwidth + 3, line);
    }

    if (line.length() > 0) {
      printString(line.toString().trim());
      printNewline();
      line.setLength(0);
    }
  }
  @SuppressWarnings("unchecked")
  public List<MessageBundleProperty> search(
      String searchQuery, String module, String baseName, String locale) {
    List<String> values = new ArrayList<String>();
    StringBuffer queryString = new StringBuffer("");

    try {
      if (searchQuery != null && searchQuery.length() > 0) {
        queryString.append("(defaultValue like ? OR value like ? OR propertyName = ?)");
        values.add("%" + searchQuery + "%");
        values.add("%" + searchQuery + "%");
        values.add(searchQuery);
      }
      if (module != null && module.length() > 0) {
        if (queryString.length() > 0) {
          queryString.append(" AND ");
        }
        queryString.append("moduleName = ? ");
        values.add(module);
      }
      if (baseName != null && baseName.length() > 0) {
        if (queryString.length() > 0) {
          queryString.append(" AND ");
        }
        queryString.append("baseName = ?");
        values.add(baseName);
      }
      if (locale != null && locale.length() > 0) {
        if (queryString.length() > 0) {
          queryString.append(" AND ");
        }
        queryString.append("locale = ?");
        values.add(locale);
      }

      if (queryString.length() > 0) {
        queryString.insert(0, "from MessageBundleProperty where ");
      } else {
        queryString.insert(0, "from MessageBundleProperty");
      }

      return getHibernateTemplate().find(queryString.toString(), values.toArray());

    } catch (Exception e) {
      logger.error("problem searching the message bundle data", e);
    }
    return new ArrayList<MessageBundleProperty>();
  }
Esempio n. 17
0
  public List subByDistance(SimHash simHash, int distance) {
    // 分成几组来检查
    int numEach = this.hashbits / (distance + 1);
    List characters = new ArrayList();

    StringBuffer buffer = new StringBuffer();

    int k = 0;
    for (int i = 0; i < this.intSimHash.bitLength(); i++) {
      // 当且仅当设置了指定的位时,返回 true
      boolean sr = simHash.intSimHash.testBit(i);

      if (sr) {
        buffer.append("1");
      } else {
        buffer.append("0");
      }

      if ((i + 1) % numEach == 0) {
        // 将二进制转为BigInteger
        BigInteger eachValue = new BigInteger(buffer.toString(), 2);
        buffer.delete(0, buffer.length());
        characters.add(eachValue);
      }
    }

    return characters;
  }
Esempio n. 18
0
    public void run() {
      StringBuffer data = new StringBuffer();
      Print.logDebug("Client:InputThread started");

      while (true) {
        data.setLength(0);
        boolean timeout = false;
        try {
          if (this.readTimeout > 0L) {
            this.socket.setSoTimeout((int) this.readTimeout);
          }
          ClientSocketThread.socketReadLine(this.socket, -1, data);
        } catch (InterruptedIOException ee) { // SocketTimeoutException ee) {
          // error("Read interrupted (timeout) ...");
          if (getRunStatus() != THREAD_RUNNING) {
            break;
          }
          timeout = true;
          // continue;
        } catch (Throwable t) {
          Print.logError("Client:InputThread - " + t);
          t.printStackTrace();
          break;
        }
        if (!timeout || (data.length() > 0)) {
          ClientSocketThread.this.handleMessage(data.toString());
        }
      }

      synchronized (this.threadLock) {
        this.isRunning = false;
        Print.logDebug("Client:InputThread stopped");
        this.threadLock.notify();
      }
    }
  public String toString() {
    StringBuffer b = new StringBuffer();
    b.append("ID:" + id);
    b.append("\tName:" + name);
    b.append("\tSex:" + sex + "\n");
    b.append("\tAffected:" + affection + "\n");

    if (mother == null) {
      b.append("\tMother: null");
    } else {
      b.append("\tMother:" + mother.id);
    }

    if (father == null) {
      b.append("\tFather: null");
    } else {
      b.append("\tFather:" + father.id);
    }

    b.append("\tChildren:");
    Vector<PelicanPerson> children = getChildren();
    if (children.size() > 0) {
      Iterator<PelicanPerson> it = children.iterator();
      while (it.hasNext()) {
        PelicanPerson p = it.next();
        b.append(p.id + ",");
      }
      b.deleteCharAt(b.length() - 1);
    } else {
      b.append("none");
    }
    b.append("\n");
    return b.toString();
  }
  private void parse(String filename) throws Exception {
    BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename)));
    StringBuffer sb = new StringBuffer();

    int j;
    while ((j = br.read()) != -1) {
      char next = (char) j;

      if (next >= 'A' && next <= 'z') {
        sb.append(next);
      }

      if (sb.length() == 4) {
        String qGram = sb.toString().toUpperCase();
        sb = new StringBuffer();

        int frequency = 0;

        if (map.containsKey(qGram)) {
          frequency = map.get(qGram);
        }

        frequency++;
        map.put(qGram, frequency);
      }
    }
    br.close();
  }
Esempio n. 21
0
 // ----------------------------------------------------------------------
 // for "SrvTypeRqst"
 // get the list of service types for specified scope & naming authority
 // ----------------------------------------------------------------------
 public synchronized String getServiceTypeList(String na, String scope) {
   Vector typelist = new Vector(5);
   Iterator values = table.values().iterator();
   while (values.hasNext()) {
     Entry e = (Entry) values.next();
     if (!e.getDeleted()
         && // nor deleted
         scope.equalsIgnoreCase(e.getScope())
         && // match scope
         (na.equals("*")
             || // NA wildcard
             na.equalsIgnoreCase(e.getNA()))
         && // match NA
         !typelist.contains(e.getType())) {
       typelist.addElement(e.getType());
     }
   }
   StringBuffer tl = new StringBuffer();
   for (int i = 0; i < typelist.size(); i++) {
     String s = (String) typelist.elementAt(i);
     if (tl.length() > 0) tl.append(",");
     tl.append(s);
   }
   return tl.toString();
 }
Esempio n. 22
0
 private ClassLoaderStrategy getClassLoaderStrategy(String fullyQualifiedClassName)
     throws Exception {
   try {
     // Get just the package name
     StringBuffer sb = new StringBuffer(fullyQualifiedClassName);
     sb.delete(sb.lastIndexOf("."), sb.length());
     currentPackage = sb.toString();
     // Retrieve the Java classpath from the system properties
     String cp = System.getProperty("java.class.path");
     String sepChar = System.getProperty("path.separator");
     String[] paths = StringUtils.pieceList(cp, sepChar.charAt(0));
     ClassLoaderStrategy cl =
         ClassLoaderUtil.getClassLoader(ClassLoaderUtil.FILE_SYSTEM_CLASS_LOADER, new String[] {});
     // Iterate through paths until class with the specified name is found
     String classpath = StringUtils.replaceChar(currentPackage, '.', File.separatorChar);
     for (int i = 0; i < paths.length; i++) {
       Class[] classes = cl.getClasses(paths[i] + File.separatorChar + classpath, currentPackage);
       for (int j = 0; j < classes.length; j++) {
         if (classes[j].getName().equals(fullyQualifiedClassName)) {
           return ClassLoaderUtil.getClassLoader(
               ClassLoaderUtil.FILE_SYSTEM_CLASS_LOADER, new String[] {paths[i]});
         }
       }
     }
     throw new Exception("Class could not be found.");
   } catch (Exception e) {
     System.err.println("Exception creating class loader strategy.");
     System.err.println(e.getMessage());
     throw e;
   }
 }
  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) {

    }
  }
 /**
  * Reads and returns the VM arguments specified in the running platform's .ini file, or am empty
  * string if none.
  *
  * @return VM arguments specified in the running platform's .ini file
  */
 public static String getIniVMArgs() {
   File installDirectory = new File(Platform.getInstallLocation().getURL().getFile());
   if (Platform.getOS().equals(Platform.OS_MACOSX))
     installDirectory = new File(installDirectory, "Eclipse.app/Contents/MacOS"); // $NON-NLS-1$
   File eclipseIniFile = new File(installDirectory, "eclipse.ini"); // $NON-NLS-1$
   BufferedReader in = null;
   StringBuffer result = new StringBuffer();
   if (eclipseIniFile.exists()) {
     try {
       in = new BufferedReader(new FileReader(eclipseIniFile));
       String str;
       boolean vmargs = false;
       while ((str = in.readLine()) != null) {
         if (vmargs) {
           if (result.length() > 0) result.append(" "); // $NON-NLS-1$
           result.append(str);
         }
         // start concat'ng if we have vmargs
         if (vmargs == false && str.equals("-vmargs")) // $NON-NLS-1$
         vmargs = true;
       }
     } catch (IOException e) {
       MDECore.log(e);
     } finally {
       if (in != null)
         try {
           in.close();
         } catch (IOException e) {
           MDECore.log(e);
         }
     }
   }
   return result.toString();
 }
Esempio n. 25
0
  void applyDirectives() {
    findRemoveDirectives(true);

    StringBuffer buffer = new StringBuffer();
    String head = "", toe = "; \n";

    if (crispBox.isSelected()) buffer.append(head + "crisp=true" + toe);
    if (!fontField.getText().trim().equals(""))
      buffer.append(head + "font=\"" + fontField.getText().trim() + "\"" + toe);
    if (globalKeyEventsBox.isSelected()) buffer.append(head + "globalKeyEvents=true" + toe);
    if (pauseOnBlurBox.isSelected()) buffer.append(head + "pauseOnBlur=true" + toe);
    if (!preloadField.getText().trim().equals(""))
      buffer.append(head + "preload=\"" + preloadField.getText().trim() + "\"" + toe);
    /*if ( transparentBox.isSelected() )
    buffer.append( head + "transparent=true" + toe );*/

    Sketch sketch = editor.getSketch();
    SketchCode code = sketch.getCode(0); // first tab
    if (buffer.length() > 0) {
      code.setProgram("/* @pjs " + buffer.toString() + " */\n\n" + code.getProgram());
      if (sketch.getCurrentCode() == code) // update textarea if on first tab
      {
        editor.setText(sketch.getCurrentCode().getProgram());
        editor.setSelection(0, 0);
      }

      sketch.setModified(false);
      sketch.setModified(true);
    }
  }
  private static void doCommitTransaction(
      @NotNull Document document, @NotNull DocumentChangeTransaction documentChangeTransaction) {
    DocumentEx ex = (DocumentEx) document;
    ex.suppressGuardedExceptions();
    try {
      boolean isReadOnly = !document.isWritable();
      ex.setReadOnly(false);
      final Set<Pair<MutableTextRange, StringBuffer>> affectedFragments =
          documentChangeTransaction.getAffectedFragments();
      for (final Pair<MutableTextRange, StringBuffer> pair : affectedFragments) {
        final StringBuffer replaceBuffer = pair.getSecond();
        final MutableTextRange range = pair.getFirst();
        if (replaceBuffer.length() == 0) {
          ex.deleteString(range.getStartOffset(), range.getEndOffset());
        } else if (range.getLength() == 0) {
          ex.insertString(range.getStartOffset(), replaceBuffer);
        } else {
          ex.replaceString(range.getStartOffset(), range.getEndOffset(), replaceBuffer);
        }
      }

      ex.setReadOnly(isReadOnly);
      // if(documentChangeTransaction.getChangeScope() != null) {
      //
      // LOG.assertTrue(document.getText().equals(documentChangeTransaction.getChangeScope().getText()),
      //                 "Psi to document synchronization failed (send to IK)");
      // }
    } finally {
      ex.unSuppressGuardedExceptions();
    }
  }
Esempio n. 27
0
 private static String buildAllMethodNamesString(
     String allMethodNames, List<MethodEntry> parents) {
   StringBuffer allMN = new StringBuffer(120);
   allMN.append(allMethodNames);
   if (allMN.length() > 0) {
     allMN.append(".");
   }
   if (parents.size() > 1) {
     allMN.append("[");
   }
   {
     boolean first = true;
     for (MethodEntry entry : parents) {
       if (!first) {
         allMN.append(",");
       }
       first = false;
       allMN.append(((PsiMethod) entry.myEnd).getName());
     }
   }
   if (parents.size() > 1) {
     allMN.append("]");
   }
   return allMN.toString();
 }
Esempio n. 28
0
  /**
   * This method duplicates the functionality of ExceptionUtils.describeStackLevels which is no
   * longer supported in Rice.
   *
   * @param fromLevel
   * @param toLevel
   * @return
   */
  public static String getMethodPath(int fromLevel, int toLevel) {
    StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
    // increase the levels to avoid including the method that called this.
    fromLevel = fromLevel + 1;
    toLevel = toLevel + 1;

    if (fromLevel <= 0) {
      throw new IllegalArgumentException("invalid fromLevel (" + fromLevel + " < 0)");
    }
    if (fromLevel > toLevel) {
      throw new IllegalArgumentException(
          "invalid levels (fromLevel " + fromLevel + " > toLevel " + toLevel + ")");
    }
    if (toLevel >= stackTraceElements.length) {
      throw new IllegalArgumentException(
          "invalid toLevel (" + toLevel + " >= " + stackTraceElements.length + ")");
    }

    StringBuffer result = new StringBuffer();
    int elementIndex = 0;
    for (StackTraceElement element : stackTraceElements) {
      if (elementIndex >= fromLevel && elementIndex >= toLevel) {
        if (result.length() > 0) {
          result.append(" from ");
        }
        result.append(element.getClassName()).append(".");
        result.append(element.getMethodName()).append("(");
        result.append(element.getFileName()).append(":");
        result.append(element.getLineNumber()).append(")");
      }
      elementIndex++;
    }
    return result.toString();
  }
Esempio n. 29
0
  /**
   * @return the clipboard content as a String (DataFlavor.stringFlavor) Code snippet adapted from
   *     jEdit (Registers.java), http://www.jedit.org. Returns null if clipboard is empty.
   */
  public static String getClipboardStringContent(Clipboard clipboard) {
    // Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    try {
      String selection =
          (String) (clipboard.getContents(null).getTransferData(DataFlavor.stringFlavor));
      if (selection == null) return null;

      boolean trailingEOL =
          (selection.endsWith("\n") || selection.endsWith(System.getProperty("line.separator")));

      // Some Java versions return the clipboard contents using the native line separator,
      // so have to convert it here , see jEdit's "registers.java"
      BufferedReader in = new BufferedReader(new StringReader(selection));
      StringBuffer buf = new StringBuffer();
      String line;
      while ((line = in.readLine()) != null) {
        buf.append(line);
        buf.append('\n');
      }
      // remove trailing \n
      if (!trailingEOL) buf.setLength(buf.length() - 1);
      return buf.toString();
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
Esempio n. 30
0
    /**
     * Create a Transferable to use as the source for a data transfer.
     *
     * @param c The component holding the data to be transfered. This argument is provided to enable
     *     sharing of TransferHandlers by multiple components.
     * @return The representation of the data to be transfered.
     */
    protected Transferable createTransferable(JComponent c) {
      Object[] values = null;
      if (c instanceof JList) {
        values = ((JList) c).getSelectedValues();
      } else if (c instanceof JTable) {
        JTable table = (JTable) c;
        int[] rows = table.getSelectedRows();
        if (rows != null) {
          values = new Object[rows.length];
          for (int i = 0; i < rows.length; i++) {
            values[i] = table.getValueAt(rows[i], 0);
          }
        }
      }
      if (values == null || values.length == 0) {
        return null;
      }

      StringBuffer plainBuf = new StringBuffer();
      StringBuffer htmlBuf = new StringBuffer();

      htmlBuf.append("<html>\n<body>\n<ul>\n");

      for (Object obj : values) {
        String val = ((obj == null) ? "" : obj.toString());
        plainBuf.append(val + "\n");
        htmlBuf.append("  <li>" + val + "\n");
      }

      // remove the last newline
      plainBuf.deleteCharAt(plainBuf.length() - 1);
      htmlBuf.append("</ul>\n</body>\n</html>");

      return new FileTransferable(plainBuf.toString(), htmlBuf.toString(), values);
    }