Java tutorial
/*$Id: AnnualStatisticServiceImpl.java 13072 2009-02-15 20:27:19Z jens $*/ /* **************************************************************************** * * * (c) Copyright 2004 ABM-utvikling * * * * 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 2 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. http://www.gnu.org/licenses/gpl.html * * * **************************************************************************** */ package no.abmu.abmstatistikk.annualstatistic.service.hibernate2; import java.util.Arrays; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.GregorianCalendar; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.SortedSet; import net.sf.hibernate.Hibernate; import net.sf.hibernate.HibernateException; import no.abmu.abmstatistikk.annualstatistic.domain.Answer; import no.abmu.abmstatistikk.annualstatistic.domain.Field; import no.abmu.abmstatistikk.annualstatistic.domain.FieldGroupConstraint; import no.abmu.abmstatistikk.annualstatistic.domain.FieldGroupConstraintMember; import no.abmu.abmstatistikk.annualstatistic.domain.FieldType; import no.abmu.abmstatistikk.annualstatistic.domain.Report; import no.abmu.abmstatistikk.annualstatistic.domain.Schema; import no.abmu.abmstatistikk.annualstatistic.finders.report.ReportFinderSpecification; import no.abmu.abmstatistikk.annualstatistic.service.AnnualstatisticBaseService; import no.abmu.abmstatistikk.annualstatistic.service.ReportHelper; import no.abmu.abmstatistikk.annualstatistic.service.SchemaHelper; import no.abmu.common.browsing.OrganisationUnitForBrowsing; import no.abmu.common.jasperreports.SchemaList; import no.abmu.common.reporting.OrgUnitReport; import no.abmu.common.reporting.ReportStatus; import no.abmu.common.reporting.SimpleOrgUnitReport; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; /** * Implementation of AnnualStatisticService interface. * * This class is used to abstract the database from higher layers. * The main task is to get objects from the database and populate them * Uses Hibernate with interceptors to get objects. * * @author: Henning Kulander hennikul@linpro.no * @author $Author: jens $ * @version $Rev: 13072 $ * @date $Date: 2009-02-15 21:27:19 +0100 (Sun, 15 Feb 2009) $ * @since 2004-12-09 (rev. 202) * copyright ABM-Utvikling * */ public class AnnualStatisticServiceImpl implements AnnualStatisticService { private static final Log logger = (Log) LogFactory.getLog(AnnualStatisticServiceImpl.class); private AnnualstatisticBaseService baseService; private AnnualStatisticServiceHelper serviceHelper; public AnnualStatisticServiceImpl() { this.serviceHelper = new AnnualStatisticServiceHelper(this); } /** * Create a new report. * * @param year : Year of the report * @return New report for organisation, schema and year with empty answers. */ public Report newReport(long organisationId, String schemaShortName, int year) { Report report = new Report(); Report lastYearReport = getReport(organisationId, schemaShortName, year - 1, false); long schemaId = getSchemaId(schemaShortName, year); if (schemaId < 0) { logger.error("Tried to create report for nonexsisting schema with name '" + schemaShortName + "'"); return null; } Schema schema = getSchemaById(schemaId); report.setOrganisationid(organisationId); report.setSchema(schema); report.setReport(lastYearReport); report.setCurrentpage(new Integer(1)); ReportHelper reportHelper = new ReportHelper(report); reportHelper.createEmptyAnswers(); return report; } public Object[] find(String query) { return baseService.find(query); } /* public Object[] find(String query, Object[] args, Type[] types) { return baseService.find(query, args, types); } */ /** * getReport. * * @param organisationId : DatabaseId of the organisation owning the report * @param year : Year of the report * @param createIfNecesary : Controls if a new report should be created if none exists * @return The report. */ public Report getReport(long organisationId, String schemaShortName, int year, boolean createIfNecesary) { /* Object[] organisationReportArray = baseService.find("from Report as report where " + "report.organisationid=" + organisationId + " and " + "report.schema.shortname='" + schemaShortName+"'"); */ //suppose it is not thread safe... Calendar calendar = GregorianCalendar.getInstance(); //get 1:st of june for the intended year, start and stop date is always //at the 1:st of january and last of december? calendar.set(year, 6, 1); Date date = calendar.getTime(); /* Object[] organisationReportArray = baseService.find("select report,field " + "from " + Report.class.getName() + " as report " + "join fetch report.schema as schema " + "left join fetch report.report as freport " + "left join fetch report.answers as answers " + "join fetch answers.field as field " + "left join fetch field.fieldType " + "where " + "report.organisationid=? and " + "schema.shortname=?" + " and " + "schema.startdate <= ? and " + "schema.stopdate >= ?", new Object[]{new Long(organisationId), schemaShortName, date, date}, new Type[]{new LongType(), new StringType(), new DateType(), new DateType()}); List organisationReports = Arrays.asList(organisationReportArray); */ ReportFinderSpecification finderSpecification = new ReportFinderSpecification(organisationId, schemaShortName, date, date); Collection organisationReports = baseService.find(finderSpecification); Iterator organisationReportsIterator = organisationReports.iterator(); //loop as left as it is while (organisationReportsIterator.hasNext()) { Report organisationReport = (Report) organisationReportsIterator.next(); Schema reportSchema = organisationReport.getSchema(); SchemaHelper schemaHelper = new SchemaHelper(reportSchema); if (schemaHelper.getYear() == year) { // Create empty answer objects where old answer does not exist. ReportHelper organisationReportHelper = new ReportHelper(organisationReport); organisationReportHelper.createEmptyAnswers(); // commented because we use fetch in query hibernateInitialize(organisationReport); organisationReportHelper.autoCalculate(); return organisationReport; } } if (createIfNecesary) { Report organisationReport = newReport(organisationId, schemaShortName, year); hibernateInitialize(organisationReport); return organisationReport; } else { return null; } } /** * hibernateInitialize. * * @param organisationReport - Report to initialize */ private void hibernateInitialize(Report organisationReport) { if (organisationReport != null) { try { // Initialize hibernate objects so they will work outside this class: Hibernate.initialize(organisationReport.getAnswers()); Report lastYearReport = organisationReport.getReport(); if (lastYearReport != null) { Hibernate.initialize(lastYearReport.getAnswers()); } Set answers = organisationReport.getAnswers(); Iterator answerIterator = answers.iterator(); while (answerIterator.hasNext()) { Answer answer = (Answer) answerIterator.next(); Field field = answer.getField(); Hibernate.initialize(field.getFieldAnnualChangeConstraintByFieldid()); Hibernate.initialize(field.getFieldGroupConstraintMembers()); FieldType fieldType = field.getFieldType(); if (fieldType != null) { Hibernate.initialize(fieldType.getFieldTypeConstraints()); } Set groupConstraintMemberships = field.getFieldGroupConstraintMembers(); Iterator groupConstraintMembershipsIterator = groupConstraintMemberships.iterator(); while (groupConstraintMembershipsIterator.hasNext()) { FieldGroupConstraintMember groupMember = (FieldGroupConstraintMember) groupConstraintMembershipsIterator .next(); FieldGroupConstraint groupConstraint = groupMember.getFieldGroupConstraint(); Hibernate.initialize(groupConstraint.getFieldGroupConstraintMembers()); } } } catch (HibernateException e) { logger.error("Failed to initialize report answers!"); e.printStackTrace(); } } } /** * getSchemaById. * * @param schemaId * @return */ public Schema getSchemaById(long schemaId) { Schema schema = (Schema) baseService.get(new Long(schemaId), Schema.class); return schema; } /** * getSchemaId. * * @param schemaId : Short name of schema * @param year : year schema was valid * @return DatabaseId of schema. */ public long getSchemaId(String schemaId, int year) { Object[] schemaArray = baseService .find("from Schema as schema where " + "schema.shortname = '" + schemaId + "'"); List schemaList = Arrays.asList(schemaArray); Iterator schemaIterator = schemaList.iterator(); while (schemaIterator.hasNext()) { Schema schema = (Schema) schemaIterator.next(); SchemaHelper schemaHelper = new SchemaHelper(schema); if (schemaHelper.getYear() == year) { return schema.getId().longValue(); } } return -1; } /* (non-Javadoc) * @see no.abmu.abmstatistikk.annualstatistic.service.AnnualStatisticService * #saveReport(no.abmu.abmstatistikk.annualstatistic.domain.Report) */ public boolean saveReport(Report report) { logger.debug("Saving report"); baseService.store(report); Set reportAnswers = report.getAnswers(); Iterator reportAnswersIterator = reportAnswers.iterator(); while (reportAnswersIterator.hasNext()) { Answer reportAnswer = (Answer) reportAnswersIterator.next(); if (reportAnswer.getValue() != null || reportAnswer.getComment() != null) { if (reportAnswer.getValue() == null) { /* Only comment */ reportAnswer.setValue(""); } Field reportField = reportAnswer.getField(); FieldType reportFieldType = reportField.getFieldType(); if (!reportFieldType.getDatatype().equals("AUTOCALCULATE")) { if ((reportAnswer.getValue() != null && !reportAnswer.getValue().equals(reportAnswer.getOldValue())) || (reportAnswer.getComment() != null && !reportAnswer.getComment().equals(reportAnswer.getOldComment()))) { baseService.store(reportAnswer); } } } else { /* Don't save, check if object must be deleted from DB */ if (reportAnswer.getId() != null) { logger.debug("Deleting answer for field " + reportAnswer.getField().getName()); reportAnswer.setValue(""); baseService.remove(reportAnswer); } } } return true; } public AnnualstatisticBaseService getAnnualstatisticBaseService() { return baseService; } public void setAnnualstatisticBaseService(AnnualstatisticBaseService service) { baseService = service; } /* (non-Javadoc) * @see no.abmu.abmstatistikk.annualstatistic.service.AnnualStatisticService * #getAnswerByFieldName(no.abmu.abmstatistikk.annualstatistic.domain.Report, java.lang.String) */ public Answer getAnswerByFieldName(Report report, String fieldName) { ReportHelper reportHelper = new ReportHelper(report); return reportHelper.getAnswerByFieldName(fieldName); } /* (non-Javadoc) * @see no.abmu.abmstatistikk.annualstatistic.service.AnnualStatisticService * #getVirtualReport(long, java.lang.String, int) */ public Report getVirtualReport(long organisationId, String schemaShortName, int year, Set subOrganisationReports) { if (subOrganisationReports == null || subOrganisationReports.isEmpty()) { return null; } Report virtualReport = newReport(organisationId, schemaShortName, year); ReportHelper virtualReportHelper = new ReportHelper(virtualReport); Set virtualAnswers = virtualReport.getAnswers(); Iterator subReportIterator = subOrganisationReports.iterator(); while (subReportIterator.hasNext()) { Report subReport = (Report) subReportIterator.next(); ReportHelper subReportHelper = new ReportHelper(subReport); Iterator virtualAnswerIterator = virtualAnswers.iterator(); while (virtualAnswerIterator.hasNext()) { Answer virtualAnswer = (Answer) virtualAnswerIterator.next(); Field virtualField = virtualAnswer.getField(); if (virtualField == null) { logger.error("Answer without field."); continue; } FieldType virtualFieldType = virtualField.getFieldType(); if (virtualFieldType == null) { logger.error("Answer without fieldType."); continue; } String virtualDataType = virtualFieldType.getDatatype(); if (virtualDataType != null && (virtualDataType.startsWith("DIGIT") || virtualDataType.startsWith("FLOAT") || virtualDataType.equals("YEARHOURS") || virtualDataType.equals("YEARDAYS") || virtualDataType.equals("WEEKHOURS") || virtualDataType.equals("AUTOCALCULATE"))) { Answer subAnswer = subReportHelper.getAnswerByFieldName(virtualField.getName()); try { float virtualValue = Float.parseFloat(virtualAnswer.getValue()); float subValue = Float.parseFloat(subAnswer.getValue()); virtualValue += subValue; virtualAnswer.setValue(Float.toString(virtualValue)); } catch (NumberFormatException e) { virtualAnswer.setValue("ERROR"); } } } } return virtualReport; } public ReportStatus[] getReportStatusBySchemaTypeAndYear(List<OrganisationUnitForBrowsing> orgUnitsForBrodwsing, String schemaType, int reportYear) { return serviceHelper.getReportStatusBySchemaTypeAndYear(orgUnitsForBrodwsing, schemaType, reportYear); } public SchemaList getJasperReportDataForSchemaTypeAndYear(SchemaList jasperReportDataSource, String schemaTypeName, int year) { return serviceHelper.getJasperReportDataForSchemaTypeAndYear(jasperReportDataSource, schemaTypeName, year); } public SchemaList getReportDataBySchemaTypeAndYear(SortedSet<OrgUnitReport> orgSortedSet, String schemaTypeName, int year) { return serviceHelper.getReportDataBySchemaTypeAndYear(orgSortedSet, schemaTypeName, year); } public SchemaList getCommentReportAndLastYearForSchemaTypeAndYear(SchemaList jasperReportDataSource, String schemaTypeName, int year) { return serviceHelper.getCommentReportAndLastYearForSchemaTypeAndYear(jasperReportDataSource, schemaTypeName, year); } public SchemaList getCommentReportAndLastYearForSchemaTypeAndYear( SortedSet<SimpleOrgUnitReport> simpleOrgSortedSet, String schemaTypeName, int year) { return serviceHelper.getCommentReportAndLastYearForSchemaTypeAndYear(simpleOrgSortedSet, schemaTypeName, year); } }