예제 #1
0
 @Test
 public void testJoin() {
   assertThat(StringUtils.join(',', "a", "b", "c"), is("a,b,c"));
   assertThat(StringUtils.join(',', "a"), is("a"));
   assertThat(StringUtils.join(',', "a", "b", "c,"), is("a,b,c,"));
   assertThat(StringUtils.join(','), is(""));
 }
  @Test
  public void lrange() {
    Assert.assertEquals(1L, (long) this.redis.rpush(key, "one"));
    Assert.assertEquals(2L, (long) this.redis.rpush(key, "two"));
    Assert.assertEquals(3L, (long) this.redis.rpush(key, "three"));

    Assert.assertEquals("one", StringUtils.join(this.redis.lrange(key, 0, 0), ","));
    Assert.assertEquals("one,two,three", StringUtils.join(this.redis.lrange(key, 0, -1), ","));
  }
  // @Ignore
  @Test
  public void hgetAll() {
    Assert.assertEquals(1L, (long) this.redis.hsetnx(key, "field1", "value1"));
    Assert.assertEquals(1L, (long) this.redis.hsetnx(key, "field2", "value2"));
    Map<String, String> map = this.redis.hgetAll(key);

    Assert.assertEquals(2, map.size());
    Assert.assertEquals("field1,field2", StringUtils.join(map.keySet(), ","));
    Assert.assertEquals("value1,value2", StringUtils.join(map.values(), ","));
  }
  @Test
  public void rpush() {
    Assert.assertEquals(1L, (long) this.redis.rpush(key, "hello"));
    Assert.assertEquals(2L, (long) this.redis.rpush(key, "world"));

    Assert.assertEquals("hello,world", StringUtils.join(this.redis.lrange(key, 0, -1), ","));
    Assert.assertEquals("hello,world", StringUtils.join(this.redis.lrange(key, 0, 1), ","));
    Assert.assertEquals("hello", StringUtils.join(this.redis.lrange(key, 0, 0), ","));
    Assert.assertEquals("world", StringUtils.join(this.redis.lrange(key, 1, 1), ","));
  }
예제 #5
0
 public void testJoin() {
   List<String> s = new ArrayList<String>();
   s.add("a");
   s.add("b");
   s.add("c");
   assertEquals("", StringUtils.join(":", s.subList(0, 0)));
   assertEquals("a", StringUtils.join(":", s.subList(0, 1)));
   assertEquals("a:b", StringUtils.join(":", s.subList(0, 2)));
   assertEquals("a:b:c", StringUtils.join(":", s.subList(0, 3)));
 }
  @Test
  public void zrevrangeByScore() {
    this.redis.zadd(key, 1, "one");
    this.redis.zadd(key, 2, "two");
    this.redis.zadd(key, 3, "three");

    Assert.assertEquals("two,one", StringUtils.join(redis.zrevrangeByScore(key, 2, 1, 0, 10), ","));
    Assert.assertEquals(
        "two,one", StringUtils.join(redis.zrevrangeByScore(key, "2", "1", 0, 10), ","));
    Assert.assertEquals("two,one", StringUtils.join(redis.zrevrangeByScore(key, 2, 1), ","));
    Assert.assertEquals("two,one", StringUtils.join(redis.zrevrangeByScore(key, "2", "1"), ","));
  }
 @Test
 public void hvals() {
   Assert.assertEquals(1L, (long) this.redis.hsetnx(key, "field1", "value1"));
   Assert.assertEquals(1L, (long) this.redis.hsetnx(key, "field2", "value2"));
   List<String> values = this.redis.hvals(key);
   Assert.assertEquals("value1,value2", StringUtils.join(values, ","));
 }
 @Test
 public void hkeys() {
   Assert.assertEquals(1L, (long) this.redis.hsetnx(key, "field1", "value1"));
   Assert.assertEquals(1L, (long) this.redis.hsetnx(key, "field2", "value2"));
   Set<String> keys = this.redis.hkeys(key);
   Assert.assertEquals("field1,field2", StringUtils.join(keys, ","));
 }
