Search in sources :

Example 1 with ReportingException

use of io.jmix.reports.exception.ReportingException in project jmix by jmix-framework.

the class CustomFormatter method generateReportWithScript.

protected byte[] generateReportWithScript(BandData rootBand, String customDefinition) {
    Object result;
    if (customDefinition.startsWith("/")) {
        customDefinition = StringUtils.removeStart(customDefinition, "/");
    }
    Map<String, Object> scriptParams = new HashMap<>();
    scriptParams.put(PARAMS, params);
    scriptParams.put(ROOT_BAND, rootBand);
    scriptParams.put("applicationContext", applicationContext);
    if (Pattern.matches(PATH_GROOVY_FILE, customDefinition)) {
        result = scriptEvaluator.evaluate(new ResourceScriptSource(new ClassPathResource(customDefinition)), scriptParams);
    } else {
        result = scriptEvaluator.evaluate(new StaticScriptSource(customDefinition), scriptParams);
    }
    if (result == null) {
        throw new ReportingException(format("Result returned from custom report [%s] is null " + "but only byte[] and strings are supported", customDefinition));
    }
    if (result instanceof byte[]) {
        return (byte[]) result;
    } else if (result instanceof CharSequence) {
        return result.toString().getBytes(StandardCharsets.UTF_8);
    } else {
        throw new ReportingException(format("Result returned from custom report is of type %s " + "but only byte[] and strings are supported", result.getClass()));
    }
}
Also used : StaticScriptSource(org.springframework.scripting.support.StaticScriptSource) ResourceScriptSource(org.springframework.scripting.support.ResourceScriptSource) ReportingException(io.jmix.reports.exception.ReportingException) HashMap(java.util.HashMap) ClassPathResource(org.springframework.core.io.ClassPathResource)

Example 2 with ReportingException

use of io.jmix.reports.exception.ReportingException in project jmix by jmix-framework.

the class CustomFormatter method generateReportWithUrl.

protected byte[] generateReportWithUrl(BandData rootBand, String customDefinition) {
    Map<String, Object> convertedParams = new HashMap<>();
    for (Map.Entry<String, Object> entry : params.entrySet()) {
        if (entry.getValue() instanceof Date) {
            convertedParams.put(entry.getKey(), new FormattedDate((Date) entry.getValue()));
        } else {
            convertedParams.put(entry.getKey(), entry.getValue());
        }
    }
    convertedParams.put(ROOT_BAND, rootBand);
    Object scriptResult = scriptEvaluator.evaluate(new StaticScriptSource("return \"" + customDefinition + "\""), convertedParams);
    if (scriptResult == null) {
        throw new ReportingException(format("Can not get generated URL returned from custom report [%s]", customDefinition));
    }
    String url = scriptResult.toString();
    try {
        Future<byte[]> future = executor.submit(() -> doReadBytesFromUrl(url));
        byte[] bytes = future.get(reportsProperties.getCurlTimeout(), TimeUnit.SECONDS);
        return bytes;
    } catch (InterruptedException e) {
        throw new ReportingException(format("Reading data from url [%s] has been interrupted", url), e);
    } catch (ExecutionException e) {
        throw new ReportingException(format("An error occurred while reading data from url [%s]", url), e);
    } catch (TimeoutException e) {
        throw new ReportingException(format("Reading data from url [%s] has been terminated by timeout", url), e);
    }
}
Also used : StaticScriptSource(org.springframework.scripting.support.StaticScriptSource) ReportingException(io.jmix.reports.exception.ReportingException) HashMap(java.util.HashMap) Date(java.util.Date) HashMap(java.util.HashMap) Map(java.util.Map)

Example 3 with ReportingException

use of io.jmix.reports.exception.ReportingException in project jmix by jmix-framework.

the class JmixTableFormatter method getTableData.

