Java tutorial
/*$Id: WebFlowServiceImpl.java 12173 2008-12-08 11:45:52Z jens $*/ /* **************************************************************************** * * * (c) Copyright 2008 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.webflow.hibernate2; import java.lang.reflect.Method; import java.util.Set; import no.abmu.abmstatistikk.annualstatistic.domain.Answer; import no.abmu.abmstatistikk.annualstatistic.domain.Field; import no.abmu.abmstatistikk.annualstatistic.domain.FieldType; import no.abmu.abmstatistikk.annualstatistic.domain.Report; import no.abmu.abmstatistikk.annualstatistic.service.FolkeBibScreen; import no.abmu.abmstatistikk.annualstatistic.service.SchemaReport; import no.abmu.abmstatistikk.annualstatistic.service.hibernate2.AnnualStatisticService; import no.abmu.abmstatistikk.annualstatistic.webflow.HighSchoolLibrarySchema; import no.abmu.abmstatistikk.annualstatistic.webflow.PrimarySchoolLibrarySchema; import no.abmu.abmstatistikk.annualstatistic.webflow.WebFlowService; import no.abmu.abmstatistikk.annualstatistic.webflow.WebFlowValidator; import no.abmu.abmstatistikk.annualstatistic.webflow.WebSchemaDefinition; import no.abmu.common.constants.SchemaTypeNameConst; import no.abmu.common.constants.SchemaTypeNameNotFoundException; import no.abmu.organisationregister.webflow.FlowVariables; import no.abmu.util.reflection.MethodUtil; import no.abmu.util.test.Assert; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.util.StopWatch; import org.springframework.validation.Errors; import org.springframework.webflow.execution.RequestContext; /** * <code>WebFlowServiceImpl</code> implements interface * <code>WebFlowService</code>. * * @author Jens Vindvad, Jens.Vindvad@abm-utvikling.no * @author $Author: jens $ * @version $Rev: 12173 $ * @date $Date: 2008-12-08 12:45:52 +0100 (Mon, 08 Dec 2008) $ * @since 2008-01-25 * copyright ABM-Utvikling */ public class WebFlowServiceImpl implements WebFlowService { private static final Log logger = (Log) LogFactory.getLog(WebFlowServiceImpl.class); private AnnualStatisticService annualStatisticService; public AnnualStatisticService getAnnualStatisticService() { return annualStatisticService; } public void setAnnualStatisticService(AnnualStatisticService annualStatisticService) { this.annualStatisticService = annualStatisticService; } /** * Create new empty webSchema for schema type defined in context. * * @param context - RequestContext webflow requestContext * @return - WebSchemaDefinition new empty webSchema. */ public WebSchemaDefinition createWebSchema(RequestContext context) { if (logger.isDebugEnabled()) { logger.debug("Executing createWebSchema"); } FlowVariables flowVariables = (FlowVariables) context.getFlowScope().get("flowVariables"); Long id = flowVariables.getWorkingSchemaOrganisationUnitId(); String dataBaseSchemaName = flowVariables.getDataBaseSchemaName(); String dataBaseSchemaVersion = flowVariables.getDataBaseSchemaVersion(); String webFlowSchemaName = flowVariables.getWebFlowSchemaName(); logger.info("[createWebSchema] " + flowVariables); Assert.assertNotNull("id", id); Assert.assertNotNull("dataBaseSchemaName", dataBaseSchemaName); Assert.assertNotNull("dataBaseSchemaVersion", dataBaseSchemaVersion); Assert.assertNotNull("webFlowSchemaName", webFlowSchemaName); WebSchemaDefinition webSchema; if (webFlowSchemaName.equals("primarySchoolLibrarySchema")) { webSchema = new PrimarySchoolLibrarySchema(id, dataBaseSchemaName, dataBaseSchemaVersion, webFlowSchemaName); } else if (webFlowSchemaName.equals("highSchoolLibrarySchema")) { webSchema = new HighSchoolLibrarySchema(id, dataBaseSchemaName, dataBaseSchemaVersion, webFlowSchemaName); } else { logger.error("Unsupported webFlowSchemaTypeName " + webFlowSchemaName); throw new IllegalArgumentException("Unsupported webFlowSchemaTypeName " + webFlowSchemaName); } return webSchema; } /** * Getting values from database into all fields defined in webSchema. * * @param webSchema - WebSchemaDefinition, * schema which are filled with values. */ public void databaseValuesToWebSchema(WebSchemaDefinition webSchema) { if (logger.isDebugEnabled()) { logger.debug("Executing databaseValuesToWebSchema"); } Assert.checkRequiredArgument("webSchema", webSchema); Object dataBaseSchema = getDatabaseSchema(webSchema); Method[] methods = webSchema.getClass().getMethods(); for (int i = 0; i < methods.length; i++) { Method method = methods[i]; String methodGetFieldName = method.getName(); if (methodGetFieldName.startsWith("getField") && (methodGetFieldName.length() > 8)) { String fieldNumberAsString = methodGetFieldName.substring(8); Answer answer = (Answer) MethodUtil.getValueOfPublicMethod(dataBaseSchema, methodGetFieldName); if (answer == null) { logger.error("Answer == null, for database Schema='" + dataBaseSchema.toString() + "' and method name='" + methodGetFieldName + "'"); } String fromValue = answer.getValue(); String fromComment = answer.getComment(); String methodSetFieldName = "setField" + fieldNumberAsString; String methodSetCommentName = "setComment" + fieldNumberAsString; MethodUtil.executePublicMethod(webSchema, methodSetFieldName, fromValue, String.class); MethodUtil.executePublicMethod(webSchema, methodSetCommentName, fromComment, String.class); if (logger.isDebugEnabled()) { String methodGetCommentName = "getComment" + fieldNumberAsString; String toValue = (String) MethodUtil.getValueOfPublicMethod(webSchema, methodGetFieldName); String toComment = (String) MethodUtil.getValueOfPublicMethod(webSchema, methodGetCommentName); logger.debug("Field '" + fieldNumberAsString + "' validation '" + answer.getPassedvalidation() + "' of type '" + fieldTypeInfo(answer.getField()) + "' db value '" + fromValue + "' new web value '" + toValue + "' comment '" + toComment + "'"); } } } } /** * Save database schema values in database if no error exists. * * @param schemaReport - database schema to save. * @param errors - errors to check. */ public void saveDataBaseSchemaIfNoError(SchemaReport schemaReport, Errors errors) { if (logger.isDebugEnabled()) { logger.debug("Executing saveDataBaseSchemaIfNoError"); } Assert.checkRequiredArgument("schemaReport", schemaReport); Assert.checkRequiredArgument("errors", errors); // If errors no saving this is a normal situation. if (errors.hasErrors()) { if (logger.isDebugEnabled()) { logger.debug("[validateAndSave] There was validation errors."); } return; } if (logger.isDebugEnabled()) { logger.debug("Validation went Ok, now saving results .... "); } if (annualStatisticService.saveReport(schemaReport.getReport())) { if (logger.isDebugEnabled()) { logger.debug("Result are saved."); } } else { logger.error("[validateAndSave] There was saving errors .... "); } } /** * Getting values from webSchema to an new databaseSchema, e.g. values from * user input to database schema. * * @param webFlowValidator - WebFlowValidator validator. * @param webSchemaDefinition - webSchema * @return - SchemaReport database schema. */ public SchemaReport webSchemaValuesToDataBaseSchema(WebFlowValidator webFlowValidator, WebSchemaDefinition webSchema) { Assert.checkRequiredArgument("webFlowValidator", webFlowValidator); Assert.checkRequiredArgument("webSchema", webSchema); if (logger.isDebugEnabled()) { logger.debug("Executing webSchemaValuesToDataBaseSchema with parameters, WebFlowValidator='" + webFlowValidator + ", WebSchemaDefinition='" + webSchema + "'"); } StopWatch stopWatch = new StopWatch(); stopWatch.start("webSchemaValuesToDataBaseSchema"); int notPassedValidation = 0; Object dataBaseSchema = getDatabaseSchema(webSchema); // Set up validation keys webFlowValidator.computeValidateFieldKeys(); Set<String> validateFieldKeys = webFlowValidator.getValidateFieldKeys(); if (logger.isDebugEnabled()) { for (String validateFieldKey : validateFieldKeys) { logger.debug("FieldKey to be validated='" + validateFieldKey + "'"); } } for (String fieldNumberAsString : validateFieldKeys) { String methodGetFieldName = "getField" + fieldNumberAsString; String methodGetCommentName = "getComment" + fieldNumberAsString; String value = (String) MethodUtil.getValueOfPublicMethod(webSchema, methodGetFieldName); String comment = (String) MethodUtil.getValueOfPublicMethod(webSchema, methodGetCommentName); Answer answer = (Answer) MethodUtil.getValueOfPublicMethod(dataBaseSchema, methodGetFieldName); answer.setValue(value); answer.setComment(comment); answer.setPassedvalidation(notPassedValidation); if (logger.isDebugEnabled()) { Answer newAnswer = (Answer) MethodUtil.getValueOfPublicMethod(dataBaseSchema, methodGetFieldName); logger.debug("Field '" + fieldNumberAsString + "' method get name '" + methodGetFieldName + "' web value '" + value + "' web comment '" + comment + "'"); logger.debug("Field '" + fieldNumberAsString + "' validation '" + answer.getPassedvalidation() + "' new db value '" + newAnswer.getValue() + "' new db comment '" + newAnswer.getComment() + "'"); } } SchemaReport schemaReport = (SchemaReport) dataBaseSchema; stopWatch.stop(); logger.info("[private:webSchemaValuesToDataBaseSchema] tok [" + stopWatch.getTotalTimeMillis() + "] ms"); return schemaReport; } /** * Getting database schema and values from database. * * @param webSchema - WebSchemaDefinition, schema which specify database * schema and version. * @return - Database schema with values fram database. */ private Object getDatabaseSchema(WebSchemaDefinition webSchema) { if (logger.isDebugEnabled()) { logger.debug("Executing getDatabaseSchema"); } Assert.checkRequiredArgument("webSchema", webSchema); StopWatch stopWatch = new StopWatch(); stopWatch.start("getDatabaseSchema"); Long id = webSchema.getId().longValue(); String dataBaseSchemaName = webSchema.getDataBaseSchemaName(); String dataBaseSchemaVersion = webSchema.getDataBaseSchemaVersion(); Integer year = Integer.valueOf(dataBaseSchemaVersion); Assert.assertNotNull("OrganisationUnitId was null ", id); Assert.assertNotNull("DataBaseSchemaTypeName was null ", dataBaseSchemaName); Assert.assertNotNull("SchemaVersion was null ", dataBaseSchemaVersion); Report report = annualStatisticService.getReport(id, dataBaseSchemaName, year.intValue(), true); SchemaReport schemaReport; if (report == null) { logger.error("Couldn't find report for schema " + dataBaseSchemaName + " for Organisation " + id); throw new IllegalArgumentException( "Couldn't find report for schema " + dataBaseSchemaName + " for Organisation " + id); } else { schemaReport = new SchemaReport(report); } Object dataBaseSchema; if (dataBaseSchemaName.equals(SchemaTypeNameConst.FOLKEBIBLIOTEK_SHORT_NAME)) { dataBaseSchema = new FolkeBibScreen(schemaReport.getReport()); } else { throw new SchemaTypeNameNotFoundException(dataBaseSchemaName); } stopWatch.stop(); logger.info("[getDatabaseSchema] tok [" + stopWatch.getTotalTimeMillis() + "] ms"); return dataBaseSchema; } /** * Getting data type of specified answer field. * * @param answerField - answer field to ask for data type on. * @return - String data type - kind of description. */ private String fieldTypeInfo(Field answerField) { if (answerField == null) { return "Answer not associated with a field in database!"; } FieldType fieldType = answerField.getFieldType(); if (fieldType == null) { return "Field has no type, can't validate..."; } String dataType = fieldType.getDatatype(); if (dataType == null) { return "Field has undefined dataType, can't validate..."; } return dataType; } }