Search in sources :

Example 11 with AxelorException

use of com.axelor.exception.AxelorException in project axelor-open-suite by axelor.

the class DataImportServiceImpl method process.

private List<CSVInput> process(DataReaderService reader, AdvancedImport advancedImport) throws AxelorException, IOException, ClassNotFoundException {
    String[] sheets = reader.getSheetNames();
    boolean isConfig = advancedImport.getIsConfigInFile();
    int linesToIgnore = advancedImport.getNbOfFirstLineIgnore();
    boolean isTabConfig = advancedImport.getIsFileTabConfigAdded();
    List<CSVInput> inputList = new ArrayList<CSVInput>();
    validatorService.sortFileTabList(advancedImport.getFileTabList());
    for (FileTab fileTab : advancedImport.getFileTabList()) {
        if (!Arrays.stream(sheets).anyMatch(sheet -> sheet.equals(fileTab.getName()))) {
            continue;
        }
        this.initializeVariables();
        String fileName = createDataFileName(fileTab);
        csvInput = this.createCSVInput(fileTab, fileName);
        ifList = new ArrayList<String>();
        try (CSVWriter csvWriter = new CSVWriter(new FileWriter(new File(dataDir, fileName)), CSV_SEPRATOR)) {
            int totalLines = reader.getTotalLines(fileTab.getName());
            if (totalLines == 0) {
                continue;
            }
            Mapper mapper = advancedImportService.getMapper(fileTab.getMetaModel().getFullName());
            List<String[]> allLines = new ArrayList<String[]>();
            int startIndex = isConfig ? 1 : linesToIgnore;
            String[] row = reader.read(fileTab.getName(), startIndex, 0);
            String[] headers = this.createHeader(row, fileTab, isConfig, mapper);
            allLines.add(headers);
            int tabConfigRowCount = 0;
            if (isTabConfig) {
                String[] objectRow = reader.read(fileTab.getName(), 0, 0);
                tabConfigRowCount = advancedImportService.getTabConfigRowCount(fileTab.getName(), reader, totalLines, objectRow);
            }
            startIndex = isConfig ? tabConfigRowCount + 3 : fileTab.getAdvancedImport().getIsHeader() ? linesToIgnore + 1 : linesToIgnore;
            for (int line = startIndex; line < totalLines; line++) {
                String[] dataRow = reader.read(fileTab.getName(), line, row.length);
                if (dataRow == null || Arrays.stream(dataRow).allMatch(StringUtils::isBlank)) {
                    continue;
                }
                String[] data = this.createData(dataRow, fileTab, isConfig, mapper);
                allLines.add(data);
            }
            csvWriter.writeAll(allLines);
            csvWriter.flush();
        }
        inputList.add(csvInput);
        importContext.put("ifConditions" + fileTab.getId(), ifList);
        importContext.put("jsonContextValues" + fileTab.getId(), createJsonContext(fileTab));
        importContext.put("actionsToApply" + fileTab.getId(), fileTab.getActions());
        XStream stream = XStreamUtils.createXStream();
        stream.processAnnotations(CSVConfig.class);
        LOG.debug("CSV Config created :" + "\n" + stream.toXML(csvInput));
    }
    return inputList;
}
Also used : XStream(com.thoughtworks.xstream.XStream) Arrays(java.util.Arrays) Date(java.util.Date) Inject(com.google.inject.Inject) CSVInput(com.axelor.data.csv.CSVInput) LoggerFactory(org.slf4j.LoggerFactory) Mapper(com.axelor.db.mapper.Mapper) JsonContext(com.axelor.rpc.JsonContext) FileField(com.axelor.apps.base.db.FileField) ByteArrayInputStream(java.io.ByteArrayInputStream) Map(java.util.Map) Inflector(com.axelor.common.Inflector) ZipEntry(java.util.zip.ZipEntry) TranslationService(com.axelor.apps.tool.service.TranslationService) ZipException(java.util.zip.ZipException) MethodHandles(java.lang.invoke.MethodHandles) CSVImporter(com.axelor.data.csv.CSVImporter) StringUtils(com.axelor.common.StringUtils) DataAdapter(com.axelor.data.adapter.DataAdapter) MetaModel(com.axelor.meta.db.MetaModel) List(java.util.List) CSVBind(com.axelor.data.csv.CSVBind) MetaSelectRepository(com.axelor.meta.db.repo.MetaSelectRepository) Entry(java.util.Map.Entry) FileTab(com.axelor.apps.base.db.FileTab) AdvancedImport(com.axelor.apps.base.db.AdvancedImport) ZipInputStream(java.util.zip.ZipInputStream) MetaSelectItem(com.axelor.meta.db.MetaSelectItem) Property(com.axelor.db.mapper.Property) SimpleDateFormat(java.text.SimpleDateFormat) HashMap(java.util.HashMap) ImporterListener(com.axelor.apps.base.service.imports.listener.ImporterListener) ArrayList(java.util.ArrayList) Strings(com.google.common.base.Strings) AxelorException(com.axelor.exception.AxelorException) Files(com.google.common.io.Files) CollectionUtils(org.apache.commons.collections.CollectionUtils) XStreamUtils(com.axelor.data.XStreamUtils) MetaSelectItemRepository(com.axelor.meta.db.repo.MetaSelectItemRepository) DataReaderFactory(com.axelor.apps.tool.reader.DataReaderFactory) MetaFiles(com.axelor.meta.MetaFiles) Logger(org.slf4j.Logger) Model(com.axelor.db.Model) FileWriter(java.io.FileWriter) TraceBackService(com.axelor.exception.service.TraceBackService) FileOutputStream(java.io.FileOutputStream) CSVWriter(com.opencsv.CSVWriter) IOException(java.io.IOException) FileUtils(org.apache.commons.io.FileUtils) JavaTimeAdapter(com.axelor.data.adapter.JavaTimeAdapter) FileInputStream(java.io.FileInputStream) File(java.io.File) DataReaderService(com.axelor.apps.tool.reader.DataReaderService) MetaFile(com.axelor.meta.db.MetaFile) FileFieldRepository(com.axelor.apps.base.db.repo.FileFieldRepository) CSVConfig(com.axelor.data.csv.CSVConfig) MetaSelect(com.axelor.meta.db.MetaSelect) Context(com.axelor.rpc.Context) XStream(com.thoughtworks.xstream.XStream) FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) CSVInput(com.axelor.data.csv.CSVInput) CSVWriter(com.opencsv.CSVWriter) Mapper(com.axelor.db.mapper.Mapper) FileTab(com.axelor.apps.base.db.FileTab) File(java.io.File) MetaFile(com.axelor.meta.db.MetaFile)

