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 char ch, final int repeat) 

Source Link

Document

<p>Returns padding using the specified delimiter repeated to a given length.</p> <pre> StringUtils.repeat('e', 0) = "" StringUtils.repeat('e', 3) = "eee" StringUtils.repeat('e', -2) = "" </pre> <p>Note: this method doesn't not support padding with <a href="http://www.unicode.org/glossary/#supplementary_character">Unicode Supplementary Characters</a> as they require a pair of char s to be represented.

Usage

From source file:com.baidu.oped.apm.common.buffer.AutomaticBufferTest.java

@Test
public void testPadString_Error() throws Exception {

    Buffer buffer1_1 = new AutomaticBuffer(32);
    try {//w  ww . ja  v a2 s  .c  o m
        buffer1_1.putPadString(StringUtils.repeat('a', 11), 10);
        Assert.fail("error");
    } catch (IndexOutOfBoundsException ignore) {
    }

    Buffer buffer1_2 = new AutomaticBuffer(32);
    try {
        buffer1_2.putPadString(StringUtils.repeat('a', 20), 10);
        Assert.fail("error");
    } catch (Exception ignore) {
    }

    Buffer buffer2 = new AutomaticBuffer(32);
    buffer2.putPadString(StringUtils.repeat('a', 10), 10);

    Buffer buffer3 = new AutomaticBuffer(5);
    buffer3.putPadString(StringUtils.repeat('a', 10), 10);
}

From source file:at.ac.tuwien.big.moea.print.SolutionWriter.java

protected SolutionWriter<S> decreaseIndent(final int spaces) {
    return setIndent(StringUtils.repeat(' ', getIndent().length() - spaces));
}

From source file:com.gmarciani.gmparser.commons.TestDeterministicFunction.java

@Test
public void createCompleteAndRemoveAllY() {
    System.out.println("#createCompleteAndRemoveAllY");
    GSet<Character> domainX = new GSet<Character>();
    domainX.add('a');
    domainX.add('b');
    domainX.add('c');
    GSet<Integer> domainY = new GSet<Integer>();
    domainY.add(1);/*from   w w  w .j  a  v a2  s  . co  m*/
    domainY.add(2);
    domainY.add(3);
    GSet<String> domainZ = new GSet<String>();

    for (Character c : domainX)
        for (Integer n : domainY)
            domainZ.add(StringUtils.repeat(c, n));

    Function<Character, Integer, String> function = new DeterministicFunction<Character, Integer, String>(
            domainX, domainY, domainZ);

    for (Character c : domainX)
        for (Integer n : domainY)
            function.add(c, n, StringUtils.repeat(c, n));

    function.removeAllForY(2);

    System.out.println(function);
    System.out.println(function.toFormattedFunction());
}

From source file:com.opensymphony.xwork2.conversion.impl.StringConverterTest.java

public void testBigDecimalToStringConversionPL() throws Exception {
    // given//from w  ww . jav a2 s  .co m
    StringConverter converter = new StringConverter();
    Map<String, Object> context = new HashMap<>();
    context.put(ActionContext.LOCALE, new Locale("pl", "PL"));

    // when a bit bigger than double
    String aBitBiggerThanDouble = "17976931348623157" + StringUtils.repeat('0', 291) + "1."
            + StringUtils.repeat('0', 324) + "49";
    Object value = converter.convertValue(context, null, null, null, new BigDecimal(aBitBiggerThanDouble),
            null);

    // then does not lose integer and fraction digits
    assertEquals(aBitBiggerThanDouble.substring(0, 309) + "," + aBitBiggerThanDouble.substring(310), value);
}

From source file:com.emr.utilities.CSVLoader.java

