public String getUrl() {
    StringBuilder sb = new StringBuilder();
    StringBuilder ori = getOut();
    this.setOut(sb);
    TreeMap<Integer, cn.bran.japid.template.ActionRunner> parentActionRunners = actionRunners;
    actionRunners = new TreeMap<Integer, cn.bran.japid.template.ActionRunner>();
    // line 48, japidviews\AdminController\flashPurchaseList.html
    p("            	"); // line 48, japidviews\AdminController\flashPurchaseList.html
    p(
        lookup(
            "AdminController.flashPurchaseList",
            new Object[] {})); // line 49, japidviews\AdminController\flashPurchaseList.html
    p("            "); // line 49, japidviews\AdminController\flashPurchaseList.html

    this.setOut(ori);
    if (actionRunners.size() > 0) {
      StringBuilder _sb2 = new StringBuilder();
      int segStart = 0;
      for (Map.Entry<Integer, cn.bran.japid.template.ActionRunner> _arEntry :
          actionRunners.entrySet()) {
        int pos = _arEntry.getKey();
        _sb2.append(sb.substring(segStart, pos));
        segStart = pos;
        cn.bran.japid.template.ActionRunner _a_ = _arEntry.getValue();
        _sb2.append(_a_.run().getContent().toString());
      }
      _sb2.append(sb.substring(segStart));
      actionRunners = parentActionRunners;
      return _sb2.toString();
    } else {
      actionRunners = parentActionRunners;
      return sb.toString();
    }
  }
Ejemplo n.º 2
1
  /** 選択されている行をコピーする。 */
  public void copyRow() {

    StringBuilder sb = new StringBuilder();
    int numRows = view.getTable().getSelectedRowCount();
    int[] rowsSelected = view.getTable().getSelectedRows();
    int numColumns = view.getTable().getColumnCount();

    for (int i = 0; i < numRows; i++) {
      if (tableModel.getObject(rowsSelected[i]) != null) {
        StringBuilder s = new StringBuilder();
        for (int col = 0; col < numColumns; col++) {
          Object o = view.getTable().getValueAt(rowsSelected[i], col);
          if (o != null) {
            s.append(o.toString());
          }
          s.append(",");
        }
        if (s.length() > 0) {
          s.setLength(s.length() - 1);
        }
        sb.append(s.toString()).append("\n");
      }
    }
    if (sb.length() > 0) {
      StringSelection stsel = new StringSelection(sb.toString());
      Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stsel, stsel);
    }
  }
Ejemplo n.º 3
1
  @Override
  public Map<String, Object> saveMap(Map<String, Object> object, Class clazz) throws Exception {

    StringBuilder sql = new StringBuilder();
    EntityInfo entityInfo = ClassUtils.getEntityInfoByClazz(clazz);

    sql.append("INSERT INTO ");
    sql.append(entityInfo.getTableName());
    sql.append("(");

    List<String> columns = new ArrayList<String>();
    List<Object> values = new ArrayList<Object>();
    Map<String, String> ptcMap = ClassUtils.propToColumnMap.get(entityInfo.getClazzName());
    for (Map.Entry<String, Object> entry : object.entrySet()) {
      columns.add(ptcMap.get(entry.getKey()));
      values.add(entry.getValue());
    }
    sql.append(StringUtils.join(columns, ","));
    sql.append(") VALUES(");
    String[] params = new String[values.size()];
    Arrays.fill(params, "?");
    sql.append(StringUtils.join(params, ","));
    sql.append(")");
    if (entityInfo.getStrategy().equals(GenerationType.IDENTITY)) {
      Long id = addReutrnId(sql.toString(), values);
      if (id != null) {
        object.put(entityInfo.getPkName(), id);
      }
    } else {
      add(sql.toString(), values);
    }
    return object;
  }