protected JmixTableData getTableData(TemplateTableDescription templateTableDescription, Map<String, List<KeyValueEntity>> transformedData, Map<String, Set<JmixTableData.ColumnInfo>> headerMap, Map<String, List<BandData>> childrenBands) {
    for (TemplateTableBand band : templateTableDescription.getTemplateTableBands()) {
        String bandName = band.getBandName();
        if (bandName.startsWith(HEADER_BAND_PREFIX)) {
            break;
        }
        List<BandData> bandDataList = childrenBands.get(bandName);
        if (bandDataList == null) {
            throw new ReportingException(String.format("Report template has an unknown band [%s]", bandName));
        }
        List<KeyValueEntity> entities = new ArrayList<>();
        Set<JmixTableData.ColumnInfo> headers = new LinkedHashSet<>();
        bandDataList.forEach(bandData -> {
            Map<String, Object> data = bandData.getData();
            final String pkName;
            final boolean pkInFetchPlan;
            if (data instanceof EntityMap) {
                Entity instance = ((EntityMap) data).getInstance();
                pkName = metadataTools.getPrimaryKeyName(metadata.getClass(instance));
                FetchPlan fetchPlan = ((EntityMap) data).getFetchPlan();
                pkInFetchPlan = fetchPlan != null && pkName != null && fetchPlan.containsProperty(pkName);
            } else {
                pkName = null;
                pkInFetchPlan = false;
            }
            KeyValueEntity entityRow = new KeyValueEntity();
            for (TemplateTableColumn column : band.getColumns()) {
                String key = column.getKey();
                Object value = data.get(key);
                if (INSTANCE_NAME_KEY.equals(key)) {
                    return;
                }
                if (checkAddHeader(pkName, pkInFetchPlan, key)) {
                    checkInstanceNameLoaded(value);
                    String transformationKey = transformationKey(key);
                    if (isFormat(bandName, key)) {
                        String formattedValue = getFormattedValue(bandName, key, value);
                        entityRow.setValue(transformationKey, formattedValue);
                    } else {
                        entityRow.setValue(transformationKey, value);
                    }
                }
            }
            if (headers.isEmpty() || headers.size() < data.size()) {
                for (TemplateTableColumn column : band.getColumns()) {
                    String key = column.getKey();
                    Object value = data.get(key);
                    if (INSTANCE_NAME_KEY.equals(key)) {
                        return;
                    }
                    if (checkAddHeader(pkName, pkInFetchPlan, key)) {
                        String transformationKey = transformationKey(key);
                        if (value != null) {
                            Class valueClass = getColumnClass(bandName, key, value);
                            headers.add(new JmixTableData.ColumnInfo(transformationKey, valueClass, column.getCaption(), column.getPosition()));
                        } else {
                            headers.add(new JmixTableData.ColumnInfo(transformationKey, String.class, column.getCaption(), column.getPosition()));
                        }
                    }
                }
            }
            entities.add(entityRow);
        });
        headers.removeIf(header -> containsLowerCaseDuplicate(header, headers));
        transformedData.put(bandName, entities);
        headerMap.put(bandName, headers);
    }
    return new JmixTableData(transformedData, headerMap);
}
Also used : KeyValueEntity(io.jmix.core.entity.KeyValueEntity) ReportingException(io.jmix.reports.exception.ReportingException) JmixTableData(io.jmix.reports.entity.JmixTableData) EntityMap(io.jmix.reports.app.EntityMap) TemplateTableColumn(io.jmix.reports.entity.table.TemplateTableColumn) TemplateTableBand(io.jmix.reports.entity.table.TemplateTableBand) KeyValueEntity(io.jmix.core.entity.KeyValueEntity) BandData(com.haulmont.yarg.structure.BandData)

Example 4 with ReportingException

use of io.jmix.reports.exception.ReportingException in project jmix by jmix-framework.

the class PrototypesLoader method loadData.

/**
 * Load parameter data
 *
 * @param parameterPrototype Parameter prototype
 * @return Entities list
 */
public List loadData(ParameterPrototype parameterPrototype) {
    MetaClass metaClass = metadata.getSession().getClass(parameterPrototype.getMetaClassName());
    FetchPlan queryFetchPlan = parameterPrototype.getFetchPlan();
    if (queryFetchPlan == null) {
        queryFetchPlan = fetchPlanRepository.getFetchPlan(metaClass, parameterPrototype.getFetchPlanName());
    }
    LoadContext loadContext = new LoadContext(metaClass);
    LoadContext.Query query = new LoadContext.Query(parameterPrototype.getQueryString());
    query.setParameters(parameterPrototype.getQueryParams());
    query.setCondition(parameterPrototype.getCondition());
    query.setSort(parameterPrototype.getSort());
    query.setFirstResult(parameterPrototype.getFirstResult() == null ? 0 : parameterPrototype.getFirstResult());
    if (parameterPrototype.getMaxResults() != null && !parameterPrototype.getMaxResults().equals(0)) {
        query.setMaxResults(parameterPrototype.getMaxResults());
    } else {
        query.setMaxResults(reportsProperties.getParameterPrototypeQueryLimit());
    }
    loadContext.setFetchPlan(queryFetchPlan);
    loadContext.setQuery(query);
    List queryResult;
    try {
        queryResult = dataManager.loadList(loadContext);
    } catch (Exception e) {
        throw new ReportingException(e);
    }
    return queryResult;
}
Also used : MetaClass(io.jmix.core.metamodel.model.MetaClass) ReportingException(io.jmix.reports.exception.ReportingException) List(java.util.List) ReportingException(io.jmix.reports.exception.ReportingException)