/**
* Parse CSV file using OpenCSV library and load in 
* given database table. //from  ww  w .j ava  2  s. c  o  m
* @param csvFile {@link String} Input CSV file
* @param tableName {@link String} Database table name to import data
* @param truncateBeforeLoad {@link boolean} Truncate the table before inserting 
*          new records.
 * @param destinationColumns {@link String[]} Array containing the destination columns
*/
public void loadCSV(String csvFile, String tableName, boolean truncateBeforeLoad, String[] destinationColumns,
        List columnsToBeMapped) throws Exception {
    CSVReader csvReader = null;
    if (null == this.connection) {
        throw new Exception("Not a valid connection.");
    }
    try {

        csvReader = new CSVReader(new FileReader(csvFile), this.seprator);

    } catch (Exception e) {
        String stacktrace = org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(e);
        JOptionPane.showMessageDialog(null, "Error occured while executing file. Error Details: " + stacktrace,
                "File Error", JOptionPane.ERROR_MESSAGE);
        throw new Exception("Error occured while executing file. " + stacktrace);
    }
    String[] headerRow = csvReader.readNext();

    if (null == headerRow) {
        throw new FileNotFoundException(
                "No columns defined in given CSV file." + "Please check the CSV file format.");
    }
    //Get indices of columns to be mapped
    List mapColumnsIndices = new ArrayList();
    for (Object o : columnsToBeMapped) {
        String column = (String) o;
        column = column.substring(column.lastIndexOf(".") + 1, column.length());
        int i;

        for (i = 0; i < headerRow.length; i++) {

            if (headerRow[i].equals(column)) {
                mapColumnsIndices.add(i);
            }
        }
    }

    String questionmarks = StringUtils.repeat("?,", headerRow.length);
    questionmarks = (String) questionmarks.subSequence(0, questionmarks.length() - 1);

    String query = SQL_INSERT.replaceFirst(TABLE_REGEX, tableName);
    query = query.replaceFirst(KEYS_REGEX, StringUtils.join(destinationColumns, ","));
    query = query.replaceFirst(VALUES_REGEX, questionmarks);

    String log_query = query.substring(0, query.indexOf("VALUES("));

    String[] nextLine;
    Connection con = null;
    PreparedStatement ps = null;
    PreparedStatement ps2 = null;
    PreparedStatement reader = null;
    ResultSet rs = null;
    try {
        con = this.connection;
        con.setAutoCommit(false);
        ps = con.prepareStatement(query);

        File file = new File("sqlite/db");
        if (!file.exists()) {
            file.createNewFile();
        }
        db = new SQLiteConnection(file);
        db.open(true);

        //if destination table==person, also add an entry in the table person_identifier
        //get column indices for the person_id and uuid columns
        int person_id_column_index = -1;
        int uuid_column_index = -1;
        int maxLength = 100;
        int firstname_index = -1;
        int middlename_index = -1;
        int lastname_index = -1;
        int clanname_index = -1;
        int othername_index = -1;
        if (tableName.equals("person")) {
            int i;
            ps2 = con.prepareStatement(
                    "insert ignore into person_identifier(person_id,identifier_type_id,identifier) values(?,?,?)");
            for (i = 0; i < headerRow.length; i++) {
                if (headerRow[i].equals("person_id")) {
                    person_id_column_index = i;
                }
                if (headerRow[i].equals("uuid")) {
                    uuid_column_index = i;
                }
                /*if(headerRow[i].equals("first_name")){
                    System.out.println("Found firstname index: " + i);
                    firstname_index=i;
                }
                if(headerRow[i].equals("middle_name")){
                    System.out.println("Found firstname index: " + i);
                    middlename_index=i;
                }
                if(headerRow[i].equals("last_name")){
                    System.out.println("Found firstname index: " + i);
                    lastname_index=i;
                }
                if(headerRow[i].equals("clan_name")){
                    System.out.println("Found firstname index: " + i);
                    clanname_index=i;
                }
                if(headerRow[i].equals("other_name")){
                    System.out.println("Found firstname index: " + i);
                    othername_index=i;
                }*/
            }
        }

        if (truncateBeforeLoad) {
            //delete data from table before loading csv
            try (Statement stmnt = con.createStatement()) {
                stmnt.execute("DELETE FROM " + tableName);
                stmnt.close();
            }
        }
        if (tableName.equals("person")) {
            try (Statement stmt2 = con.createStatement()) {
                stmt2.execute(
                        "ALTER TABLE person CHANGE COLUMN first_name first_name VARCHAR(50) NULL DEFAULT NULL AFTER person_guid,CHANGE COLUMN middle_name middle_name VARCHAR(50) NULL DEFAULT NULL AFTER first_name,CHANGE COLUMN last_name last_name VARCHAR(50) NULL DEFAULT NULL AFTER middle_name;");
                stmt2.close();
            }
        }
        final int batchSize = 1000;
        int count = 0;
        Date date = null;

        while ((nextLine = csvReader.readNext()) != null) {

            if (null != nextLine) {
                int index = 1;
                int person_id = -1;
                String uuid = "";
                int identifier_type_id = 3;
                if (tableName.equals("person")) {
                    reader = con.prepareStatement(
                            "select identifier_type_id from identifier_type where identifier_type_name='UUID'");
                    rs = reader.executeQuery();
                    if (!rs.isBeforeFirst()) {
                        //no uuid row
                        //insert it
                        Integer numero = 0;
                        Statement stmt = con.createStatement();
                        numero = stmt.executeUpdate(
                                "insert into identifier_type(identifier_type_id,identifier_type_name) values(50,'UUID')",
                                Statement.RETURN_GENERATED_KEYS);
                        ResultSet rs2 = stmt.getGeneratedKeys();
                        if (rs2.next()) {
                            identifier_type_id = rs2.getInt(1);
                        }
                        rs2.close();
                        stmt.close();
                    } else {
                        while (rs.next()) {
                            identifier_type_id = rs.getInt("identifier_type_id");
                        }
                    }

                }
                int counter = 1;
                String temp_log = log_query + "VALUES("; //string to be logged

                for (String string : nextLine) {
                    //if current index is in the list of columns to be mapped, we apply that mapping
                    for (Object o : mapColumnsIndices) {
                        int i = (int) o;
                        if (index == (i + 1)) {
                            //apply mapping to this column
                            string = applyDataMapping(string);
                        }
                    }
                    if (tableName.equals("person")) {
                        //get person_id and uuid

                        if (index == (person_id_column_index + 1)) {
                            person_id = Integer.parseInt(string);
                        }

                        if (index == (uuid_column_index + 1)) {
                            uuid = string;
                        }

                    }
                    //check if string is a date
                    if (string.matches("\\d{2}-[a-zA-Z]{3}-\\d{4} \\d{2}:\\d{2}:\\d{2}")
                            || string.matches("\\d{2}-[a-zA-Z]{3}-\\d{4}")) {
                        java.sql.Date dt = formatDate(string);
                        temp_log = temp_log + "'" + dt.toString() + "'";
                        ps.setDate(index++, dt);
                    } else {
                        if ("".equals(string)) {
                            temp_log = temp_log + "''";
                            ps.setNull(index++, Types.NULL);
                        } else {
                            temp_log = temp_log + "'" + string + "'";
                            ps.setString(index++, string);
                        }

                    }
                    if (counter < headerRow.length) {
                        temp_log = temp_log + ",";
                    } else {
                        temp_log = temp_log + ");";
                        System.out.println(temp_log);
                    }
                    counter++;
                }
                if (tableName.equals("person")) {
                    if (!"".equals(uuid) && person_id != -1) {
                        ps2.setInt(1, person_id);
                        ps2.setInt(2, identifier_type_id);
                        ps2.setString(3, uuid);

                        ps2.addBatch();
                    }
                }

                ps.addBatch();
            }
            if (++count % batchSize == 0) {
                ps.executeBatch();
                if (tableName.equals("person")) {
                    ps2.executeBatch();
                }
            }
        }
        ps.executeBatch(); // insert remaining records
        if (tableName.equals("person")) {
            ps2.executeBatch();
        }

        con.commit();
    } catch (Exception e) {
        if (con != null)
            con.rollback();
        if (db != null)
            db.dispose();
        String stacktrace = org.apache.commons.lang3.exception.ExceptionUtils.getStackTrace(e);
        JOptionPane.showMessageDialog(null, "Error occured while executing file. Error Details: " + stacktrace,
                "File Error", JOptionPane.ERROR_MESSAGE);
        throw new Exception("Error occured while executing file. " + stacktrace);
    } finally {
        if (null != reader)
            reader.close();
        if (null != ps)
            ps.close();
        if (null != ps2)
            ps2.close();
        if (null != con)
            con.close();

        csvReader.close();
    }
}

