Example #1
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;
  }
 @Override
 public void validate(final MavenEnvironment env) throws ValidationException {
   if (!env.outdir().exists()
       || "pom".equals(env.project().getPackaging())
       || env.exclude("dependencies", "")) {
     Logger.info(this, "No dependency analysis in this project");
     return;
   }
   final Collection<String> unused = DependenciesValidator.unused(env);
   if (!unused.isEmpty()) {
     Logger.warn(
         this,
         "Unused declared dependencies found:%s%s",
         DependenciesValidator.SEP,
         StringUtils.join(unused, DependenciesValidator.SEP));
   }
   final Collection<String> used = DependenciesValidator.used(env);
   if (!used.isEmpty()) {
     Logger.warn(
         this,
         "Used undeclared dependencies found:%s%s",
         DependenciesValidator.SEP,
         StringUtils.join(used, DependenciesValidator.SEP));
   }
   final Integer failures = used.size() + unused.size();
   if (failures > 0) {
     throw new ValidationException("%d dependency problem(s) found", failures);
   }
   Logger.info(this, "No dependency problems found");
 }
Example #3
0
 /**
  * Tests that spacing is correct.
  *
  * @throws IOException
  */
 @Test
 public void spacing_no_constructor() throws IOException {
   // Class structure
   JClass c = new JClass("sido.test", "Test");
   c.addImport(List.class);
   c.addImport(ArrayList.class);
   c.addField("String", "name");
   c.addField("List<String>", "otherNames").setInitialisation("new ArrayList<String>()");
   c.addMethod("getName", "String").addContent("return name;");
   c.addMethod("setName").addParam("String", "value").addContent("this.name = value;");
   // Output
   StringWriter s = new StringWriter();
   PrintWriter writer = new PrintWriter(s);
   // Generation
   c.write(writer);
   // Output
   List<String> actual = readLines(s.toString());
   // Gets the expected content
   List<String> expected = readReference("/jclass/SpacingNoConstructor.java");
   // Difference between the two sets
   Patch diff = DiffUtils.diff(expected, actual);
   List<Delta> deltas = diff.getDeltas();
   if (!deltas.isEmpty()) {
     // Creates the diff
     String original = StringUtils.join(expected, "\n");
     String revised = StringUtils.join(actual, "\n");
     List<String> unifiedDiff =
         DiffUtils.generateUnifiedDiff(original, revised, expected, diff, 3);
     String diffDisplay = StringUtils.join(unifiedDiff, "\n");
     System.err.println(diffDisplay);
     fail("spacing-no-constructor");
   }
 }
Example #4
0
 public void assertJClass(JClass c, String referenceResourcePath, String testId)
     throws IOException {
   // Output
   StringWriter s = new StringWriter();
   PrintWriter writer = new PrintWriter(s);
   // Generation
   c.write(writer);
   // Output
   List<String> actual = readLines(s.toString());
   // Gets the expected content
   List<String> expected = readReference(referenceResourcePath);
   // Difference between the two sets
   Patch diff = DiffUtils.diff(expected, actual);
   List<Delta> deltas = diff.getDeltas();
   if (!deltas.isEmpty()) {
     // Creates the diff
     String original = StringUtils.join(expected, "\n");
     String revised = StringUtils.join(actual, "\n");
     List<String> unifiedDiff =
         DiffUtils.generateUnifiedDiff(original, revised, expected, diff, 3);
     String diffDisplay = StringUtils.join(unifiedDiff, "\n");
     System.err.println(diffDisplay);
     fail(testId);
   }
 }
Example #5
0
  /**
   * diff commit message로 pull request의 title과 body를 채운다.<br>
   * <br>
   * case 1 : commit이 한개이고 message가 한줄일 경우 title에 추가한다.<br>
   * case 2 : commit이 한개이고 message가 여러줄일 경우 첫번째줄 mesage는 title 나머지 message는 body에 추가<br>
   * case 3 : commit이 여러개일 경우 각 commit의 첫번째줄 message들을 모아서 body에 추가 <br>
   *
   * @param commits
   * @return
   */
  private Map<String, String> suggestTitleAndBodyFromDiffCommit(List<GitCommit> commits) {
    Map<String, String> messageMap = new HashMap<>();

    String message;

    if (commits.isEmpty()) {
      return messageMap;

    } else if (commits.size() == 1) {
      message = commits.get(0).getMessage();
      String[] messages = message.split(Constants.NEW_LINE_DELIMETER);

      if (messages.length > 1) {
        String[] msgs = Arrays.copyOfRange(messages, 1, messages.length);
        messageMap.put("title", messages[0]);
        messageMap.put("body", StringUtils.join(msgs, Constants.NEW_LINE_DELIMETER));

      } else {
        messageMap.put("title", messages[0]);
        messageMap.put("body", StringUtils.EMPTY);
      }

    } else {
      String[] firstMessages = new String[commits.size()];
      for (int i = 0; i < commits.size(); i++) {
        String[] messages = commits.get(i).getMessage().split(Constants.NEW_LINE_DELIMETER);
        firstMessages[i] = messages[0];
      }
      messageMap.put("body", StringUtils.join(firstMessages, Constants.NEW_LINE_DELIMETER));
    }

    return messageMap;
  }
