Example usage for org.apache.commons.lang3 StringUtils repeat

List of usage examples for org.apache.commons.lang3 StringUtils repeat

Introduction

In this page you can find the example usage for org.apache.commons.lang3 StringUtils repeat.

Prototype

public static String repeat(final String str, final String separator, final int repeat) 

Source Link

Document

Repeat a String repeat times to form a new String, with a String separator injected each time.

Usage

From source file:kenh.expl.functions.Repeat.java

public String process(String str, String separator, int repeat) {
    return StringUtils.repeat(str, separator, repeat);
}

From source file:com.thoughtworks.go.server.database.DbDeployMigration.java

private void upgradeWithDbDeploy() {
    LOG.info("Upgrading database at {}. This might take a while depending on the size of the database.",
            dataSource);/*ww w  . jav  a2s.  c o  m*/

    List<String> messages = Arrays.asList(StringUtils.repeat("*", "", 72),
            "WARNING: Shutting down your server at this point will lead to a database corruption. Please wait until the database upgrade completes.",
            StringUtils.repeat("*", "", 72));
    for (String message : messages) {
        System.err.println(message);
        LOG.info(message);
    }

    File upgradePath = env.getDBDeltasPath();
    bombUnless(upgradePath.exists(),
            "Database upgrade scripts do not exist in directory " + upgradePath.getAbsolutePath());
    InMemory dbDeploy = new InMemory(dataSource, new HsqlDbmsSyntax(), upgradePath, "DDL");
    try {
        String migrationSql = dbDeploy.migrationSql();
        new JdbcTemplate(dataSource).execute(migrationSql);

        System.err.println("Database upgrade completed successfully.");
        LOG.info("Database upgrade completed.");

    } catch (Exception e) {
        String message = "Unable to create database upgrade script for database " + dataSource.getUrl()
                + ". The problem was: " + e.getMessage();
        if (e.getCause() != null) {
            message += ". The cause was: " + e.getCause().getMessage();
        }
        LOG.error(message, e);
        System.err.println(message);
        e.printStackTrace(System.err);
        throw bomb(message, e);
    }
}

From source file:com.streamsets.pipeline.lib.jdbc.MultiRowInsertMap.java

public PreparedStatement getInsertFor(SortedMap<String, String> columns, int numRecords) throws SQLException {
    // The INSERT query we're going to perform (parameterized).
    if (cache.containsKey(columns)) {
        return cache.get(columns);
    } else {/*from   w w  w  . j a v  a  2  s  .  c  om*/
        String valuePlaceholder = String.format("(%s)", Joiner.on(", ").join(columns.values()));
        String valuePlaceholders = StringUtils.repeat(valuePlaceholder, ", ", numRecords);
        String query = String.format("INSERT INTO %s (%s) VALUES %s", tableName,
                // keySet and values will both return the same ordering, due to using a SortedMap
                Joiner.on(", ").join(columns.keySet()), valuePlaceholders);
        PreparedStatement statement = connection.prepareStatement(query);
        cache.put(columns, statement);
        return statement;
    }
}

From source file:hu.bme.mit.sette.tools.spf.SpfGenerator.java