예제 #9
0
  /**
   * @param listOfLists
   * @param path2Dir
   * @param fileName
   */
  public static void writeCSVRows(
      List<List<? extends Object>> listOfLists, String path2Dir, String fileName) {

    File newFile = new File(path2Dir + fileName + ".csv");
    Writer out = null;
    try {

      out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newFile), "UTF8"));
      for (int i = 0; i < listOfLists.size(); i++) {
        List<? extends Object> list = listOfLists.get(i);
        String csv = StringUtils.join(list, ",") + System.getProperty("line.separator");
        out.write(csv);
      }

    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (out != null) {
        try {
          out.flush();
          out.close();
        } catch (IOException e) {
          // NOP
        }
      }
    }
  }
예제 #10
0
    public BulkSQLLoader_Direct(Connection conn, String schema, String table, String[] fieldNames)
        throws RemoteException {
      super(conn, schema, table, fieldNames);

      try {
        prevAutoCommit = conn.getAutoCommit();
        if (prevAutoCommit) conn.setAutoCommit(false);

        String quotedTable = SQLUtils.quoteSchemaTable(conn, schema, table);

        String[] columns = new String[fieldNames.length];
        for (int i = 0; i < fieldNames.length; i++)
          columns[i] = SQLUtils.quoteSymbol(conn, fieldNames[i]);

        baseQuery =
            String.format(
                "INSERT INTO %s(%s) VALUES ", quotedTable, StringUtils.join(",", columns));

        rowQuery = "(" + StringUtils.mult(",", "?", fieldNames.length) + ")";

        rowBuffer = new Vector<Object[]>(setQueryRowCount(DEFAULT_BUFFER_SIZE));
      } catch (SQLException e) {
        throw new RemoteException("Error initializing BulkSQLLoader_Direct", e);
      }
    }
  @Test
  public void zinterstore() {
    redis.zadd("zset1", 1, "one");
    redis.zadd("zset1", 2, "two");
    redis.zadd("zset2", 1, "one");
    redis.zadd("zset2", 2, "two");
    redis.zadd("zset2", 3, "three");

    this.redis.zinterstore(key, "zset1", "zset2");
    Set<Tuple> set = this.redis.zrangeWithScores(key, 0, -1);

    // Json.print(set, "set");

    Assert.assertEquals("one,two", StringUtils.join(RedisUtil.tupleToString(set), ","));
    Assert.assertEquals("2.0,4.0", StringUtils.join(RedisUtil.tupleToScores(set), ","));
  }
예제 #12
0
 /**
  * Creates an URI query given the request parameters.
  *
  * @return an URI query given the request parameters.
  */
 public static String getURIQuery(Map<String, String> parameters) {
   String query = null;
   if (parameters != null) {
     try {
       List<String> items = new ArrayList<String>();
       for (Map.Entry<String, String> paramInfo : parameters.entrySet()) {
         String key = paramInfo.getKey();
         String value = paramInfo.getValue();
         // XXX AT: see if needs encoding
         if (key != null) {
           if (value == null) {
             value = "";
           }
           items.add(
               String.format(
                   "%s=%s", URLEncoder.encode(key, "UTF-8"), URLEncoder.encode(value, "UTF-8")));
         }
       }
       query = StringUtils.join(items, "&");
     } catch (UnsupportedEncodingException e) {
       log.error("Failed to get uri query", e);
     }
   }
   return query;
 }
  @Test
  public void zrange() {
    Assert.assertEquals(1L, (long) this.redis.zadd(key, 1, "one"));
    Assert.assertEquals(1L, (long) this.redis.zadd(key, 2, "two"));
    Assert.assertEquals(1L, (long) this.redis.zadd(key, 3, "three"));

    Assert.assertEquals("one,two,three", StringUtils.join(this.redis.zrange(key, 0, -1), ","));
  }
  @Test
  public void zinterstore2() {
    redis.zadd("zset1", 1, "one");
    redis.zadd("zset1", 2, "two");
    redis.zadd("zset2", 1, "one");
    redis.zadd("zset2", 2, "two");
    redis.zadd("zset2", 3, "three");

    ZParams params = new ZParams().aggregate(ZParams.Aggregate.SUM);
    params.weights(2, 3);
    this.redis.zinterstore(key, params, "zset1", "zset2");
    Set<Tuple> set = this.redis.zrangeWithScores(key, 0, -1);

    // Json.print(set, "set");

    Assert.assertEquals("one,two", StringUtils.join(RedisUtil.tupleToString(set), ","));
    Assert.assertEquals("5.0,10.0", StringUtils.join(RedisUtil.tupleToScores(set), ","));
  }
  @Test
  public void hmget() {
    Assert.assertEquals(1L, (long) this.redis.hsetnx(key, "field1", "value1"));
    Assert.assertEquals(1L, (long) this.redis.hsetnx(key, "field2", "value2"));

    List<String> list = this.redis.hmget(key, "field1", "field2");

    Assert.assertEquals("value1,value2", StringUtils.join(list, ","));
  }