Example #6
0
  /**
   * Get user ratings from gcvote.com
   *
   * @param guids
   * @param geocodes
   * @return
   */
  @NonNull
  private static Map<String, GCVoteRating> getRating(
      final List<String> guids, final List<String> geocodes) {
    if (guids == null && geocodes == null) {
      return Collections.emptyMap();
    }

    final Parameters params = new Parameters("version", "cgeo");
    final ImmutablePair<String, String> login = Settings.getGCvoteLogin();
    if (login != null) {
      params.put("userName", login.left, "password", login.right);
    }

    // use guid or gccode for lookup
    final boolean requestByGuids = CollectionUtils.isNotEmpty(guids);
    if (requestByGuids) {
      params.put("cacheIds", StringUtils.join(guids, ','));
    } else {
      params.put("waypoints", StringUtils.join(geocodes, ','));
    }
    final InputStream response =
        Network.getResponseStream(Network.getRequest("http://gcvote.com/getVotes.php", params));
    if (response == null) {
      return Collections.emptyMap();
    }
    try {
      return getRatingsFromXMLResponse(response, requestByGuids);
    } finally {
      IOUtils.closeQuietly(response);
    }
  }
 private void updateCollaboratorsRights(Map<String, BaseObject> rightsObjects, XWikiDocument doc) {
   for (Map.Entry<AccessLevel, List<DocumentReference>> entry : getCollaborators(doc).entrySet()) {
     BaseObject right;
     if ("manage".equals(entry.getKey().getName()) || "owner".equals(entry.getKey().getName())) {
       right = rightsObjects.get("view,edit,delete");
     } else if ("edit".equals(entry.getKey().getName())) {
       right = rightsObjects.get("view,edit");
     } else if ("view".equals(entry.getKey().getName())) {
       right = rightsObjects.get("view");
     } else {
       return;
     }
     List<String> users = new LinkedList<String>();
     List<String> groups = new LinkedList<String>();
     for (DocumentReference userOrGroup : entry.getValue()) {
       if (isUser(userOrGroup)) {
         users.add(userOrGroup.toString());
       } else if (isGroup(userOrGroup)) {
         groups.add(userOrGroup.toString());
       }
     }
     setRights(right, "users", StringUtils.join(users, ","));
     setRights(right, "groups", StringUtils.join(groups, ","));
   }
 }
  private static JSONObject runCmd(List<String> cmd) throws Exception {
    ProcessBuilder builder = new ProcessBuilder(cmd);

    StopWatch stopWatch = new StopWatch();
    stopWatch.start();
    Process process = builder.start();
    int exitCode = process.waitFor();
    stopWatch.stop();

    String stdout = streamToString(process.getInputStream());
    String stderr = streamToString(process.getErrorStream());
    log.warn(String.format("stdout:%n%s", stdout));
    log.warn(String.format("stderr:%n%s", stderr));
    String message = createOutputMessage(stdout, stderr);

    if (exitCode == 0) {
      log.info(
          String.format(
              "Command succeeded in %dms: %s", stopWatch.getTime(), StringUtils.join(cmd, " ")));
    } else {
      log.warn(
          String.format(
              "Command failed with code=%d in %dms: %s",
              exitCode, stopWatch.getTime(), StringUtils.join(cmd, " ")));
      log.warn(String.format("stdout:\n%s", stdout));
      log.warn(String.format("stderr:\n%s", stderr));
    }

    JSONObject obj = new JSONObject();
    obj.put("message", message);

    return obj;
  }
 /**
  * Devuelve la lista de objetos que satisfacen todas las condiciones del array pasado como
  * parámetro
  *
  * @param conditions Objetos de la clase QueryCondition que especifican las condiciones de los
  *     objetos a buscar
  * @return Lista de objetos de la tabla que cumplen las condiciones dadas. Si ninguno de ellos las
  *     cumple, se devuelve una lista vacía.
  */
 protected List<T> findByConditions(QueryCondition[] conditions) {
   Connection con = null;
   PreparedStatement pst = null;
   ResultSet rs = null;
   List<T> resul = new LinkedList<T>();
   try {
     con = ds.getConnection();
     String[] columnNames = getColumnNames();
     String columnNamesWithCommas = StringUtils.join(columnNames, ", ");
     String sql =
         "SELECT "
             + columnNamesWithCommas
             + " FROM "
             + getTableName()
             + " WHERE "
             + StringUtils.join(getWhereConditions(conditions), " AND ");
     pst = con.prepareStatement(sql);
     rs = pst.executeQuery();
     while (rs.next()) {
       resul.add(buildObject(rs));
     }
     return resul;
   } catch (SQLException e) {
     e.printStackTrace();
   } finally {
     try {
       if (rs != null) rs.close();
       if (pst != null) pst.close();
       if (con != null) con.close();
     } catch (Exception e) {
     }
   }
   return null;
 }
 /**
  * Convert to String from the result of execute().
  *
  * @param <T> the type of result object.
  * @param result the result of execute().
  * @return converted string.
  */
 public static <T> String convertToString(T result) {
   if (result == null) return "";
   else if (result instanceof Object[]) return StringUtils.join((Object[]) result, ',');
   else if (result instanceof Iterable) return StringUtils.join((Iterable<?>) result, ',');
   else if (result instanceof Iterator) return StringUtils.join((Iterator<?>) result, ',');
   else return result.toString();
 }