Ejemplo n.º 4
1
    // create from a dataset
    public VariableBean(Variable vs) {
      this.vs = vs;
      // vs = (v instanceof VariableEnhanced) ? (VariableEnhanced) v : new VariableStandardized( v);

      setName(vs.getShortName());
      setDescription(vs.getDescription());
      setUnits(vs.getUnitsString());
      setDataType(vs.getDataType().toString());

      // Attribute csAtt = vs.findAttribute("_coordSystems");
      // if (csAtt != null)
      //  setCoordSys( csAtt.getStringValue());

      // collect dimensions
      StringBuilder lens = new StringBuilder();
      StringBuilder names = new StringBuilder();
      java.util.List dims = vs.getDimensions();
      for (int j = 0; j < dims.size(); j++) {
        ucar.nc2.Dimension dim = (ucar.nc2.Dimension) dims.get(j);
        if (j > 0) {
          lens.append(",");
          names.append(",");
        }
        String name = dim.isShared() ? dim.getName() : "anon";
        names.append(name);
        lens.append(dim.getLength());
      }
      setDimensions(names.toString());
      setShape(lens.toString());
    }
  /**
   * Returns date in the format: neededDatePattern, in case if year or month isn't entered, current
   * year/month is put.
   *
   * @return correct date.
   */
  private Date getCorrectedDate(String enteredDate) {
    Queue<String> dateParts = new ArrayDeque<>(3);
    StringBuilder number = new StringBuilder();
    for (char symbol : enteredDate.toCharArray()) {
      if (Character.isDigit(symbol)) {
        number.append(symbol);
      } else if (number.length() > 0) {
        dateParts.add(number.toString());
        number = new StringBuilder();
      }
    }
    if (number.length() > 0) {
      dateParts.add(number.toString());
    }

    Calendar currentDate = Calendar.getInstance();
    switch (dateParts.size()) {
      case 1:
        dateParts.add(Integer.toString(currentDate.get(Calendar.MONTH) + 1));
      case 2:
        dateParts.add(Integer.toString(currentDate.get(Calendar.YEAR)));
    }

    try {
      return new SimpleDateFormat("dd.MM.yyyy")
          .parse(dateParts.remove() + '.' + dateParts.remove() + '.' + dateParts.remove());

    } catch (ParseException e) {
      throw new RuntimeException(e); // todo change exception
    }
  }
Ejemplo n.º 6
1
  /**
   * Configures the basic escapes based on the configured options.
   *
   * @param options Options that will affect what is escaped.
   */
  private void setupEscapes(Options options) {
    escapes = new ArrayList<Escape>();

    // confusingly, this replaces single backslashes with double backslashes.
    // Man, I miss Groovy's slashy strings in these moments...
    escapes.add(new Escape("\\\\", "\\\\\\\\"));

    // creates an set of characters that are universally escaped.
    // these characters are wrapped in \Q...\E to ensure they aren't treated as special characters.
    StringBuilder chars = new StringBuilder("([\\Q`*_{}[]#");
    if (options.tables.isConvertedToText() && !options.tables.isRenderedAsCode()) {
      chars.append('|');
    }
    chars.append("\\E])");
    escapes.add(new Escape(chars.toString(), "\\\\$1"));

    // finally, escape certain characters only if they are leading characters
    StringBuilder leadingChars = new StringBuilder("^( ?+)([\\Q-+");
    if (options.definitionLists) {
      leadingChars.append(':');
    }
    leadingChars.append("\\E])");
    escapes.add(new Escape(leadingChars.toString(), "$1\\\\$2"));

    // setup the leading character reverser
    // this is a bit of a hack to undo leading character escapes.
    unescapeLeadingChars = Pattern.compile(leadingChars.insert(6, "\\\\").toString());
  }
Ejemplo n.º 7
1
 /**
  * Given a string, return an array of tokens. The separator can be escaped with the '\' character.
  * The '\' character may also be escaped by the '\' character.
  *
  * @param s the string to tokenize.
  * @param separator the separator char.
  * @param maxTokens the maxmimum number of tokens returned. If the max is reached, the remaining
  *     part of s is appended to the end of the last token.
  * @return an array of tokens.
  */
 public static String[] tokenize(String s, char separator, int maxTokens) {
   List tokens = new ArrayList();
   StringBuilder token = new StringBuilder();
   boolean prevIsEscapeChar = false;
   for (int i = 0; i < s.length(); i += Character.charCount(i)) {
     int currentChar = s.codePointAt(i);
     if (prevIsEscapeChar) {
       // Case 1:  escaped character
       token.appendCodePoint(currentChar);
       prevIsEscapeChar = false;
     } else if (currentChar == separator && tokens.size() < maxTokens - 1) {
       // Case 2:  separator
       tokens.add(token.toString());
       token = new StringBuilder();
     } else if (currentChar == '\\') {
       // Case 3:  escape character
       prevIsEscapeChar = true;
     } else {
       // Case 4:  regular character
       token.appendCodePoint(currentChar);
     }
   }
   if (token.length() > 0) {
     tokens.add(token.toString());
   }
   return (String[]) tokens.toArray(new String[] {});
 }
