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

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

Introduction

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

Prototype

public static String repeat(String str, int repeat) 

Source Link

Document

Repeat a String repeat times to form a new String.

Usage

From source file:consultor.CSVLoader.java

/**
 * Parse CSV file using OpenCSV library and load in 
 * given database table. //  w  w  w  . ja va  2  s. co  m
 * @param csvFile Input CSV file
 * @param tableName Database table name to import data
 * @param truncateBeforeLoad Truncate the table before inserting 
 *          new records.
 * @throws Exception
 */
public void loadCSV(String csvFile, String tableName, boolean truncateBeforeLoad) 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) {
        e.printStackTrace();
        throw new Exception("Error occured while executing file. " + e.getMessage());
    }

    String[] headerRow = csvReader.readNext();

    if (null == headerRow) {
        throw new FileNotFoundException(
                "No columns defined in given CSV file." + "Please check the CSV file format.");
    }

    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(headerRow, ","));
    query = query.replaceFirst(VALUES_REGEX, questionmarks);

    System.out.println("Query: " + query);

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

        if (truncateBeforeLoad) {
            //delete data from table before loading csv
            con.createStatement().execute("DELETE FROM " + tableName);
        }

        final int batchSize = 1000;
        int count = 0;
        Date date = null;
        while ((nextLine = csvReader.readNext()) != null) {

            if (null != nextLine) {
                int index = 1;
                for (String string : nextLine) {
                    date = DateUtil.convertToDate(string);
                    if (null != date) {
                        ps.setDate(index++, new java.sql.Date(date.getTime()));
                    } else {
                        ps.setString(index++, string);
                    }
                }
                ps.addBatch();
            }
            if (++count % batchSize == 0) {
                ps.executeBatch();
            }
        }
        ps.executeBatch(); // insert remaining records
        con.commit();
    } catch (Exception e) {
        con.rollback();
        e.printStackTrace();
        throw new Exception("Error occured while loading data from file to database." + e.getMessage());
    } finally {
        if (null != ps)
            ps.close();
        if (null != con)
            con.close();

        csvReader.close();
    }
}

From source file:com.cloudbees.plugins.credentials.cli.ListCredentialsContextResolversCommand.java

/**
 * {@inheritDoc}/*w  ww .  j  a v  a  2s. c  o  m*/
 */
@Override
protected int run() throws Exception {
    Map<String, CredentialsSelectHelper.ContextResolver> resolversByName = CredentialsSelectHelper
            .getResolversByName();
    int maxNameLen = 0, maxDisplayLen = 0;
    for (Map.Entry<String, CredentialsSelectHelper.ContextResolver> entry : resolversByName.entrySet()) {
        maxNameLen = Math.max(maxNameLen, entry.getKey().length());
        maxDisplayLen = Math.max(maxDisplayLen,
                CredentialsSelectHelper.ContextResolver.displayName(entry.getValue()).length());
    }
    stdout.println(StringUtils.rightPad("Name", maxNameLen) + " Resolves");
    stdout.println(StringUtils.repeat("=", maxNameLen) + " " + StringUtils.repeat("=", maxDisplayLen));
    for (Map.Entry<String, CredentialsSelectHelper.ContextResolver> entry : resolversByName.entrySet()) {
        stdout.println(StringUtils.rightPad(entry.getKey(), maxNameLen) + " "
                + CredentialsSelectHelper.ContextResolver.displayName(entry.getValue()));
    }
    return 0;
}

From source file:com.adobe.acs.commons.util.InfoWriterTest.java

@Test
public void testTitle_Message() throws Exception {
    String expected = LS + StringUtils.repeat("-", 80) + LS + "The Title".concat(LS)
            + StringUtils.repeat("=", 80);

    iw.title("The Title");

    assertEquals(expected.concat(LS), iw.toString());
}

From source file:com.codenjoy.dojo.tetris.model.TetrisGlassTest.java

@Before
public void setUp() throws Exception {
    glass = new TetrisGlass(WIDTH, HEIGHT, glassEventListener);
    point = new TetrisFigure();
    glassWidthFigure = new TetrisFigure(0, 0, StringUtils.repeat("#", WIDTH));
    line9Width = new TetrisFigure(0, 0, StringUtils.repeat("#", WIDTH - 1));
}

From source file:herddb.jdbc.ScanHugeTableTest.java

