@NotNull
 public static String getLibraryName(@NotNull Library library) {
   final String result = library.getName();
   if (result != null) {
     return result;
   }
   String[] endingsToStrip = {"/", "!", ".jar"};
   StringBuilder buffer = new StringBuilder();
   for (OrderRootType type : OrderRootType.getAllTypes()) {
     for (String url : library.getUrls(type)) {
       buffer.setLength(0);
       buffer.append(url);
       for (String ending : endingsToStrip) {
         if (buffer.lastIndexOf(ending) == buffer.length() - ending.length()) {
           buffer.setLength(buffer.length() - ending.length());
         }
       }
       final int i = buffer.lastIndexOf(PATH_SEPARATOR);
       if (i < 0 || i >= buffer.length() - 1) {
         continue;
       }
       String candidate = buffer.substring(i + 1);
       if (!StringUtil.isEmpty(candidate)) {
         return candidate;
       }
     }
   }
   assert false;
   return "unknown-lib";
 }
 /**
  * Create result values from observation according to ResultEncoding and ResultStructure
  *
  * @param observations Observation to create result values from
  * @param sosResultEncoding The ResultEncoding
  * @param sosResultStructure The ResultStructure
  * @return Result values String from observation according to ResultEncoding and ResultStructure
  * @throws OwsExceptionReport If creation fails
  */
 public static String createResultValuesFromObservations(
     final List<AbstractObservation> observations,
     final SosResultEncoding sosResultEncoding,
     final SosResultStructure sosResultStructure)
     throws OwsExceptionReport {
   final StringBuilder builder = new StringBuilder();
   if (CollectionHelper.isNotEmpty(observations)) {
     final String tokenSeparator = getTokenSeparator(sosResultEncoding.getEncoding());
     final String blockSeparator = getBlockSeparator(sosResultEncoding.getEncoding());
     final Map<Integer, String> valueOrder =
         getValueOrderMap(sosResultStructure.getResultStructure());
     addElementCount(builder, observations.size(), blockSeparator);
     for (final AbstractObservation observation : observations) {
       for (final Integer intger : valueOrder.keySet()) {
         final String definition = valueOrder.get(intger);
         if (definition.equals(PHENOMENON_TIME)) {
           builder.append(
               getTimeStringForPhenomenonTime(
                   observation.getPhenomenonTimeStart(), observation.getPhenomenonTimeEnd()));
         } else if (definition.equals(RESULT_TIME)) {
           builder.append(getTimeStringForResultTime(observation.getResultTime()));
         } else {
           builder.append(getValueAsStringForObservedProperty(observation, definition));
         }
         builder.append(tokenSeparator);
       }
       builder.delete(builder.lastIndexOf(tokenSeparator), builder.length());
       builder.append(blockSeparator);
     }
     if (builder.length() > 0) {
       builder.delete(builder.lastIndexOf(blockSeparator), builder.length());
     }
   }
   return builder.toString();
 }
Example #3
1
  /**
   * List the entities in JSON format
   *
   * @param entities entities to return as JSON strings
   */
  public static String writeJSON(Iterable<Entity> entities) {
    logger.log(Level.INFO, "creating JSON format object");
    StringBuilder sb = new StringBuilder();

    int i = 0;
    sb.append("{\"data\": [");
    for (Entity result : entities) {
      Map<String, Object> properties = result.getProperties();
      sb.append("{");
      if (result.getKey().getName() == null)
        sb.append("\"name\" : \"" + result.getKey().getId() + "\",");
      else sb.append("\"name\" : \"" + result.getKey().getName() + "\",");

      for (String key : properties.keySet()) {
        Object object = properties.get(key);
        if (object instanceof Text) {
          Text value = (Text) properties.get(key);
          sb.append("\"" + key + "\" : \"" + value.getValue() + "\",");
          // logger.info(value.getValue());//debug;
        } else {
          sb.append("\"" + key + "\" : \"" + properties.get(key) + "\",");
        }
      }
      sb.deleteCharAt(sb.lastIndexOf(","));
      sb.append("},");
      i++;
    }
    if (i > 0) {
      sb.deleteCharAt(sb.lastIndexOf(","));
    }
    sb.append("]}");
    return sb.toString();
  }