Ejemplo n.º 8
1
  protected void calculateModelAttributes() {
    String pakkage = calculateJavaModelPackage();

    StringBuilder sb = new StringBuilder();
    sb.append(pakkage);
    sb.append('.');
    sb.append(fullyQualifiedTable.getDomainObjectName());
    sb.append("Key"); // $NON-NLS-1$
    setPrimaryKeyType(sb.toString());

    sb.setLength(0);
    sb.append(pakkage);
    sb.append('.');
    sb.append(fullyQualifiedTable.getDomainObjectName());
    setBaseRecordType(sb.toString());

    sb.setLength(0);
    sb.append(pakkage);
    sb.append('.');
    sb.append(fullyQualifiedTable.getDomainObjectName());
    sb.append("WithBLOBs"); // $NON-NLS-1$
    setRecordWithBLOBsType(sb.toString());

    sb.setLength(0);
    sb.append(pakkage);
    sb.append('.');
    sb.append(fullyQualifiedTable.getDomainObjectName());
    sb.append("Example"); // $NON-NLS-1$
    setExampleType(sb.toString());
  }
Ejemplo n.º 9
1
  protected void calculateJavaClientAttributes() {
    if (context.getJavaClientGeneratorConfiguration() == null) {
      return;
    }

    StringBuilder sb = new StringBuilder();
    sb.append(calculateJavaClientImplementationPackage());
    sb.append('.');
    sb.append(fullyQualifiedTable.getDomainObjectName());
    sb.append("DAOImpl"); // $NON-NLS-1$
    setDAOImplementationType(sb.toString());

    sb.setLength(0);
    sb.append(calculateJavaClientInterfacePackage());
    sb.append('.');
    sb.append(fullyQualifiedTable.getDomainObjectName());
    sb.append("DAO"); // $NON-NLS-1$
    setDAOInterfaceType(sb.toString());

    sb.setLength(0);
    sb.append(calculateJavaClientInterfacePackage());
    sb.append('.');
    sb.append(fullyQualifiedTable.getDomainObjectName());
    sb.append("Mapper"); // $NON-NLS-1$
    setMyBatis3JavaMapperType(sb.toString());

    sb.setLength(0);
    sb.append(calculateJavaClientInterfacePackage());
    sb.append('.');
    sb.append(fullyQualifiedTable.getDomainObjectName());
    sb.append("SqlProvider"); // $NON-NLS-1$
    setMyBatis3SqlProviderType(sb.toString());
  }
 /**
  * Provided only for convenience.
  *
  * @see #fastaToAfpChain(ProteinSequence, ProteinSequence, Structure, Structure)
  * @throws StructureException
  */
 public static AFPChain fastaToAfpChain(
     SequencePair<Sequence<AminoAcidCompound>, AminoAcidCompound> alignment,
     Structure structure1,
     Structure structure2)
     throws StructureException {
   List<AlignedSequence<Sequence<AminoAcidCompound>, AminoAcidCompound>> seqs =
       alignment.getAlignedSequences();
   StringBuilder sb1 = new StringBuilder();
   for (AminoAcidCompound a : seqs.get(0)) {
     sb1.append(a.getBase());
   }
   try {
     ProteinSequence seq1 = new ProteinSequence(sb1.toString());
     StringBuilder sb2 = new StringBuilder();
     for (AminoAcidCompound a : seqs.get(1)) {
       sb1.append(a.getBase());
     }
     ProteinSequence seq2 = new ProteinSequence(sb2.toString());
     LinkedHashMap<String, ProteinSequence> map = new LinkedHashMap<String, ProteinSequence>();
     map.put(structure1.getName(), seq1);
     map.put(structure2.getName(), seq2);
     return fastaToAfpChain(map, structure1, structure2);
   } catch (CompoundNotFoundException e) {
     logger.error(
         "Unexpected error while creating protein sequences: {}. This is most likely a bug.",
         e.getMessage());
     return null;
   }
 }