@Test
public void testBatch() throws Exception {
    try (Server server = new Server(new ServerConfiguration(folder.newFolder().toPath()))) {
        server.getManager().setMaxDataUsedMemory(750 * 1024 * 1024);
        server.start();//www.java  2 s  .  c  om
        server.waitForStandaloneBoot();
        try (HDBClient client = new HDBClient(new ClientConfiguration(folder.newFolder().toPath()));) {
            client.setClientSideMetadataProvider(new StaticClientSideMetadataProvider(server));
            try (BasicHerdDBDataSource dataSource = new BasicHerdDBDataSource(client);
                    Connection con = dataSource.getConnection();
                    Statement s = con.createStatement();
                    PreparedStatement ps = con
                            .prepareStatement("INSERT INTO mytable (n1, name) values(?,?)");) {
                s.execute("CREATE TABLE mytable (n1 int primary key, name string)");

                String bigPrefix = StringUtils.repeat("Test", 300);
                // int size = 1_000_000;
                int size = 100_000;
                {
                    long _start = System.currentTimeMillis();
                    con.setAutoCommit(false);
                    for (int i = 0; i < size; i++) {
                        ps.setInt(1, i);
                        ps.setString(2, bigPrefix + i);
                        ps.addBatch();
                        if (i % 60000 == 0) {
                            ps.executeBatch();
                            con.commit();
                            long _stop = System.currentTimeMillis();
                            System.out.println("written " + i + " records_ " + (_stop - _start) + " ms");
                        }
                    }
                    ps.executeBatch();
                    con.commit();
                    long _stop = System.currentTimeMillis();
                    System.out.println("insert: " + (_stop - _start) + " ms");
                }

                server.getManager().checkpoint();

                con.setAutoCommit(true);
                {
                    long _start = System.currentTimeMillis();
                    try (ResultSet rs = s.executeQuery("SELECT COUNT(*) from mytable")) {
                        assertTrue(rs.next());
                        long res = rs.getLong(1);
                        assertEquals(size, res);
                    }
                    long _stop = System.currentTimeMillis();
                    System.out.println("count: " + (_stop - _start) + " ms");
                }
                {
                    long _start = System.currentTimeMillis();
                    try (ResultSet rs = s.executeQuery("SELECT * from mytable")) {
                        int i = 0;
                        while (rs.next()) {
                            if (i % 100000 == 0) {
                                System.out.println("read " + i + " records");
                            }
                            i++;
                        }
                        assertEquals(size, i);
                    }
                    long _stop = System.currentTimeMillis();
                    System.out.println("read: " + (_stop - _start) + " ms");
                }

            }
        }
    }

}

From source file:com.gisgraphy.domain.geoloc.entity.GisFeatureTest.java

@Test
public void testAddAlternateNamesShouldNotAddTooLongAlternateNames() {
    GisFeature gisFeature = GisgraphyTestHelper.createGisFeatureWithAlternateNames("toto", 3);
    List<AlternateName> alternateNames = new ArrayList<AlternateName>();
    AlternateName a1 = new AlternateName();
    a1.setName(StringUtils.repeat("a", GisFeature.MAX_ALTERNATENAME_SIZE + 1));
    AlternateName a2 = new AlternateName();
    a2.setName("bar");
    alternateNames.add(a1);/*ww  w  .j  ava  2 s  . c  om*/
    alternateNames.add(a2);
    gisFeature.addAlternateNames(alternateNames);
    assertEquals("The long alternateName should not be added", 4, gisFeature.getAlternateNames().size());
}

From source file:musite.io.xml.ProteinResidueAnnotationWriter.java

public void write(OutputStream os, Map<String, MultiMap<Integer, Map<String, Object>>> residueAnnotations)
        throws IOException {
    if (os == null || residueAnnotations == null)
        return;/*from w ww  .jav  a 2 s.c  om*/

    String prefix = StringUtils.repeat("\t", getIndent());

    OutputStreamWriter osw = new OutputStreamWriter(os);
    BufferedWriter bufWriter = new BufferedWriter(osw);

    for (Map.Entry<String, MultiMap<Integer, Map<String, Object>>> entry : residueAnnotations.entrySet()) {
        String type = entry.getKey();
        bufWriter.write(prefix + "<" + type + ">\n");
        writeMultiMap(os, bufWriter, entry.getValue(), prefix + "\t");
        bufWriter.write(prefix + "</" + type + ">\n");
    }

    bufWriter.flush();
    osw.flush();
}

From source file:com.genericconf.bbbgateway.domain.Server.java

@Override
public String toString() {
    return "Server [context=" + context + ", domain=" + domain + ", securitySalt="
            + StringUtils.repeat("*", securitySalt.length()) + "]";
}

From source file:com.hp.autonomy.frontend.find.core.view.AbstractViewController.java

private String getBaseUrl(final HttpServletRequest request) {
    final String path = request.getRequestURI().replaceFirst(request.getContextPath(), "");

    final int depth = StringUtils.countMatches(path, "/") - 1;

    final String baseUrl;

    if (depth == 0) {
        baseUrl = ".";
    } else {//w ww  . j  a v a2 s  .  co m
        baseUrl = StringUtils.repeat("../", depth);
    }

    return baseUrl;
}

From source file:com.dianping.lion.api.http.GetConfigServlet.java

protected void checkAccessibility(HttpServletRequest req) {
    String userIP = IPUtils.getUserIP(req);
    String whiteList = systemSettingService.getSetting(ServiceConstants.SETTING_GETCONFIG_WHITELIST);
    if (StringUtils.isBlank(whiteList)) {
        return;//from w  w  w  .  ja  v a  2  s .  com
    }
    if (whiteList.contains(userIP) || whiteList.contains("*.*.*.*")) {
        return;
    }
    String[] ipSegments = StringUtils.split(userIP, '.');
    if (ipSegments.length == 4) {
        for (int i = 3; i >= 1; i--) {
            String left = StringUtils.join(ipSegments, '.', 0, i);
            String pattern = left + StringUtils.repeat(".*", 4 - i);
            if (whiteList.contains(pattern)) {
                return;
            }
        }
    }
    throw new RuntimeBusinessException("You have no privilege.");
}