Search in sources :

Example 76 with TDPException

use of org.talend.dataprep.exception.TDPException in project data-prep by Talend.

the class FileSystemFolderRepository method children.

@Override
public Stream<Folder> children(String parentId) {
    final FolderPath parentDpPath = fromId(parentId);
    try {
        Path folderPath;
        if (parentDpPath != null) {
            folderPath = pathsConverter.toPath(parentDpPath);
        } else {
            folderPath = pathsConverter.getRootFolder();
        }
        Stream<Folder> children;
        if (Files.notExists(folderPath)) {
            children = Stream.empty();
        } else {
            children = // 
            Files.list(folderPath).map(p -> toFolderIfDirectory(p, security.getUserId())).filter(Objects::nonNull);
        }
        return children;
    } catch (IOException e) {
        throw new TDPException(UNABLE_TO_LIST_FOLDER_CHILDREN, e, build().put("path", parentDpPath == null ? null : parentDpPath.serializeAsString()));
    }
}
Also used : Path(java.nio.file.Path) TDPException(org.talend.dataprep.exception.TDPException) IOException(java.io.IOException) Folder(org.talend.dataprep.api.folder.Folder)

Example 77 with TDPException

use of org.talend.dataprep.exception.TDPException in project data-prep by Talend.

the class PreparationExportStrategy method performPreparation.

public void performPreparation(final ExportParameters parameters, final OutputStream outputStream) {
    final String stepId = parameters.getStepId();
    final String preparationId = parameters.getPreparationId();
    final String formatName = parameters.getExportType();
    final PreparationMessage preparation = getPreparation(preparationId, stepId);
    final String dataSetId = preparation.getDataSetId();
    final ExportFormat format = getFormat(parameters.getExportType());
    // get the dataset content (in an auto-closable block to make sure it is properly closed)
    boolean releasedIdentity = false;
    // Allow get dataset and get dataset metadata access whatever share status is
    securityProxy.asTechnicalUser();
    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))) {
            // head is not allowed as step id
            final String version = getCleanStepId(preparation, stepId);
            // Create dataset
            final DataSet dataSet = mapper.readerFor(DataSet.class).readValue(parser);
            dataSet.setMetadata(dataSetGetMetadata.execute());
            // All good, can already release identity
            securityProxy.releaseIdentity();
            releasedIdentity = true;
            // get the actions to apply (no preparation ==> dataset export ==> no actions)
            final String actions = getActions(preparationId, version);
            final TransformationCacheKey key = // 
            cacheKeyGenerator.generateContentKey(// 
            dataSetId, // 
            preparationId, // 
            version, // 
            formatName, // 
            parameters.getFrom(), // 
            parameters.getArguments(), // 
            parameters.getFilter());
            LOGGER.debug("Cache key: " + key.getKey());
            LOGGER.debug("Cache key details: " + key.toString());
            try (final TeeOutputStream tee = new TeeOutputStream(outputStream, contentCache.put(key, ContentCache.TimeToLive.DEFAULT))) {
                final Configuration configuration = // 
                Configuration.builder().args(// 
                parameters.getArguments()).outFilter(// 
                rm -> filterService.build(parameters.getFilter(), rm)).sourceType(parameters.getFrom()).format(// 
                format.getName()).actions(// 
                actions).preparation(// 
                preparation).stepId(// 
                version).volume(// 
                Configuration.Volume.SMALL).output(// 
                tee).limit(// 
                limit).build();
                factory.get(configuration).buildExecutable(dataSet, configuration).execute();
                tee.flush();
            } catch (Throwable e) {
                // NOSONAR
                contentCache.evict(key);
                throw e;
            }
        }
    } catch (TDPException e) {
        throw e;
    } catch (Exception e) {
        throw new TDPException(TransformationErrorCodes.UNABLE_TO_TRANSFORM_DATASET, e);
    } finally {
        if (!releasedIdentity) {
            // Release identity in case of error.
            securityProxy.releaseIdentity();
        }
    }
}
Also used : ExportFormat(org.talend.dataprep.format.export.ExportFormat) StringUtils(org.apache.commons.lang.StringUtils) DataSetGet(org.talend.dataprep.command.dataset.DataSetGet) TDPException(org.talend.dataprep.exception.TDPException) TransformationErrorCodes(org.talend.dataprep.exception.error.TransformationErrorCodes) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) Configuration(org.talend.dataprep.transformation.api.transformer.configuration.Configuration) PreparationMessage(org.talend.dataprep.api.preparation.PreparationMessage) CacheKeyGenerator(org.talend.dataprep.cache.CacheKeyGenerator) TeeOutputStream(org.apache.commons.io.output.TeeOutputStream) ExportUtils(org.talend.dataprep.transformation.service.ExportUtils) DataSet(org.talend.dataprep.api.dataset.DataSet) OutputStream(java.io.OutputStream) ExportParameters(org.talend.dataprep.api.export.ExportParameters) Logger(org.slf4j.Logger) HEAD(org.talend.dataprep.api.export.ExportParameters.SourceType.HEAD) BaseExportStrategy(org.talend.dataprep.transformation.service.BaseExportStrategy) JsonParser(com.fasterxml.jackson.core.JsonParser) UTF_8(java.nio.charset.StandardCharsets.UTF_8) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) StreamingResponseBody(org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody) InputStreamReader(java.io.InputStreamReader) ContentCache(org.talend.dataprep.cache.ContentCache) SecurityProxy(org.talend.dataprep.security.SecurityProxy) CSVFormat(org.talend.dataprep.transformation.format.CSVFormat) Component(org.springframework.stereotype.Component) TransformationCacheKey(org.talend.dataprep.cache.TransformationCacheKey) DataSetGetMetadata(org.talend.dataprep.command.dataset.DataSetGetMetadata) InputStream(java.io.InputStream) DataSetGet(org.talend.dataprep.command.dataset.DataSetGet) TeeOutputStream(org.apache.commons.io.output.TeeOutputStream) 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) TransformationCacheKey(org.talend.dataprep.cache.TransformationCacheKey) TDPException(org.talend.dataprep.exception.TDPException) PreparationMessage(org.talend.dataprep.api.preparation.PreparationMessage) JsonParser(com.fasterxml.jackson.core.JsonParser)