From source file:io.crate.protocols.http.CrateHttpsTransportIntegrationTest.java

@Test
public void testBlobLayer() throws IOException {
    try {//  w w w. ja v  a2 s . c o  m
        execute("create blob table test");
        final String blob = StringUtils.repeat("abcdefghijklmnopqrstuvwxyz", 1024 * 600);
        String blobUrl = upload("test", blob);
        assertThat(blobUrl, not(isEmptyOrNullString()));
        HttpGet httpGet = new HttpGet(blobUrl);
        CloseableHttpResponse response = httpClient.execute(httpGet);
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertThat(response.getEntity().getContentLength(), is((long) blob.length()));
    } finally {
        execute("drop table if exists test");
    }
}

From source file:de.uniwue.info6.webapp.lists.ExGroupTableBean.java

/**
 *
 *
 * @param d/*w  w  w .  j a  va2s . c  o  m*/
 * @return
 */
public static String formatDouble(double d, int places) {
    DecimalFormat f = new DecimalFormat("#0." + StringUtils.repeat("0", places));
    return f.format(d);
}

From source file:de.weltraumschaf.jebnf.ast.visitor.XmlVisitor.java

/**
 * Generates an indentation string depending on the actual indentation level.
 *
 * @return Returns string with white spaces.
 *///from   w w  w  .ja va2  s . c  om