Example #4
1
  private void initIfNeed() {
    if (myInitialized) return;
    myInitialized = true;
    for (Map.Entry<String, Pair<String, List<String>>> entry : myTree.entrySet()) {
      final String group = entry.getKey();
      if (CORE.equals(group)) continue;

      List<IdSet> idSets = new ArrayList<IdSet>();
      StringBuilder description = new StringBuilder();
      for (String idDescription : entry.getValue().getSecond()) {
        IdSet idSet = new IdSet(idDescription);
        String idSetTitle = idSet.getTitle();
        if (idSetTitle == null) continue;
        idSets.add(idSet);
        if (description.length() > 0) {
          description.append(", ");
        }
        description.append(idSetTitle);
      }
      myGroups.put(group, idSets);

      if (description.length() > MAX_DESCR_LENGTH) {
        int lastWord = description.lastIndexOf(",", MAX_DESCR_LENGTH);
        description.delete(lastWord, description.length()).append("...");
      }
      description.insert(0, "<html><body><center><i>");
      myDescriptions.put(group, description.toString());
    }
  }
Example #5
1
 public StringBuilder findLocations(Document doc, StringBuilder sb) {
   for (Tag tag : doc.tags) {
     StringBuilder nb = new StringBuilder();
     for (int i = tag.begin; i < tag.end; i++) {
       nb.append(doc.terms.get(i) + " ");
     }
     if (!(nb.lastIndexOf(" ") == -1)) {
       nb.deleteCharAt(nb.lastIndexOf(" "));
     }
     String name = nb.toString();
     sb.append(name);
     sb.append(",");
     sb.append(doc.name);
     sb.append("\n");
   }
   return sb;
 }
Example #6
0
  /**
   * 描述:从输入流中获得String.
   *
   * @param is 输入流
   * @return 获得的String
   */
  public static String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    try {
      while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
      }

      // 最后一个\n删除
      if (sb.indexOf("\n") != -1 && sb.lastIndexOf("\n") == sb.length() - 1) {
        sb.delete(sb.lastIndexOf("\n"), sb.lastIndexOf("\n") + 1);
      }

    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        is.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    return sb.toString();
  }
  @Nullable
  private static String trimToValue(@Nullable StringBuilder output) {
    if (output == null) {
      return null;
    }
    int pos = output.lastIndexOf("  ");
    int pos2 = output.lastIndexOf("\t");
    pos = Math.max(pos, pos2);
    if (pos == -1) {
      return null;
    }

    output.delete(0, pos + 1);
    String blackList = "\r\n \"";
    int startPos = 0;
    int endPos = output.length() - 1;
    while (true) {
      if (startPos >= endPos) {
        return null;
      }
      if (blackList.indexOf(output.charAt(startPos)) != -1) {
        startPos++;
      } else {
        break;
      }
    }
    while (true) {
      if (blackList.indexOf(output.charAt(endPos)) != -1) {
        endPos--;
      } else {
        break;
      }
    }
    return output.subSequence(startPos, endPos + 1).toString();
  }