Example #11
0
 /**
  * Return a string representing how this function is translated into SQL in the given dialect
  *
  * @param dialect
  * @param args
  * @return
  */
 @Override
 public String getNative(KiWiDialect dialect, String... args) {
   if (dialect instanceof PostgreSQLDialect) {
     return String.format("(%s)", StringUtils.join(args, "||"));
   } else if (dialect instanceof H2Dialect || dialect instanceof MySQLDialect) {
     return String.format("CONCAT(%s)", StringUtils.join(args, ","));
   }
   throw new UnsupportedOperationException("CONCAT not supported by " + dialect);
 }
  public boolean update(T old, T newObjeto) {
    Connection con = null;
    PreparedStatement pst = null;
    ResultSet rs = null;
    T objetos = findById(getIdFromObject(old));
    if (objetos == null) return false;
    try {
      con = ds.getConnection();
      String[] columnNames = getColumnNames();
      String[] keyColumnNames = getKeyColumnName();
      String[] assignaments = new String[columnNames.length];
      String[] keyValues = new String[keyColumnNames.length];
      for (int i = 0; i < assignaments.length; i++) {
        assignaments[i] = columnNames[i] + " = ?";
      }
      for (int i = 0; i < keyValues.length; i++) {
        keyValues[i] = keyColumnNames[i] + " = ?";
      }
      pst =
          con.prepareStatement(
              "UPDATE "
                  + getTableName()
                  + " SET "
                  + StringUtils.join(assignaments, ", ")
                  + " WHERE "
                  + StringUtils.join(keyValues, " AND "));

      Object[] objectFields = serializableObject(newObjeto);

      int j = 1;
      for (int i = 0; i < objectFields.length; i++) {
        pst.setObject(j, objectFields[i]);
        j++;
      }
      String[] key = getValuesKeyFromObject(old);
      for (int i = 0; i < keyValues.length; i++) {
        pst.setObject(j, key[i]);
        j++;
      }
      pst.executeUpdate();

    } catch (SQLException e) {
      e.printStackTrace();
    } finally {
      try {
        if (rs != null) rs.close();
        if (pst != null) pst.close();
        if (con != null) con.close();
      } catch (Exception e) {
      }
    }
    return true;
  }