Example 12 with AxelorException

use of com.axelor.exception.AxelorException in project axelor-open-suite by axelor.

the class PrintServiceImpl method generatePDF.

@Override
@Transactional
public Map<String, Object> generatePDF(Print print) throws AxelorException {
    try {
        print = printRepo.find(print.getId());
        String html = generateHtml(print);
        ByteArrayOutputStream pdfOutputStream = new ByteArrayOutputStream();
        try (PdfDocument pdfDoc = new PdfDocument(new PdfWriter(pdfOutputStream))) {
            pdfDoc.setDefaultPageSize(print.getDisplayTypeSelect() == PrintRepository.DISPLAY_TYPE_LANDSCAPE ? PageSize.A4.rotate() : PageSize.A4);
            if (print.getPrintPdfFooter() != null && !print.getHidePrintSettings()) {
                com.itextpdf.layout.Document doc = new com.itextpdf.layout.Document(pdfDoc);
                pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE, new TableFooterEventHandler(doc, print));
            }
            ConverterProperties converterProperties = new ConverterProperties();
            converterProperties.setBaseUri(attachmentPath);
            HtmlConverter.convertToPdf(html, pdfDoc, converterProperties);
        }
        String documentName = (StringUtils.notEmpty(print.getDocumentName()) ? print.getDocumentName() : "") + "-" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd")) + FILE_EXTENSION_PDF;
        InputStream pdfInputStream = new ByteArrayInputStream(pdfOutputStream.toByteArray());
        MetaFile metaFile = metaFiles.upload(pdfInputStream, documentName);
        File file = MetaFiles.getPath(metaFile).toFile();
        String fileLink = PdfTool.getFileLinkFromPdfFile(PdfTool.printCopiesToFile(file, 1), metaFile.getFileName());
        if (ObjectUtils.notEmpty(file) && file.exists() && (print.getAttach() || StringUtils.notEmpty(print.getMetaFileField()))) {
            Class<? extends Model> modelClass = (Class<? extends Model>) Class.forName(print.getMetaModel().getFullName());
            Model objectModel = JPA.find(modelClass, print.getObjectId());
            if (ObjectUtils.notEmpty(objectModel)) {
                if (print.getAttach()) {
                    metaFiles.attach(metaFile, documentName, objectModel);
                }
                if (StringUtils.notEmpty(print.getMetaFileField())) {
                    saveMetaFileInModel(modelClass, objectModel, metaFile, print.getMetaFileField());
                }
            }
        }
        if (CollectionUtils.isNotEmpty(print.getPrintSet())) {
            for (Print subPrint : print.getPrintSet()) {
                generatePDF(subPrint);
            }
        }
        return ActionView.define(documentName).add("html", fileLink).map();
    } catch (IOException | ClassNotFoundException e) {
        throw new AxelorException(e, TraceBackRepository.CATEGORY_INCONSISTENCY);
    }
}
Also used : ConverterProperties(com.itextpdf.html2pdf.ConverterProperties) AxelorException(com.axelor.exception.AxelorException) PdfWriter(com.itextpdf.kernel.pdf.PdfWriter) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) PdfDocument(com.itextpdf.kernel.pdf.PdfDocument) PdfDocument(com.itextpdf.kernel.pdf.PdfDocument) Print(com.axelor.apps.base.db.Print) ByteArrayInputStream(java.io.ByteArrayInputStream) Model(com.axelor.db.Model) MetaFile(com.axelor.meta.db.MetaFile) File(java.io.File) MetaFile(com.axelor.meta.db.MetaFile) Transactional(com.google.inject.persist.Transactional)