Example #8
0
 /** @param toInsert */
 public void insertAtEndOfBody(String toInsert) {
   int insertPoint = sb.lastIndexOf("</body>");
   if (-1 == insertPoint) {
     insertPoint = sb.lastIndexOf("</BODY>");
   }
   if (-1 == insertPoint) {
     insertPoint = sb.length();
   }
   sb.insert(insertPoint, toInsert);
 }
  @Override
  protected String exportData() throws ExportException {
    List<IntakeNode> intakeNodes = intake.getNode().getChildren();
    StringBuilder buf = new StringBuilder();

    IntakeNode file4Node = null;

    for (IntakeNode inode : intakeNodes) {
      if (inode.getLabelStr().startsWith(FILE_PREFIX)) {
        file4Node = inode;
        break;
      }
    }

    Set<IntakeAnswer> answers = intake.getAnswers();

    int counter = 0;
    for (IntakeAnswer ans : answers) {
      if (counter == fields.size()) {
        break;
      }
      if (ans.getNode().getGrandParent().equals(file4Node)) {
        final String lbl = ans.getNode().getParent().getLabelStr().toUpperCase();
        DATISField found =
            (DATISField)
                CollectionUtils.find(
                    fields,
                    new Predicate() {

                      public boolean evaluate(Object arg0) {
                        DATISField field = (DATISField) arg0;
                        if (lbl.startsWith(field.getName())) {
                          return true;
                        }
                        return false;
                      }
                    });

        if (found != null) {
          writeCSV(buf, ans, found);
          // writeData(buf, ans, found);
          counter++;
        }
      }
    }

    if (buf.lastIndexOf(",") == -1) {
      return buf.toString();
    }

    return buf.substring(0, buf.lastIndexOf(",")).toString();
  }
  protected String buildInsertSQL1(T t) {
    StringBuilder sb = new StringBuilder("insert into ");
    StringBuilder srowName = new StringBuilder();
    StringBuilder srowVal = new StringBuilder();
    String clzName = getEntityClass().getName();
    clzName = getEntityClass().getName().substring(clzName.lastIndexOf(".") + 1, clzName.length());
    sb.append(clzName);
    sb.append(" ( ");
    Field f[] = getEntityClass().getDeclaredFields();
    for (int i = 0; i < f.length; i++) {
      //            System.out.println( f[i].getName() );
      try {
        String rowName = f[i].getName();

        //                String rowVal = (String) f[i].get(user);
        if (!"id".equalsIgnoreCase(rowName)) {

          // 参数1为person类中属性的名(首字母大写),参数2为person类转化的Class
          String methodName =
              rowName.substring(0, 1).toUpperCase() + rowName.substring(1, rowName.length());
          PropertyDescriptor pd = new PropertyDescriptor(methodName, getEntityClass());
          // 获取PropertyDescriptor 类的写入方法
          Method m = pd.getReadMethod();
          // 因为是读取属性中的方法,所以不需要传值进去
          //                    Object o = new Object();
          Object obj = m.invoke(t, null);
          String rowVal = (String) obj;
          rowVal = rowVal == null ? "" : rowVal;
          srowName.append(" [" + rowName + "], ");
          srowVal.append("'" + rowVal + "', ");
        }

      } catch (IllegalAccessException ex) {
        Logger.getLogger(BaseService.class.getName()).log(Level.SEVERE, null, ex);
      } catch (InvocationTargetException ex) {
        Logger.getLogger(BaseService.class.getName()).log(Level.SEVERE, null, ex);
      } catch (IllegalArgumentException ex) {
        Logger.getLogger(UserService.class.getName()).log(Level.SEVERE, null, ex);
      } catch (IntrospectionException ex) {
        Logger.getLogger(UserService.class.getName()).log(Level.SEVERE, null, ex);
      }
    }

    sb.append(srowName.substring(0, srowName.lastIndexOf(",")));
    sb.append(" ) values ( ");
    sb.append(srowVal.substring(0, srowVal.lastIndexOf(",")));
    sb.append(" ) ");

    return sb.toString();
  }
Example #11
0
  @Override
  public String buildQuerySql(Class<?> entityClass, Connection conn) throws SQLException {
    if (!SqlCache.VOSQL.containsKey(entityClass)) {
      String orderBy = "";
      AnnotationUtil annotationUtil = AnnotationUtil.getInstance();
      // 获取表名
      String tableName = annotationUtil.getAnnotationTableName(entityClass);
      List<ColumnMeta> list = DaoOptemplate.getInstance().refresh(tableName, conn);
      StringBuilder sb = new StringBuilder("select ");
      for (int i = 0; i < list.size(); i++) {
        ColumnMeta cm = list.get(i);
        String columnName = cm.getColumnName();
        sb.append(columnName + ",");
        // 如果是自动增长,或者是日期,则设置自动降序排列
        if (orderBy.equalsIgnoreCase("")) {
          if (cm.isAutoIncrement() || cm.getColumnType().indexOf("date") != -1) {
            orderBy = " order by " + columnName + " desc";
          }
        }
      }
      sb.deleteCharAt(sb.lastIndexOf(","));
      sb.append(" from " + tableName);
      sb.append(SqlConstant.ORDERBY_SPLIT + orderBy);
      SqlCache.VOSQL.put(entityClass, sb.toString());
    }

    return SqlCache.VOSQL.get(entityClass);
  }
  @Override
  public UriBuilder replaceMatrixParam(String name, Object... values) {
    checkSsp();

    if (name == null) {
      throw new IllegalArgumentException("Name parameter is null");
    }

    if (matrixParams == null) {
      int i = path.lastIndexOf("/");
      if (i != -1) {
        i = 0;
      }
      matrixParams = UriComponent.decodeMatrix((i != -1) ? path.substring(i) : "", false);
      i = path.indexOf(";", i);
      if (i != -1) {
        path.setLength(i);
      }
    }

    name = encode(name, UriComponent.Type.MATRIX_PARAM);
    matrixParams.remove(name);
    if (values != null) {
      for (Object value : values) {
        if (value == null) {
          throw new IllegalArgumentException("One or more of matrix value parameters are null");
        }

        matrixParams.add(name, encode(value.toString(), UriComponent.Type.MATRIX_PARAM));
      }
    }
    return this;
  }