private void createGeneratedFiles() throws IOException {
    // generate main() for each snippet
    for (SnippetContainer container : getSnippetProject().getModel().getContainers()) {
        // skip container with higher java version than supported
        if (container.getRequiredJavaVersion().compareTo(getTool().getSupportedJavaVersion()) > 0) {
            // TODO error handling
            System.err.println("Skipping container: " + container.getJavaClass().getName()
                    + " (required Java version: " + container.getRequiredJavaVersion() + ")");
            continue;
        }/*from ww  w  . j  av a2s  .  c  o m*/

        for (Snippet snippet : container.getSnippets().values()) {
            Method method = snippet.getMethod();
            Class<?> javaClass = method.getDeclaringClass();
            Class<?>[] parameterTypes = method.getParameterTypes();

            // create .jpf descriptor
            JPFConfig jpfConfig = new JPFConfig();
            jpfConfig.target = javaClass.getName() + '_' + method.getName();

            String symbMethod = javaClass.getName() + '.' + method.getName() + '('
                    + StringUtils.repeat("sym", "#", parameterTypes.length) + ')';

            jpfConfig.symbolicMethod.add(symbMethod);

            jpfConfig.classpath = "build/";

            for (File libraryFile : getSnippetProject().getFiles().getLibraryFiles()) {
                jpfConfig.classpath += ',' + getSnippetProjectSettings().getLibraryDirectoryPath() + '/'
                        + libraryFile.getName();
            }

            jpfConfig.listener = JPFConfig.SYMBOLIC_LISTENER;
            jpfConfig.symbolicDebug = JPFConfig.ON;

            jpfConfig.searchMultipleErrors = JPFConfig.TRUE;
            jpfConfig.decisionProcedure = JPFConfig.DP_CORAL;

            // generate main()
            JavaClassWithMain main = new JavaClassWithMain();
            main.setPackageName(javaClass.getPackage().getName());
            main.setClassName(javaClass.getSimpleName() + '_' + method.getName());

            main.imports().add(javaClass.getName());

            String[] parameterLiterals = new String[parameterTypes.length];

            int i = 0;
            for (Class<?> parameterType : parameterTypes) {
                parameterLiterals[i] = SpfGenerator.getParameterLiteral(parameterType);
                i++;
            }

            main.codeLines().add(javaClass.getSimpleName() + '.' + method.getName() + '('
                    + StringUtils.join(parameterLiterals, ", ") + ");");

            // save files
            String relativePath = JavaFileUtils.packageNameToFilename(main.getFullClassName());
            String relativePathJPF = relativePath + '.' + JPFConfig.JPF_CONFIG_EXTENSION;
            String relativePathMain = relativePath + '.' + JavaFileUtils.JAVA_SOURCE_EXTENSION;

            File targetJPFFile = new File(getRunnerProjectSettings().getGeneratedDirectory(), relativePathJPF);
            FileUtils.forceMkdir(targetJPFFile.getParentFile());
            FileUtils.write(targetJPFFile, jpfConfig.generate().toString());

            File targetMainFile = new File(getRunnerProjectSettings().getGeneratedDirectory(),
                    relativePathMain);
            FileUtils.forceMkdir(targetMainFile.getParentFile());
            FileUtils.write(targetMainFile, main.generateJavaCode().toString());
        }
    }
}

From source file:it.attocchi.db.JdbcConnector.java

@Deprecated
public boolean executeStored(boolean keepConnOpen, String storedName, Object... params) throws Exception {
    boolean res = false;

    try {// w ww . j a v a  2 s  . co  m

        String paramSign = StringUtils.repeat("?", ",", params.length);
        String query = "EXEC " + storedName + " " + paramSign;

        // res = getConnection().prepareStatement(aQuery).executeQuery();
        PreparedStatement ps = getConnection().prepareStatement(query);
        // ps.setEscapeProcessing(true);

        for (int i = 0; i < params.length; i++) {
            Object param = params[i];
            if (param instanceof String)
                ps.setString(i + 1, params[i].toString());
            else if (param instanceof Integer) {
                ps.setInt(i + 1, Integer.parseInt(params[i].toString()));
            } else if (param instanceof Double) {
                ps.setDouble(i + 1, Double.parseDouble(params[i].toString()));
            } else if (param instanceof Float) {
                ps.setDouble(i + 1, Float.parseFloat(params[i].toString()));
            }
        }

        logger.debug(ps);
        res = ps.execute();

    } finally {
        if (!keepConnOpen)
            close();
    }

    return res;
}

From source file:com.streamsets.pipeline.lib.jdbc.JdbcMultiRowRecordWriter.java

private static PreparedStatement generatePreparedStatement(SortedMap<String, String> columns, int numRecords,
        Object tableName, Connection connection) throws SQLException {
    String valuePlaceholder = String.format("(%s)", Joiner.on(", ").join(columns.values()));
    String valuePlaceholders = StringUtils.repeat(valuePlaceholder, ", ", numRecords);
    String query = String.format("INSERT INTO %s (%s) VALUES %s", tableName,
            // keySet and values will both return the same ordering, due to using a SortedMap
            Joiner.on(", ").join(columns.keySet()), valuePlaceholders);

    return connection.prepareStatement(query);
}