Ejemplo n.º 11
1
 /**
  * Returns a map with variable bindings.
  *
  * @param opts main options
  * @return bindings
  */
 public static HashMap<String, String> bindings(final MainOptions opts) {
   final HashMap<String, String> bindings = new HashMap<>();
   final String bind = opts.get(MainOptions.BINDINGS).trim();
   final StringBuilder key = new StringBuilder();
   final StringBuilder val = new StringBuilder();
   boolean first = true;
   final int sl = bind.length();
   for (int s = 0; s < sl; s++) {
     final char ch = bind.charAt(s);
     if (first) {
       if (ch == '=') {
         first = false;
       } else {
         key.append(ch);
       }
     } else {
       if (ch == ',') {
         if (s + 1 == sl || bind.charAt(s + 1) != ',') {
           bindings.put(key.toString().trim(), val.toString());
           key.setLength(0);
           val.setLength(0);
           first = true;
           continue;
         }
         // literal commas are escaped by a second comma
         s++;
       }
       val.append(ch);
     }
   }
   if (key.length() != 0) bindings.put(key.toString().trim(), val.toString());
   return bindings;
 }
Ejemplo n.º 12
1
 /**
  * 移除执行语句中的数据库名
  *
  * @param stmt 执行语句
  * @param schema 数据库名
  * @return 执行语句
  * @author mycat
  */
 public static String removeSchema(String stmt, String schema) {
   final String upStmt = stmt.toUpperCase();
   final String upSchema = schema.toUpperCase() + ".";
   int strtPos = 0;
   int indx = 0;
   boolean flag = false;
   indx = upStmt.indexOf(upSchema, strtPos);
   if (indx < 0) {
     StringBuilder sb = new StringBuilder("`").append(schema.toUpperCase()).append("`.");
     indx = upStmt.indexOf(sb.toString(), strtPos);
     flag = true;
     if (indx < 0) {
       return stmt;
     }
   }
   StringBuilder sb = new StringBuilder();
   while (indx > 0) {
     sb.append(stmt.substring(strtPos, indx));
     strtPos = indx + upSchema.length();
     if (flag) {
       strtPos += 2;
     }
     indx = upStmt.indexOf(upSchema, strtPos);
   }
   sb.append(stmt.substring(strtPos));
   return sb.toString();
 }
Ejemplo n.º 13
1
  /**
   * Draws as much as possible of a given string into a 2d square region in a graphical space.
   *
   * @param g component onto which to draw
   * @param f font to use in drawing the string
   * @param s string to be drawn
   * @param xPos
   * @param yPos
   * @param width
   * @param height
   */
  public static void drawStringMultiline(
      Graphics2D g, Font f, String s, double xPos, double yPos, double width, double height) {
    FontMetrics fm = g.getFontMetrics(f);
    int w = fm.stringWidth(s);
    int h = fm.getAscent();
    // g.setColor(Color.LIGHT_GRAY);
    g.setColor(Color.BLACK);
    g.setFont(f);

    Scanner lineSplitter = new Scanner(s);
    // draw as much as can fit in each item
    // read all content from scanner, storing in string lists (where each string == 1 line), each
    // string should be as long as possible without overflowing the space
    int maxRows = (int) height / h;
    List<String> textRows = new ArrayList<>();
    while (lineSplitter.hasNextLine() && textRows.size() < maxRows) {
      String line = lineSplitter.nextLine();
      // if line is blank, insert to maintain paragraph seps
      if (line.trim().equals("")) {
        textRows.add("");
      }
      // else, pass to inner loop
      StringBuilder currentBuilder = new StringBuilder();
      int currentStrWidth = 0;
      Scanner splitter = new Scanner(line);
      while (splitter.hasNext() && textRows.size() < maxRows) {
        String token = splitter.next() + " ";
        // TODO incorporate weight detection, formatting for token?
        currentStrWidth += fm.stringWidth(token);
        if (currentStrWidth >= width) {
          // if string length >= glyph width, build row
          textRows.add(currentBuilder.toString());
          currentBuilder = new StringBuilder();
          currentBuilder.append(token);
          currentStrWidth = fm.stringWidth(token);
        } else {
          // if not yet at end of row, append to builder
          currentBuilder.append(token);
        }
      }

      // if we've still space and still have things to write, add them here
      if (textRows.size() < maxRows) {
        textRows.add(currentBuilder.toString());
        currentBuilder = new StringBuilder();
        currentStrWidth = 0;
      }
    }

    // write each line to object
    for (int t = 0; t < textRows.size(); t++) {
      String line = textRows.get(t);
      if (fm.stringWidth(line) <= width) {
        // ensure that string doesn't overflow the box
        //                g.drawString(line, (float) (xPos-(width/2.)), (float) (yPos-(height/2.) +
        // h * (t+1)));
        g.drawString(line, (float) xPos, (float) (yPos + h * (t + 1)));
      }
    }
  }