Example #13
0
 public int update(T object) {
   Connection con = null;
   PreparedStatement pst = null;
   ResultSet rs = null;
   int resul = 0;
   try {
     con = ds.getConnection();
     String[] columnName = getColumnNames();
     String[] assignments = new String[columnName.length - 1];
     String[] keyColumns = getKeyColumnNames();
     String[] conditions = new String[keyColumns.length];
     for (int i = 0; i < assignments.length; i++) {
       assignments[i] = columnName[i + 1] + "=?";
     }
     for (int i = 0; i < keyColumns.length; i++) {
       conditions[i] = keyColumns[i] + "=?";
     }
     String sql =
         "UPDATE "
             + getTableName()
             + " SET "
             + StringUtils.join(assignments, ",")
             + " WHERE "
             + StringUtils.join(conditions, " AND ");
     pst = con.prepareStatement(sql);
     Object[] objectField = serializeObject(object);
     int pos = 1;
     for (int j = 1; j < columnName.length; j++) {
       pst.setObject(j, objectField[j]);
       pos = j;
     }
     // Condiciones del where
     Object[] primaryKeys = serializeKey(getKey(object));
     pos++;
     for (int j = 0; j < primaryKeys.length; j++) {
       pst.setObject(pos, primaryKeys[j]);
       pos++;
     }
     resul = pst.executeUpdate();
   } catch (SQLException e) {
     e.printStackTrace();
   } finally {
     try {
       if (rs != null) rs.close();
       if (pst != null) pst.close();
       if (con != null) con.close();
     } catch (Exception e) {
     }
   }
   return resul;
 }
  @Override
  public String toQueryString() {
    System.out.println("TokenCountFromDocumentsQueryTemplate.toQueryString");
    List<String> cypher = new ArrayList<String>();
    String group = query.getGroup().split("_")[0];
    String key = query.getGroup().replaceFirst(group + "_", "");

    if (hasEmptyFilter)
      cypher.add(
          "MATCH (:Metadatum{group:'"
              + group
              + "',key:'"
              + key
              + "'})<-[r:HAS_METADATUM]-(document:Document) "
              + "WITH DISTINCT r.value AS "
              + query.getGroup()
              + ", document "
              + "RETURN "
              + query.getGroup()
              + ", SUM(document.token_count) AS hit_count;");
    else {
      if (startNodes.size() > 0) {
        List<String> start = new ArrayList<String>();
        for (String nodeId : startNodes.keySet()) {
          start.add(nodeId + "=" + startNodes.get(nodeId));
        }
        cypher.add("START " + StringUtils.join(start.toArray(), ", "));
      }
      cypher.add(metadataFilter);

      //			if (group.equals("Corpus") || group.equals("Collection"))
      //				cypher.add(" RETURN DISTINCT "+group.toLowerCase()+"."+key+" AS "+query.getGroup()+",
      // "+group.toLowerCase()+".token_count AS hit_count;");
      //			else
      cypher.add(
          "MATCH (:Metadatum{group:'"
              + group
              + "',key:'"
              + key
              + "'})<-[r:HAS_METADATUM]-(document) "
              + "WITH DISTINCT r.value AS "
              + query.getGroup()
              + ", document "
              + "RETURN "
              + query.getGroup()
              + ", SUM(document.token_count) AS hit_count;");
    }

    return StringUtils.join(cypher.toArray(), " ");
  }
Example #15
0
 @Override
 public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
   if (args.length == 0) {
     return false;
   }
   if (!(sender instanceof Player)) {
     sender.sendMessage("This can only be used in-game.");
     return true;
   }
   Player player = (Player) sender;
   String nick = StringUtils.join(args, " ");
   int standard = 0;
   for (char Char : nick.toCharArray()) {
     if (standard >= 3) {
       continue;
     } else if (Char >= 'a' && Char <= 'z') {
       standard++;
     } else if (Char >= 'A' && Char <= 'Z') {
       standard++;
     } else if (Char >= '0' && Char <= '9') {
       standard++;
     } else {
       standard = 0;
     }
   }
   if (standard < 3) {
     sender.sendMessage(
         ChatColor.RED + "Your nick must have at least 3 alphanumeric characters consecutively.");
     return true;
   }
   player.sendMessage(
       ChatColor.GREEN
           + "Setting nick to "
           + CUtils_Methods.colour(StringUtils.join(args, " "))
           + ChatColor.GREEN
           + ".");
   try {
     Connection c = FOPMR_DatabaseInterface.getConnection();
     PreparedStatement statement =
         c.prepareStatement("UPDATE PLAYERS SET NICK = ? WHERE UUID = ?");
     statement.setString(1, nick + "&r");
     statement.setString(2, player.getUniqueId().toString());
     statement.executeUpdate();
     FOPMR_Rank.nicks.put(player.getName(), nick + "&r");
     c.commit();
   } catch (Exception ex) {
     FreedomOpModRemastered.plugin.handleException(ex);
   }
   return true;
 }