예제 #16
0
  @Override
  protected void fillVoiceXmlDocument(
      Document document, Element formElement, VoiceXmlDialogueContext dialogueContext)
      throws VoiceXmlDocumentRenderingException {

    List<String> submitNameList = new ArrayList<String>();
    VariableList submitVariableList = mSubmitParameters;
    if (submitVariableList != null) {
      addVariables(formElement, submitVariableList);

      for (Entry<String, String> entry : mSubmitParameters) {
        submitNameList.add(entry.getKey());
      }
    }

    Element subdialogueElement = DomUtils.appendNewElement(formElement, SUBDIALOG_ELEMENT);
    subdialogueElement.setAttribute(NAME_ATTRIBUTE, SUBDIALOGUE_FORM_ITEM_NAME);
    subdialogueElement.setAttribute(SRC_ATTRIBUTE, mUri);

    if (!submitNameList.isEmpty()) {
      subdialogueElement.setAttribute(NAME_LIST_ATTRIBUTE, StringUtils.join(submitNameList, " "));
    }

    for (Parameter parameter : mParameters) {
      Element paramElement = DomUtils.appendNewElement(subdialogueElement, PARAM_ELEMENT);
      paramElement.setAttribute(NAME_ATTRIBUTE, parameter.getName());
      setAttribute(paramElement, VALUE_ATTRIBUTE, parameter.getValue());
      setAttribute(paramElement, EXPR_ATTRIBUTE, parameter.getExpression());
    }

    SubmitMethod submitMethod = mMethod;
    if (submitMethod != null) {
      subdialogueElement.setAttribute(METHOD_ATTRIBUTE, submitMethod.name());
    }

    DocumentFetchConfiguration fetchConfiguration = mFetchConfiguration;
    if (fetchConfiguration != null) {
      applyFetchAudio(subdialogueElement, fetchConfiguration.getFetchAudio());
      applyRessourceFetchConfiguration(subdialogueElement, fetchConfiguration);
    }

    Element filledElement = DomUtils.appendNewElement(subdialogueElement, FILLED_ELEMENT);

    createVarElement(
        filledElement, SUBDIALOGUE_RESULT_VARIABLE_NAME, "dialog." + SUBDIALOGUE_FORM_ITEM_NAME);

    if (mPostDialogueScript != null) {
      createScript(filledElement, mPostDialogueScript);
    }

    createScript(
        filledElement,
        RIVR_SCOPE_OBJECT + ".addValueResult(" + SUBDIALOGUE_RESULT_VARIABLE_NAME + ");");
    createGotoSubmit(filledElement);
  }
예제 #17
0
 public String toString() {
   return "Entry{"
       + ((tokensRegex != null) ? tokensRegex : StringUtils.join(regex))
       + ' '
       + type
       + ' '
       + overwritableTypes
       + ' '
       + priority
       + '}';
 }
예제 #18
0
 /**
  * 修复路径,将 \\ 或 / 等替换为 File.separator
  *
  * @param path
  * @return
  */
 public static String path(String path) {
   String p = StringUtils.replace(path, "\\", "/");
   p = StringUtils.join(StringUtils.split(p, "/"), "/");
   if (!StringUtils.startsWithAny(p, "/") && StringUtils.startsWithAny(path, "\\", "/")) {
     p += "/";
   }
   if (!StringUtils.endsWithAny(p, "/") && StringUtils.endsWithAny(path, "\\", "/")) {
     p = p + "/";
   }
   return p;
 }