Ejemplo n.º 14
1
  public static String[] splitStringToArray(final CharSequence s, final char c) {
    if (s == null || s.length() == 0) {
      return Strings.EMPTY_ARRAY;
    }
    int count = 1;
    for (int i = 0; i < s.length(); i++) {
      if (s.charAt(i) == c) {
        count++;
      }
    }
    final String[] result = new String[count];
    final StringBuilder builder = new StringBuilder();
    int res = 0;
    for (int i = 0; i < s.length(); i++) {
      if (s.charAt(i) == c) {
        if (builder.length() > 0) {
          result[res++] = builder.toString();
          builder.setLength(0);
        }

      } else {
        builder.append(s.charAt(i));
      }
    }
    if (builder.length() > 0) {
      result[res++] = builder.toString();
    }
    if (res != count) {
      // we have empty strings, copy over to a new array
      String[] result1 = new String[res];
      System.arraycopy(result, 0, result1, 0, res);
      return result1;
    }
    return result;
  }
Ejemplo n.º 15
1
  @Override
  public <T> Page<T> searchPage(String sql, Class<T> clazz, List<Object> params, Page<T> page)
      throws Exception {
    if (StringUtils.isBlank(sql)) {
      List<T> list = new ArrayList<>();
      page.setTotalCount(0);
      page.setResult(list);
      return page;
    }
    if (params == null) {
      params = new ArrayList<>();
    }
    StringBuilder sb = new StringBuilder(sql);
    int count = getCount(sb.toString(), params);
    page.setTotalCount(count);
    if (!StringUtils.isBlank(page.getOrder())) {
      sb.append(" ORDER BY ").append(page.getOrder());
      if (!StringUtils.isBlank(page.getSort())) {
        sb.append(" ").append(page.getSort());
      }
    }
    sb.append(" LIMIT ");
    sb.append(String.valueOf(page.getFirstResult()));
    sb.append(",");
    sb.append(String.valueOf(page.getPageSize()));
    List<T> list = searchForList(sb.toString(), clazz, params);
    page.setResult(list);

    return page;
  }
Ejemplo n.º 16
1
Archivo: Macro.java Proyecto: bramk/bnd
  public String _range(String args[]) {
    verifyCommand(args, _rangeHelp, _rangePattern, 2, 3);
    Version version = null;
    if (args.length >= 3) version = new Version(args[2]);
    else {
      String v = domain.getProperty("@");
      if (v == null) return null;
      version = new Version(v);
    }
    String spec = args[1];

    Matcher m = RANGE_MASK.matcher(spec);
    m.matches();
    String floor = m.group(1);
    String floorMask = m.group(2);
    String ceilingMask = m.group(3);
    String ceiling = m.group(4);

    String left = version(version, floorMask);
    String right = version(version, ceilingMask);
    StringBuilder sb = new StringBuilder();
    sb.append(floor);
    sb.append(left);
    sb.append(",");
    sb.append(right);
    sb.append(ceiling);

    String s = sb.toString();
    VersionRange vr = new VersionRange(s);
    if (!(vr.includes(vr.getHigh()) || vr.includes(vr.getLow()))) {
      domain.error(
          "${range} macro created an invalid range %s from %s and mask %s", s, version, spec);
    }
    return sb.toString();
  }
Ejemplo n.º 17
1
  /**
   * Break on commas, except those inside quotes, e.g.: size(300, 200, PDF, "output,weirdname.pdf");
   * No special handling implemented for escaped (\") quotes.
   */
  private static StringList breakCommas(String contents) {
    StringList outgoing = new StringList();

    boolean insideQuote = false;
    // The current word being read
    StringBuilder current = new StringBuilder();
    char[] chars = contents.toCharArray();
    for (int i = 0; i < chars.length; i++) {
      char c = chars[i];
      if (insideQuote) {
        current.append(c);
        if (c == '\"') {
          insideQuote = false;
        }
      } else {
        if (c == ',') {
          if (current.length() != 0) {
            outgoing.append(current.toString());
            current.setLength(0);
          }
        } else {
          current.append(c);
          if (c == '\"') {
            insideQuote = true;
          }
        }
      }
    }
    if (current.length() != 0) {
      outgoing.append(current.toString());
    }
    return outgoing;
  }
