Example usage for org.springframework.jdbc.core JdbcTemplate setMaxRows

List of usage examples for org.springframework.jdbc.core JdbcTemplate setMaxRows

Introduction

In this page you can find the example usage for org.springframework.jdbc.core JdbcTemplate setMaxRows.

Prototype

public void setMaxRows(int maxRows) 

Source Link

Document

Set the maximum number of rows for this JdbcTemplate.

Usage

From source file:org.openmrs.module.tribe.TribeActivator.java

private void extractTribeColumn() {
    // check whether tribe module is installed in an old OpenMRS
    // throw exception if it is
    boolean isOldOpenMRS = true;
    try {/*w w w . j  a v  a  2  s.  c  o m*/
        Class cls = OpenmrsClassLoader.getInstance().loadClass("org.openmrs.Tribe");
        if (cls.isAnnotationPresent(Deprecated.class))
            isOldOpenMRS = false;
    } catch (ClassNotFoundException e) {
        // OpenMRS version ok
        isOldOpenMRS = false;
    }
    if (isOldOpenMRS) {
        throw new ModuleException(
                "Tribe module cannot be used with this OpenMRS version. Please upgrade OpenMRS.");
    }

    // now convert patient tribes to tribe attributes
    AdministrationService as = Context.getAdministrationService();

    // check whether patient table has tribe column
    log.info("Ignore the error message if occurs: "
            + "Error while running sql: SELECT distinct tribe from patient where 1 = 0");
    log.info("The above message indicates that you are running a new implementation "
            + "which does not have a tribe column in the patient table.");
    boolean isTribeColumnExists = true;

    DataSource ds = new SingleConnectionDataSource(Context.getRuntimeProperties().getProperty("connection.url"),
            Context.getRuntimeProperties().getProperty("connection.username"),
            Context.getRuntimeProperties().getProperty("connection.password"), true);
    JdbcTemplate jdbc = new JdbcTemplate(ds);

    jdbc.setMaxRows(1);
    try {

        jdbc.queryForList("SELECT distinct tribe from patient where 1 = 0");

    } catch (Exception e) {
        isTribeColumnExists = false;

    }

    // now convert patient tribes to tribe attributes

    if (isTribeColumnExists) {
        // create tribe attributes
        try {
            log.info("Transforming tribe details");
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_SQL_LEVEL_ACCESS);
            as.executeSQL(
                    "INSERT INTO person_attribute (person_id, value, person_attribute_type_id, creator, date_created, uuid)"
                            + " SELECT patient_id, tribe,"
                            + " (SELECT person_attribute_type_id FROM person_attribute_type WHERE name = 'Tribe')"
                            + " , 1, now(), UUID() FROM patient WHERE tribe IS NOT NULL;",
                    false);
        } finally {
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_SQL_LEVEL_ACCESS);
        }

        // drop tribe column in patient, this will make these scripts not run again
        log.info("Dropping old tribe column");
        try {
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_SQL_LEVEL_ACCESS);
            as.executeSQL("ALTER TABLE patient DROP FOREIGN KEY belongs_to_tribe;", false);
        } catch (Exception e) {
            log.warn("Unable to drop foreign key patient.belongs_to_tribe", e);
        } finally {
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_SQL_LEVEL_ACCESS);
        }

        try {
            Context.addProxyPrivilege(OpenmrsConstants.PRIV_SQL_LEVEL_ACCESS);
            as.executeSQL("ALTER TABLE patient DROP COLUMN tribe;", false);
        } catch (Exception e) {
            log.warn("Unable to drop column patient.tribe", e);
        } finally {
            Context.removeProxyPrivilege(OpenmrsConstants.PRIV_SQL_LEVEL_ACCESS);
        }

        log.info("Tribe data conversion complete");
    }

    // add View Tribes privilege to Authenticated role if not exists
    try {
        Context.addProxyPrivilege(OpenmrsConstants.PRIV_SQL_LEVEL_ACCESS);
        UserService us = Context.getUserService();
        Role authenticatedRole = us.getRole(OpenmrsConstants.AUTHENTICATED_ROLE);
        if (!authenticatedRole.hasPrivilege(TribeConstants.PRIV_VIEW_TRIBES)) {
            as.executeSQL("INSERT INTO role_privilege (role, privilege) VALUES ('"
                    + OpenmrsConstants.AUTHENTICATED_ROLE + "', '" + TribeConstants.PRIV_VIEW_TRIBES + "')",
                    false);
        }
    } finally {
        Context.removeProxyPrivilege(OpenmrsConstants.PRIV_SQL_LEVEL_ACCESS);
    }
}