Example 13 with AxelorException

use of com.axelor.exception.AxelorException in project axelor-open-suite by axelor.

the class PrintTemplateServiceImpl method processPrintTemplateLineList.

private void processPrintTemplateLineList(List<PrintTemplateLine> templateLineList, Print print, PrintLine parent, Context scriptContext, TemplateMaker maker, int level) throws AxelorException {
    int seq = 1;
    if (ObjectUtils.notEmpty(templateLineList.get(0)) && ObjectUtils.notEmpty(templateLineList.get(0).getSequence())) {
        seq = templateLineList.get(0).getSequence().intValue();
    }
    for (PrintTemplateLine printTemplateLine : templateLineList) {
        if (printTemplateLine.getIgnoreTheLine()) {
            continue;
        }
        try {
            boolean present = true;
            if (StringUtils.notEmpty(printTemplateLine.getConditions())) {
                Object evaluation = templateContextService.computeTemplateContext(printTemplateLine.getConditions(), scriptContext);
                if (evaluation instanceof Boolean) {
                    present = (Boolean) evaluation;
                } else {
                    throw new AxelorException(TraceBackRepository.CATEGORY_INCONSISTENCY, I18n.get(IExceptionMessage.PRINT_TEMPLATE_CONDITION_MUST_BE_BOOLEAN));
                }
            }
            if (present) {
                ++rank;
                String title = null;
                String content = null;
                if (StringUtils.notEmpty(printTemplateLine.getTitle())) {
                    maker.setTemplate(printTemplateLine.getTitle());
                    addSequencesInContext(maker, level, seq, parent);
                    title = maker.make();
                }
                if (StringUtils.notEmpty(printTemplateLine.getContent())) {
                    maker.setTemplate(printTemplateLine.getContent());
                    addSequencesInContext(maker, level, seq, parent);
                    if (CollectionUtils.isNotEmpty(printTemplateLine.getTemplateContextList())) {
                        for (TemplateContext templateContext : printTemplateLine.getTemplateContextList()) {
                            Object result = templateContextService.computeTemplateContext(templateContext, scriptContext);
                            maker.addContext(templateContext.getName(), result);
                        }
                    }
                    content = maker.make();
                }
                PrintLine printLine = new PrintLine();
                printLine.setRank(rank);
                printLine.setSequence(seq);
                printLine.setTitle(title);
                printLine.setContent(content);
                printLine.setIsEditable(printTemplateLine.getIsEditable());
                printLine.setIsSignature(printTemplateLine.getIsSignature());
                printLine.setNbColumns(printTemplateLine.getNbColumns());
                printLine.setParent(parent);
                printLine.setIsWithPageBreakAfter(printTemplateLine.getIsWithPageBreakAfter());
                if (CollectionUtils.isNotEmpty(printTemplateLine.getPrintTemplateLineList())) {
                    processPrintTemplateLineList(printTemplateLine.getPrintTemplateLineList(), print, printLine, scriptContext, maker, level + 1);
                }
                print.addPrintLineListItem(printLine);
                seq++;
            }
        } catch (Exception e) {
            throw new AxelorException(TraceBackRepository.CATEGORY_INCONSISTENCY, I18n.get(IExceptionMessage.PRINT_TEMPLATE_ERROR_ON_LINE_WITH_SEQUENCE_AND_TITLE), printTemplateLine.getSequence(), printTemplateLine.getTitle());
        }
    }
}
Also used : AxelorException(com.axelor.exception.AxelorException) PrintLine(com.axelor.apps.base.db.PrintLine) PrintTemplateLine(com.axelor.apps.base.db.PrintTemplateLine) TemplateContext(com.axelor.apps.message.db.TemplateContext) Print(com.axelor.apps.base.db.Print) AxelorException(com.axelor.exception.AxelorException) IOException(java.io.IOException)