Example #16
0
  /**
   * Get the DDL for a table. Only works with tables created with TableHelper.quickTable(..) above.
   */
  public static String ddlForTable(VoltTable table) {
    assert (table.m_originalColumnInfos != null);

    // for each column, one line
    String[] colLines = new String[table.m_originalColumnInfos.length];
    for (int i = 0; i < table.m_originalColumnInfos.length; i++) {
      VoltTable.ColumnInfo colInfo = table.m_originalColumnInfos[i];
      String col = colInfo.name + " " + colInfo.type.toSQLString().toUpperCase();
      if ((colInfo.type == VoltType.STRING) || (colInfo.type == VoltType.VARBINARY)) {
        col += String.format("(%d)", colInfo.size);
      }
      if (colInfo.defaultValue != VoltTable.ColumnInfo.NO_DEFAULT_VALUE) {
        col += " DEFAULT ";
        if (colInfo.defaultValue == null) {
          col += "NULL";
        } else if (colInfo.type.isNumber()) {
          col += colInfo.defaultValue;
        } else {
          col += "'" + colInfo.defaultValue + "'";
        }
      }
      if (colInfo.nullable == false) {
        col += " NOT NULL";
      }
      if (colInfo.unique == true) {
        col += " UNIQUE";
      }
      colLines[i] = col;
    }

    String s = "CREATE TABLE " + table.m_name + " (\n  ";
    s += StringUtils.join(colLines, ",\n  ");

    // pkey line
    int[] pkeyIndexes = table.getPkeyColumnIndexes();
    if (pkeyIndexes.length > 0) {
      s += ",\n  PRIMARY KEY (";
      String[] pkeyColNames = new String[pkeyIndexes.length];
      for (int i = 0; i < pkeyColNames.length; i++) {
        pkeyColNames[i] = table.getColumnName(pkeyIndexes[i]);
      }
      s += StringUtils.join(pkeyColNames, ",");
      s += ")";
    }

    s += "\n);";

    return s;
  }
  static List<Feature> computeGeneLevelExpression(
      Map<String, FeatureCount> featureCounts,
      Map<String, Feature> geneInfos,
      double numberOfReads) {
    List<Feature> geneFeatures = new LinkedList<Feature>();

    HashMap<String, List<FeatureCount>> geneFeaturesMap = new HashMap<>();

    // Organize exons by gene
    Collection<FeatureCount> exons = featureCounts.values();
    for (FeatureCount fc : exons) {
      String geneId = fc.getFeature().getAttribute("gene_id");
      if (geneFeaturesMap.containsKey(geneId)) {
        geneFeaturesMap.get(geneId).add(fc);
      } else {
        LinkedList<FeatureCount> fcs = new LinkedList<>();
        fcs.add(fc);
        geneFeaturesMap.put(geneId, fcs);
      }
    }

    // compute total counts and total length
    for (Map.Entry<String, List<FeatureCount>> entry : geneFeaturesMap.entrySet()) {
      List<FeatureCount> fcsForGene = entry.getValue();
      Collections.sort(fcsForGene);
      Feature geneInfo = geneInfos.get(entry.getKey());

      if (geneInfo == null) {
        throw new IllegalStateException(entry.getKey() + " has no entry in geneInfos");
      }

      if (!geneInfo.type().equals("gene")) {
        throw new IllegalStateException(geneInfo + " is not a gene");
      }

      // get total length and counts
      double count = 0.0;
      int length = 0;
      List<String> exonIds = new LinkedList<>();
      for (FeatureCount fc : fcsForGene) {
        count += fc.getCount();
        length += fc.getFeature().location().length();
        exonIds.add(fc.getId());
      }

      // comput rpkm
      double rpkm = count / length / numberOfReads * Math.pow(10, 9);

      HashMap<String, String> info = new HashMap<>();
      info.put("reads", Double.toString(count));
      info.put("RPKM", Double.toString(rpkm));
      info.put("length", Integer.toString(length));
      info.put("exons", StringUtils.join(exonIds, ","));

      Feature newGeneInfo = GTFFeatureBuilder.addAttributesToFeature(geneInfo, info);

      geneFeatures.add(newGeneInfo);
    }
    return geneFeatures;
  }