From source file:org.apache.syncope.core.logic.report.AuditReportlet.java

private void doExtractConf(final ContentHandler handler) throws SAXException {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource);
    jdbcTemplate.setMaxRows(conf.getSize());
    List<Map<String, Object>> rows = jdbcTemplate
            .queryForList("SELECT * FROM SYNCOPEAUDIT ORDER BY EVENT_DATE DESC");

    handler.startElement("", "", "events", null);
    AttributesImpl atts = new AttributesImpl();
    for (Map<String, Object> row : rows) {
        AuditEntry auditEntry = POJOHelper.deserialize(row.get("MESSAGE").toString(), AuditEntry.class);

        atts.clear();//from   w w w . j  av a2 s .  c o  m
        if (StringUtils.isNotBlank(auditEntry.getWho())) {
            atts.addAttribute("", "", "who", ReportXMLConst.XSD_STRING, auditEntry.getWho());
        }
        handler.startElement("", "", "event", atts);

        atts.clear();
        if (StringUtils.isNotBlank(auditEntry.getLogger().getCategory())) {
            atts.addAttribute("", "", "category", ReportXMLConst.XSD_STRING,
                    auditEntry.getLogger().getCategory());
        }
        if (StringUtils.isNotBlank(auditEntry.getLogger().getSubcategory())) {
            atts.addAttribute("", "", "subcategory", ReportXMLConst.XSD_STRING,
                    auditEntry.getLogger().getSubcategory());
        }
        if (StringUtils.isNotBlank(auditEntry.getLogger().getEvent())) {
            atts.addAttribute("", "", "event", ReportXMLConst.XSD_STRING, auditEntry.getLogger().getEvent());
        }
        if (auditEntry.getLogger().getResult() != null) {
            atts.addAttribute("", "", "result", ReportXMLConst.XSD_STRING,
                    auditEntry.getLogger().getResult().name());
        }
        handler.startElement("", "", "logger", atts);
        handler.endElement("", "", "logger");

        if (auditEntry.getBefore() != null) {
            char[] before = ToStringBuilder
                    .reflectionToString(auditEntry.getBefore(), ToStringStyle.MULTI_LINE_STYLE).toCharArray();
            handler.startElement("", "", "before", null);
            handler.characters(before, 0, before.length);
            handler.endElement("", "", "before");
        }

        if (auditEntry.getInput() != null) {
            handler.startElement("", "", "inputs", null);
            for (Object inputObj : auditEntry.getInput()) {
                char[] input = ToStringBuilder.reflectionToString(inputObj, ToStringStyle.MULTI_LINE_STYLE)
                        .toCharArray();
                handler.startElement("", "", "input", null);
                handler.characters(input, 0, input.length);
                handler.endElement("", "", "input");
            }
            handler.endElement("", "", "inputs");
        }

        if (auditEntry.getOutput() != null) {
            char[] output = ToStringBuilder
                    .reflectionToString(auditEntry.getOutput(), ToStringStyle.MULTI_LINE_STYLE).toCharArray();
            handler.startElement("", "", "output", null);
            handler.characters(output, 0, output.length);
            handler.endElement("", "", "output");
        }

        handler.startElement("", "", "throwable", null);
        char[] throwable = row.get("THROWABLE").toString().toCharArray();
        handler.characters(throwable, 0, throwable.length);
        handler.endElement("", "", "throwable");

        handler.endElement("", "", "event");
    }
    handler.endElement("", "", "events");
}