Example 5 with ReportingException

use of io.jmix.reports.exception.ReportingException in project jmix by jmix-framework.

the class ReportRestControllerManager method runReport.

public ReportRestResult runReport(String entityId, String bodyJson) {
    Report report = loadReportInternal(entityId);
    final ReportRunRestBody body;
    try {
        body = createGson().fromJson(bodyJson, ReportRunRestBody.class);
    } catch (JsonSyntaxException e) {
        throw new RestAPIException("Invalid JSON body", e.getMessage(), HttpStatus.BAD_REQUEST, e);
    }
    if (body.template != null) {
        ReportTemplate reportTemplate = report.getTemplates().stream().filter(t -> Objects.equals(t.getCode(), body.template)).findFirst().orElseThrow(() -> new RestAPIException("Template not found", String.format("Template with code %s not found for report %s", body.template, entityId), HttpStatus.BAD_REQUEST));
        checkReportOutputType(reportTemplate);
    } else {
        checkReportOutputType(report.getDefaultTemplate());
    }
    Map<String, Object> preparedValues = prepareValues(report, body.parameters);
    if (body.template != null) {
        try {
            ReportOutputDocument document = reportRunner.byReportEntity(report).withTemplateCode(body.template).withParams(preparedValues).run();
            return new ReportRestResult(document, body.attachment);
        } catch (FailedToConnectToOpenOfficeException e) {
            throw new RestAPIException("Run report error", "Couldn't find LibreOffice instance", HttpStatus.INTERNAL_SERVER_ERROR);
        } catch (NoOpenOfficeFreePortsException e) {
            throw new RestAPIException("Run report error", "Couldn't connect to LibreOffice instance. No free ports available.", HttpStatus.INTERNAL_SERVER_ERROR);
        } catch (ReportingException e) {
            throw new RestAPIException("Run report error", e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    } else {
        try {
            return new ReportRestResult(reportRunner.run(new ReportRunContext(report).setParams(preparedValues)), body.attachment);
        } catch (FailedToConnectToOpenOfficeException e) {
            throw new RestAPIException("Run report error", "Couldn't find LibreOffice instance", HttpStatus.INTERNAL_SERVER_ERROR);
        } catch (NoOpenOfficeFreePortsException e) {
            throw new RestAPIException("Run report error", "Couldn't connect to LibreOffice instance. No free ports available.", HttpStatus.INTERNAL_SERVER_ERROR);
        } catch (ReportingException e) {
            throw new RestAPIException("Run report error", e.getMessage(), HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
Also used : ReportOutputDocument(com.haulmont.yarg.reporting.ReportOutputDocument) ReportingException(io.jmix.reports.exception.ReportingException) ReportRunContext(io.jmix.reports.runner.ReportRunContext) JsonSyntaxException(com.google.gson.JsonSyntaxException) NoOpenOfficeFreePortsException(io.jmix.reports.exception.NoOpenOfficeFreePortsException) FailedToConnectToOpenOfficeException(io.jmix.reports.exception.FailedToConnectToOpenOfficeException)

Aggregations

ReportingException (io.jmix.reports.exception.ReportingException)12 ReportOutputDocument (com.haulmont.yarg.reporting.ReportOutputDocument)2 Report (io.jmix.reports.entity.Report)2 FailedToConnectToOpenOfficeException (io.jmix.reports.exception.FailedToConnectToOpenOfficeException)2 NoOpenOfficeFreePortsException (io.jmix.reports.exception.NoOpenOfficeFreePortsException)2 File (java.io.File)2 IOException (java.io.IOException)2 HashMap (java.util.HashMap)2 StaticScriptSource (org.springframework.scripting.support.StaticScriptSource)2 JsonSyntaxException (com.google.gson.JsonSyntaxException)1 BandData (com.haulmont.yarg.structure.BandData)1 KeyValueEntity (io.jmix.core.entity.KeyValueEntity)1 MetaClass (io.jmix.core.metamodel.model.MetaClass)1 EntityMap (io.jmix.reports.app.EntityMap)1 CustomTemplateDefinedBy (io.jmix.reports.entity.CustomTemplateDefinedBy)1 JmixTableData (io.jmix.reports.entity.JmixTableData)1 TemplateTableBand (io.jmix.reports.entity.table.TemplateTableBand)1 TemplateTableColumn (io.jmix.reports.entity.table.TemplateTableColumn)1 ReportRunContext (io.jmix.reports.runner.ReportRunContext)1 ShowChartScreen (io.jmix.reportsui.screen.report.run.ShowChartScreen)1