Package com.vst.webapp.action

Source Code of com.vst.webapp.action.RTFListController

package com.vst.webapp.action;

import com.lowagie.text.Image;
import com.vst.model.*;
import com.vst.model.internal.DefectPhoto;
import com.vst.service.*;
import com.vst.util.ReportUtil;
import com.vst.util.StringUtil;
import com.vst.webapp.util.FileHelper;
import com.vst.webapp.util.ObjectPicture;
import com.vst.webapp.util.ImageUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;
import org.hibernate.Hibernate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.imageio.ImageIO;
import java.io.*;
import java.sql.Blob;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.awt.image.BufferedImage;
import java.awt.*;

/**
* Created by IntelliJ IDEA.
* User: ALEXEI
* Date: 04.01.2008
* Time: 14:43:45
* To change this template use File | Settings | File Templates.
*/
public class RTFListController implements Controller {
    private transient final Log log = LogFactory.getLog(UserController.class);
    private ObjectConstructionManager objectConstructionManager=null;
    private BuildingObjectManager buildingObjectManager = null;
    private StrengthManager strengthManager = null;
    private ReasonManager reasonManager = null;
    private ConstructionDefectManager constructionDefectManager = null;
    private ConstructionExampleManager constructionExampleManager = null;
    private DefectRecomendationManager defectRecomendationManager = null;
    private TemplateManager templateManager = null;

    private String tmp2 = "VERY BIG HELLO TO ACTIVE SYSTEMS COMPANY";


    public void setObjectConstructionManager(ObjectConstructionManager objectConstructionManager) {
        this.objectConstructionManager = objectConstructionManager;
    }

    public void setTemplateManager(TemplateManager templateManager) {
        this.templateManager = templateManager;
    }

    public void setDefectRecomendationManager(DefectRecomendationManager defectRecomendationManager) {
        this.defectRecomendationManager = defectRecomendationManager;
    }

    public void setConstructionExampleManager(ConstructionExampleManager constructionExampleManager) {
        this.constructionExampleManager = constructionExampleManager;
    }

    public void setConstructionDefectManager(ConstructionDefectManager constructionDefectManager) {
        this.constructionDefectManager = constructionDefectManager;
    }

    public void setReasonManager(ReasonManager reasonManager) {
        this.reasonManager = reasonManager;
    }

    public void setStrengthManager(StrengthManager strengthManager) {
        this.strengthManager = strengthManager;
    }

    public void setBuildingObjectManager(BuildingObjectManager buildingObjectManager) {
        this.buildingObjectManager = buildingObjectManager;
    }

    private String getObjectDangerCategoryText(DangerCategory dangerCategory) {
        if (dangerCategory != null) {
            if (dangerCategory.getCategoryName().equals("А")) {
                return " неработоспособном состоянии";
            }

            if (dangerCategory.getCategoryName().equals("Б")) {
                return " ограниченно работоспособном состоянии";
            }
            if (dangerCategory.getCategoryName().equals("В")) {
                return " работоспособном состоянии";
            }
            return " работоспособном состоянии";
        }
        return "";
    }