Example #13
0
 @Override
 public void keyTyped(KeyEvent e) {
   Character typed = e.getKeyChar();
   switch (typed) {
     case KeyEvent.VK_BACK_SPACE:
       if (input.length() > 0) {
         input.deleteCharAt(input.length() - 1);
         if (!Words.isDictionaryWord(input.toString()))
           suggestion = Words.ending(input.toString());
         else suggestion = "";
       }
       word = null;
       break;
     case KeyEvent.VK_ENTER:
       if (suggestion != null && suggestion.length() > 0) {
         input.append(suggestion);
         suggestion = "";
       }
       word = Words.getWord(input.toString());
       break;
     case KeyEvent.VK_TAB:
       previous = mode;
       previousSet = System.currentTimeMillis();
       mode = Theme.next(mode);
       break;
   }
   if (allowed.matcher(typed.toString()).matches()) {
     input.append(typed);
     String focus = input.substring(input.lastIndexOf(" ") + 1);
     word = Words.getWord(focus);
     suggestion = word == null ? Words.ending(focus) : "";
   }
 }
  @Override
  public String toString() {
    StringBuilder sb = new StringBuilder();

    sb.append("FRAGMENT_RESPONSE (FROM ");
    sb.append(m_executorSiteId);
    sb.append(" TO ");
    sb.append(m_destinationSiteId);
    sb.append(") FOR TXN ");
    sb.append(m_txnId);

    if (m_status == SUCCESS) sb.append("\n  SUCCESS");
    else if (m_status == UNEXPECTED_ERROR) sb.append("\n  UNEXPECTED_ERROR");
    else sb.append("\n  USER_ERROR");

    if (m_dirty) sb.append("\n  DIRTY");
    else sb.append("\n  PRISTINE");

    for (int i = 0; i < m_dependencyCount; i++) {
      sb.append("\n  DEP ").append(m_dependencyIds.get(i));
      sb.append(" WITH ").append(m_dependencies.get(i).getRowCount()).append(" ROWS (");
      for (int j = 0; j < m_dependencies.get(i).getColumnCount(); j++) {
        sb.append(m_dependencies.get(i).getColumnName(j)).append(", ");
      }
      sb.setLength(sb.lastIndexOf(", "));
      sb.append(")");
    }

    return sb.toString();
  }
  /**
   * Returns a SQL ALTER statement based on the supplied SQL CREATE statement input.
   *
   * <p>This method will look for certain keywords in the CREATE statement and will insert FOREIGN
   * KEY references to the OpenHDS tables visit, individual, socialgroup or location accordingly.
   *
   * <p>Keywords that are checked for in the SQL CREATE statement are: - OPENHDS_VISIT_ID -
   * OPENHDS_INDIVIDUAL_ID, INDIVIDUAL_INFO_INDIVIDUAL_ID - OPENHDS_HOUSEHOLD_ID -
   * OPENHDS_LOCATION_ID
   *
   * @param sql SQL CREATE extra-form table statement
   * @param coreTable name of the extra-form CORE TABLE
   * @return A String containing the ALTER SQL statement for the coreTable with foreign keys
   */
  private String alterTableForeignKey(String sql, String coreTable) {
    StringBuilder builder = new StringBuilder();
    builder.append("ALTER TABLE " + schemaName + "." + coreTable + " ");

    // ADD FOREIGN KEY CONSTRAINTS
    if (sql.contains("OPENHDS_VISIT_ID")) {
      builder.append("ADD VISIT_UUID VARCHAR(32) NOT NULL, ");
      builder.append("ADD CONSTRAINT " + coreTable + "_vuuidfk_1 FOREIGN KEY (VISIT_UUID) ");
      builder.append("REFERENCES " + schemaName + ".visit(uuid), ");
    }
    if (sql.contains("OPENHDS_INDIVIDUAL_ID") || sql.contains("INDIVIDUAL_INFO_INDIVIDUAL_ID")) {
      builder.append("ADD INDIVIDUAL_UUID VARCHAR(32) NOT NULL, ");
      builder.append("ADD CONSTRAINT " + coreTable + "_iuuidfk_1 FOREIGN KEY (INDIVIDUAL_UUID) ");
      builder.append("REFERENCES " + schemaName + ".individual(uuid), ");
    }
    if (sql.contains("OPENHDS_HOUSEHOLD_ID")) {
      builder.append("ADD HOUSEHOLD_UUID VARCHAR(32) NOT NULL, ");
      builder.append("ADD CONSTRAINT " + coreTable + "_hhuuidfk_1 FOREIGN KEY (HOUSEHOLD_UUID) ");
      builder.append("REFERENCES " + schemaName + ".socialgroup(uuid), ");
    }
    if (sql.contains("OPENHDS_LOCATION_ID")) {
      builder.append("ADD LOCATION_UUID VARCHAR(32) NOT NULL, ");
      builder.append("ADD CONSTRAINT " + coreTable + "_luuidfk_1 FOREIGN KEY (LOCATION_UUID) ");
      builder.append("REFERENCES " + schemaName + ".location(uuid), ");
    }
    if (builder.toString().contains(",")) {
      builder.deleteCharAt(builder.lastIndexOf(","));
    }

    builder.append(";");
    builder.append("\n");
    return builder.toString();
  }
