Search in sources :

Example 6 with DataSet

use of org.talend.dataprep.api.dataset.DataSet in project data-prep by Talend.

the class DataSetJSONTest method testColumnAtEnd.

@Test
public void testColumnAtEnd() throws Exception {
    DataSet dataSet = from(this.getClass().getResourceAsStream("test4.json"));
    // There are 4 columns, but Jackson doesn't take them into account if at end of content. This is not "expected"
    // but known. This test ensure the known behavior remains the same.
    assertThat(dataSet.getMetadata(), nullValue());
}
Also used : DataSet(org.talend.dataprep.api.dataset.DataSet) ServiceBaseTest(org.talend.ServiceBaseTest) Test(org.junit.Test)

Example 7 with DataSet

use of org.talend.dataprep.api.dataset.DataSet in project data-prep by Talend.

the class TransformationService method getSemanticDomains.

/**
 * Return the semantic domains for the given parameters.
 *
 * @param metadata the dataset metadata.
 * @param columnId the column id to analyze.
 * @param records the dataset records.
 * @return the semantic domains for the given parameters.
 * @throws IOException can happen...
 */
private List<SemanticDomain> getSemanticDomains(DataSetMetadata metadata, String columnId, InputStream records) throws IOException {
    // copy the column metadata and set the semantic domain forced flag to false to make sure the statistics adapter set all
    // available domains
    final ColumnMetadata columnMetadata = // 
    column().copy(// 
    metadata.getRowMetadata().getById(columnId)).semanticDomainForce(// 
    false).build();
    final Analyzer<Analyzers.Result> analyzer = analyzerService.build(columnMetadata, SEMANTIC);
    analyzer.init();
    try (final JsonParser parser = mapper.getFactory().createParser(new InputStreamReader(records, UTF_8))) {
        final DataSet dataSet = mapper.readerFor(DataSet.class).readValue(parser);
        dataSet.getRecords().map(// 
        r -> r.get(columnId)).forEach(analyzer::analyze);
        analyzer.end();
    }
    final List<Analyzers.Result> analyzerResult = analyzer.getResult();
    statisticsAdapter.adapt(singletonList(columnMetadata), analyzerResult);
    return columnMetadata.getSemanticDomains();
}
Also used : VolumeMetered(org.talend.dataprep.metrics.VolumeMetered) LocaleContextHolder(org.springframework.context.i18n.LocaleContextHolder) StringUtils(org.apache.commons.lang.StringUtils) ContentCacheKey(org.talend.dataprep.cache.ContentCacheKey) TdqCategories(org.talend.dataquality.semantic.broadcast.TdqCategories) Autowired(org.springframework.beans.factory.annotation.Autowired) ApiParam(io.swagger.annotations.ApiParam) PreviewParameters(org.talend.dataprep.transformation.preview.api.PreviewParameters) ExportFormatMessage(org.talend.dataprep.format.export.ExportFormatMessage) ActionContext(org.talend.dataprep.transformation.api.action.context.ActionContext) Collections.singletonList(java.util.Collections.singletonList) ScopeCategory(org.talend.dataprep.transformation.actions.category.ScopeCategory) Valid(javax.validation.Valid) SemanticDomain(org.talend.dataprep.api.dataset.statistics.SemanticDomain) BeanConversionService(org.talend.dataprep.conversions.BeanConversionService) GetPrepMetadataAsyncCondition(org.talend.dataprep.async.conditional.GetPrepMetadataAsyncCondition) TaskExecutor(org.springframework.core.task.TaskExecutor) DataSet(org.talend.dataprep.api.dataset.DataSet) ExportParametersUtil(org.talend.dataprep.api.export.ExportParametersUtil) StepDiff(org.talend.dataprep.api.preparation.StepDiff) PreparationDetailsGet(org.talend.dataprep.command.preparation.PreparationDetailsGet) HEAD(org.talend.dataprep.api.export.ExportParameters.SourceType.HEAD) APPLICATION_OCTET_STREAM_VALUE(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM_VALUE) Resource(javax.annotation.Resource) StreamingResponseBody(org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody) JSON(org.talend.dataprep.transformation.format.JsonFormat.JSON) PreparationGetContentUrlGenerator(org.talend.dataprep.async.result.PreparationGetContentUrlGenerator) SecurityProxy(org.talend.dataprep.security.SecurityProxy) Stream(java.util.stream.Stream) Builder.column(org.talend.dataprep.api.dataset.ColumnMetadata.Builder.column) org.springframework.web.bind.annotation(org.springframework.web.bind.annotation) GZIPOutputStream(java.util.zip.GZIPOutputStream) DynamicType(org.talend.dataprep.transformation.api.action.dynamic.DynamicType) RunnableAction(org.talend.dataprep.transformation.actions.common.RunnableAction) Analyzers(org.talend.dataquality.common.inference.Analyzers) java.util(java.util) TransformationErrorCodes(org.talend.dataprep.exception.error.TransformationErrorCodes) GenericParameter(org.talend.dataprep.transformation.api.action.dynamic.GenericParameter) Configuration(org.talend.dataprep.transformation.api.transformer.configuration.Configuration) PreviewConfiguration(org.talend.dataprep.transformation.api.transformer.configuration.PreviewConfiguration) AnalyzerService(org.talend.dataprep.quality.AnalyzerService) TransformationMetadataCacheKey(org.talend.dataprep.cache.TransformationMetadataCacheKey) PrepMetadataExecutionIdGenerator(org.talend.dataprep.async.generator.PrepMetadataExecutionIdGenerator) PREPARATION_DOES_NOT_EXIST(org.talend.dataprep.exception.error.PreparationErrorCodes.PREPARATION_DOES_NOT_EXIST) Api(io.swagger.annotations.Api) Preparation(org.talend.dataprep.api.preparation.Preparation) ActionRegistry(org.talend.dataprep.transformation.pipeline.ActionRegistry) GetPrepContentAsyncCondition(org.talend.dataprep.async.conditional.GetPrepContentAsyncCondition) TransformationContext(org.talend.dataprep.transformation.api.action.context.TransformationContext) AggregationService(org.talend.dataprep.transformation.aggregation.AggregationService) NullOutputStream(org.apache.commons.io.output.NullOutputStream) StatisticsAdapter(org.talend.dataprep.dataset.StatisticsAdapter) DataSetGetMetadata(org.talend.dataprep.command.dataset.DataSetGetMetadata) Timed(org.talend.dataprep.metrics.Timed) ColumnMetadata(org.talend.dataprep.api.dataset.ColumnMetadata) DataSetGet(org.talend.dataprep.command.dataset.DataSetGet) AggregationResult(org.talend.dataprep.transformation.aggregation.api.AggregationResult) LoggerFactory(org.slf4j.LoggerFactory) Flag(org.talend.dataprep.api.dataset.row.Flag) SEMANTIC(org.talend.dataprep.quality.AnalyzerService.Analysis.SEMANTIC) ActionParser(org.talend.dataprep.transformation.api.action.ActionParser) CacheKeyGenerator(org.talend.dataprep.cache.CacheKeyGenerator) ApiOperation(io.swagger.annotations.ApiOperation) DataSetMetadata(org.talend.dataprep.api.dataset.DataSetMetadata) ExportParameters(org.talend.dataprep.api.export.ExportParameters) PrepMetadataGetContentUrlGenerator(org.talend.dataprep.async.result.PrepMetadataGetContentUrlGenerator) MediaType(org.springframework.http.MediaType) PublicAPI(org.talend.dataprep.security.PublicAPI) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) Collectors(java.util.stream.Collectors) ContentCache(org.talend.dataprep.cache.ContentCache) UNEXPECTED_EXCEPTION(org.talend.dataprep.exception.error.TransformationErrorCodes.UNEXPECTED_EXCEPTION) TransformerFactory(org.talend.dataprep.transformation.api.transformer.TransformerFactory) CommonErrorCodes(org.talend.dataprep.exception.error.CommonErrorCodes) Analyzer(org.talend.dataquality.common.inference.Analyzer) ActionDefinition(org.talend.dataprep.api.action.ActionDefinition) PreparationExportStrategy(org.talend.dataprep.transformation.service.export.PreparationExportStrategy) RowMetadata(org.talend.dataprep.api.dataset.RowMetadata) ExportFormat(org.talend.dataprep.format.export.ExportFormat) TDPException(org.talend.dataprep.exception.TDPException) JsonErrorCodeDescription(org.talend.dataprep.exception.json.JsonErrorCodeDescription) ExceptionContext.build(org.talend.daikon.exception.ExceptionContext.build) ExportParametersExecutionIdGenerator(org.talend.dataprep.async.generator.ExportParametersExecutionIdGenerator) ExceptionContext(org.talend.daikon.exception.ExceptionContext) org.talend.dataprep.async(org.talend.dataprep.async) Suggestion(org.talend.dataprep.transformation.api.transformer.suggestion.Suggestion) SuggestionEngine(org.talend.dataprep.transformation.api.transformer.suggestion.SuggestionEngine) Logger(org.slf4j.Logger) LocaleContextHolder.getLocale(org.springframework.context.i18n.LocaleContextHolder.getLocale) JsonParser(com.fasterxml.jackson.core.JsonParser) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Step(org.talend.dataprep.api.preparation.Step) APPLICATION_JSON_VALUE(org.springframework.http.MediaType.APPLICATION_JSON_VALUE) ApplicationContext(org.springframework.context.ApplicationContext) ActionForm(org.talend.dataprep.api.action.ActionForm) AggregationParameters(org.talend.dataprep.transformation.aggregation.api.AggregationParameters) java.io(java.io) TdqCategoriesFactory(org.talend.dataquality.semantic.broadcast.TdqCategoriesFactory) ColumnMetadata(org.talend.dataprep.api.dataset.ColumnMetadata) DataSet(org.talend.dataprep.api.dataset.DataSet) AggregationResult(org.talend.dataprep.transformation.aggregation.api.AggregationResult) JsonParser(com.fasterxml.jackson.core.JsonParser)