    public ModelAndView handleRequest(HttpServletRequest request,
                                      HttpServletResponse response)
            throws Exception {


        NumberFormat nf = NumberFormat.getInstance();
        String filename = FileHelper.getUniqueFileName(request);
        List defectPhotoList = new ArrayList();
        //retrieving specialist list from session
        String buildingObjectId = request.getParameter("objectId");


        if (buildingObjectId != null) {
            BuildingObject buildingObject = buildingObjectManager.getBuildingObject(buildingObjectId);
            //getting trmplate
            FileInputStream fileInputStream = new FileInputStream(FileHelper.getCurrentPath(request) + "doc_template1.doc");
            File file = new File(FileHelper.getCurrentPath(request) + "doc_template1.doc");

            byte[] templateBytes = new byte[(int) file.length()];
            fileInputStream.read(templateBytes);

            StringBuilder template = ReportUtil.convertToStringBuilder(templateBytes);
            template = ReportUtil.changeFile(template, "doc_template1", "26F25CD1");


            fileInputStream.close();
            if (template.length() == 0) {
                throw new Exception("Template is not specifired.");
            }
            //%companyLicense %
            // hack for deleting abnormal line break
            ReportUtil.replaceAllLabel(template, String.valueOf(new char[]{(char) 61, (char) 13, (char) 10}), "");

            //filling the first pages by common information
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            ReportUtil.replaceAllLabel(template, "objectName", buildingObject.getName());
            ReportUtil.replaceAllLabel(template, "%current_year%", String.valueOf(calendar.get(Calendar.YEAR)));
            ReportUtil.replaceAllLabel(template, "%organization_name%", buildingObject.getOrganizationName());
            ReportUtil.replaceAllLabel(template, "%researcher_family%", buildingObject.getUser().getFirstName() + " " + buildingObject.getUser().getLastName());
            ReportUtil.replaceAllLabel(template, "%research_company_name%", buildingObject.getResearchCompanyName() != null ? buildingObject.getResearchCompanyName() : "ООО "СУ ВСТ"");
            ReportUtil.replaceAllLabel(template, "%principal_name%", buildingObject.getResearchCompanyPrincipal() != null ? buildingObject.getResearchCompanyPrincipal() : "Рылов А.О.");

            //filling technical task if it exists
            if (buildingObject.getTechnicalTask() != null) {
                file = new File(com.vst.util.FileHelper.getCurrentPath(request) + buildingObject.getWayToTechnicalTask());
                if (file.exists()) {
                    file.delete();
                }
                file.createNewFile();
                FileOutputStream fileOutputStream = new FileOutputStream(FileHelper.getCurrentPath(request) + buildingObject.getWayToTechnicalTask());
                Blob blob = buildingObject.getTechnicalTask();
                byte[] bufer = new byte[62000];
                InputStream inputStream = blob.getBinaryStream();
                while (inputStream.read(bufer) != -1) {
                    fileOutputStream.write(bufer);
                }
                inputStream.close();
                fileOutputStream.close();

                File technicalFile = new File(FileHelper.getCurrentPath(request) + buildingObject.getWayToTechnicalTask());
                byte[] technicalTemplateBytes = new byte[(int) technicalFile.length()];
                FileInputStream technicalFileInputStream = new FileInputStream(FileHelper.getCurrentPath(request) + buildingObject.getWayToTechnicalTask());
                technicalFileInputStream.read(technicalTemplateBytes);

                StringBuilder technicalTaskText = ReportUtil.convertToStringBuilder(technicalTemplateBytes);
                ReportUtil.replaceAllLabel(template, "%tz_text%", ReportUtil.extractBodyContent(technicalTaskText));
            } else {
                ReportUtil.replaceAllLabel(template, "%tz_text%", "");
            }

//            ReportUtil.replaceAllLabel(template, "%research_year%",""+calendar.get(Calendar.YEAR)+"");


            ReportUtil.replaceAllLabel(template, "%organization_city%", buildingObject.getOrganizationCity());
            ReportUtil.replaceAllLabel(template, "%object_description%", buildingObject.getDescription());

            //filling the table of common condition
            String tableRow = ReportUtil.extractBookmarkForTable(template, "condition_table_rows", "%rows%");
            String result = "";
            //    String newRow = "";

            List objectConstructionTypes = buildingObjectManager.getObjectGroupedConstructionTypes(buildingObjectId);

            //writing all the specialists from the list
            for (int i = 0; i < objectConstructionTypes.size(); i++) {

                //first column
                ConstructionType constructionType = (ConstructionType) objectConstructionTypes.get(i);
                //type examples number
                Integer commonNumber = buildingObjectManager.getObjectConstructionTypeExampleNum(buildingObjectId, constructionType.getConstructionTypeId().toString());
                Integer cNumber = buildingObjectManager.getObjectConstructionTypeExampleByCategory(buildingObjectId, constructionType.getConstructionTypeId().toString(), "C");
                Integer bNumber = buildingObjectManager.getObjectConstructionTypeExampleByCategory(buildingObjectId, constructionType.getConstructionTypeId().toString(), "B");
                Integer aNumber = buildingObjectManager.getObjectConstructionTypeExampleByCategory(buildingObjectId, constructionType.getConstructionTypeId().toString(), "A");
                cNumber = new Integer(commonNumber - bNumber - aNumber);

                result += tableRow.replaceAll("%number%", String.valueOf(i + 1))
                        .replaceAll("%construction_type%", constructionType.toString())
                        .replaceAll("%construction_type%", constructionType.toString())
                        .replaceAll("%common_num%", commonNumber.toString())
                        .replaceAll("%c_number%", cNumber.toString())
                        .replaceAll("%b_number%", aNumber.toString())
                        .replaceAll("%a_number%", bNumber.toString());

            }

            ReportUtil.replaceAllLabel(template, "%rows%", result);

            String dangerCategoryText = getObjectDangerCategoryText(buildingObject.getDangerCategory());
            ReportUtil.replaceAllLabel(template, "objectCondition", dangerCategoryText);

//filling the table of object desicions
            //filling the table of common condition


            String desicionTableRow = ReportUtil.extractBookmarkForTable(template, "desicion_table_rows", "%rows%");

            String resultDesicionTable = "";
            String newDesicionRow = "";

            List structureAnswerList = buildingObjectManager.getAnswersByDocumentation(buildingObjectId, "1");
            int nm = 0;
            for (int i = 0; i < structureAnswerList.size(); i++) {
                ObjectAnswer objectAnswer = (ObjectAnswer) structureAnswerList.get(i);
                //number
                nm++;
                newDesicionRow = desicionTableRow.replaceAll("%o_num%", String.valueOf(nm));

                //question contents
                newDesicionRow = newDesicionRow.replaceAll("%article_name%", objectAnswer.getQuestion().getContents());

                //answer
                String answerText = "";
                List answers = objectAnswer.getAnswers();
                if (answers.size() > 0 && (!((Answer) answers.get(0)).getAnswerId().equals(new Integer(-1)) && answers.size() == 1)) {
                    for (int j = 0; j < answers.size(); j++) {
                        Answer answer = (Answer) answers.get(j);

                        if (answer.getAnswerInterpritation() == null || "".equals(answer.getAnswerInterpritation())) {
                            answerText += answer.getContents() + "<br/>";
                        } else {
                            answerText += answer.getAnswerInterpritation() + "<br/>";
                        }

                    }
                } else {
                    answerText += objectAnswer.getAnswerContents();
                }
                newDesicionRow = newDesicionRow.replaceAll("%desicion_name%", answerText);

                resultDesicionTable += newDesicionRow;
            }

            //filling construction varity list
            List constructionVarityList = buildingObject.getConstructionTypes();
            for (int i = 0; i < constructionVarityList.size(); i++) {
                ObjectConstruction objectConstruction = (ObjectConstruction) constructionVarityList.get(i);
                //number
                nm++;

                newDesicionRow = desicionTableRow.replaceAll("%o_num%", String.valueOf(nm));

                newDesicionRow = newDesicionRow.replaceAll("%article_name%", objectConstruction.getConstructionType().toString());

                //answer
                String answerText = "";

                List constructionAnswerList = objectConstruction.getDocumentationQuestions();
                for (int j = 0; j < constructionAnswerList.size(); j++) {
                    ObjectAnswer objectAnswer = (ObjectAnswer) constructionAnswerList.get(j);

                    List answers = objectAnswer.getAnswers();
                    answerText += objectAnswer.getQuestion().getContents() + " - ";

                    if (answers.size() > 0 && !((Answer) answers.get(0)).getAnswerId().equals(new Integer(-1))) {
                        for (int s = 0; s < answers.size(); s++) {
                            Answer answer = (Answer) answers.get(s);
                            if (answer.getAnswerInterpritation() == null || "".equals(answer.getAnswerInterpritation())) {
                                answerText += answer.getContents() + "<br/>";
                            } else {
                                answerText += answer.getAnswerInterpritation() + "<br/>";
                            }
                        }
                    } else {
                        answerText += objectAnswer.getAnswerContents();
                    }
                }
                newDesicionRow = newDesicionRow.replaceAll("%desicion_name%", answerText);
                resultDesicionTable += newDesicionRow;

            }

            ReportUtil.replaceAllLabel(template, "%rows%", resultDesicionTable);

            String tableDocumentRow = ReportUtil.extractBookmarkForTable(template, "document_table_rows", "%rows%");
            String resultDocument = "";
            String newRowDocument = "";

            List documentationAnswerList = buildingObjectManager.getAnswersByDocumentation(buildingObjectId, "0");
            String documentType = "";
            for (int i = 0; i < documentationAnswerList.size(); i++) {
                ObjectAnswer objectAnswer = (ObjectAnswer) documentationAnswerList.get(i);

                if (!documentType.equals(objectAnswer.getQuestion().getDocumentType().toString()) || i == 0) {
                    //marking the new documentation type
                    documentType = objectAnswer.getQuestion().getDocumentType().toString();

                    newRowDocument = tableDocumentRow.replaceAll("%doc_num%", "");

                    newRowDocument = newRowDocument.replaceAll("%doc_name%", "<b>" + documentType + "</b>");
                    newRowDocument = newRowDocument.replaceAll("%doc_answer%", "");
                    newRowDocument = newRowDocument.replaceAll("%doc_comment%", "");
                    resultDocument += newRowDocument;

                }
                //number
                newRowDocument = tableDocumentRow.replaceAll("%doc_num%", String.valueOf(i + 1));


                newRowDocument = newRowDocument.replaceAll("%doc_name%", objectAnswer.getQuestion().getContents());

                //answer
                String answerText = "";
                List answers = objectAnswer.getAnswers();
                if (answers.size() > 0 && (!((Answer) answers.get(0)).getAnswerId().equals(new Integer(-1)) && answers.size() == 1)) {
                    for (int j = 0; j < answers.size(); j++) {
                        Answer answer = (Answer) answers.get(j);
                        if (answer.getAnswerInterpritation() == null || "".equals(answer.getAnswerInterpritation())) {
                            answerText += answer.getContents() + "<br/>";
                        } else {
                            answerText += answer.getAnswerInterpritation() + "<br/>";
                        }
                    }
                } else {
                    answerText += objectAnswer.getAnswerContents() + "<br/>";
                }

                newRowDocument = newRowDocument.replaceAll("%doc_answer%", answerText);
                newRowDocument = newRowDocument.replaceAll("%doc_comment%", objectAnswer.getAnswerComment() != null ? objectAnswer.getAnswerComment() : "");
                resultDocument += newRowDocument;

            }
            ReportUtil.replaceAllLabel(template, "%rows%", resultDocument);

            //grouping defects construction varities


            String tableConstructionDefectBlock = ReportUtil.extractBookmark(template, "constructionType_defects", "%defectBlocks%");


            String resultConstructionDefectBlock = "";
            String newDefectBlock = "";



            for (int l = 0; l < objectConstructionTypes.size(); l++) {


                ConstructionType constructionType = (ConstructionType) objectConstructionTypes.get(l);
                newDefectBlock = tableConstructionDefectBlock.replaceAll("%defect_construction_type%", constructionType.toString());
                //filling the current table by defects
                StringBuilder newDefectBlockBuilder = new StringBuilder(newDefectBlock);


                String tableDefectRow = ReportUtil.extractBookmarkForTableInTable2(newDefectBlockBuilder, "example_defects_table_rows", "%rowsDefects%");


                newDefectBlock = newDefectBlockBuilder.toString();
                String resultDefect = "";
                String newRowDefect = "";
                List constructionVarities = buildingObjectManager.getObjectConstructionsByTypeId(buildingObjectId, constructionType.getConstructionTypeId().toString());
                int num = 0;
                List constructionExamples = new ArrayList();
                for (int j = 0; j < constructionVarities.size(); j++) {
                    ObjectConstruction objectConstruction = (ObjectConstruction) constructionVarities.get(j);
                    constructionExamples.addAll(objectConstruction.getConstructionExamples());
                }
                for (int k = 0; k < constructionExamples.size(); k++) {
                    ConstructionExample constructionExample = (ConstructionExample) constructionExamples.get(k);
                    num++;
                    newRowDefect = tableDefectRow.replaceAll("%num%", String.valueOf(num));
                    String exampleName = "";
                    if (constructionExample.getExampleName() == null) {
                        exampleName = String.valueOf(constructionExample.getExampleRelativeNumber());
                    } else {
                        exampleName = constructionExample.getExampleName();
                    }
                    newRowDefect = newRowDefect.replaceAll("%example_name%", exampleName);
                    newRowDefect = newRowDefect.replaceAll("%comment%", "");

                    //filling defect inner table
                    StringBuilder newRowDefectBuilder = new StringBuilder(newRowDefect);

                    String tableInnerDefectRow = ReportUtil.extractBookmarkForTableInTable(newRowDefectBuilder, "inner_defect_table_rows", "%rowsInnerDefects%");
                    newRowDefect = newRowDefectBuilder.toString();
                    String resultInnerDefect = "";
                    String newRowInnerDefect = "";
                    List defectList = constructionExample.getExampleDefects();
                    List defectListZone = constructionExample.getExampleDefectsZone();

                    if (defectListZone.size() != 0 && defectList.size() == 0) {
                        newRowDefectBuilder = new StringBuilder(newRowDefect);
                        ReportUtil.replaceAllLabel(newRowDefectBuilder, "%rowsInnerDefects%", "Имеются групповые дефекты");
                        newRowDefect = newRowDefectBuilder.toString();
                    } else {
                        if (defectList.size() == 0 && defectListZone.size() == 0) {
                            if (constructionExample.isNoDeffects()) {
                                //marking the construction example as without any defects
                                newRowDefectBuilder = new StringBuilder(newRowDefect);
                                ReportUtil.replaceAllLabel(newRowDefectBuilder, "%rowsInnerDefects%", "Дефектов не обнаружено");
                                newRowDefect = newRowDefectBuilder.toString();
                            } else {
                                newRowDefectBuilder = new StringBuilder(newRowDefect);
                                ReportUtil.replaceAllLabel(newRowDefectBuilder, "%rowsInnerDefects%", "Не обследовано!");
                                newRowDefect = newRowDefectBuilder.toString();
                            }
                        } else {
                            //retrieving all information about defects and adding it to the inner table for the current construction example
                            for (int s = 0; s < defectList.size(); s++) {
                                String defectText = "";
                                String extraComment = "";
                                ConstructionDefect constructionDefect = (ConstructionDefect) defectList.get(s);
                                defectText += constructionDefect.getDefectType() + "<br/>" + constructionDefect.getDefectVarity() + "<br/>";
                                extraComment += (constructionExample.getExampleName() != null ? constructionExample.getExampleName() : "Конструкция " + String.valueOf(constructionExample.getExampleRelativeNumber())) + ". " + constructionDefect.getDefectType() + " " + constructionDefect.getDefectVarity() + " ";


                                extraComment += (constructionDefect.getComment() != null && !constructionDefect.getComment().equals("")) ? "<br>" + constructionDefect.getComment() + " " : "";


                                List defectParameters = constructionDefect.getDefectParameters();
                                for (int m = 0; m < defectParameters.size(); m++) {
                                    DefectParameter defectParameter = (DefectParameter) defectParameters.get(m);
                                    nf.setMaximumFractionDigits(2);
                                    defectText += defectParameter.getParameter() + " - " + nf.format(defectParameter.getParameterValue()) + " " + defectParameter.getParameter().getMeasure() + "<br/>";
                                    extraComment += "<br>" + defectParameter.getParameter() + " - " + nf.format(defectParameter.getParameterValue()) + " " + defectParameter.getParameter().getMeasure();
                                }
                                defectText += "<br/>" + constructionDefect.getComment() + "<br/>";
                                DefectPhoto defectPhoto = new DefectPhoto();
                                if (constructionDefect.getPhotoBlob() != null) {

                                    defectPhoto.setPhotoBlob(constructionDefect.getPhotoBlob());
                                    defectPhoto.setWayToPhoto(constructionDefect.getWayToPhoto());
                                    defectPhoto.setPhotoRefference("Фото " + (l + 1) + "." + (k + 1) + "." + (s + 1));
                                    defectPhoto.setExtraComment(extraComment);
                                    defectPhotoList.add(defectPhoto);


                                } else {
                                    defectPhoto.setPhotoRefference("-");
                                }

                                //defect cell
                                newRowInnerDefect = tableInnerDefectRow.replaceAll("%defect_name%", defectText);

                                //defect photo cell

                                newRowInnerDefect = newRowInnerDefect.replaceAll("%defect_photo%", defectPhoto.getPhotoRefference());
                                resultInnerDefect += newRowInnerDefect;

                            }
                            newRowDefectBuilder = new StringBuilder(newRowDefect);

                            ReportUtil.replaceAllLabel(newRowDefectBuilder, "%rowsInnerDefects%", resultInnerDefect);
                            newRowDefect = newRowDefectBuilder.toString();


                        }

                    }

                    //construction example danger category
                    String exampleDangerCategory = "";
                    if (constructionExample.getDangerCategory() != null) {
                        exampleDangerCategory = constructionExample.getDangerCategory().toString();
                    }
                    newRowDefect = newRowDefect.replaceAll("%example_danger%", exampleDangerCategory);
                    resultDefect += newRowDefect;
                }
                newDefectBlockBuilder = new StringBuilder(newDefectBlock);
                ReportUtil.replaceAllLabel(newDefectBlockBuilder, "%rowsDefects%", resultDefect);
                newDefectBlock = newDefectBlockBuilder.toString();
                newDefectBlockBuilder = new StringBuilder(newDefectBlock);


                tableDefectRow = ReportUtil.extractBookmarkForTable(newDefectBlockBuilder, "zone_defects_table_rows", "%zoneRowsDefects%");

                newDefectBlock = newDefectBlockBuilder.toString();
                resultDefect = "";
                List constructionDefectZones = constructionDefectManager.getConstructionDefectZonesBuConstrType(constructionType.getConstructionTypeId().toString(), buildingObjectId, FileHelper.getCurrentPath(request));
                num = 0;
                for (int k = 0; k < constructionDefectZones.size(); k++) {
                    ConstructionDefectZone constructionDefectZone = (ConstructionDefectZone) constructionDefectZones.get(k);
                    List examplesList = constructionDefectManager.getExamplesByDefect(constructionDefectZone.getUniqueForExamples(), FileHelper.getCurrentPath(request));
                    String examples = "";
                    for (int g = 0; g < examplesList.size(); g++) {
                        ConstructionExample constructionExample = constructionExampleManager.getConstructionExample(examplesList.get(g).toString());
                        if (constructionExample.getExampleName() == null || constructionExample.getExampleName().trim().equals("")) {
                            examples += constructionExample.getExampleRelativeNumber();
                        } else {
                            examples += constructionExample.getExampleName();
                        }

                        if (g != examplesList.size() - 1) {
                            examples += ";  ";
                        }
                    }
                    num++;
                    String defectText = constructionDefectZone.getDefectType() + "<br/>" + constructionDefectZone.getDefectVarity() + "<br/>";
                    List defectParameters = constructionDefectZone.getDefectParameters();
                    for (int m = 0; m < defectParameters.size(); m++) {
                        DefectParameterZone defectParameter = (DefectParameterZone) defectParameters.get(m);
                        nf.setMaximumFractionDigits(2);
                        defectText += "<br>" + defectParameter.getParameter() + " : " + nf.format(defectParameter.getParameterValue()) + "-" + nf.format(defectParameter.getParameterValueSecond()) + " " + defectParameter.getParameter().getMeasure();
                    }
                    defectText += "<br/>" + constructionDefectZone.getComment() + "<br/>";
                    newRowDefect = tableDefectRow.replaceAll("%num%", String.valueOf(num));
                    newRowDefect = newRowDefect.replaceAll("%defect_zone%", defectText);
                    newRowDefect = newRowDefect.replaceAll("%examples%", examples);
                    resultDefect += newRowDefect;
                }
                newDefectBlockBuilder = new StringBuilder(newDefectBlock);
                ReportUtil.replaceAllLabel(newDefectBlockBuilder, "%zoneRowsDefects%", resultDefect);
                newDefectBlock = newDefectBlockBuilder.toString();

                //power table filling
                newDefectBlockBuilder = new StringBuilder(newDefectBlock);


                String tableStrengthRow = ReportUtil.extractBookmarkForTable(newDefectBlockBuilder, "strength_table_rows", "%rowsStrengths%");


                newDefectBlock = newDefectBlockBuilder.toString();
                String resultStrength = "";
                String newRowStrength = "";
                constructionVarities = buildingObjectManager.getObjectConstructionsByTypeId(buildingObjectId, constructionType.getConstructionTypeId().toString());
                num = 0;


                for (int k = 0; k < constructionExamples.size(); k++) {

                    ConstructionExample constructionExample = (ConstructionExample) constructionExamples.get(k);
                    if (constructionExample.getStrengthPoints().size() != 0) {
                        num++;
                        newRowStrength = tableStrengthRow.replaceAll("%strength_number%", String.valueOf(num));
                        newRowStrength = newRowStrength.replaceAll("%strength_point%", constructionExample.getExampleName() != null ? constructionExample.getExampleName() : String.valueOf(constructionExample.getExampleRelativeNumber()));
                        List strengthPoints = constructionExample.getStrengthPoints();

                        //filling inner table
                        StringBuilder newRowStrengthBuilder = new StringBuilder(newRowStrength);


                        String tableStrengthInnerRow = ReportUtil.extractBookmarkForTableInTable(newRowStrengthBuilder, "strength_table_inner_rows", "%rowsStrengthsInner%");


                        newRowStrength = newRowStrengthBuilder.toString();
                        String resultStrengthInner = "";
                        String newRowStrengthInner = "";

                        for (int i = 0; i < strengthPoints.size(); i++) {
                            Strength strength = (Strength) strengthPoints.get(i);
                            newRowStrengthInner = tableStrengthInnerRow.replaceAll("%strength_marking%", strength.getPointRelativeNumber().toString());
                            newRowStrengthInner = newRowStrengthInner.replaceAll("%strength_value%", String.valueOf(strength.getStrengthValue()));
                            resultStrengthInner += newRowStrengthInner;
                        }
                        newRowStrengthBuilder = new StringBuilder(newRowStrength);
                        ReportUtil.replaceAllLabel(newRowStrengthBuilder, "%rowsStrengthsInner%", resultStrengthInner);
                        newRowStrength = newRowStrengthBuilder.toString();
                        resultStrength += newRowStrength;


                    }
                }

                newDefectBlockBuilder = new StringBuilder(newDefectBlock);
                if (!"".equals(resultStrength)) {
                    ReportUtil.replaceAllLabel(newDefectBlockBuilder, "%rowsStrengths%", resultStrength);
                } else {
                    //removing tables head from report, because it's empty
                    //ReportUtil.extractBookmarkForTable(newDefectBlockBuilder, "main_strength_table", "");

                }


                newDefectBlock = newDefectBlockBuilder.toString();
                //defect rreason table filling
                newDefectBlockBuilder = new StringBuilder(newDefectBlock);


                String tableReasonRow = ReportUtil.extractBookmarkForTable2(newDefectBlockBuilder, "common_reason_table_rows", "%rowsReasons%");
                newDefectBlock = newDefectBlockBuilder.toString();
                String resultReason = "";
                String newRowReason = "";

                StringBuilder newReasonRowBuilder = new StringBuilder();
                String tableReasonInnerRow = "";

                List reasonList = reasonManager.getReasonsForConstrcutionsInObject(constructionType.getConstructionTypeId().toString(), buildingObjectId);
                List otherReasonList = reasonManager.getOtherReasonsForConstrcutionsInObject(constructionType.getConstructionTypeId().toString(), buildingObjectId);
                reasonList.addAll(otherReasonList);
                for (int i = 0; i < reasonList.size(); i++) {

                    newRowReason = tableReasonRow;
                    newReasonRowBuilder = new StringBuilder(newRowReason);


                    tableReasonInnerRow = ReportUtil.extractBookmarkForTableInTableFirstColumn(newReasonRowBuilder, "defect_description_reason_table_rows", "%rowsReasonsInner%");


                    String resultReasonInner = "";
                    String newRowReasonInner = "";
                    List defectList;
                    Reason reason = new Reason();
                    String otherReason = "";
                    boolean standartReason = false;
                    if (reasonList.get(i) instanceof Reason) {
                        reason = (Reason) reasonList.get(i);

                        defectList = constructionDefectManager.getConstructionDefectsForReason(reason.getReasonId().toString(), constructionType.getConstructionTypeId().toString(), buildingObjectId);
                        standartReason = true;
                    } else {
                        standartReason = false;
                        otherReason = (String) reasonList.get(i);
                        defectList = constructionDefectManager.getConstructionDefectsForOtherReason(otherReason, constructionType.getConstructionTypeId().toString(), buildingObjectId);

                    }

                    //TODO find out how to get maximum if one parameter is maximum and the other one is small  and make it by sql query
                    double maxParameter = 0;
                    Integer currentDefectTypeId = null;
                    Integer currentDefectVarityId = null;
                    List finalDefectList = new ArrayList();
                    ConstructionDefect curConstructionDefect = defectList.size() != 0 ? (ConstructionDefect) defectList.get(0) : null;
                    for (int j = 0; j < defectList.size(); j++) {
                        ConstructionDefect constructionDefect = (ConstructionDefect) defectList.get(j);
                        if ((!constructionDefect.getDefectType().getDefectTypeId().equals(currentDefectTypeId) || !constructionDefect.getDefectVarity().getVarityId().equals(currentDefectVarityId))) {
                            currentDefectTypeId = constructionDefect.getDefectType().getDefectTypeId();
                            currentDefectVarityId = constructionDefect.getDefectVarity().getVarityId();
                            finalDefectList.add(curConstructionDefect);
                            curConstructionDefect = constructionDefect;
                            maxParameter = 0;
                        }
                        List parameterList = constructionDefect.getDefectParameters();
                        for (int k = 0; k < parameterList.size(); k++) {
                            DefectParameter defectParameter = (DefectParameter) parameterList.get(k);
                            if (maxParameter < defectParameter.getParameterValue()) {
                                maxParameter = defectParameter.getParameterValue();
                            }
                        }

                    }
                    defectList = finalDefectList;
                    for (int j = 0; j < defectList.size(); j++) {
                        ConstructionDefect constructionDefect = (ConstructionDefect) defectList.get(j);
                        //constructiondefect
                        ConstructionExample constructionExample = constructionExampleManager.getConstructionExample(constructionDefect.getExampleId().toString());
                        String defectText = constructionDefect.getDefectType().toString() + " " + constructionDefect.getDefectVarity() + " <br/>";
                        List parameterList = constructionDefect.getDefectParameters();
                        for (int k = 0; k < parameterList.size(); k++) {
                            DefectParameter defectParameter = (DefectParameter) parameterList.get(k);
                            defectText += defectParameter.getParameter() + " - " + nf.format(defectParameter.getParameterValue()) + " " + defectParameter.getParameter().getMeasure() + "<br/>";
                        }

                        newRowReasonInner = tableReasonInnerRow.replaceAll("%defect_name%", defectText);
                        newRowReasonInner = newRowReasonInner.replaceAll("%defect_category%", constructionDefect.getDangerCategory().toString());
                        resultReasonInner += newRowReasonInner;


                    }

                    ReportUtil.replaceAllLabel(newReasonRowBuilder, "%rowsReasonsInner%", resultReasonInner);
                    newRowReason = newReasonRowBuilder.toString();

                    if (standartReason) {
                        newRowReason = newRowReason.replaceAll("%defect_reason%", reason.toString());
                    } else {
                        newRowReason = newRowReason.replaceAll("%defect_reason%", otherReason);
                    }
                    resultReason += newRowReason;

                }


                newDefectBlockBuilder = new StringBuilder(newDefectBlock);
                if (!"".equals(resultReason)) {
                    ReportUtil.replaceAllLabel(newDefectBlockBuilder, "%rowsReasons%", resultReason);
                } else {
                    //removing tables head from report, because it's empty
                    ReportUtil.extractBookmarkForTable(newDefectBlockBuilder, "main_strength_table", "");

                }
                //defining construction type condition


                String tableCondition = ReportUtil.extractBookmarkForTable(newDefectBlockBuilder, "common_condition_table", "%rowsCondition%");
                newDefectBlock = newDefectBlockBuilder.toString();
                String resultCondition = "";
                String newRowCondition = "";

                Integer bNumber = buildingObjectManager.getObjectConstructionTypeExampleByCategory(buildingObjectId, constructionType.getConstructionTypeId().toString(), "B");
                Integer aNumber = buildingObjectManager.getObjectConstructionTypeExampleByCategory(buildingObjectId, constructionType.getConstructionTypeId().toString(), "A");
                Integer commonNumber = buildingObjectManager.getObjectConstructionTypeExampleNum(buildingObjectId, constructionType.getConstructionTypeId().toString());
                Integer cNumber = new Integer(commonNumber - bNumber - aNumber);
                double aPercent = (aNumber.floatValue() / commonNumber.floatValue()) * 100;
                double bPercent = (bNumber.floatValue() / commonNumber.floatValue()) * 100;
                double cPercent = (cNumber.floatValue() / commonNumber.floatValue()) * 100;
                newRowCondition = tableCondition.replaceAll("%construction_type%", constructionType.toString());
                StringBuilder newRowConditionBuilder = new StringBuilder(newRowCondition);

                //filling inner table


                String tableConditionInner = ReportUtil.extractBookmarkForTableInTable(newRowConditionBuilder, "private_condition_table", "%rowsConditionInner%");
                newRowCondition = newRowConditionBuilder.toString();
                String resultConditionInner = "";
                String newRowConditionInner = "";


                if (aPercent > 0) {
                    newRowConditionInner = tableConditionInner.replaceAll("%condition_danger%", "Неработоспособное состояние");
                    newRowConditionInner = newRowConditionInner.replaceAll("%condition_number%", aNumber + "/" + aPercent + "%");
                    resultConditionInner += newRowConditionInner;
                }

                if (bPercent > 0) {
                    newRowConditionInner = tableConditionInner.replaceAll("%condition_danger%", "Ограниченно работоспособное состояние");
                    newRowConditionInner = newRowConditionInner.replaceAll("%condition_number%", bNumber + "/" + bPercent + "%");
                    resultConditionInner += newRowConditionInner;
                }

                if (cPercent > 0) {
                    newRowConditionInner = tableConditionInner.replaceAll("%condition_danger%", "Работоспособное состояние");
                    newRowConditionInner = newRowConditionInner.replaceAll("%condition_number%", cNumber + "/" + cPercent + "%");
                    resultConditionInner += newRowConditionInner;
                }
                newRowConditionBuilder = new StringBuilder(newRowCondition);
                ReportUtil.replaceAllLabel(newRowConditionBuilder, "%rowsConditionInner%", resultConditionInner);
                newRowCondition = newRowConditionBuilder.toString();
                resultCondition += newRowCondition;
                newDefectBlockBuilder = new StringBuilder(newDefectBlock);
                ReportUtil.replaceAllLabel(newDefectBlockBuilder, "%rowsCondition%", resultCondition);
                ReportUtil.replaceAllLabel(newDefectBlockBuilder, "%cond_construction_type%", constructionType.toString());
                newDefectBlock = newDefectBlockBuilder.toString();
                resultConstructionDefectBlock += newDefectBlock;


            }


            ReportUtil.replaceAllLabel(template, "%defectBlocks%", resultConstructionDefectBlock);

//            //adding recomendations


            String tableRecomendation = ReportUtil.extractBookmark(template, "recomendation_table", "%rowsRecomendation%");


            String resultRecomendation = "";
            String newRowRecomendation = "";

            for (int l = 0; l < objectConstructionTypes.size(); l++) {
                ConstructionType constructionType = (ConstructionType) objectConstructionTypes.get(l);
                //getting recomendations
                List defectRecomendationList = defectRecomendationManager.getRecomendationsForConstructionType(constructionType.getConstructionTypeId().toString(), buildingObjectId);

                String recomendationText = "";

                if (defectRecomendationList.size() != 0) {
                    recomendationText += constructionType.toString() + "<br>";
                    for (int i = 0; i < defectRecomendationList.size(); i++) {
                        DefectRecomendation defectRecomendation = (DefectRecomendation) defectRecomendationList.get(i);
                        recomendationText += "- " + defectRecomendation.getContent() + "<br/>";

                    }
                    newRowRecomendation = tableRecomendation.replaceAll("%recomendation_body%", recomendationText);
                    // ReportUtil.replaceAllLabel(template, "%recomendation_body%", recomendationText);

                    resultRecomendation += newRowRecomendation.replaceAll("%recomendation_construction_type%", constructionType.toString());

                }

            }

            ReportUtil.replaceAllLabel(template, "%rowsRecomendation%", resultRecomendation);


            if (defectPhotoList.size() > 0) {


                ReportUtil.extractBookmarkForImageList(template, "defect_illustration", "%illustrations%");
                String resultPhoto = "";
                String newRowPhoto = "";
                for (int i = 0; i < defectPhotoList.size(); i++) {
                    DefectPhoto defectPhoto = (DefectPhoto) defectPhotoList.get(i);
                    File filePhoto = new File(defectPhoto.getWayToPhoto());
                    if (filePhoto.exists()) {
                        filePhoto.delete();
                    }
                    filePhoto.createNewFile();
                    FileOutputStream fileOutputStream = new FileOutputStream(defectPhoto.getWayToPhoto());
                    Blob blob = defectPhoto.getPhotoBlob();
                    byte[] bufer = new byte[62000];
                    InputStream inputStream = blob.getBinaryStream();
                    while (inputStream.read(bufer) != -1) {
                        fileOutputStream.write(bufer);
                    }
                    inputStream.close();
                    fileOutputStream.close();
                    Image image = Image.getInstance(defectPhoto.getWayToPhoto());
                    newRowPhoto = ReportUtil.createPhoto("defect_illustration", image.height(), image.width(), defectPhoto.getWayToPhoto());
                    newRowPhoto += "\n<p class=3DMsoNormal align=3Dcenter style=3D'text-align:center'>" + (defectPhoto.getPhotoRefference() + ". " + defectPhoto.getExtraComment()) + "</p>\n";
                    ReportUtil.insertImage(defectPhoto.getWayToPhoto(), defectPhoto.getPhotoBlob().getBytes(1, (int) defectPhoto.getPhotoBlob().length()), template);
                    resultPhoto += newRowPhoto;
                }
                ReportUtil.replaceAllLabel(template, "%illustrations%", resultPhoto);
            } else {

            }


            ReportUtil.extractBookmarkForImageList(template, "object_illustration", "%objectIllustrations%");
            String resultObjectPhoto = "";
            String newRowObjectPhoto = "";
            List objectPhotoes = buildingObject.getPhotoes();
            for (int i = 0; i < objectPhotoes.size(); i++) {
                ObjectPhoto objectPhoto = (ObjectPhoto) objectPhotoes.get(i);
                File filePhoto = new File(objectPhoto.getWayToPhoto());
                if (filePhoto.exists()) {
                    filePhoto.delete();
                }
                filePhoto.createNewFile();
                FileOutputStream fileOutputStream = new FileOutputStream(objectPhoto.getWayToPhoto());
                Blob blob = objectPhoto.getPhotoBlob();
                byte[] bufer = new byte[62000];
                InputStream inputStream = blob.getBinaryStream();
                while (inputStream.read(bufer) != -1) {
                    fileOutputStream.write(bufer);
                }
                inputStream.close();
                fileOutputStream.close();

                Image image = Image.getInstance(objectPhoto.getWayToPhoto());
                newRowObjectPhoto = ReportUtil.createPhoto("object_illustration", image.height(), image.width(), objectPhoto.getWayToPhoto());
                ReportUtil.insertImage(objectPhoto.getWayToPhoto(), objectPhoto.getPhotoBlob().getBytes(1, (int) objectPhoto.getPhotoBlob().length()), template);
                resultObjectPhoto += newRowObjectPhoto;
            }
            ReportUtil.replaceAllLabel(template, "%objectIllustrations%", resultObjectPhoto);



             List levelPlanList = buildingObject.getLevelPlanList();
            result = "";
            for (int i = 0; i < levelPlanList.size(); i++) {
                LevelPlan levelPlan = (LevelPlan) levelPlanList.get(i);


                String newInformation = levelPlan.getComment();
                String savePathImage = FileHelper.getCurrentPath(request) + levelPlan.getWayToLevelPlanImage();

                byte[]  bytes = createImage(levelPlan.getWayToLevelPlan(), levelPlan.getWayToLevelPlanImage(), FileHelper.getCurrentPath(request));

                Image image = Image.getInstance(savePathImage);
                newInformation += ReportUtil.createPhoto("CompanyLicense", image.height(), image.width(), savePathImage);
                ReportUtil.insertImage(savePathImage,bytes, template);
                result += newInformation;


            }

             ReportUtil.replaceAllLabel(template, "LevelPlanImages", result);






            List objectExampleList = objectConstructionManager.getObjectConstructions(buildingObject.getObjectId());

           // ReportUtil.extractBookmark(template, "defectMapImages", "%defect_Map_Images%");

            String extractBookmark = ReportUtil.extractBookmark(template, "defectMapBookMark", "%defect_Map_Book_Mark%");
            result = "";
            String res = "";
            for (int i = 0; i < objectExampleList.size(); i++) {

                ObjectConstruction objectConstruction = (ObjectConstruction) objectExampleList.get(i);
                String newInformation = extractBookmark.replaceAll("defectMapIndex", String.valueOf(i + 1));
                newInformation = newInformation.replaceAll("defectMapDescription", objectConstruction.getDescription());
                result += newInformation;

                String savePathImage = FileHelper.getCurrentPath(request) + objectConstruction.getWayToDefectMapImage();



                newInformation = "<br><br>";
                byte[] bytes = createImage(objectConstruction.getWayToDefectMap(), objectConstruction.getWayToDefectMapImage(), FileHelper.getCurrentPath(request));

                Image image = Image.getInstance(savePathImage);
                newInformation += ReportUtil.createPhoto("CompanyLicense", image.height(), image.width(), savePathImage);

                ReportUtil.insertImage(savePathImage, bytes, template);



                res += newInformation;

            }



            ReportUtil.replaceAllLabel(template, "%defect_Map_Book_Mark%", result);
            ReportUtil.replaceAllLabel(template, "defectMapImages", res);
           // ReportUtil.replaceAllLabel(template, "%defect_Map_Images%", res);



            //correcting russian encoding
            template = new StringBuilder(StringUtil.modifyRussianEncoding(template.toString()));

            File tmpFile = new File(filename);

            FileOutputStream fileOutputStream = new FileOutputStream(tmpFile.getAbsolutePath());
            fileOutputStream.write(template.toString().getBytes());
            fileOutputStream.close();
        }

        return new ModelAndView("redirect:" + FileHelper.getFileName(filename));


    }