예제 #19
0
  /**
   * Write map into xml file.
   *
   * @param m map
   * @param outputFile output xml file
   */
  public void writeMapToXML(final Map<String, Set<String>> m, final File outputFile) {
    if (m == null) {
      return;
    }
    final Properties prop = new Properties();
    for (Map.Entry<String, Set<String>> entry : m.entrySet()) {
      final String key = entry.getKey();
      final String value = StringUtils.join(entry.getValue(), COMMA);
      prop.setProperty(key, value);
    }
    // File outputFile = new File(tempDir, filename);

    final DocumentBuilder db = XMLUtils.getDocumentBuilder();
    final Document doc = db.newDocument();
    final Element properties = (Element) doc.appendChild(doc.createElement("properties"));

    final Set<Object> keys = prop.keySet();
    for (Object key1 : keys) {
      final String key = (String) key1;
      final Element entry = (Element) properties.appendChild(doc.createElement("entry"));
      entry.setAttribute("key", key);
      entry.appendChild(doc.createTextNode(prop.getProperty(key)));
    }
    final TransformerFactory tf = TransformerFactory.newInstance();
    Transformer t = null;
    try {
      t = tf.newTransformer();
      t.setOutputProperty(OutputKeys.INDENT, "yes");
      t.setOutputProperty(OutputKeys.METHOD, "xml");
      t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    } catch (final TransformerConfigurationException tce) {
      throw new RuntimeException(tce);
    }
    final DOMSource doms = new DOMSource(doc);
    OutputStream out = null;
    try {
      out = new FileOutputStream(outputFile);
      final StreamResult sr = new StreamResult(out);
      t.transform(doms, sr);
    } catch (final Exception e) {
      logger.error("Failed to process map: " + e.getMessage(), e);
    } finally {
      if (out != null) {
        try {
          out.close();
        } catch (final IOException e) {
          logger.error("Failed to close output stream: " + e.getMessage());
        }
      }
    }
  }
예제 #20
0
  public static ItemMatcher[] getItemStringToMatchers(
      final String line, final CompassDirection facing) {

    String str = StringUtils.removeBrackets(line).toLowerCase();
    str = str.trim();
    if (str.isEmpty()) return new ItemMatcher[0];

    // Check the given direction and intended direction from the sign
    final CompassDirection direction = getLineItemDirection(str);

    // Praitaq - Added to debug Directional Conditions not working.
    MinecartManiaLogger.getInstance().debug("Direction Returned: " + direction.toString());

    if (direction != CompassDirection.NO_DIRECTION) {
      str = str.substring(2, str.length()); // remove the direction for further parsing.

      // Praitaq - Added to debug Directional Conditions not working.
      MinecartManiaLogger.getInstance().debug("Line - Direction: " + str + " Line:" + line);
    }
    if ((facing != null) && (direction != facing) && (direction != CompassDirection.NO_DIRECTION))
      return new ItemMatcher[0];

    final ItemMatcher matcher = new ItemMatcher();
    final ArrayList<ItemMatcher> matchers = new ArrayList<ItemMatcher>();

    final String[] parts = str.split(":");
    for (int i = 0; i < parts.length; i++) {
      parts[i] = StringUtils.removeBrackets(parts[i]).toLowerCase().trim();
    }
    str = StringUtils.join(parts, 0, ":");

    if (preparsed.containsKey(str)) {
      matchers.add(preparsed.get(str));
    }
    if (matcher.parse(str)) {
      preparsed.put(str, matcher);
      saveDebugMap();
      matchers.add(matcher);
    }
    final ItemMatcher[] ret = new ItemMatcher[matchers.size()];
    matchers.toArray(ret);
    return ret;
  }
예제 #21
0
 public void updateTickets(JiraTickets tickets) throws ExecutionException, InterruptedException {
   for (JiraTicket t : tickets) {
     Promise<Issue> issuePromise = issueRestClient.getIssue(t.getId());
     Issue i = issuePromise.get();
     // find transition (we need ID)
     Iterable<Transition> transitions =
         issueRestClient.getTransitions(i.getTransitionsUri()).get();
     String tName = "Hotfix Failed";
     if (t.isValid()) {
       tName = "Out On Dev";
     }
     Transition transition = find(transitions, tName);
     if (transition == null) {
       continue;
     }
     // prepare fields
     // List<FieldInput> fields = Arrays.asList(   new FieldInput("resolution",
     // ComplexIssueInputFieldValue.with("name", "RerunPass")));
     Comment comment = Comment.valueOf(StringUtils.join(t.getValidationMessages(), "\n"));
     issueRestClient.transition(i, new TransitionInput(transition.getId(), comment));
   }
 }