Example #18
0
  public MrrrMethodCall(String classAndArgs) {
    String classPartString = classAndArgs.substring(0, classAndArgs.indexOf("("));
    List<String> classParts = Arrays.asList(classPartString.split("\\."));

    packagePart =
        classParts.subList(0, classParts.size() - 1).toArray(new String[classParts.size() - 1]);
    methodPart = classParts.get(classParts.size() - 1);
    packagePartString = StringUtils.join(packagePart, ".");

    String replace = "<<.<!!~~ESCAPED_COMMA~~!!>.>>";
    String args =
        classAndArgs
            .substring(classAndArgs.indexOf("(") + 1, classAndArgs.lastIndexOf(")"))
            .replace("\\,", replace);

    List<MrrrArgument> arguments = new ArrayList<MrrrArgument>();
    for (String arg : args.split(",")) {
      arg = arg.replace(replace, ",").trim();
      if (arg.length() > 0) {
        MrrrArgument mrrrArgument = new MrrrArgument(arg);
        arguments.add(mrrrArgument);
      }
    }
    this.arguments = arguments;

    // get return variable name
    if (classAndArgs.contains("->")) {
      returnVariable = classAndArgs.substring(classAndArgs.indexOf("->") + 2).trim();
    }
  }
Example #19
0
 public AttributionModel(AuthorAttribution authorAttribution) {
   this.offerAttributionList = authorAttribution.offerAttributionList();
   this.authors =
       (this.offerAttributionList)
           ? StringUtils.join(authorAttribution.getAuthorList(), ", ")
           : "";
 }
  @Override
  public String renderQueryFilter(
      QueryFilter<JsonPointer> filter,
      Map<String, Object> replacementTokens,
      Map<String, Object> params) {
    final int offsetParam = Integer.parseInt((String) params.get(PAGED_RESULTS_OFFSET));
    final int pageSizeParam = Integer.parseInt((String) params.get(PAGE_SIZE));
    String filterString = getFilterString(filter, replacementTokens);
    String keysClause = "";

    // JsonValue-cheat to avoid an unchecked cast
    final List<SortKey> sortKeys = new JsonValue(params).get(SORT_KEYS).asList(SortKey.class);
    // Check for sort keys and build up order-by syntax
    if (sortKeys != null && sortKeys.size() > 0) {
      List<String> keys = new ArrayList<String>();
      prepareSortKeyStatements(sortKeys, keys, replacementTokens);
      keysClause = StringUtils.join(keys, ", ");
    } else {
      keysClause = "objectid DESC";
    }

    return "WITH results AS ( SELECT rowNo = ROW_NUMBER() OVER( ORDER BY "
        + keysClause
        + " ), ${_dbSchema}.${_mainTable}.* FROM ${_dbSchema}.${_mainTable} "
        + filterString
        + ") SELECT * FROM results WHERE rowNo BETWEEN "
        + (offsetParam + 1)
        + " AND "
        + (offsetParam + pageSizeParam);
  }
Example #21
0
@RunWith(Parameterized.class)
public class VXQueryXMarkTest extends AbstractXQueryTest {

  private static String VXQUERY_XMARK_CATALOG =
      StringUtils.join(
          new String[] {"src", "test", "resources", "VXQueryXMarkCatalog.xml"}, File.separator);

  public VXQueryXMarkTest(TestCase tc) throws Exception {
    super(tc);
  }

  @Parameters
  public static Collection<Object[]> tests() throws Exception {
    JUnitTestCaseFactory jtcf_vxquery = new JUnitTestCaseFactory(getOptions());
    Collection<Object[]> tests = jtcf_vxquery.getList();
    return tests;
  }

  public static XTestOptions getOptions() {
    XTestOptions options = getDefaultTestOptions();
    options.catalog = VXQUERY_XMARK_CATALOG;
    return options;
  }