Example 8 with DataSet

use of org.talend.dataprep.api.dataset.DataSet in project data-prep by Talend.

the class TransformationService method aggregate.

/**
 * Compute the given aggregation.
 *
 * @param rawParams the aggregation rawParams as body rawParams.
 */
// @formatter:off
@RequestMapping(value = "/aggregate", method = POST, consumes = APPLICATION_JSON_VALUE)
@ApiOperation(value = "Compute the aggregation according to the request body rawParams", consumes = APPLICATION_JSON_VALUE)
@VolumeMetered
public AggregationResult aggregate(@ApiParam(value = "The aggregation rawParams in json") @RequestBody final String rawParams) {
    // @formatter:on
    // parse the aggregation parameters
    final AggregationParameters parameters;
    try {
        parameters = mapper.readerFor(AggregationParameters.class).readValue(rawParams);
        LOG.debug("Aggregation requested {}", parameters);
    } catch (IOException e) {
        throw new TDPException(CommonErrorCodes.BAD_AGGREGATION_PARAMETERS, e);
    }
    InputStream contentToAggregate;
    // get the content of the preparation (internal call with piped streams)
    if (StringUtils.isNotBlank(parameters.getPreparationId())) {
        try {
            PipedOutputStream temp = new PipedOutputStream();
            contentToAggregate = new PipedInputStream(temp);
            // because of piped streams, processing must be asynchronous
            Runnable r = () -> {
                try {
                    final ExportParameters exportParameters = new ExportParameters();
                    exportParameters.setPreparationId(parameters.getPreparationId());
                    exportParameters.setDatasetId(parameters.getDatasetId());
                    final String filter = parameters.getFilter();
                    if (filter != null) {
                        if (filter.isEmpty()) {
                            throw new TDPException(CommonErrorCodes.UNABLE_TO_AGGREGATE, new IllegalArgumentException("Source should not be empty"));
                        }
                        exportParameters.setFilter(mapper.readTree(filter));
                    }
                    exportParameters.setExportType(JSON);
                    exportParameters.setStepId(parameters.getStepId());
                    final StreamingResponseBody body = executeSampleExportStrategy(exportParameters);
                    body.writeTo(temp);
                } catch (IOException e) {
                    throw new TDPException(CommonErrorCodes.UNABLE_TO_AGGREGATE, e);
                }
            };
            executor.execute(r);
        } catch (IOException e) {
            throw new TDPException(CommonErrorCodes.UNABLE_TO_AGGREGATE, e);
        }
    } else {
        final DataSetGet dataSetGet = context.getBean(DataSetGet.class, parameters.getDatasetId(), false, true);
        contentToAggregate = dataSetGet.execute();
    }
    // apply the aggregation
    try (JsonParser parser = mapper.getFactory().createParser(new InputStreamReader(contentToAggregate, UTF_8))) {
        final DataSet dataSet = mapper.readerFor(DataSet.class).readValue(parser);
        return aggregationService.aggregate(parameters, dataSet);
    } catch (IOException e) {
        throw new TDPException(CommonErrorCodes.UNABLE_TO_PARSE_JSON, e);
    } finally {
        // don't forget to release the connection
        if (contentToAggregate != null) {
            try {
                contentToAggregate.close();
            } catch (IOException e) {
                LOG.warn("Could not close dataset input stream while aggregating", e);
            }
        }
    }
}
Also used : DataSetGet(org.talend.dataprep.command.dataset.DataSetGet) StreamingResponseBody(org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody) DataSet(org.talend.dataprep.api.dataset.DataSet) AggregationParameters(org.talend.dataprep.transformation.aggregation.api.AggregationParameters) TDPException(org.talend.dataprep.exception.TDPException) ExportParameters(org.talend.dataprep.api.export.ExportParameters) JsonParser(com.fasterxml.jackson.core.JsonParser) VolumeMetered(org.talend.dataprep.metrics.VolumeMetered) ApiOperation(io.swagger.annotations.ApiOperation)