Ejemplo n.º 18
0
  public void testPsi2DocMergeMultipleAdditionsWithReplace() throws Exception {
    StringBuilder buffer = new StringBuilder("0123456789");
    RangeMarker marker = createMarker(buffer.toString(), 2, 5);
    synchronizer.startTransaction(getProject(), document, psiFile);
    final PsiToDocumentSynchronizer.DocumentChangeTransaction transaction =
        synchronizer.getTransaction(document);
    final Set<Pair<PsiToDocumentSynchronizer.MutableTextRange, StringBuffer>> affectedFragments =
        transaction.getAffectedFragments();

    for (int i = 0; i < 10; i++) {
      synchronizer.insertString(document, i, "" + i);
      buffer.insert(i, "" + i);
    }

    assertEquals(1, affectedFragments.size());
    synchronizer.replaceString(document, 0, 20, "0123456789");
    buffer.replace(0, 20, "0123456789");

    assertEquals(1, affectedFragments.size());

    synchronizer.commitTransaction(document);

    assertEquals(buffer.toString(), document.getText());

    assertValidMarker(marker, 2, 5);
  }
Ejemplo n.º 19
0
  /**
   * Returns a String explaining the runtime parameter usage. It will take the form
   *
   * <pre>
   * command - description <dataType> [<required>]
   * </pre>
   *
   * @return a String explaining the runtime parameter usage.
   */
  public String getParameterUsageTable() {
    int minLen = 0;

    final Collection<ApplicationParameter> params = getParameters();
    final HashMap<ApplicationParameter, String> verboseKeys =
        new HashMap<ApplicationParameter, String>(params.size());

    for (ApplicationParameter param : params) {
      final String[] keys = param.getKeys();
      final StringBuilder keyString = new StringBuilder(64);
      for (int i = 0; i < keys.length; i++) {
        keyString.append(keys[i]);
        if (i < keys.length - 1) keyString.append(", ");
      }
      verboseKeys.put(param, keyString.toString());
      minLen = Math.max(minLen, keyString.length());
    }

    final StringBuilder builder = new StringBuilder(256);
    for (Iterator<ApplicationParameter> it = params.iterator(); it.hasNext(); ) {
      final ApplicationParameter param = it.next();
      final String str = verboseKeys.get(param);
      builder.append(str);
      for (int i = str.length(); i < minLen; i++) builder.append(' ');
      builder.append(" - ").append(param.getName());
      if (param.isRequired()) builder.append("[required]");
      builder.append(" (").append(param.getType()).append(')');
      if (it.hasNext()) builder.append('\n');
    }

    return builder.toString();
  }
Ejemplo n.º 20
0
  private void assertMatchEquals(List<Completion> res, String... expected) {
    String[] result = new String[res.size()];
    for (int i = 0; i < res.size(); i++) {
      result[i] = res.get(i).toString();
    }

    if (!Arrays.equals(stripScore(expected), stripScore(result))) {
      int colLen = Math.max(maxLen(expected), maxLen(result));

      StringBuilder b = new StringBuilder();
      String format = "%" + colLen + "s  " + "%" + colLen + "s\n";
      b.append(String.format(Locale.ROOT, format, "Expected", "Result"));
      for (int i = 0; i < Math.max(result.length, expected.length); i++) {
        b.append(
            String.format(
                Locale.ROOT,
                format,
                i < expected.length ? expected[i] : "--",
                i < result.length ? result[i] : "--"));
      }

      System.err.println(b.toString());
      fail("Expected different output:\n" + b.toString());
    }
  }
Ejemplo n.º 21
0
  public void testPsi2DocSurround() throws Exception {
    StringBuilder buffer = new StringBuilder("0123456789");
    RangeMarker marker = createMarker(buffer.toString(), 2, 5);
    synchronizer.startTransaction(getProject(), document, psiFile);

    synchronizer.replaceString(document, 3, 5, "3a4");
    buffer.replace(3, 5, "3a4");

    synchronizer.insertString(document, 3, "b");
    buffer.insert(3, "b");

    synchronizer.insertString(document, 7, "d");
    buffer.insert(7, "d");

    final PsiToDocumentSynchronizer.DocumentChangeTransaction transaction =
        synchronizer.getTransaction(document);
    final Set<Pair<PsiToDocumentSynchronizer.MutableTextRange, StringBuffer>> affectedFragments =
        transaction.getAffectedFragments();
    assertEquals(3, affectedFragments.size());

    synchronizer.commitTransaction(document);

    assertEquals(buffer.toString(), document.getText());

    assertValidMarker(marker, 2, 7);
  }