Example 78 with TDPException

use of org.talend.dataprep.exception.TDPException in project data-prep by Talend.

the class SaveAsyncExecution method init.

@PostConstruct
public void init() {
    execute(() -> {
        try {
            final HttpPost post = new HttpPost(remoteRepositoryUrl + "/executions");
            post.setHeader(new BasicHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE));
            final StringWriter executionAsString = new StringWriter();
            mapper.writerFor(AsyncExecution.class).writeValue(executionAsString, execution);
            post.setEntity(new StringEntity(executionAsString.toString()));
            return post;
        } catch (IOException e) {
            throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
        }
    });
}
Also used : TDPException(org.talend.dataprep.exception.TDPException) HttpPost(org.apache.http.client.methods.HttpPost) StringEntity(org.apache.http.entity.StringEntity) StringWriter(java.io.StringWriter) AsyncExecution(org.talend.dataprep.async.AsyncExecution) IOException(java.io.IOException) BasicHeader(org.apache.http.message.BasicHeader) PostConstruct(javax.annotation.PostConstruct)

Example 79 with TDPException

use of org.talend.dataprep.exception.TDPException in project data-prep by Talend.

the class CommandHelper method toPublisher.

/**
 * Return a Publisher of type T out of the the hystrix command.
 *
 * @param clazz the wanted stream type.
 * @param mapper the object mapper used to parse objects.
 * @param command the hystrix command to deal with.
 * @param <T> the type of objects to stream.
 * @return a Publisher<T></T> out of the hystrix command response body.
 */