From source file:org.apache.syncope.core.provisioning.java.job.report.AuditReportlet.java

private void doExtractConf(final ContentHandler handler) throws SAXException {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(datasource);
    jdbcTemplate.setMaxRows(conf.getSize());
    List<Map<String, Object>> rows = jdbcTemplate
            .queryForList("SELECT * FROM SYNCOPEAUDIT ORDER BY EVENT_DATE DESC");

    handler.startElement("", "", "events", null);
    AttributesImpl atts = new AttributesImpl();
    for (Map<String, Object> row : rows) {
        AuditEntry auditEntry = POJOHelper.deserialize(row.get("MESSAGE").toString(), AuditEntry.class);

        atts.clear();//w ww .ja  v  a2s .  c  o  m
        if (StringUtils.isNotBlank(auditEntry.getWho())) {
            atts.addAttribute("", "", "who", ReportXMLConst.XSD_STRING, auditEntry.getWho());
        }
        handler.startElement("", "", "event", atts);

        atts.clear();
        if (StringUtils.isNotBlank(auditEntry.getLogger().getCategory())) {
            atts.addAttribute("", "", "category", ReportXMLConst.XSD_STRING,
                    auditEntry.getLogger().getCategory());
        }
        if (StringUtils.isNotBlank(auditEntry.getLogger().getSubcategory())) {
            atts.addAttribute("", "", "subcategory", ReportXMLConst.XSD_STRING,
                    auditEntry.getLogger().getSubcategory());
        }
        if (StringUtils.isNotBlank(auditEntry.getLogger().getEvent())) {
            atts.addAttribute("", "", "event", ReportXMLConst.XSD_STRING, auditEntry.getLogger().getEvent());
        }
        if (auditEntry.getLogger().getResult() != null) {
            atts.addAttribute("", "", "result", ReportXMLConst.XSD_STRING,
                    auditEntry.getLogger().getResult().name());
        }
        handler.startElement("", "", "logger", atts);
        handler.endElement("", "", "logger");

        if (auditEntry.getBefore() != null) {
            char[] before = ToStringBuilder.reflectionToString(auditEntry.getBefore(), ToStringStyle.JSON_STYLE)
                    .toCharArray();
            handler.startElement("", "", "before", null);
            handler.characters(before, 0, before.length);
            handler.endElement("", "", "before");
        }

        if (auditEntry.getInput() != null) {
            handler.startElement("", "", "inputs", null);
            for (Object inputObj : auditEntry.getInput()) {
                char[] input = ToStringBuilder.reflectionToString(inputObj, ToStringStyle.JSON_STYLE)
                        .toCharArray();
                handler.startElement("", "", "input", null);
                handler.characters(input, 0, input.length);
                handler.endElement("", "", "input");
            }
            handler.endElement("", "", "inputs");
        }

        if (auditEntry.getOutput() != null) {
            char[] output = ToStringBuilder.reflectionToString(auditEntry.getOutput(), ToStringStyle.JSON_STYLE)
                    .toCharArray();
            handler.startElement("", "", "output", null);
            handler.characters(output, 0, output.length);
            handler.endElement("", "", "output");
        }

        handler.startElement("", "", "throwable", null);
        char[] throwable = row.get("THROWABLE").toString().toCharArray();
        handler.characters(throwable, 0, throwable.length);
        handler.endElement("", "", "throwable");

        handler.endElement("", "", "event");
    }
    handler.endElement("", "", "events");
}

From source file:org.openscore.engine.queue.repositories.ExecutionQueueRepositoryImpl.java