private String indent() {
    return StringUtils.repeat(' ', indentationLevel * DEFAULT_INDENTATION);
}

From source file:com.opensymphony.xwork2.conversion.impl.NumberConverterTest.java

public void testStringToDoubleConversionPL() throws Exception {
    // given//from  w  ww  . j  a  v  a  2 s .c  o  m
    NumberConverter converter = new NumberConverter();
    Map<String, Object> context = new HashMap<>();
    context.put(ActionContext.LOCALE, new Locale("pl", "PL"));

    // when has max fraction digits
    Object value = converter.convertValue(context, null, null, null, "0," + StringUtils.repeat('0', 323) + "49",
            Double.class);

    // then does not lose fraction digits
    assertEquals(Double.MIN_VALUE, value);

    // when has max integer digits
    value = converter.convertValue(context, null, null, null,
            "17976931348623157" + StringUtils.repeat('0', 292) + ",0", Double.class);

    // then does not lose integer digits
    assertEquals(Double.MAX_VALUE, value);
}

From source file:com.nortal.petit.core.util.SqlUtil.java

private static void addRemainderBlock(String columnName, StringBuilder result, int remainderBlockSize,
        String operator, String logicalOp, StringBuilder fullBlocks) {
    StringBuilder remainderBlock = new StringBuilder();
    if (remainderBlockSize > 0) {
        remainderBlock.append(columnName).append(' ').append(operator).append(" (?");
        remainderBlock.append(StringUtils.repeat(",?", remainderBlockSize - 1)).append(')');
    }/* ww w.j av a  2s  .c  om*/

    result.append(" ( ");
    result.append(fullBlocks);
    if (fullBlocks.length() > 0 && remainderBlock.length() > 0) {
        result.append(' ').append(logicalOp).append(' ');
    }
    result.append(remainderBlock);
}