Example #16
0
  public String render(OsFamily family) {
    StringBuilder switchClause = new StringBuilder();
    addArgValidation(switchClause, family);
    switchClause.append(
        Utils.replaceTokens(OS_TO_SWITCH_PATTERN.get(family), ImmutableMap.of("arg", arg + "")));

    for (Entry<String, Statement> entry : valueToActions.entrySet()) {

      StringBuilder actionBuilder = new StringBuilder();
      boolean inRunScript = false;
      for (String line :
          Splitter.on(ShellToken.LF.to(family)).split(entry.getValue().render(family))) {
        if (!inRunScript) actionBuilder.append(INDENT);
        actionBuilder.append(line).append(ShellToken.LF.to(family));
        if (line.indexOf(CreateRunScript.MARKER) != -1) {
          inRunScript = inRunScript ? false : true;
        }
      }
      actionBuilder.delete(
          actionBuilder.lastIndexOf(ShellToken.LF.to(family)), actionBuilder.length());
      switchClause.append(
          Utils.replaceTokens(
              OS_TO_CASE_PATTERN.get(family),
              ImmutableMap.of("value", entry.getKey(), "action", actionBuilder.toString())));
    }

    switchClause.append(OS_TO_END_SWITCH_PATTERN.get(family));
    return switchClause.toString();
  }
 @Override
 @SuppressWarnings("unchecked")
 public List<T> getCollection(String jpql, String[] attributes, Object[] params)
     throws DaoExceptions {
   if (!JPAHelper.validJpql(jpql)) {
     throw new DaoExceptions("JPQL语句不合法,请核实!");
   }
   if (attributes != null && attributes.length > 0) {
     StringBuilder builder = new StringBuilder();
     builder.append(" order by");
     for (String attribute : attributes) {
       builder.append(" o." + attribute + " ,");
     }
     String orderString = builder.substring(0, builder.lastIndexOf(","));
     jpql = jpql.substring(0, jpql.lastIndexOf("order")) + orderString;
   } else {
     if (jpql.indexOf("order") < 1) jpql += " order by o.id";
   }
   final Query query = entityManager.createQuery(jpql);
   if (null != params && params.length > 0) {
     for (int i = 0; i < params.length; i++) {
       query.setParameter(i + 1, params[i]);
     }
   }
   return query.getResultList();
 }
Example #18
0
  public String matrixProduct(PCM pcm) throws IOException {
    // Load a PCM
    StringBuilder builbder = new StringBuilder();
    //   			pcm = loader.load(pcmFile).get(0).getPcm();
    //   			assertNotNull(pcm);
    builbder.append("{\n");
    for (int i = 0; i < pcm.getProducts().size(); i++) {

      List<Cell> cells = pcm.getProducts().get(i).getCells();
      builbder.append(
          "{\"nomProduit\": " + "\"" + pcm.getProducts().get(i).getName() + "\", \"valeurs\" : [");
      for (Cell cl : cells) {
        builbder.append(
            "{\"nomFeature\": "
                + "\""
                + cl.getFeature().getName()
                + "\","
                + "\"contenuCellule\": "
                + "\""
                + cl.getContent().toString()
                + "\"},");
      }
      builbder.deleteCharAt(builbder.lastIndexOf(","));
      builbder.append("]\n");
    }
    builbder.append("}");
    return builbder.toString();
  }