  @Override
  protected XTestOptions getTestOptions() {
    return getOptions();
  }
}
Example #22
0
 public static String mergeString(String... strings) {
   String[] ret = new String[strings.length];
   for (int i = 0; i < strings.length; i++) {
     ret[i] = strings[i].replace(",", "\\,");
   }
   return StringUtils.join(ret, ",");
 }
  protected void propagateCatalogTableProperties(
      Output output, CatalogStorage tableStorage, Properties props) {
    String prefix = "falcon_" + output.getName();

    propagateCommonCatalogTableProperties(tableStorage, props, prefix);

    // pig and java actions require partition expression as "key1=val1, key2=val2"
    props.put(prefix + "_partitions_pig", "${coord:dataOutPartitions('" + output.getName() + "')}");
    props.put(
        prefix + "_partitions_java", "${coord:dataOutPartitions('" + output.getName() + "')}");

    // hive requires partition expression as "key1='val1', key2='val2'" (with quotes around values)
    // there is no direct EL expression in oozie
    List<String> partitions = new ArrayList<String>();
    for (String key : tableStorage.getDatedPartitionKeys()) {
      StringBuilder expr = new StringBuilder();
      expr.append("${coord:dataOutPartitionValue('")
          .append(output.getName())
          .append("', '")
          .append(key)
          .append("')}");
      props.put(prefix + "_dated_partition_value_" + key, expr.toString());
      partitions.add(key + "='" + expr + "'");
    }
    props.put(prefix + "_partitions_hive", StringUtils.join(partitions, ","));
  }
  /** the pretty printer uses a stack to keep track of the current nodes. */
  private class StackItem {
    private String id = StringUtils.join("i", PrettyPrintVisitor.sequence++);

    /** name will be used as label for the DOT diagram. */
    private final String name;

    /**
     * if an item carries a semantic value (like the id of an idToken, etc.) the value will be
     * stored here.
     */
    private final String value;

    public StackItem(String name, String value) {
      this.name = name;
      this.value = value;
    }

    public String getLabel() {
      return StringUtils.isBlank(value) ? name : StringUtils.join(name, ":", value);
    }

    public String getId() {
      return id;
    }
  }
    /** 艦隊が出撃中で大破した場合に警告を行います */
    private void postFatal(List<ShipDto> badlyDamaged) {
      if (badlyDamaged.size() > 0) {
        if (AppConfig.get().isBalloonBybadlyDamage()) {
          StringBuilder sb = new StringBuilder();
          sb.append(AppConstants.MESSAGE_STOP_SORTIE);
          sb.append("\n");
          for (ShipDto shipDto : badlyDamaged) {
            sb.append(shipDto.getName());
            sb.append("(" + shipDto.getLv() + ")");
            sb.append(" : ");
            List<ItemInfoDto> items = shipDto.getItem();
            List<String> names = new ArrayList<String>();
            for (ItemInfoDto itemDto : items) {
              if (itemDto != null) {
                names.add(itemDto.getName());
              }
            }
            sb.append(StringUtils.join(names, ","));
            sb.append("\n");
          }
          ToolTip tip = new ToolTip(this.main.getShell(), SWT.BALLOON | SWT.ICON_ERROR);
          tip.setText("大破警告");
          tip.setMessage(sb.toString());

          this.main.getTrayItem().setToolTip(tip);
          tip.setVisible(true);
        }
        // 大破時にサウンドを再生する
        Sound.randomBadlySoundPlay();
      }
    }
Example #26
0
    @Override
    String process(Block block, State state) {
      List<String> queryLines = new ArrayList<String>();
      boolean queryStarted = false;
      for (String line : block.lines) {
        if (!queryStarted) {
          if (line.startsWith(CODE_BLOCK)) {
            queryStarted = true;
          }
        } else {
          if (line.startsWith(CODE_BLOCK)) {
            break;
          } else {
            queryLines.add(line);
          }
        }
      }
      String query = StringUtils.join(queryLines, CypherDoc.EOL);
      try (Transaction tx = state.database.beginTx()) {
        state.latestResult = new Result(query, state.engine.profile(query));
        tx.success();
      }
      String prettifiedQuery = state.engine.prettify(query);
      StringBuilder output = new StringBuilder(512);
      output
          .append(AsciidocHelper.createCypherSnippetFromPreformattedQuery(prettifiedQuery))
          .append(CypherDoc.EOL)
          .append(CypherDoc.EOL);

      return output.toString();
    }
