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;
}
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);
}
}
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());
}
}
}
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;
}
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;
}
Aggregations