Example #19
0
  public String getAuthorizationHeaderString() throws PropertyNotFoundException {
    StringBuilder builder = new StringBuilder();
    builder.append("OAuth ");
    for (OAuthHeaderParameters param : OAuthHeaderParameters.values()) {
      String key = OAuth.percentEncode(param.name());
      String value = OAuth.percentEncode(properties.getProperty(param.name()));

      if (value == null)
        throw new PropertyNotFoundException(
            "Property \"" + key + "\" not found in config file, did you forget to add?");

      if (param.equals(OAuthHeaderParameters.oauth_timestamp)) {
        value = OAuth.percentEncode(String.valueOf(timestamp));
      }
      if (param.equals(OAuthHeaderParameters.oauth_signature)) {
        String method = properties.getProperty(ProgramConstants.http_method.name());
        String baseUrl = properties.getProperty(ProgramConstants.base_url.name());

        value =
            OAuth.percentEncode(
                calculateSigningKey(
                    createSignatureBaseString(method, baseUrl, createParameterString()),
                    createSigningKey()));
      }
      if (param.equals(OAuthHeaderParameters.oauth_nonce)) {
        value = OAuth.percentEncode(nonce);
      }

      builder.append(key).append("=").append("\"").append(value).append("\"").append(", ");
    }
    builder.setLength(builder.lastIndexOf(","));
    return builder.toString();
  }
Example #20
0
  private String createParameterString() {

    // put required parameters
    for (OauthConstants constant : OauthConstants.values()) {
      String key = OAuth.percentEncode(constant.name());
      String value = OAuth.percentEncode(properties.getProperty(constant.name()));
      if (constant.equals(OauthConstants.oauth_nonce)) {
        value = OAuth.percentEncode(nonce);
      }
      if (constant.equals(OauthConstants.oauth_timestamp)) {
        value = OAuth.percentEncode(String.valueOf(timestamp));
      }
      parameterMap.put(key, value);
    }

    // put optional parameters
    for (Object key_ : optionalParameters.keySet()) {
      String keyStr = (String) key_;
      String key = OAuth.percentEncode(keyStr);
      String value = OAuth.percentEncode(optionalParameters.get(keyStr).toString());
      parameterMap.put(key, value);
    }

    StringBuilder builder = new StringBuilder();

    for (String s : parameterMap.keySet()) {
      builder.append(s).append('=').append(parameterMap.get(s)).append("&");
    }
    builder.setLength(builder.lastIndexOf("&"));
    return builder.toString();
  }
