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

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

Introduction

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

Prototype

@Override
    @Nullable
    public <T> T queryForObject(String sql, Class<T> requiredType) throws DataAccessException 

Source Link

Usage

From source file:dao.AdvSearchDAO.java

public static ObjectNode searchFlows(JsonNode searchOpt, int page, int size) {
    ObjectNode resultNode = Json.newObject();
    int count = 0;
    List<String> appcodeInList = new ArrayList<String>();
    List<String> appcodeNotInList = new ArrayList<String>();
    List<String> flowInList = new ArrayList<String>();
    List<String> flowNotInList = new ArrayList<String>();
    List<String> jobInList = new ArrayList<String>();
    List<String> jobNotInList = new ArrayList<String>();

    if (searchOpt != null && (searchOpt.isContainerNode())) {
        if (searchOpt.has("appcode")) {
            JsonNode appcodeNode = searchOpt.get("appcode");
            if (appcodeNode != null && appcodeNode.isContainerNode()) {
                if (appcodeNode.has("in")) {
                    JsonNode appcodeInNode = appcodeNode.get("in");
                    if (appcodeInNode != null) {
                        String appcodeInStr = appcodeInNode.asText();
                        if (StringUtils.isNotBlank(appcodeInStr)) {
                            String[] appcodeInArray = appcodeInStr.split(",");
                            if (appcodeInArray != null) {
                                for (String value : appcodeInArray) {
                                    if (StringUtils.isNotBlank(value)) {
                                        appcodeInList.add(value.trim());
                                    }/*from   ww  w .j a v  a2s .c  om*/
                                }
                            }
                        }
                    }
                }
                if (appcodeNode.has("not")) {
                    JsonNode appcodeNotInNode = appcodeNode.get("not");
                    if (appcodeNotInNode != null) {
                        String appcodeNotInStr = appcodeNotInNode.asText();
                        if (StringUtils.isNotBlank(appcodeNotInStr)) {
                            String[] appcodeNotInArray = appcodeNotInStr.split(",");
                            if (appcodeNotInArray != null) {
                                for (String value : appcodeNotInArray) {
                                    if (StringUtils.isNotBlank(value)) {
                                        appcodeNotInList.add(value.trim());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        if (searchOpt.has("flow")) {
            JsonNode flowNode = searchOpt.get("flow");
            if (flowNode != null && flowNode.isContainerNode()) {
                if (flowNode.has("in")) {
                    JsonNode flowInNode = flowNode.get("in");
                    if (flowInNode != null) {
                        String flowInStr = flowInNode.asText();
                        if (StringUtils.isNotBlank(flowInStr)) {
                            String[] flowInArray = flowInStr.split(",");
                            if (flowInArray != null) {
                                for (String value : flowInArray) {
                                    if (StringUtils.isNotBlank(value)) {
                                        flowInList.add(value.trim());
                                    }
                                }
                            }
                        }
                    }
                }
                if (flowNode.has("not")) {
                    JsonNode flowNotInNode = flowNode.get("not");
                    if (flowNotInNode != null) {
                        String flowNotInStr = flowNotInNode.asText();
                        if (StringUtils.isNotBlank(flowNotInStr)) {
                            String[] flowNotInArray = flowNotInStr.split(",");
                            if (flowNotInArray != null) {
                                for (String value : flowNotInArray) {
                                    if (StringUtils.isNotBlank(value)) {
                                        flowNotInList.add(value.trim());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        if (searchOpt.has("job")) {
            JsonNode jobNode = searchOpt.get("job");
            if (jobNode != null && jobNode.isContainerNode()) {
                if (jobNode.has("in")) {
                    JsonNode jobInNode = jobNode.get("in");
                    if (jobInNode != null) {
                        String jobInStr = jobInNode.asText();
                        if (StringUtils.isNotBlank(jobInStr)) {
                            String[] jobInArray = jobInStr.split(",");
                            if (jobInArray != null) {
                                for (String value : jobInArray) {
                                    if (StringUtils.isNotBlank(value)) {
                                        jobInList.add(value.trim());
                                    }
                                }
                            }
                        }
                    }
                }
                if (jobNode.has("not")) {
                    JsonNode jobNotInNode = jobNode.get("not");
                    if (jobNotInNode != null) {
                        String jobNotInStr = jobNotInNode.asText();
                        if (StringUtils.isNotBlank(jobNotInStr)) {
                            String[] jobNotInArray = jobNotInStr.split(",");
                            if (jobNotInArray != null) {
                                for (String value : jobNotInArray) {
                                    if (StringUtils.isNotBlank(value)) {
                                        jobNotInList.add(value.trim());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        boolean needAndKeyword = false;

        final List<FlowJob> pagedFlows = new ArrayList<FlowJob>();
        final JdbcTemplate jdbcTemplate = getJdbcTemplate();
        javax.sql.DataSource ds = jdbcTemplate.getDataSource();
        DataSourceTransactionManager tm = new DataSourceTransactionManager(ds);

        TransactionTemplate txTemplate = new TransactionTemplate(tm);

        ObjectNode result;
        String query = null;
        if (jobInList.size() > 0 || jobNotInList.size() > 0) {
            query = ADV_SEARCH_JOB;
        } else {
            query = ADV_SEARCH_FLOW;
        }

        if (appcodeInList.size() > 0 || appcodeNotInList.size() > 0) {
            boolean appcodeNeedAndKeyword = false;
            if (appcodeInList.size() > 0) {
                int indexForAppcodeInList = 0;
                for (String appcode : appcodeInList) {
                    if (indexForAppcodeInList == 0) {
                        query += "WHERE a.app_code in ('" + appcode + "'";
                    } else {
                        query += ", '" + appcode + "'";
                    }
                    indexForAppcodeInList++;
                }
                query += ") ";
                appcodeNeedAndKeyword = true;
            }
            if (appcodeNotInList.size() > 0) {
                if (appcodeNeedAndKeyword) {
                    query += " AND ";
                } else {
                    query += " WHERE ";
                }
                int indexForAppcodeNotInList = 0;
                for (String appcode : appcodeNotInList) {
                    if (indexForAppcodeNotInList == 0) {
                        query += "a.app_code not in ('" + appcode + "'";
                    } else {
                        query += ", '" + appcode + "'";
                    }
                    indexForAppcodeNotInList++;
                }
                query += ") ";
            }
            needAndKeyword = true;
        }

        if (flowInList.size() > 0 || flowNotInList.size() > 0) {
            if (needAndKeyword) {
                query += " AND ";
            } else {
                query += " WHERE ";
            }
            boolean flowNeedAndKeyword = false;
            if (flowInList.size() > 0) {
                query += "( ";
                int indexForFlowInList = 0;
                for (String flow : flowInList) {
                    if (indexForFlowInList == 0) {
                        query += "f.flow_name LIKE '%" + flow + "%'";
                    } else {
                        query += " or f.flow_name LIKE '%" + flow + "%'";
                    }
                    indexForFlowInList++;
                }
                query += ") ";
                flowNeedAndKeyword = true;
            }
            if (flowNotInList.size() > 0) {
                if (flowNeedAndKeyword) {
                    query += " AND ";
                }
                query += "( ";
                int indexForFlowNotInList = 0;
                for (String flow : flowNotInList) {
                    if (indexForFlowNotInList == 0) {
                        query += "f.flow_name NOT LIKE '%" + flow + "%'";
                    } else {
                        query += " and f.flow_name NOT LIKE '%" + flow + "%'";
                    }
                    indexForFlowNotInList++;
                }
                query += ") ";
            }
            needAndKeyword = true;
        }

        if (jobInList.size() > 0 || jobNotInList.size() > 0) {
            if (needAndKeyword) {
                query += " AND ";
            } else {
                query += " WHERE ";
            }
            query += "( ";
            boolean jobNeedAndKeyword = false;
            if (jobInList.size() > 0) {
                query += "( ";
                int indexForJobInList = 0;
                for (String job : jobInList) {
                    if (indexForJobInList == 0) {
                        query += "j.job_name LIKE '%" + job + "%'";
                    } else {
                        query += " or j.job_name LIKE '%" + job + "%'";
                    }
                    indexForJobInList++;
                }
                query += ") ";
                jobNeedAndKeyword = true;
            }
            if (jobNotInList.size() > 0) {
                if (jobNeedAndKeyword) {
                    query += " AND ";
                }
                query += "( ";
                int indexForJobNotInList = 0;
                for (String job : jobNotInList) {
                    if (indexForJobNotInList == 0) {
                        query += "j.job_name NOT LIKE '%" + job + "%'";
                    } else {
                        query += " and j.job_name NOT LIKE '%" + job + "%'";
                    }
                    indexForJobNotInList++;
                }
                query += ") ";
            }
            query += " ) ";
        }

        query += " LIMIT " + (page - 1) * size + ", " + size;
        final String queryString = query;

        result = txTemplate.execute(new TransactionCallback<ObjectNode>() {
            public ObjectNode doInTransaction(TransactionStatus status) {
                List<Map<String, Object>> rows = null;
                rows = jdbcTemplate.queryForList(queryString);

                for (Map row : rows) {

                    FlowJob flow = new FlowJob();
                    flow.appCode = (String) row.get("app_code");
                    flow.flowName = (String) row.get("flow_name");
                    flow.flowPath = (String) row.get("flow_path");
                    flow.flowGroup = (String) row.get("flow_group");
                    flow.jobName = (String) row.get("job_name");
                    flow.jobPath = (String) row.get("job_path");
                    flow.flowId = (Long) row.get("flow_id");
                    if (StringUtils.isNotBlank(flow.jobName)) {
                        flow.displayName = flow.jobName;
                    } else {
                        flow.displayName = flow.flowName;
                    }
                    flow.link = "#/flows/name/" + flow.appCode + "/" + Long.toString(flow.flowId)
                            + "/page/1?urn=" + flow.flowGroup;
                    flow.path = flow.appCode + "/" + flow.flowPath;
                    pagedFlows.add(flow);
                }
                long count = 0;
                try {
                    count = jdbcTemplate.queryForObject("SELECT FOUND_ROWS()", Long.class);
                } catch (EmptyResultDataAccessException e) {
                    Logger.error("Exception = " + e.getMessage());
                }

                ObjectNode resultNode = Json.newObject();
                resultNode.put("count", count);
                resultNode.put("page", page);
                resultNode.put("isFlowJob", true);
                resultNode.put("itemsPerPage", size);
                resultNode.put("totalPages", (int) Math.ceil(count / ((double) size)));
                resultNode.set("data", Json.toJson(pagedFlows));

                return resultNode;
            }
        });
        return result;
    }
    resultNode.put("count", 0);
    resultNode.put("page", page);
    resultNode.put("itemsPerPage", size);
    resultNode.put("totalPages", 0);
    resultNode.set("data", Json.toJson(""));
    return resultNode;
}

From source file:dao.AdvSearchDAO.java

public static ObjectNode searchMetrics(JsonNode searchOpt, int page, int size) {
    ObjectNode resultNode = Json.newObject();
    int count = 0;
    List<String> dashboardInList = new ArrayList<String>();
    List<String> dashboardNotInList = new ArrayList<String>();
    List<String> groupInList = new ArrayList<String>();
    List<String> groupNotInList = new ArrayList<String>();
    List<String> categoryInList = new ArrayList<String>();
    List<String> categoryNotInList = new ArrayList<String>();
    List<String> metricInList = new ArrayList<String>();
    List<String> metricNotInList = new ArrayList<String>();

    if (searchOpt != null && (searchOpt.isContainerNode())) {
        if (searchOpt.has("dashboard")) {
            JsonNode dashboardNode = searchOpt.get("dashboard");
            if (dashboardNode != null && dashboardNode.isContainerNode()) {
                if (dashboardNode.has("in")) {
                    JsonNode dashboardInNode = dashboardNode.get("in");
                    if (dashboardInNode != null) {
                        String dashboardInStr = dashboardInNode.asText();
                        if (StringUtils.isNotBlank(dashboardInStr)) {
                            String[] dashboardInArray = dashboardInStr.split(",");
                            if (dashboardInArray != null) {
                                for (String value : dashboardInArray) {
                                    if (StringUtils.isNotBlank(value)) {
                                        dashboardInList.add(value.trim());
                                    }/*w  w w . j a  v  a  2 s.  c o m*/
                                }
                            }
                        }
                    }
                }
                if (dashboardNode.has("not")) {
                    JsonNode dashboardNotInNode = dashboardNode.get("not");
                    if (dashboardNotInNode != null) {
                        String dashboardNotInStr = dashboardNotInNode.asText();
                        if (StringUtils.isNotBlank(dashboardNotInStr)) {
                            String[] dashboardNotInArray = dashboardNotInStr.split(",");
                            if (dashboardNotInArray != null) {
                                for (String value : dashboardNotInArray) {
                                    if (StringUtils.isNotBlank(value)) {
                                        dashboardNotInList.add(value.trim());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        if (searchOpt.has("group")) {
            JsonNode groupNode = searchOpt.get("group");
            if (groupNode != null && groupNode.isContainerNode()) {
                if (groupNode.has("in")) {
                    JsonNode groupInNode = groupNode.get("in");
                    if (groupInNode != null) {
                        String groupInStr = groupInNode.asText();
                        if (StringUtils.isNotBlank(groupInStr)) {
                            String[] groupInArray = groupInStr.split(",");
                            if (groupInArray != null) {
                                for (String value : groupInArray) {
                                    if (StringUtils.isNotBlank(value)) {
                                        groupInList.add(value.trim());
                                    }
                                }
                            }
                        }
                    }
                }
                if (groupNode.has("not")) {
                    JsonNode groupNotInNode = groupNode.get("not");
                    if (groupNotInNode != null) {
                        String groupNotInStr = groupNotInNode.asText();
                        if (StringUtils.isNotBlank(groupNotInStr)) {
                            String[] groupNotInArray = groupNotInStr.split(",");
                            if (groupNotInArray != null) {
                                for (String value : groupNotInArray) {
                                    if (StringUtils.isNotBlank(value)) {
                                        groupNotInList.add(value.trim());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        if (searchOpt.has("cat")) {
            JsonNode categoryNode = searchOpt.get("cat");
            if (categoryNode != null && categoryNode.isContainerNode()) {
                if (categoryNode.has("in")) {
                    JsonNode categoryInNode = categoryNode.get("in");
                    if (categoryInNode != null) {
                        String categoryInStr = categoryInNode.asText();
                        if (StringUtils.isNotBlank(categoryInStr)) {
                            String[] categoryInArray = categoryInStr.split(",");
                            if (categoryInArray != null) {
                                for (String value : categoryInArray) {
                                    if (StringUtils.isNotBlank(value)) {
                                        categoryInList.add(value.trim());
                                    }
                                }
                            }
                        }
                    }
                }
                if (categoryNode.has("not")) {
                    JsonNode categoryNotInNode = categoryNode.get("not");
                    if (categoryNotInNode != null) {
                        String categoryNotInStr = categoryNotInNode.asText();
                        if (StringUtils.isNotBlank(categoryNotInStr)) {
                            String[] categoryNotInArray = categoryNotInStr.split(",");
                            if (categoryNotInArray != null) {
                                for (String value : categoryNotInArray) {
                                    if (StringUtils.isNotBlank(value)) {
                                        categoryNotInList.add(value.trim());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        if (searchOpt.has("metric")) {
            JsonNode metricNode = searchOpt.get("metric");
            if (metricNode != null && metricNode.isContainerNode()) {
                if (metricNode.has("in")) {
                    JsonNode metricInNode = metricNode.get("in");
                    if (metricInNode != null) {
                        String metricInStr = metricInNode.asText();
                        if (StringUtils.isNotBlank(metricInStr)) {
                            String[] metricInArray = metricInStr.split(",");
                            if (metricInArray != null) {
                                for (String value : metricInArray) {
                                    if (StringUtils.isNotBlank(value)) {
                                        metricInList.add(value.trim());
                                    }
                                }
                            }
                        }
                    }
                }
                if (metricNode.has("not")) {
                    JsonNode metricNotInNode = metricNode.get("not");
                    if (metricNotInNode != null) {
                        String metricNotInStr = metricNotInNode.asText();
                        if (StringUtils.isNotBlank(metricNotInStr)) {
                            String[] metricNotInArray = metricNotInStr.split(",");
                            if (metricNotInArray != null) {
                                for (String value : metricNotInArray) {
                                    if (StringUtils.isNotBlank(value)) {
                                        metricNotInList.add(value.trim());
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        boolean needAndKeyword = false;

        final List<Metric> pagedMetrics = new ArrayList<Metric>();
        final JdbcTemplate jdbcTemplate = getJdbcTemplate();
        javax.sql.DataSource ds = jdbcTemplate.getDataSource();
        DataSourceTransactionManager tm = new DataSourceTransactionManager(ds);

        TransactionTemplate txTemplate = new TransactionTemplate(tm);

        ObjectNode result;
        String query = ADV_SEARCH_METRIC;

        if (dashboardInList.size() > 0 || dashboardNotInList.size() > 0) {
            boolean dashboardNeedAndKeyword = false;
            if (dashboardInList.size() > 0) {
                int indexForDashboardInList = 0;
                for (String dashboard : dashboardInList) {
                    if (indexForDashboardInList == 0) {
                        query += "WHERE dashboard_name in ('" + dashboard + "'";
                    } else {
                        query += ", '" + dashboard + "'";
                    }
                    indexForDashboardInList++;
                }
                query += ") ";
                dashboardNeedAndKeyword = true;
            }
            if (dashboardNotInList.size() > 0) {
                if (dashboardNeedAndKeyword) {
                    query += " AND ";
                } else {
                    query += " WHERE ";
                }
                int indexForDashboardNotInList = 0;
                for (String dashboard : dashboardNotInList) {
                    if (indexForDashboardNotInList == 0) {
                        query += "dashboard_name not in ('" + dashboard + "'";
                    } else {
                        query += ", '" + dashboard + "'";
                    }
                    indexForDashboardNotInList++;
                }
                query += ") ";
            }
            needAndKeyword = true;
        }

        if (groupInList.size() > 0 || groupNotInList.size() > 0) {
            if (needAndKeyword) {
                query += " AND ";
            } else {
                query += " WHERE ";
            }
            query += "( ";
            boolean groupNeedAndKeyword = false;
            if (groupInList.size() > 0) {
                query += "( ";
                int indexForGroupInList = 0;
                for (String group : groupInList) {
                    if (indexForGroupInList == 0) {
                        query += "metric_group LIKE '%" + group + "%'";
                    } else {
                        query += " or metric_group LIKE '%" + group + "%'";
                    }
                    indexForGroupInList++;
                }
                query += ") ";
                groupNeedAndKeyword = true;
            }
            if (groupNotInList.size() > 0) {
                if (groupNeedAndKeyword) {
                    query += " AND ";
                }
                query += "( ";
                int indexForGroupNotInList = 0;
                for (String group : groupNotInList) {
                    if (indexForGroupNotInList == 0) {
                        query += "metric_group NOT LIKE '%" + group + "%'";
                    } else {
                        query += " and metric_group NOT LIKE '%" + group + "%'";
                    }
                    indexForGroupNotInList++;
                }
                query += ") ";
            }
            query += ") ";
            needAndKeyword = true;
        }

        if (categoryInList.size() > 0 || categoryNotInList.size() > 0) {
            if (needAndKeyword) {
                query += " AND ";
            } else {
                query += " WHERE ";
            }
            query += "( ";
            boolean categoryNeedAndKeyword = false;
            if (categoryInList.size() > 0) {
                int indexForCategoryInList = 0;
                query += "( ";
                for (String category : categoryInList) {
                    if (indexForCategoryInList == 0) {
                        query += "metric_category LIKE '%" + category + "%'";
                    } else {
                        query += " or metric_category LIKE '%" + category + "%'";
                    }
                    indexForCategoryInList++;
                }
                query += ") ";
                categoryNeedAndKeyword = true;
            }
            if (categoryNotInList.size() > 0) {
                if (categoryNeedAndKeyword) {
                    query += " AND ";
                }
                query += "( ";
                int indexForCategoryNotInList = 0;
                for (String category : categoryNotInList) {
                    if (indexForCategoryNotInList == 0) {
                        query += "metric_category NOT LIKE '%" + category + "%'";
                    } else {
                        query += " and metric_category NOT LIKE '%" + category + "%'";
                    }
                    indexForCategoryNotInList++;
                }
                query += ") ";
            }
            query += ") ";
            needAndKeyword = true;
        }

        if (metricInList.size() > 0 || metricNotInList.size() > 0) {
            if (needAndKeyword) {
                query += " AND ";
            } else {
                query += " WHERE ";
            }
            query += "( ";
            boolean metricNeedAndKeyword = false;
            if (metricInList.size() > 0) {
                int indexForMetricInList = 0;
                query += " ( ";
                for (String metric : metricInList) {
                    if (indexForMetricInList == 0) {
                        query += "metric_name LIKE '%" + metric + "%'";
                    } else {
                        query += " or metric_name LIKE '%" + metric + "%'";
                    }
                    indexForMetricInList++;
                }
                query += ") ";
                metricNeedAndKeyword = true;
            }
            if (metricNotInList.size() > 0) {
                if (metricNeedAndKeyword) {
                    query += " AND ";
                }
                query += "( ";
                int indexForMetricNotInList = 0;
                for (String metric : metricNotInList) {
                    if (indexForMetricNotInList == 0) {
                        query += "metric_name NOT LIKE '%" + metric + "%'";
                    } else {
                        query += " and metric_name NOT LIKE '%" + metric + "%'";
                    }
                    indexForMetricNotInList++;
                }
                query += ") ";
            }
            query += " )";
        }

        query += " LIMIT " + (page - 1) * size + ", " + size;
        final String queryString = query;

        result = txTemplate.execute(new TransactionCallback<ObjectNode>() {
            public ObjectNode doInTransaction(TransactionStatus status) {
                List<Metric> pagedMetrics = jdbcTemplate.query(queryString, new MetricRowMapper());

                long count = 0;
                try {
                    count = jdbcTemplate.queryForObject("SELECT FOUND_ROWS()", Long.class);
                } catch (EmptyResultDataAccessException e) {
                    Logger.error("Exception = " + e.getMessage());
                }

                ObjectNode resultNode = Json.newObject();
                resultNode.put("count", count);
                resultNode.put("page", page);
                resultNode.put("isMetrics", true);
                resultNode.put("itemsPerPage", size);
                resultNode.put("totalPages", (int) Math.ceil(count / ((double) size)));
                resultNode.set("data", Json.toJson(pagedMetrics));

                return resultNode;
            }
        });
        return result;
    }
    resultNode.put("count", 0);
    resultNode.put("page", page);
    resultNode.put("itemsPerPage", size);
    resultNode.put("totalPages", 0);
    resultNode.set("data", Json.toJson(""));
    return resultNode;
}

From source file:org.agnitas.dao.impl.MailingDaoImpl.java

public Map<String, String> loadAction(int mailingID, int companyID) {
    Map<String, String> actions = new HashMap<String, String>();
    JdbcTemplate jdbc = new JdbcTemplate((DataSource) applicationContext.getBean("dataSource"));

    String stmt = "select action_id, shortname, full_url from rdir_url_tbl where mailing_id = ? and company_id = ?";
    try {/*  www.j  av  a 2s  .  co  m*/
        List list = jdbc.queryForList(stmt, new Object[] { new Integer(mailingID), new Integer(companyID) });
        for (int i = 0; i < list.size(); i++) {
            Map map = (Map) list.get(i);
            int action_id = ((Number) map.get("action_id")).intValue();
            if (action_id > 0) {
                stmt = "select shortname from rdir_action_tbl where company_id = " + companyID
                        + " and action_id = " + action_id;
                String action_short = (String) jdbc.queryForObject(stmt, stmt.getClass());

                String name = "";
                if (map.get("shortname") != null) {
                    name = (String) map.get("shortname");
                } else {
                    name = (String) map.get("full_url");
                }
                actions.put(action_short, name);
            }
        }
    } catch (Exception e) {
        AgnUtils.sendExceptionMail("sql:" + stmt + ", " + mailingID + ", " + companyID, e);
        System.err.println(e.getMessage());
        System.err.println(AgnUtils.getStackTrace(e));
    }
    return actions;
}

From source file:org.apache.syncope.core.persistence.dao.impl.ContentLoader.java

@Transactional
public void load() {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);

    boolean existingData;
    try {//from   ww  w.j  a v  a  2 s  . c  o m
        existingData = jdbcTemplate.queryForObject("SELECT COUNT(0) FROM " + SyncopeConf.class.getSimpleName(),
                Integer.class) > 0;
    } catch (DataAccessException e) {
        LOG.error("Could not access to table " + SyncopeConf.class.getSimpleName(), e);
        existingData = true;
    }

    if (existingData) {
        LOG.info("Data found in the database, leaving untouched");
    } else {
        LOG.info("Empty database found, loading default content");

        loadDefaultContent();
        createIndexes();
        createViews();
    }
}

From source file:org.apache.syncope.core.persistence.jpa.content.XMLContentLoader.java

@Override
public void load() {
    for (Map.Entry<String, DataSource> entry : domainsHolder.getDomains().entrySet()) {
        // create EntityManager so OpenJPA will build the SQL schema
        EntityManagerFactoryUtils/*from   w ww .ja v a 2s . c om*/
                .findEntityManagerFactory(ApplicationContextProvider.getBeanFactory(), entry.getKey())
                .createEntityManager();

        JdbcTemplate jdbcTemplate = new JdbcTemplate(entry.getValue());
        boolean existingData;
        try {
            existingData = jdbcTemplate.queryForObject("SELECT COUNT(0) FROM " + JPAConf.TABLE,
                    Integer.class) > 0;
        } catch (DataAccessException e) {
            LOG.error("[{}] Could not access to table " + JPAConf.TABLE, entry.getKey(), e);
            existingData = true;
        }

        if (existingData) {
            LOG.info("[{}] Data found in the database, leaving untouched", entry.getKey());
        } else {
            LOG.info("[{}] Empty database found, loading default content", entry.getKey());

            try {
                ResourceWithFallbackLoader contentXML = ApplicationContextProvider.getBeanFactory()
                        .getBean(entry.getKey() + "ContentXML", ResourceWithFallbackLoader.class);
                loadDefaultContent(entry.getKey(), contentXML, entry.getValue());
            } catch (Exception e) {
                LOG.error("[{}] While loading default content", entry.getKey(), e);
            }
            try {
                createIndexes(entry.getKey(), entry.getValue());
                createViews(entry.getKey(), entry.getValue());
            } catch (IOException e) {
                LOG.error("[{}] While creating indexes and views", entry.getKey(), e);
            }
        }
    }
}

From source file:org.apereo.portal.jdbc.DatabaseMetaDataImpl.java

/**
 * Tests if the uPortal tables exist that are needed for this test. 
 *///  w  w w .  j ava 2  s. c om
private void testDatabaseInitialized(final JdbcTemplate jdbcTemplate) {
    try {
        jdbcTemplate.queryForObject("SELECT COUNT(USER_ID) FROM UP_USER", Integer.class);
        this.portalTablesExist = true;
    } catch (BadSqlGrammarException bsge) {
        LOG.warn("The uPortal database is not initialized, the database tests will not be performed.");
    }
}

From source file:org.cloudfoundry.identity.uaa.mock.providers.IdentityProviderEndpointsMockMvcTests.java

protected void addScopeToIdentityClient(String scope) throws Exception {
    JdbcTemplate template = getWebApplicationContext().getBean(JdbcTemplate.class);
    String scopes = template.queryForObject(
            "select scope from oauth_client_details where identity_zone_id='uaa' and client_id='identity'",
            String.class);
    boolean update = false;
    if (!StringUtils.hasText(scopes)) {
        scopes = scope;//from ww w  .  java 2 s  . com
        update = true;
    } else if (!scopes.contains(scope)) {
        scopes = scopes + "," + scope;
        update = true;
    }
    if (update) {
        assertEquals(1, template.update(
                "UPDATE oauth_client_details SET scope=? WHERE identity_zone_id='uaa' AND client_id='identity'",
                scopes));
    }
}

From source file:org.cloudfoundry.identity.uaa.mock.zones.IdentityProviderEndpointsMockMvcTests.java

protected void addScopeToIdentityClient(String scope) {
    JdbcTemplate template = getWebApplicationContext().getBean(JdbcTemplate.class);
    String scopes = template.queryForObject(
            "select scope from oauth_client_details where identity_zone_id='uaa' and client_id='identity'",
            String.class);
    boolean update = false;
    if (!StringUtils.hasText(scopes)) {
        scopes = scope;/*from ww w  . j a va 2s.c  om*/
        update = true;
    } else if (!scopes.contains(scope)) {
        scopes = scopes + "," + scope;
        update = true;
    }
    if (update) {
        assertEquals(1, template.update(
                "UPDATE oauth_client_details SET scope=? WHERE identity_zone_id='uaa' AND client_id='identity'",
                scopes));
    }
}

From source file:org.jumpmind.metl.core.runtime.component.Assert.java

@Override
public void flowCompleted(boolean cancelled) {
    StringBuilder assertFailed = new StringBuilder();
    if (expectedControlMessageCount != controlMessageCount) {
        assertFailed.append(String.format("\nExpected %d control messages but received %s.",
                expectedControlMessageCount, controlMessageCount));
    }//ww  w  .j a  v  a2  s  .  c om

    if (expectedEmptyPayloadMessageCount != emptyPayloadMessageCount) {
        assertFailed.append(String.format("\nExpected %d empty messages but received %s.",
                expectedEmptyPayloadMessageCount, emptyPayloadMessageCount));
    }

    if (expectedEntityMessageCount != entityMessageCount) {
        assertFailed.append(String.format("\nExpected %d entity messages but received %s.",
                expectedEntityMessageCount, entityMessageCount));
    }

    if (expectedTextMessageCount != textMessageCount) {
        assertFailed.append(String.format("\nExpected %d text messages but received %s.",
                expectedTextMessageCount, textMessageCount));
    }

    if (expectedBinaryMessageCount != binaryMessageCount) {
        assertFailed.append(String.format("\nExpected %d binary messages but received %s.",
                expectedBinaryMessageCount, binaryMessageCount));
    }

    if (expectedEntityCountPerMessage.intValue() != -1
            && expectedEntityCountPerMessage.intValue() != entityCountPerMessage) {
        assertFailed.append(String.format("\nExpected %d entities per message but received %s.",
                expectedEntityCountPerMessage.intValue(), entityCountPerMessage));
    }

    if (isNotBlank(sql)) {
        IResourceRuntime targetResource = context.getDeployedResources().get(dataSourceId);
        DataSource ds = targetResource.reference();
        JdbcTemplate template = new JdbcTemplate(ds);
        int sqlCount = template.queryForObject(sql, Integer.class);
        if (expectedSqlCount != sqlCount) {
            assertFailed.append(
                    String.format("\nExpected %d sql count but received %s.", expectedSqlCount, sqlCount));
        }
    }

    if (assertFailed.length() > 0) {
        throw new AssertException(assertFailed.toString());
    }
}

From source file:org.lexevs.dao.database.ibatis.codingscheme.IbatisCodingSchemeDaoTest.java

@Test
@Transactional/* w  w  w  .  j a  v  a 2  s  .co m*/
public void testInsertSupportedHierarchy() throws SQLException {
    JdbcTemplate template = new JdbcTemplate(this.getDataSource());

    template.execute(
            "Insert into codingScheme (codingSchemeGuid, codingSchemeName, codingSchemeUri, representsVersion) "
                    + "values ('1', 'csname', 'csuri', 'csversion')");

    SupportedHierarchy hier = new SupportedHierarchy();
    hier.setLocalId("test");
    hier.setAssociationNames(new String[] { "test", "test2", "test3" });

    ibatisCodingSchemeDao.insertURIMap("1", hier);

    template.queryForObject("Select * from cssupportedattrib", new RowMapper() {

        public Object mapRow(ResultSet rs, int arg1) throws SQLException {

            assertEquals("test,test2,test3", rs.getString(7));

            return true;
        }
    });

}