From source file:com.nortal.petit.orm.statement.StatementBuilder.java

public String getInsert() {
    StringBuilder expression = new StringBuilder("INSERT INTO ").append(table).append(" (");
    Joiner.on(", ").appendTo(expression, Iterables.transform(setBy, propertyNameMapper));
    expression.append(") VALUES (").append(StringUtils.repeat("?", ", ", setBy.size())).append(")");
    return expression.toString();
}

From source file:io.lavagna.service.SearchService.java

private SearchResults find(List<SearchFilter> unmergedSearchFilter, Integer projectId, Integer boardId,
        UserWithPermission currentUser, boolean paginate, int page) {

    // if a user don't have access to the specified project id we skip the
    // whole search
    final boolean userHasNotProjectAccess = projectId != null
            && !currentUser.getBasePermissions().containsKey(Permission.READ)
            && !currentUser.projectsWithPermission(Permission.READ)
                    .contains(projectService.findById(projectId).getShortName());
    final boolean userHasNoReadAccess = projectId == null
            && !currentUser.getBasePermissions().containsKey(Permission.READ)
            && currentUser.projectsWithPermission(Permission.READ).isEmpty();

    final boolean noProjectIdForBoardId = projectId == null && boardId != null;

    final boolean boardIsntInProject = projectId != null && boardId != null
            && boardRepository.findBoardById(boardId).getProjectId() != projectId;

    if (userHasNotProjectAccess || userHasNoReadAccess || noProjectIdForBoardId || boardIsntInProject) {
        return new SearchResults(Collections.<CardFullWithCounts>emptyList(), 0, page,
                paginate ? CARDS_PER_PAGE : Integer.MAX_VALUE, paginate);
    }//from  ww w . jav  a 2  s.co  m

    List<SearchFilter> searchFilters = mergeFreeTextFilters(unmergedSearchFilter);
    //

    List<Object> params = new ArrayList<>();
    int filteringConditionsCount = 0;
    //

    List<String> usersOrCardToSearch = new ArrayList<>();
    // fetch all possible user->id, card->id in the value types with string
    // (thus unknown use)
    for (SearchFilter searchFilter : searchFilters) {
        if (searchFilter.getValue() != null && searchFilter.getValue().getType() == ValueType.STRING) {
            usersOrCardToSearch.add(searchFilter.getValue().getValue().toString());
        }
    }
    //

    Map<String, Integer> cardNameToId = cardRepository.findCardsIds(usersOrCardToSearch);
    Map<String, Integer> userNameToId = userRepository.findUsersId(usersOrCardToSearch);

    SearchContext searchContext = new SearchContext(currentUser, userNameToId, cardNameToId);

    //

    StringBuilder baseQuery = new StringBuilder(queries.findFirstFrom()).append("SELECT CARD_ID FROM ( ");

    // add filter conditions
    for (int i = 0; i < searchFilters.size(); i++) {
        SearchFilter searchFilter = searchFilters.get(i);

        String filterConditionQuery = searchFilter.getType().toBaseQuery(searchFilter, queries, params,
                searchContext);

        baseQuery.append("( ").append(filterConditionQuery).append(" ) ");
        if (i < searchFilters.size() - 1) {
            baseQuery.append(" UNION ALL ");
        }
        filteringConditionsCount++;
    }
    //

    /* AS CARD_IDS -> table alias for mysql */
    baseQuery.append(" ) AS CARD_IDS GROUP BY CARD_ID HAVING COUNT(CARD_ID) = ?").append(queries.findSecond());
    params.add(filteringConditionsCount);

    if (boardId != null) {
        baseQuery.append(queries.findThirdWhere()).append(queries.findFourthInBoardId());
        params.add(boardId);
    } else if (projectId != null) {
        baseQuery.append(queries.findThirdWhere()).append(queries.findInFifthProjectId());
        params.add(projectId);
    } else if (!currentUser.getBasePermissions().containsKey(Permission.READ)) {

        Set<Integer> projectsWithPermission = currentUser.projectsIdWithPermission(Permission.READ);
        baseQuery.append(queries.findThirdWhere()).append(queries.findSixthRestrictedReadAccess()).append(" (")
                .append(StringUtils.repeat("?", " , ", projectsWithPermission.size())).append(" ) ");

        params.addAll(projectsWithPermission);
    }

    String findCardsQuery = queries.findFirstSelect() + baseQuery.toString() + queries.findSeventhOrderBy();

    if (paginate) {
        params.add(CARDS_PER_PAGE + 1);// limit
        params.add(page * CARDS_PER_PAGE);// offset
        findCardsQuery += queries.findEighthLimit();
    }

    List<Integer> sr = jdbc.getJdbcOperations().queryForList(findCardsQuery, params.toArray(), Integer.class);

    //

    int count = sr.size();
    if (paginate && page == 0 && sr.size() == (CARDS_PER_PAGE + 1) || page > 0) {
        String countCardsQuery = queries.findFirstSelectCount() + baseQuery.toString();
        count = jdbc.getJdbcOperations().queryForObject(countCardsQuery,
                params.subList(0, params.size() - 2).toArray(), Integer.class);
    }

    //
    return new SearchResults(cardFullWithCounts(sr), count, page, paginate ? CARDS_PER_PAGE : Integer.MAX_VALUE,
            paginate);
}