private <T> List<T> doSelect(String sql, int maxRows, RowMapper<T> rowMapper, Object... params) {
    JdbcTemplate template = jdbcTemplateMap.get(maxRows);
    if (template == null)
        try {//from  w ww .  ja  v  a 2s  .  c om
            lock.lock();
            template = new JdbcTemplate(dataSource);
            template.setFetchSize(maxRows);
            template.setMaxRows(maxRows);
            jdbcTemplateMap.put(maxRows, template);
        } finally {
            lock.unlock();
        }
    return doSelect0(template, sql, rowMapper, params);
}

From source file:org.springframework.jdbc.core.JdbcTemplateTests.java

private void doTestStrings(JdbcTemplateCallback jdbcTemplateCallback, boolean usePreparedStatement,
        Integer fetchSize, Integer maxRows, Integer queryTimeout, Object argument) throws Exception {

    String sql = "SELECT FORENAME FROM CUSTMR";
    String[] results = { "rod", "gary", " portia" };

    class StringHandler implements RowCallbackHandler {
        private List list = new LinkedList();

        public void processRow(ResultSet rs) throws SQLException {
            list.add(rs.getString(1));//from  w  w  w.  j  ava2 s .  c  o  m
        }

        public String[] getStrings() {
            return (String[]) list.toArray(new String[list.size()]);
        }
    }

    MockControl ctrlResultSet = MockControl.createControl(ResultSet.class);
    ResultSet mockResultSet = (ResultSet) ctrlResultSet.getMock();
    mockResultSet.next();
    ctrlResultSet.setReturnValue(true);
    mockResultSet.getString(1);
    ctrlResultSet.setReturnValue(results[0]);
    mockResultSet.next();
    ctrlResultSet.setReturnValue(true);
    mockResultSet.getString(1);
    ctrlResultSet.setReturnValue(results[1]);
    mockResultSet.next();
    ctrlResultSet.setReturnValue(true);
    mockResultSet.getString(1);
    ctrlResultSet.setReturnValue(results[2]);
    mockResultSet.next();
    ctrlResultSet.setReturnValue(false);
    mockResultSet.close();
    ctrlResultSet.setVoidCallable();

    MockControl ctrlStatement = MockControl.createControl(PreparedStatement.class);
    PreparedStatement mockStatement = (PreparedStatement) ctrlStatement.getMock();
    if (fetchSize != null) {
        mockStatement.setFetchSize(fetchSize.intValue());
    }
    if (maxRows != null) {
        mockStatement.setMaxRows(maxRows.intValue());
    }
    if (queryTimeout != null) {
        mockStatement.setQueryTimeout(queryTimeout.intValue());
    }
    if (argument != null) {
        mockStatement.setObject(1, argument);
    }
    if (usePreparedStatement) {
        mockStatement.executeQuery();
    } else {
        mockStatement.executeQuery(sql);
    }
    ctrlStatement.setReturnValue(mockResultSet);
    if (debugEnabled) {
        mockStatement.getWarnings();
        ctrlStatement.setReturnValue(null);
    }
    mockStatement.close();
    ctrlStatement.setVoidCallable();

    if (usePreparedStatement) {
        mockConnection.prepareStatement(sql);
    } else {
        mockConnection.createStatement();
    }
    ctrlConnection.setReturnValue(mockStatement);

    ctrlResultSet.replay();
    ctrlStatement.replay();
    replay();

    StringHandler sh = new StringHandler();
    JdbcTemplate template = new JdbcTemplate();
    template.setDataSource(mockDataSource);
    if (fetchSize != null) {
        template.setFetchSize(fetchSize.intValue());
    }
    if (maxRows != null) {
        template.setMaxRows(maxRows.intValue());
    }
    if (queryTimeout != null) {
        template.setQueryTimeout(queryTimeout.intValue());
    }
    jdbcTemplateCallback.doInJdbcTemplate(template, sql, sh);

    // Match
    String[] forenames = sh.getStrings();
    assertTrue("same length", forenames.length == results.length);
    for (int i = 0; i < forenames.length; i++) {
        assertTrue("Row " + i + " matches", forenames[i].equals(results[i]));
    }

    ctrlResultSet.verify();
    ctrlStatement.verify();
}