    private byte[] createImage(String getFileName, String setFileName, String fullPath) throws Exception {


        try {

            ObjectInputStream in = new ObjectInputStream(new FileInputStream(fullPath+getFileName));
            try {

                ObjectPicture objectPicture = (ObjectPicture) in.readObject();
                if (objectPicture != null) {



                    return saveToJPEG(objectPicture, setFileName, fullPath);


                }
            } catch (ClassNotFoundException e) {

            }
            in.close();
        } catch (IOException e) {

        }

        return null;
    }


    public static byte[] saveToJPEG(ObjectPicture objectPicture, String setFileName, String fullPath) throws Exception {


        String savePathImage = fullPath + setFileName;
        String loadPath = fullPath + "blank.jpg";




        InputStream imageStream = new FileInputStream(loadPath);
        java.awt.Image image = ImageIO.read(imageStream);
        objectPicture.drawObjects(image.getGraphics(),0,0);

        int w = image.getWidth(null);
        int h = image.getHeight(null);

        BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);

        Graphics2D g2 = bi.createGraphics();
        g2.drawImage(image, 0, 0, null);
        FileOutputStream fileOutputStream = new FileOutputStream(savePathImage);
        ImageIO.write(bi, "jpg", fileOutputStream);
        imageStream.close();
        fileOutputStream.close();

        InputStream imStream = new FileInputStream(savePathImage);
        byte[] bytes=new byte[imStream.available()];
        imStream.read(bytes);
        imStream.close();


        return bytes;
    }


}
TOP

Related Classes of com.vst.webapp.action.RTFListController

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.