Ejemplo n.º 22
0
 @Override
 protected TypedAST doTransform(TypedAST transform) {
   List<List<SCCNode>> sccs =
       TarjansSCCCheck(
           new ImportGraphBuilder(
                   new ImportGraphBuilder.NodeFactory<SCCNode>() {
                     @Override
                     public SCCNode create(
                         String name, TypedAST ast, LinkedList<Node<SCCNode>> links) {
                       return new SCCNode(name, ast, links);
                     }
                   })
               .getGraph("entry", transform));
   if (sccs.size() > 0) {
     StringBuilder allSCCs = new StringBuilder(sccs.size());
     for (List<SCCNode> scc : sccs) {
       StringBuilder sccBuilder = new StringBuilder(scc.size() * 2 + 1);
       sccBuilder.append("\t");
       Iterator<SCCNode> iterator = scc.iterator();
       while (iterator.hasNext()) {
         SCCNode component = iterator.next();
         sccBuilder.append(component.getName());
         sccBuilder.append(" -> ");
       }
       sccBuilder.append(scc.get(0).getName() + "\n");
       allSCCs.append(sccBuilder.toString());
     }
     ToolError.reportError(ErrorMessage.IMPORT_CYCLE, allSCCs.toString(), transform);
   }
   return transform;
 }
  private void initExecute(Element executeRoot) throws XmlaException {
    Element[] childElems = XmlaUtil.filterChildElements(executeRoot, NS_XMLA, "Command");
    if (childElems.length != 1) {
      StringBuilder buf = new StringBuilder(100);
      buf.append(MSG_INVALID_XMLA);
      buf.append(": Wrong number of Command elements: ");
      buf.append(childElems.length);
      throw new XmlaException(
          CLIENT_FAULT_FC,
          HSB_BAD_COMMAND_CODE,
          HSB_BAD_COMMAND_FAULT_FS,
          Util.newError(buf.toString()));
    }
    initCommand(childElems[0]); // <Command><Statement>

    childElems = XmlaUtil.filterChildElements(executeRoot, NS_XMLA, "Properties");
    if (childElems.length != 1) {
      StringBuilder buf = new StringBuilder(100);
      buf.append(MSG_INVALID_XMLA);
      buf.append(": Wrong number of Properties elements: ");
      buf.append(childElems.length);
      throw new XmlaException(
          CLIENT_FAULT_FC,
          HSB_BAD_PROPERTIES_CODE,
          HSB_BAD_PROPERTIES_FAULT_FS,
          Util.newError(buf.toString()));
    }
    initProperties(childElems[0]); // <Properties><PropertyList>
  }
  public String getHtmlReport() {
    StringBuilder generationReport = new StringBuilder();

    Enumeration<String> e = myElecInputs.keys();

    while (e.hasMoreElements()) {
      String elecInputName = e.nextElement();

      StimulationSettings s = project.elecInputInfo.getStim(elecInputName);

      generationReport.append(
          "<b>"
              + ClickProjectHelper.getElecInputLink(elecInputName)
              + "</b> ("
              + s.getElectricalInput().toLinkedString()
              + " on "
              + s.getCellChooser().toNiceString()
              + " of "
              + ClickProjectHelper.getCellGroupLink(s.getCellGroup())
              + ", segs: "
              + s.getSegChooser()
              + ")<br>");

      generationReport.append(
          "Number of individual inputs: <b>"
              + project.generatedElecInputs.getNumberSingleInputs(elecInputName)
              + "</b><br><br>");
    }

    if (generationReport.toString().length() == 0) {
      generationReport.append("No Electrical Inputs generated<br><br>");
    }

    return generationReport.toString();
  }
Ejemplo n.º 25
0
  /**
   * insert actual from, until, and set parameters into the identifierQuery String
   *
   * @param oaiIdentifier The OAI identifier
   * @return a String containing an SQL query
   */
  private String populateAboutQuery(String oaiIdentifier) throws OAIInternalServerError {
    StringTokenizer tokenizer = new StringTokenizer(aboutQuery, "\\");
    StringBuilder sb = new StringBuilder();
    if (tokenizer.hasMoreTokens()) {
      sb.append(tokenizer.nextToken());
    } else {
      throw new OAIInternalServerError("Invalid identifierQuery");
    }

    while (tokenizer.hasMoreTokens()) {
      String token = tokenizer.nextToken();
      switch (token.charAt(0)) {
        case 'i':
          sb.append(getRecordFactory().fromOAIIdentifier(oaiIdentifier));
          break;
        case 'o':
          sb.append(oaiIdentifier);
          break;
        default: // ignore it
          sb.append("\\");
          sb.append(token.charAt(0));
      }
      sb.append(token.substring(1));
    }
    LOGGER.debug(sb.toString());
    return sb.toString();
  }