public static <T> Publisher<T> toPublisher(final Class<T> clazz, final ObjectMapper mapper, final HystrixCommand<InputStream> command) {
    AtomicInteger count = new AtomicInteger(0);
    return Flux.create(sink -> {
        final Observable<InputStream> observable = command.toObservable();
        observable.map(i -> {
            try {
                return mapper.readerFor(clazz).<T>readValues(i);
            } catch (IOException e) {
                throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
            }
        }).doOnCompleted(// 
        () -> LOGGER.debug("Completed command '{}' (emits '{}') with '{}' records.", command.getClass().getName(), clazz.getName(), count.get())).toBlocking().forEach(s -> {
            while (s.hasNext()) {
                sink.next(s.next());
                count.incrementAndGet();
            }
            sink.complete();
        });
    }, FluxSink.OverflowStrategy.BUFFER);
}
Also used : TDPException(org.talend.dataprep.exception.TDPException) Logger(org.slf4j.Logger) HttpHeaders(org.springframework.http.HttpHeaders) Publisher(org.reactivestreams.Publisher) FluxSink(reactor.core.publisher.FluxSink) LoggerFactory(org.slf4j.LoggerFactory) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) MultiValueMap(org.springframework.util.MultiValueMap) StreamingResponseBody(org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody) IOException(java.io.IOException) Header(org.apache.http.Header) Observable(rx.Observable) IOUtils(org.apache.commons.io.IOUtils) HttpStatus(org.springframework.http.HttpStatus) Flux(reactor.core.publisher.Flux) HystrixCommand(com.netflix.hystrix.HystrixCommand) Stream(java.util.stream.Stream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CommonErrorCodes(org.talend.dataprep.exception.error.CommonErrorCodes) ResponseEntity(org.springframework.http.ResponseEntity) Collections(java.util.Collections) InputStream(java.io.InputStream) TDPException(org.talend.dataprep.exception.TDPException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) InputStream(java.io.InputStream) IOException(java.io.IOException)

Example 80 with TDPException

use of org.talend.dataprep.exception.TDPException in project data-prep by Talend.

the class DataSetGetMetadata method configureLimitedDataset.

private void configureLimitedDataset(final String dataSetId) {
    execute(() -> new HttpGet(datasetServiceUrl + "/datasets/" + dataSetId + "/metadata"));
    on(HttpStatus.OK).then((req, res) -> {
        try {
            final DataSet dataSet = objectMapper.readerFor(DataSet.class).readValue(res.getEntity().getContent());
            return dataSet.getMetadata();
        } catch (IOException e) {
            throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
        } finally {
            req.releaseConnection();
        }
    });
}
Also used : TDPException(org.talend.dataprep.exception.TDPException) DataSet(org.talend.dataprep.api.dataset.DataSet) HttpGet(org.apache.http.client.methods.HttpGet) IOException(java.io.IOException)

Aggregations

TDPException (org.talend.dataprep.exception.TDPException)123 IOException (java.io.IOException)43 InputStream (java.io.InputStream)25 DataSetMetadata (org.talend.dataprep.api.dataset.DataSetMetadata)21 Test (org.junit.Test)17 ApiOperation (io.swagger.annotations.ApiOperation)16 Timed (org.talend.dataprep.metrics.Timed)14 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)13 DataSet (org.talend.dataprep.api.dataset.DataSet)13 ServiceBaseTest (org.talend.ServiceBaseTest)11 StringEntity (org.apache.http.entity.StringEntity)10 JsonParser (com.fasterxml.jackson.core.JsonParser)9 URISyntaxException (java.net.URISyntaxException)9 HttpPost (org.apache.http.client.methods.HttpPost)9 Autowired (org.springframework.beans.factory.annotation.Autowired)9 ColumnMetadata (org.talend.dataprep.api.dataset.ColumnMetadata)9 List (java.util.List)8 URIBuilder (org.apache.http.client.utils.URIBuilder)8 Marker (org.slf4j.Marker)8 ErrorCode (org.talend.daikon.exception.error.ErrorCode)8