Java tutorial
/* * Copyright (C) 2010 {Apertum}Projects. web: www.apertum.ru email: info@apertum.ru * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ru.apertum.qsystem.reports.formirovators; import java.sql.Connection; import java.sql.Statement; import java.sql.ResultSet; import java.sql.DriverManager; import java.sql.SQLException; import java.text.ParseException; import java.util.Date; import java.util.HashMap; import java.util.Map; import java.util.ArrayList; import org.apache.commons.lang.time.DateUtils; import net.sf.jasperreports.engine.JRDataSource; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JRField; import org.apache.http.HttpRequest; import ru.apertum.qsystem.common.Uses; import ru.apertum.qsystem.common.QLog; import ru.apertum.qsystem.common.exceptions.ReportException; import ru.apertum.qsystem.reports.common.Response; /** * ?? ? * * @author Igor Savin */ public class ResponsesDateReport extends AFormirovator { private class ResponsesDateDataSource implements JRDataSource { public ResponsesDateDataSource(Connection conn, Date sd, Date ed) { index = -1; ArrayList<ArrayList<Object>> data_tmp = new ArrayList<>(); // fill array try { String ssd = (new java.text.SimpleDateFormat("yyyy-MM-dd")).format(sd); ssd = "'" + ssd + "'"; String sed = (new java.text.SimpleDateFormat("yyyy-MM-dd")).format(ed); sed = "'" + sed + "'"; Statement stmt = conn.createStatement(); String query = "SELECT " + "r.id, " + "r.`name` AS responses_name, " //H2+ "DATE_FORMAT(IFNULL(e.`resp_date`,#sd#),'%Y-%m-%d') AS responses_date, " + "IFNULL(e.`resp_date`,#sd#) AS responses_date, " + "count(e.`resp_date`) AS responses_count, " + "(SELECT count(*) " + "FROM " + "`responses` r JOIN `response_event` e ON r.`id` = e.`response_id` " + "WHERE " + "e.`resp_date` >= #sd# AND e.`resp_date` <= #ed#) AS all_count, " + "IFNULL((SELECT count(e.`resp_date`) " + "FROM `response_event` e WHERE r.`id` = e.`response_id` " + "AND " + "e.`resp_date` >= #sd# AND e.`resp_date` <= #ed# " + "GROUP BY r.id), 0) AS all_count_period " + "FROM " + "`responses` r LEFT JOIN `response_event` e " + "ON r.`id` = e.`response_id` AND " + "e.`resp_date` >= #sd# AND e.`resp_date` <= #ed# " + "GROUP BY r.id, responses_date"; query = query.replaceAll("#sd#", ssd).replaceAll("#ed#", sed); ResultSet rs = stmt.executeQuery(query); int id, prev_id = -1; ArrayList<HashMap<String, Integer>> id_set = new ArrayList<>(); int ind = 0; while (rs.next()) { id = rs.getInt(1); if (id != prev_id) { HashMap<String, Integer> hash_id = new HashMap<>(); hash_id.put("id", id); hash_id.put("ind", ind); id_set.add(hash_id); } ArrayList<Object> line = new ArrayList<>(6); line.add(rs.getInt(1)); line.add(rs.getString(2)); line.add(rs.getDate(3)); line.add(rs.getInt(4)); line.add(rs.getInt(5)); line.add(rs.getInt(6)); data_tmp.add(line); prev_id = id; ind++; } data = new ArrayList<>(); int isd = (int) (sd.getTime() / 86400000L) + 1; // ? ? 1970 int ied = (int) (ed.getTime() / 86400000L) + 1; int i; int idt; java.util.Date dt; ArrayList<Object> ext_line; HashMap<String, Integer> hash_id; int need_id; int need_ind; String name; java.util.Date date; int idate; int count; int all_count; int all_count_period; for (i = 0; i < id_set.size(); i++) { try { hash_id = id_set.get(i); need_id = hash_id.get("id"); need_ind = hash_id.get("ind"); ind = need_ind; for (idt = isd; idt <= ied; idt++) // idt - ? { dt = new java.util.Date(); dt.setTime(idt * 86400000L); if (ind >= data_tmp.size()) { ind = data_tmp.size() - 1; } ext_line = data_tmp.get(ind); id = ((Integer) ext_line.get(0)); if (need_id == id) { name = (String) ext_line.get(1); date = (java.util.Date) ext_line.get(2); idate = (int) (date.getTime() / 86400000L) + 1; count = ((Integer) ext_line.get(3)); all_count = ((Integer) ext_line.get(4)); all_count_period = ((Integer) ext_line.get(5)); if (idt != idate) // ins_before, ins_after { ArrayList<Object> new_line = new ArrayList<>(6); new_line.add(id); new_line.add(name); new_line.add(dt); new_line.add(0); new_line.add(all_count); new_line.add(all_count_period); data.add(new_line); } else if (idt == idate) // copy, next { @SuppressWarnings("unchecked") ArrayList<Object> copy_line = (ArrayList<Object>) ext_line.clone(); data.add(copy_line); ind++; } } else { ext_line = data_tmp.get(need_ind); name = (String) ext_line.get(1); all_count = ((Integer) ext_line.get(4)); all_count_period = ((Integer) ext_line.get(5)); ArrayList<Object> new_line = new ArrayList<>(6); new_line.add(need_id); new_line.add(name); new_line.add(dt); new_line.add(0); new_line.add(all_count); new_line.add(all_count_period); data.add(new_line); ind++; } } } catch (ArrayIndexOutOfBoundsException e) { throw new ReportException( " ? ? ResponsesDateDataSource" + e); } } } catch (SQLException ex) { throw new ReportException( " ? ? ResponsesDateDataSource" + ex); } } private ArrayList<ArrayList<Object>> data; private int index; @Override public boolean next() throws JRException { index++; return (index < data.size()); } @Override public Object getFieldValue(JRField field) throws JRException { Object value = null; String fieldName = field.getName(); try { final ArrayList line = (ArrayList) data.get(index); if (null != fieldName) { switch (fieldName) { case "id": value = line.get(0); break; case "responses_name": value = line.get(1); break; case "responses_date": value = line.get(2); break; case "responses_count": value = line.get(3); break; case "all_count": value = line.get(4); break; case "all_count_period": value = line.get(5); break; default: value = "unk_field"; break; } } } catch (Exception e) { value = "ResponsesDateDataSource: index is out of range!"; return value; } return value; } } /** * ? ? . * * @param driverClassName * @param url * @param username * @param password * @param request * @return ? ? ? ? . */ @Override public JRDataSource getDataSource(String driverClassName, String url, String username, String password, HttpRequest request) { Connection conn = connect_to_db(driverClassName, url, username, password, request); Date sd = paramMap.get("sd"); Date ed1 = paramMap.get("ed1"); return new ResponsesDateDataSource(conn, sd, ed1); } /** * ? ? . . ?? . ? , ? * ? . * * @param driverClassName * @param url * @param password * @param request * @param username * @return */ @Override public Map getParameters(String driverClassName, String url, String username, String password, HttpRequest request) { return paramMap; } /** * ? */ final private HashMap<String, Date> paramMap = new HashMap<>(); private Connection connect_to_db(String driverClassName, String url, String username, String password, HttpRequest request) { final Connection connection; try { Class.forName(driverClassName); connection = DriverManager.getConnection(url, username, password); } catch (SQLException | ClassNotFoundException ex) { throw new ReportException(StatisticServices.class.getName() + " " + ex); } return connection; } /** * ? ? ??? . ? ??? , , null. * * @param driverClassName * @param url * @param username * @param password * @param request * @return ?? null. */ @Override public Connection getConnection(String driverClassName, String url, String username, String password, HttpRequest request) { return null; } /* @Override public byte[] preparation(String driverClassName, String url, String username, String password, HttpRequest request) { // ? ? ??? , // null. final String data = NetUtil.getEntityContent(request); QLog.l().logger().trace("? \"" + data + "\"."); // ? boolean flag = false; String mess = ""; if ("".equals(data)) { flag = true; } else { //sd=20.01.2009&ed=28.01.2009 // ? final String[] ss = data.split("&"); if (ss.length == 2) { final String[] ss0 = ss[0].split("="); final String[] ss1 = ss[1].split("="); Date sd = null; Date fd = null; Date fd1 = null; flag = !(ss0.length == 2 && ss1.length == 2); if (!flag) { try { sd = Uses.format_dd_MM_yyyy.parse(ss0[1]); fd = Uses.format_dd_MM_yyyy.parse(ss1[1]); fd1 = DateUtils.addDays(Uses.format_dd_MM_yyyy.parse(ss1[1]), 1); } catch (ParseException ex) { mess = "<br> ! ? ? (..)."; flag = true; } } else { mess = "<br> ! ? ? (..)."; } if (!flag) { if (!sd.after(fd)) { paramMap.put(ss0[0], sd); paramMap.put(ss1[0], fd); paramMap.put("ed1", fd1); } else { mess = "<br> ! ?."; flag = true; } } } else { mess = "<br> !"; flag = true; } } if (flag) { // ? ?? // . // ? ? ?? ? ? null, // getDataSource ? . // ? ? ? . ? , ? . // get_period_for_statistic_services.html final InputStream inStream = getClass().getResourceAsStream("/ru/apertum/qsystem/reports/web/get_period_for_statistic_date_responses.html"); String result = null; try { result = new String(Uses.readInputStream(inStream), "UTF-8"); } catch (IOException ex) { throw new Uses.ReportException(" ? ?? ? . " + ex); } result = result.replaceFirst(Uses.ANCHOR_DATA_FOR_REPORT, request.getRequestLine().getUri()).replaceFirst(Uses.ANCHOR_ERROR_INPUT_DATA, mess); try { return result.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { return result.getBytes(); } } else { return null; } } */ @Override public Response getDialog(String driverClassName, String url, String username, String password, HttpRequest request, String errorMessage) { return getDialog("/ru/apertum/qsystem/reports/web/get_period_for_statistic_date_responses.html", request, errorMessage); } @Override public String validate(String driverClassName, String url, String username, String password, HttpRequest request, HashMap<String, String> params) { // ? QLog.l().logger().trace("? \"" + params.toString() + "\"."); if (params.size() == 2) { Date sd; Date fd; Date fd1; try { sd = Uses.format_dd_MM_yyyy.parse(params.get("sd")); fd = Uses.format_dd_MM_yyyy.parse(params.get("ed")); fd1 = DateUtils.addDays(Uses.format_dd_MM_yyyy.parse(params.get("ed")), 1); } catch (ParseException ex) { return "<br> ! ? ? (..)."; } if (!sd.after(fd)) { paramMap.put("sd", sd); paramMap.put("ed", fd); paramMap.put("ed1", fd1); } else { return "<br> ! ?."; } } else { return "<br> !"; } return null;// ? } }