Example 14 with AxelorException

use of com.axelor.exception.AxelorException in project axelor-open-suite by axelor.

the class YearServiceImpl method generatePeriods.

public List<Period> generatePeriods(Year year) throws AxelorException {
    List<Period> periods = new ArrayList<Period>();
    Integer duration = year.getPeriodDurationSelect();
    LocalDate fromDate = year.getFromDate();
    LocalDate toDate = year.getToDate();
    LocalDate periodToDate = fromDate;
    Integer periodNumber = 1;
    int c = 0;
    int loopLimit = 1000;
    while (periodToDate.isBefore(toDate)) {
        if (periodNumber != 1)
            fromDate = fromDate.plusMonths(duration);
        if (c >= loopLimit) {
            throw new AxelorException(TraceBackRepository.CATEGORY_INCONSISTENCY, I18n.get(IExceptionMessage.PERIOD_3));
        }
        c += 1;
        periodToDate = fromDate.plusMonths(duration).minusDays(1);
        if (periodToDate.isAfter(toDate))
            periodToDate = toDate;
        if (fromDate.isAfter(toDate))
            continue;
        Period period = new Period();
        period.setFromDate(fromDate);
        period.setToDate(periodToDate);
        period.setYear(year);
        period.setName(String.format("%02d", periodNumber) + "/" + year.getCode());
        period.setCode((String.format("%02d", periodNumber) + "/" + year.getCode() + "_" + year.getCompany().getCode()).toUpperCase());
        period.setStatusSelect(year.getStatusSelect());
        periods.add(period);
        periodNumber++;
    }
    return periods;
}
Also used : AxelorException(com.axelor.exception.AxelorException) ArrayList(java.util.ArrayList) Period(com.axelor.apps.base.db.Period) LocalDate(java.time.LocalDate)

Example 15 with AxelorException

use of com.axelor.exception.AxelorException in project axelor-open-suite by axelor.

the class XmlHandler method exportObject.

@Transactional
public MetaFile exportObject() {
    group = Beans.get(GroupRepository.class).all().filter("self.code = 'admins'").fetchOne();
    try {
        log.debug("Attachment dir: {}", AppService.getFileUploadDir());
        String uploadDir = AppService.getFileUploadDir();
        if (uploadDir == null || !new File(uploadDir).exists()) {
            return null;
        }
        MetaFile metaFile = new MetaFile();
        String fileName = "ExportObject-" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyMMddHHmmSS")) + ".csv";
        metaFile.setFileName(fileName);
        metaFile.setFilePath(fileName);
        metaFile = Beans.get(MetaFileRepository.class).save(metaFile);
        SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        saxParserFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
        saxParserFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
        saxParserFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
        saxParserFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
        saxParserFactory.setXIncludeAware(false);
        SAXParser parser = saxParserFactory.newSAXParser();
        updateObjectMap(ModuleManager.getResolution(), parser, new XmlHandler());
        writeObjects(MetaFiles.getPath(metaFile).toFile());
        return metaFile;
    } catch (ParserConfigurationException | SAXException | IOException | AxelorException e) {
        e.printStackTrace();
    }
    return null;
}
Also used : AxelorException(com.axelor.exception.AxelorException) SAXParser(javax.xml.parsers.SAXParser) MetaFile(com.axelor.meta.db.MetaFile) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) IOException(java.io.IOException) File(java.io.File) MetaFile(com.axelor.meta.db.MetaFile) SAXParserFactory(javax.xml.parsers.SAXParserFactory) SAXException(org.xml.sax.SAXException) Transactional(com.google.inject.persist.Transactional)

Aggregations

AxelorException (com.axelor.exception.AxelorException)546 Transactional (com.google.inject.persist.Transactional)126 BigDecimal (java.math.BigDecimal)118 ArrayList (java.util.ArrayList)84 IOException (java.io.IOException)73 Product (com.axelor.apps.base.db.Product)64 Company (com.axelor.apps.base.db.Company)63 LocalDate (java.time.LocalDate)58 Partner (com.axelor.apps.base.db.Partner)48 List (java.util.List)45 StockMoveLine (com.axelor.apps.stock.db.StockMoveLine)40 HashMap (java.util.HashMap)38 Invoice (com.axelor.apps.account.db.Invoice)33 StockMove (com.axelor.apps.stock.db.StockMove)32 Map (java.util.Map)31 Beans (com.axelor.inject.Beans)30 I18n (com.axelor.i18n.I18n)28 Inject (com.google.inject.Inject)28 MoveLine (com.axelor.apps.account.db.MoveLine)27 Context (com.axelor.rpc.Context)27