Example 9 with DataSet

use of org.talend.dataprep.api.dataset.DataSet in project data-prep by Talend.

the class TransformationService method executeDiffOnDataset.

private void executeDiffOnDataset(final PreviewParameters previewParameters, final OutputStream output) {
    final DataSetGet dataSetGet = context.getBean(DataSetGet.class, previewParameters.getDataSetId(), false, true);
    boolean identityReleased = false;
    securityProxy.asTechnicalUser();
    // because of dataset records streaming, the dataset content must be within an auto closeable block
    try (// 
    final InputStream dataSetContent = dataSetGet.execute();
        final JsonParser parser = mapper.getFactory().createParser(new InputStreamReader(dataSetContent, UTF_8))) {
        securityProxy.releaseIdentity();
        identityReleased = true;
        final DataSet dataSet = mapper.readerFor(DataSet.class).readValue(parser);
        executePreview(// 
        previewParameters.getNewActions(), // 
        previewParameters.getBaseActions(), // 
        previewParameters.getTdpIds(), // 
        dataSet, // 
        output);
    } catch (IOException e) {
        throw new TDPException(TransformationErrorCodes.UNABLE_TO_PERFORM_PREVIEW, e);
    } finally {
        // make sure the technical identity is released
        if (!identityReleased) {
            securityProxy.releaseIdentity();
        }
    }
}
Also used : TDPException(org.talend.dataprep.exception.TDPException) DataSetGet(org.talend.dataprep.command.dataset.DataSetGet) DataSet(org.talend.dataprep.api.dataset.DataSet) JsonParser(com.fasterxml.jackson.core.JsonParser)