Example #21
0
 private String writeToString(Set<String> container) {
   StringBuilder sb = new StringBuilder();
   for (String s : container) {
     sb.append(s).append(" |");
   }
   return sb.toString().substring(0, sb.lastIndexOf("|"));
 }
  /**
   * Inserts a given string into another padding it with spaces. Is aware if the insertion point has
   * a space on either end and does not add extra spaces. If the string-to-insert is already present
   * (and not part of another word) we return the original string unchanged.
   *
   * @param s the string to insert into
   * @param insertAt the position to insert the string
   * @param stringToInsert the string to insert
   * @return the result of inserting the stringToInsert into the passed in string
   * @throws IndexOutOfBoundsException if the insertAt is negative, or insertAt is larger than the
   *     length of s String object
   */
  public static String insertPaddedIfNeeded(String s, int insertAt, String stringToInsert) {
    if (Strings.isEmptyOrNull(stringToInsert)) {
      return s;
    }

    boolean found = false;
    int startPos = 0;

    while ((startPos < s.length()) && (!found)) {
      int pos = s.indexOf(stringToInsert, startPos);

      if (pos < 0) break;

      startPos = pos + 1;
      int before = pos - 1;
      int after = pos + stringToInsert.length();

      if (((pos == 0) || (Character.isWhitespace(s.charAt(before))))
          && ((after >= s.length()) || (Character.isWhitespace(s.charAt(after))))) found = true;
    }

    if (found) {
      StringBuilder newText = new StringBuilder(s);

      if (newText.lastIndexOf(SINGLE_SPACE) != newText.length() - 1) {
        newText.append(SINGLE_SPACE);
      }

      return (newText.toString());
    } else return (Strings.insertPadded(s, insertAt, stringToInsert));
  }
  /**
   * Inserts a given string into another padding it with spaces. Is aware if the insertion point has
   * a space on either end and does not add extra spaces.
   *
   * @param s the string to insert into
   * @param insertAt the position to insert the string
   * @param stringToInsert the string to insert
   * @return the result of inserting the stringToInsert into the passed in string
   * @throws IndexOutOfBoundsException if the insertAt is negative, or insertAt is larger than the
   *     length of s String object
   */
  public static String insertPadded(String s, int insertAt, String stringToInsert) {
    if (Strings.isEmptyOrNull(stringToInsert)) {
      return s;
    }

    if (insertAt < 0) {
      throw new IndexOutOfBoundsException(
          "Invalid insertAt of [" + insertAt + "] for string [" + s + "]");
    }

    StringBuilder newText = new StringBuilder();
    if (insertAt > 0) {
      newText.append(s.substring(0, insertAt));
      if (newText.lastIndexOf(SINGLE_SPACE) != newText.length() - 1) {
        newText.append(SINGLE_SPACE);
      }
      newText.append(stringToInsert);
      String postItem = s.substring(insertAt);
      if (postItem.indexOf(SINGLE_SPACE) != 0) {
        newText.append(SINGLE_SPACE);
      }
      newText.append(postItem);
    } else {
      newText.append(stringToInsert);
      if (s.indexOf(SINGLE_SPACE) != 0) {
        newText.append(SINGLE_SPACE);
      }
      newText.append(s);
    }
    return newText.toString();
  }
  @Override
  public String getMessage() {
    String displayName = null;
    String displayValue = null;

    if (this.buttonSetting != null && this.currentValue != null) {
      ButtonAppearance buttonAppearance =
          appearances.get(new EnumPair(this.buttonSetting, this.currentValue));
      if (buttonAppearance == null) {
        return "No Such Message";
      }

      displayName = buttonAppearance.displayName;
      displayValue = buttonAppearance.displayValue;
    }

    if (displayName != null) {
      String name = StatCollector.translateToLocal(displayName);
      String value = StatCollector.translateToLocal(displayValue);

      if (name == null || name.isEmpty()) {
        name = displayName;
      }
      if (value == null || value.isEmpty()) {
        value = displayValue;
      }

      if (this.fillVar != null) {
        value = COMPILE.matcher(value).replaceFirst(this.fillVar);
      }

      value = PATTERN_NEW_LINE.matcher(value).replaceAll("\n");
      StringBuilder sb = new StringBuilder(value);

      int i = sb.lastIndexOf("\n");
      if (i <= 0) {
        i = 0;
      }
      while (i + 30 < sb.length() && (i = sb.lastIndexOf(" ", i + 30)) != -1) {
        sb.replace(i, i + 1, "\n");
      }

      return name + '\n' + sb;
    }
    return null;
  }
 private String buildDocSelection() {
   StringBuilder selection = new StringBuilder();
   Iterator<String> iter = Util.sDocMimeTypesSet.iterator();
   while (iter.hasNext()) {
     selection.append("(" + FileColumns.MIME_TYPE + "=='" + iter.next() + "') OR ");
   }
   return selection.substring(0, selection.lastIndexOf(")") + 1);
 }
 /**
  * Attempts to append <tt>c</tt> until the current line gets the length <tt> newLength</tt>. If
  * the line is already as long or longer than <tt> newLength</tt>, then nothing is appended.
  *
  * @param newLength Minimal new length of the last line.
  * @param c Character to append.
  * @return The updated instance of FormattedStringBuilder.
  */
 public FormattedStringBuilder fill(int newLength, char c) {
   int lineStart = _delegate.lastIndexOf(NL);
   if (lineStart == -1) {
     return fillBuffer(newLength, c);
   }
   lineStart += NL.length();
   return fillBuffer(lineStart + newLength, c);
 }
  public static Map<String, String> findNetworkSource(String url) throws Exception {

    Map<String, String> result = new HashMap<String, String>();

    String source = null;
    String username = null;

    StringBuilder builder = new StringBuilder();

    if (url.startsWith("https://www.youtube.com/user")) {

      source = "Youtube";

      username = builder.append(url).replace(0, 29, "").toString();

    } else if (url.startsWith("https://www.youtube.com/channel")) {

      source = "Youtube";

      username = builder.append(url).replace(0, 32, "").toString();

    } else if (url.startsWith("https://www.facebook.com/")) {

      source = "Facebook";

      username = builder.append(url).replace(0, 25, "").toString();

    } else if (url.startsWith("https://plus.google.com/u/0/+")) {

      source = "gplus";

      builder.append(url).replace(0, 29, "");

      int position = builder.lastIndexOf("/");

      username = builder.substring(0, position);

    } else if (url.startsWith("http://instagram.com")) {

      source = "Instagram";

      username = builder.append(url).replace(0, 21, "").toString();

    } else if (url.startsWith("https://www.flickr.com/photos")) {

      source = "Flickr";

      username = builder.append(url).replace(0, 30, "").toString();

    } else {

      throw new Exception("malformed network url");
    }

    result.put(username, source);

    return result;
  }