Ejemplo n.º 26
0
 public static String[] formatCollection(Collection<String> c) {
   if (c.isEmpty()) return new String[] {""};
   else {
     List<String> lines = new ArrayList<String>();
     StringBuilder sb = new StringBuilder();
     String s;
     for (Iterator<String> iter = c.iterator(); iter.hasNext(); ) {
       s = iter.next();
       if (sb.length() + s.length() > CHARS_PER_LINE && sb.length() != 0) {
         lines.add(sb.toString());
         sb = new StringBuilder();
       }
       sb.append(s);
       if (iter.hasNext()) {
         if (sb.length() + 2 > CHARS_PER_LINE && sb.length() != 0) {
           lines.add(sb.toString());
           sb = new StringBuilder();
         } else {
           sb.append(", ");
         }
       } else {
         lines.add(sb.toString());
       }
     }
     return lines.toArray(new String[lines.size()]);
   }
 }
Ejemplo n.º 27
0
  public String toString(String[] metricNames, String[] submetricNames) {

    StringBuilder rankStr = new StringBuilder("origRank=" + origRank);
    for (int iMetric = 0; iMetric < metricNames.length; iMetric++) {
      rankStr.append(" " + metricNames[iMetric] + "Rank=" + metricRank[iMetric]);
    }

    StringBuilder metricString = new StringBuilder();
    if (metricScores != null) {
      metricString.append(" |||");

      for (int iMetric = 0; iMetric < metricNames.length; iMetric++) {
        metricString.append(" " + metricNames[iMetric] + "=" + metricScores[iMetric]);
      }
    }

    if (submetricScores != null) {

      for (int iSub = 0; iSub < submetricNames.length; iSub++) {
        metricString.append(" " + submetricNames[iSub] + "=" + submetricScores[iSub]);
      }
    }

    return String.format(
            "%d ||| %s ||| %s ||| %f ||| %s", sentId, hyp, feats, total, rankStr.toString())
        + metricString.toString();
  }
Ejemplo n.º 28
0
  /** Convert the HTML document back to a string. */
  @Override
  public String toString() {
    try {
      StringBuilder result = new StringBuilder();

      int ch = 0;
      StringBuilder text = new StringBuilder();
      do {
        ch = read();
        if (ch == 0) {
          if (text.length() > 0) {
            System.out.println("Text:" + text.toString());
            text.setLength(0);
          }
          System.out.println("Tag:" + getTag());
        } else if (ch != -1) {
          text.append((char) ch);
        }
      } while (ch != -1);
      if (text.length() > 0) {
        System.out.println("Text:" + text.toString().trim());
      }
      return result.toString();
    } catch (IOException e) {
      return "[IO Error]";
    }
  }
Ejemplo n.º 29
0
    public void map(
        Object key, Text value, OutputCollector<IntWritable, Text> output, Reporter reporter)
        throws IOException {

      // vid neighbors_num n1 n2 ...
      // vid color 1/0 "COLOR"
      String str = value.toString();
      if (str.endsWith(COLOR)) {
        // color table
        String[] tokens = str.substring(0, str.length() - 5).split("\\s+");
        int change = Integer.parseInt(tokens[2]);
        if (change == 1) {
          IntWritable SourceId = new IntWritable(Integer.parseInt(tokens[0]));
          StringBuilder sb = new StringBuilder();
          sb.append(tokens[1]);
          sb.append(" ");
          sb.append(tokens[2]);
          sb.append(COLOR);
          output.collect(SourceId, new Text(sb.toString()));
        }
      } else {
        // edge table
        String[] tokens = value.toString().split("\\s+");
        IntWritable SourceId = new IntWritable(Integer.parseInt(tokens[0]));
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i < tokens.length; i++) {
          if (sb.length() != 0) sb.append(" ");
          sb.append(tokens[i]);
        }
        output.collect(SourceId, new Text(sb.toString()));
      }
    }
 protected String getLocalBackupsFolder() {
   StringBuilder dirName = new StringBuilder(this.getProtectedBaseDiskRoot());
   if (!dirName.toString().endsWith("\\") && !dirName.toString().endsWith("/")) {
     dirName.append(File.separator);
   }
   dirName.append("databaseBackups").append(File.separator);
   return dirName.toString();
 }