Example 10 with DataSet

use of org.talend.dataprep.api.dataset.DataSet in project data-prep by Talend.

the class DataSetExportStrategy method execute.

@Override
public StreamingResponseBody execute(ExportParameters parameters) {
    final String formatName = parameters.getExportType();
    final ExportFormat format = getFormat(formatName);
    // 
    ExportUtils.setExportHeaders(// 
    parameters.getExportName(), // 
    parameters.getArguments().get(ExportFormat.PREFIX + CSVFormat.ParametersCSV.ENCODING), format);
    return outputStream -> {
        // get the dataset content (in an auto-closable block to make sure it is properly closed)
        final String datasetId = parameters.getDatasetId();
        final DataSetGet dataSetGet = applicationContext.getBean(DataSetGet.class, datasetId, false, true);
        final DataSetGetMetadata dataSetGetMetadata = applicationContext.getBean(DataSetGetMetadata.class, datasetId);
        try (InputStream datasetContent = dataSetGet.execute()) {
            try (JsonParser parser = mapper.getFactory().createParser(new InputStreamReader(datasetContent, UTF_8))) {
                // Create dataset
                final DataSet dataSet = mapper.readerFor(DataSet.class).readValue(parser);
                dataSet.setMetadata(dataSetGetMetadata.execute());
                // get the actions to apply (no preparation ==> dataset export ==> no actions)
                Configuration configuration = // 
                Configuration.builder().args(// 
                parameters.getArguments()).outFilter(// 
                rm -> filterService.build(parameters.getFilter(), rm)).format(// 
                format.getName()).volume(// 
                Configuration.Volume.SMALL).output(// 
                outputStream).limit(// 
                limit).build();
                factory.get(configuration).buildExecutable(dataSet, configuration).execute();
            }
        } catch (TDPException e) {
            throw e;
        } catch (Exception e) {
            throw new TDPException(TransformationErrorCodes.UNABLE_TO_TRANSFORM_DATASET, e);
        }
    };
}
Also used : ExportFormat(org.talend.dataprep.format.export.ExportFormat) StringUtils(org.apache.commons.lang.StringUtils) ExportParameters(org.talend.dataprep.api.export.ExportParameters) DataSetGet(org.talend.dataprep.command.dataset.DataSetGet) TDPException(org.talend.dataprep.exception.TDPException) TransformationErrorCodes(org.talend.dataprep.exception.error.TransformationErrorCodes) BaseExportStrategy(org.talend.dataprep.transformation.service.BaseExportStrategy) JsonParser(com.fasterxml.jackson.core.JsonParser) UTF_8(java.nio.charset.StandardCharsets.UTF_8) StreamingResponseBody(org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody) Configuration(org.talend.dataprep.transformation.api.transformer.configuration.Configuration) InputStreamReader(java.io.InputStreamReader) CSVFormat(org.talend.dataprep.transformation.format.CSVFormat) Component(org.springframework.stereotype.Component) DataSetGetMetadata(org.talend.dataprep.command.dataset.DataSetGetMetadata) ExportUtils(org.talend.dataprep.transformation.service.ExportUtils) DataSet(org.talend.dataprep.api.dataset.DataSet) InputStream(java.io.InputStream) TDPException(org.talend.dataprep.exception.TDPException) DataSetGet(org.talend.dataprep.command.dataset.DataSetGet) InputStreamReader(java.io.InputStreamReader) Configuration(org.talend.dataprep.transformation.api.transformer.configuration.Configuration) DataSet(org.talend.dataprep.api.dataset.DataSet) InputStream(java.io.InputStream) ExportFormat(org.talend.dataprep.format.export.ExportFormat) DataSetGetMetadata(org.talend.dataprep.command.dataset.DataSetGetMetadata) TDPException(org.talend.dataprep.exception.TDPException) JsonParser(com.fasterxml.jackson.core.JsonParser)