Example #28
0
 /**
  * @param sb The StringBuilder to search in.
  * @param findme The substring to find.
  * @param from The position at which to begin the search.
  * @return The index of the result, or -1 if not found.
  */
 private static int find_prev_in(StringBuilder sb, String findme, int from) {
   if (from == 0) {
     return -1;
   }
   if (FindDialog.sens.isSelected()) {
     return sb.lastIndexOf(findme, from - 1);
   }
   return sb.toString().toLowerCase().lastIndexOf(findme.toLowerCase(), from - 1);
 }
Example #29
0
  private void processDsetOfComplexDatatypeWithCollectionOfComplexAttributesWithSimpleContent(
      CQLAttribute attribute,
      StringBuilder hql,
      List<java.lang.Object> parameters,
      Stack<CQLAssociatedObject> associationStack,
      List<CqlDataBucket> typesProcessingList)
      throws QueryTranslationException {
    LOG.debug(
        "Processing DSet of complex attribute with a collection of attributes with simple content");
    // strip the last where statement from the hql
    int whereStart = hql.lastIndexOf("where");
    hql.delete(whereStart, whereStart + "where".length());

    String topLevelAlias = typesProcessingList.get(typesProcessingList.size() - 4).aliasOrRoleName;
    hql.append("join ");
    hql.append(topLevelAlias).append(".");
    hql.append(typesProcessingList.get(typesProcessingList.size() - 3).aliasOrRoleName).append(".");
    hql.append(typesProcessingList.get(typesProcessingList.size() - 2).aliasOrRoleName).append(" ");
    // need a random alias
    String randAlias = "alias_" + System.currentTimeMillis();
    hql.append(randAlias).append(" where ");

    // get part names, "randalias.part_0.attributeName predicate value"
    // build the query path with a place holder for the part names
    String componentNamePlaceholder = "---placeholder---";
    StringBuffer buf = new StringBuffer();
    buf.append(randAlias).append(".");
    buf.append(componentNamePlaceholder).append(".");
    buf.append(attribute.getName());

    // get the part names out of the types information
    List<String> componentNames =
        typesInformationResolver.getNestedInnerComponentNames(
            typesProcessingList.get(typesProcessingList.size() - 4).clazz,
            typesProcessingList.get(typesProcessingList.size() - 3).aliasOrRoleName,
            typesProcessingList.get(typesProcessingList.size() - 2).aliasOrRoleName,
            typesProcessingList.get(typesProcessingList.size() - 1).aliasOrRoleName);
    Iterator<String> nameIter = componentNames.iterator();

    // build the query fragment
    hql.append("(");
    while (nameIter.hasNext()) {
      if (caseInsensitive) {
        hql.append("lower(");
      }
      String fragment = buf.toString().replace(componentNamePlaceholder, nameIter.next());
      hql.append(fragment);
      if (caseInsensitive) {
        hql.append(")");
      }
      appendPredicateAndValue(attribute, hql, parameters, associationStack.peek());
      if (nameIter.hasNext()) {
        hql.append(" or ");
      }
    }
    hql.append(")");
  }
Example #30
0
 public String toString() {
   StringBuilder sb = new StringBuilder("[");
   for (Entry<String, String> e : localeValueMap.entrySet()) {
     sb.append(e.getKey()).append(":").append('\"').append(e.getValue()).append('\"').append(",");
   }
   sb.deleteCharAt(sb.lastIndexOf(","));
   sb.append("]");
   return sb.toString();
 }