예제 #22
0
  /**
   * Tests joining strings.
   *
   * @see StringUtils#join(String, String[])
   */
  public void testJoin() {
    assertEquals("", StringUtils.join("", new String[0]));
    assertEquals("", StringUtils.join("+", new String[0]));

    assertEquals("foo", StringUtils.join("", new String[] {"foo"}));
    assertEquals("foo", StringUtils.join("+", new String[] {"foo"}));

    assertEquals("foofaafee", StringUtils.join("", new String[] {"foo", "faa", "fee"}));
    assertEquals("foo+faa+fee", StringUtils.join("+", new String[] {"foo", "faa", "fee"}));

    try {
      StringUtils.join(null, new String[0]);
      fail();
    } catch (NullPointerException expected) {
      // expected
    }

    try {
      StringUtils.join("", (String[]) null);
      fail();
    } catch (NullPointerException expected) {
      // expected
    }
  }
예제 #23
0
파일: IdUtils.java 프로젝트: beno/apricot
  /**
   * Generates an id from a non-null String.
   *
   * <p>Replaces accented characters from a string by their ascii equivalent, removes non
   * alphanumerical characters and replaces spaces by the given wordSeparator character.
   *
   * @param s the original String
   * @param wordSeparator the word separator to use (usually '-')
   * @param lower if lower is true, remove upper case
   * @param maxChars maximum longer of identifier characters
   * @return the identifier String
   */
  public static String generateId(String s, String wordSeparator, boolean lower, int maxChars) {
    s = StringUtils.toAscii(s);
    s = s.trim();
    if (lower) {
      s = s.toLowerCase();
    }
    String[] words = s.split(WORD_SPLITTING_REGEXP);
    // remove blank chars from words, did not get why they're not filtered
    List<String> wordsList = new ArrayList<String>();
    for (String word : words) {
      if (word != null && word.length() > 0) {
        wordsList.add(word);
      }
    }
    if (wordsList.isEmpty()) {
      return generateStringId();
    }
    StringBuilder sb = new StringBuilder();
    String id;
    if (maxChars > 0) {
      // be sure at least one word is used
      sb.append(wordsList.get(0));
      for (int i = 1; i < wordsList.size(); i++) {
        String newWord = wordsList.get(i);
        if (sb.length() + newWord.length() > maxChars) {
          break;
        } else {
          sb.append(wordSeparator).append(newWord);
        }
      }
      id = sb.toString();
      id = id.substring(0, Math.min(id.length(), maxChars));
    } else {
      id = StringUtils.join(wordsList.toArray(), wordSeparator);
    }

    return id;
  }
 @Test
 public void smembers() {
   Assert.assertEquals(1L, (long) this.redis.sadd(key, "Hello"));
   Assert.assertEquals(1L, (long) this.redis.sadd(key, "World"));
   Assert.assertEquals("World,Hello", StringUtils.join(this.redis.smembers(key), ","));
 }
예제 #25
0
  /**
   * @param
   * @return
   */
  public static String joinNelementsPerLine(
      String[] vn, int divisor, String sp, boolean quote, String qm, String lnsp) {
    if (!(divisor >= 1)) {
      divisor = 1;
    } else if (divisor > vn.length) {
      divisor = vn.length;
    }
    String sep = null;
    if (sp != null) {
      sep = sp;
    } else {
      sep = ", ";
    }
    String qmrk = null;
    if (quote) {
      if (qm == null) {
        qmrk = ",";
      } else {
        if (qm.equals("\"")) {
          qmrk = "\"";
        } else {
          qmrk = qm;
        }
      }
    } else {
      qmrk = "";
    }
    String lineSep = null;
    if (lnsp == null) {
      lineSep = "\n";
    } else {
      lineSep = lnsp;
    }

    String vnl = null;
    if (vn.length < divisor) {
      vnl = StringUtils.join(vn, sep);
    } else {
      StringBuilder sb = new StringBuilder();

      int iter = vn.length / divisor;
      int lastN = vn.length % divisor;
      if (lastN != 0) {
        iter++;
      }
      int iterm = iter - 1;
      for (int i = 0; i < iter; i++) {
        int terminalN = divisor;
        if ((i == iterm) && (lastN != 0)) {
          terminalN = lastN;
        }
        for (int j = 0; j < terminalN; j++) {
          if ((divisor * i + j + 1) == vn.length) {

            sb.append(qmrk + vn[j + i * divisor] + qmrk);

          } else {

            sb.append(qmrk + vn[j + i * divisor] + qmrk + sep);
          }
        }
        if (i < (iter - 1)) {
          sb.append(lineSep);
        }
      }
      vnl = sb.toString();
      dbgLog.fine("results:\n" + vnl);
    }
    return vnl;
  }