Aggregations

DataSet (org.talend.dataprep.api.dataset.DataSet)39 DataSetMetadata (org.talend.dataprep.api.dataset.DataSetMetadata)18 Test (org.junit.Test)16 TDPException (org.talend.dataprep.exception.TDPException)15 JsonParser (com.fasterxml.jackson.core.JsonParser)13 InputStream (java.io.InputStream)13 RowMetadata (org.talend.dataprep.api.dataset.RowMetadata)11 DataSetRow (org.talend.dataprep.api.dataset.row.DataSetRow)10 OutputStream (java.io.OutputStream)8 Logger (org.slf4j.Logger)8 DataSetGet (org.talend.dataprep.command.dataset.DataSetGet)8 Configuration (org.talend.dataprep.transformation.api.transformer.configuration.Configuration)8 ApiOperation (io.swagger.annotations.ApiOperation)7 IOException (java.io.IOException)7 ArrayList (java.util.ArrayList)7 LoggerFactory (org.slf4j.LoggerFactory)7 Autowired (org.springframework.beans.factory.annotation.Autowired)7 ServiceBaseTest (org.talend.ServiceBaseTest)7 ColumnMetadata (org.talend.dataprep.api.dataset.ColumnMetadata)7 ContentCache (org.talend.dataprep.cache.ContentCache)7