Example #27
0
 @ResponseBody
 @RequestMapping(value = "/delete", method = RequestMethod.POST)
 public ImmutableMap<String, String> linkDelete(Long[] linkIds, HttpSession session) {
   try {
     if (linkIds == null || linkIds.length == 0) {
       LOGGER.warn("要删除链接的ID为空!");
       return ImmutableMap.of("status", "0", "message", getMessage("link.deletefailed.message"));
     }
     List<Link> links = linkService.findAll(linkIds);
     String realPath = session.getServletContext().getRealPath("");
     List<File> deleteFiles = Lists.newArrayList();
     File deleteFile;
     for (Link link : links) {
       if (link.getLinkPic() == null || "".equals(link.getLinkPic())) continue;
       deleteFile = new File(realPath + link.getLinkPic());
       deleteFiles.add(deleteFile);
     }
     linkService.deleteInBatch(links);
     deleteLinkRes(deleteFiles);
   } catch (Exception e) {
     LOGGER.error("链接信息删除失败,失败原因:{}", e.getMessage());
     return ImmutableMap.of("status", "0", "message", getMessage("link.deletefailed.message"));
   }
   LOGGER.info("链接信息删除成功,ID为{}", StringUtils.join(linkIds, ","));
   return ImmutableMap.of("status", "1", "message", getMessage("link.deletesuccess.message"));
 }
  private void notifyInvitationServiceThatInvitationsSentToFriends(
      final BigDecimal issuingPlayerId,
      final String[] recipientIdentifiers,
      final String currentGame,
      final String screenSource) {
    final boolean hasRecipients = recipientIdentifiers != null && recipientIdentifiers.length > 0;
    if (hasRecipients) {
      for (final String recipientIdentifier : recipientIdentifiers) {
        invitationService.invitationSent(
            issuingPlayerId,
            recipientIdentifier,
            InvitationSource.FACEBOOK,
            new DateTime(),
            currentGame,
            screenSource);
      }

      LOG.debug(
          "Invitations sent via Facebook (issuer id = "
              + issuingPlayerId
              + ", recipient identifiers = ["
              + StringUtils.join(recipientIdentifiers, ", ")
              + "])");
    } else {
      LOG.warn("Invitation sent with 0 recipients (issuer id is " + issuingPlayerId + ").");
    }
  }
Example #29
0
 private ActionForward doEndDateConfirmation(
     ActionMapping mapping,
     ActionForm form,
     HttpServletRequest request,
     HttpServletResponse response,
     String questionId,
     String yesMethodName)
     throws Exception {
   List<ErrorMessage> errors =
       GlobalVariables.getMessageMap()
           .getErrorMessagesForProperty(ProposalHierarchyKeyConstants.FIELD_CHILD_NUMBER);
   List<String> proposalNumbers = new ArrayList<String>();
   for (ErrorMessage error : errors) {
     if (error
         .getErrorKey()
         .equals(ProposalHierarchyKeyConstants.QUESTION_EXTEND_PROJECT_DATE_CONFIRM)) {
       proposalNumbers.add(error.getMessageParameters()[0]);
     }
   }
   String proposalNumberList = StringUtils.join(proposalNumbers, ',');
   StrutsConfirmation question =
       buildParameterizedConfirmationQuestion(
           mapping,
           form,
           request,
           response,
           questionId,
           ProposalHierarchyKeyConstants.QUESTION_EXTEND_PROJECT_DATE_CONFIRM,
           proposalNumberList);
   GlobalVariables.getMessageMap().getErrorMessages().clear();
   GlobalVariables.getMessageMap().getWarningMessages().clear();
   GlobalVariables.getMessageMap().getInfoMessages().clear();
   return confirm(question, yesMethodName, "hierarchyActionCanceled");
 }
  /**
   * Check if is form is valid.
   *
   * @return true if form is valid, else false.
   */
  private boolean isFormValid() {
    List<String> errors = new ArrayList<>();

    if (StringUtils.isNotBlank(etTitle.getText())) {
      etTitle.setHintTextColor(color(android.R.color.white));
    } else {
      etTitle.setHintTextColor(color(android.R.color.holo_red_light));
      errors.add(getString(R.string.invalid_form_event));
    }

    if (this.isDateValid()) {
      ViewHelper.setTextViewColor(
          color(android.R.color.white),
          btDatePickerStart,
          btDatePickerEnd,
          btTimePickerStart,
          btTimePickerEnd);
    } else {
      ViewHelper.setTextViewColor(
          color(android.R.color.holo_red_light),
          btDatePickerStart,
          btDatePickerEnd,
          btTimePickerStart,
          btTimePickerEnd);
      errors.add(getString(R.string.invalid_form_date));
    }

    boolean isValid = errors.isEmpty();
    if (!isValid) {
      Toast.makeText(this, StringUtils.join(errors, "\n"), Toast.LENGTH_SHORT).show();
    }
    return isValid;
  }