From source file:com.logsniffer.event.h2.H2SnifferPersistence.java

@Override
public Map<Log, IncrementData> getIncrementDataByLog(final Sniffer sniffer, final LogSource<?> source)
        throws IOException {
    final List<Log> logs = source.getLogs();
    if (logs.size() > 0) {
        final HashMap<Log, IncrementData> incs = new HashMap<Log, IncrementData>();
        final HashMap<String, Log> logMapping = new HashMap<String, Log>();
        for (final Log log : logs) {
            logMapping.put(log.getPath(), log);
        }/*from   w  w w  .j ava  2s. c o m*/
        jdbcTemplate.query(
                "SELECT NEXT_POINTER, DATA, LOG FROM SNIFFERS_SCANNER_IDATA WHERE SNIFFER=? AND SOURCE=? AND LOG IN ("
                        + StringUtils.repeat("?", ",", logs.size()) + ") ORDER BY LOG",
                ArrayUtils.addAll(new Object[] { sniffer.getId(), source.getId() },
                        logMapping.keySet().toArray(new Object[logMapping.size()])),
                new RowCallbackHandler() {
                    @Override
                    public void processRow(final ResultSet rs) throws SQLException {
                        final String logPath = rs.getString("LOG");
                        final Log log = logMapping.get(logPath);
                        if (log != null) {
                            final IncrementData data = new IncrementData();
                            data.setData(JSONObject.fromObject(rs.getString("DATA")));
                            try {
                                final String jsonStr = rs.getString("NEXT_POINTER");
                                if (StringUtils.isNotBlank(jsonStr)) {
                                    data.setNextOffset(source.getLogAccess(log).getFromJSON(jsonStr));
                                }
                                incs.put(log, data);
                            } catch (final IOException e) {
                                throw new SQLException("Failed to construct pointer in log: " + log, e);
                            }
                        } else {
                            logger.error("Didn't find log '{}' for selected incrementdata", logPath);
                        }
                    }
                });
        // Create empty entries for not yet persisted
        for (final Log log : logMapping.values()) {
            if (!incs.containsKey(log)) {
                incs.put(log, new IncrementData());
            }
        }
        return incs;
    } else {
        return Collections.emptyMap();
    }
}

From source file:annis.administration.DefaultAdministrationDao.java

private List<String> listIndexesOnTables(List<String> tables) {
    String sql = "" + "SELECT indexname " + "FROM pg_indexes " + "WHERE tablename IN ("
            + StringUtils.repeat("?", ",", tables.size()) + ") " + "AND lower(indexname) NOT IN "
            + " (SELECT lower(conname) FROM pg_constraint WHERE contype in ('p', 'u'))";

    return jdbcTemplate.query(sql, tables.toArray(), stringRowMapper());
}