Search in sources :

Example 61 with TDPException

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

the class OptimizedExportStrategy method performOptimizedTransform.

private void performOptimizedTransform(ExportParameters parameters, OutputStream outputStream) throws IOException {
    // Initial check
    final OptimizedPreparationInput optimizedPreparationInput = new OptimizedPreparationInput(parameters).invoke();
    if (optimizedPreparationInput == null) {
        throw new IllegalStateException("Unable to use this strategy (call accept() before calling this).");
    }
    final String preparationId = parameters.getPreparationId();
    final String dataSetId = optimizedPreparationInput.getDataSetId();
    final TransformationCacheKey transformationCacheKey = optimizedPreparationInput.getTransformationCacheKey();
    final DataSetMetadata metadata = optimizedPreparationInput.getMetadata();
    final String previousVersion = optimizedPreparationInput.getPreviousVersion();
    final String version = optimizedPreparationInput.getVersion();
    final ExportFormat format = getFormat(parameters.getExportType());
    // Get content from previous step
    try (JsonParser parser = mapper.getFactory().createParser(new InputStreamReader(contentCache.get(transformationCacheKey), UTF_8))) {
        // Create dataset
        final DataSet dataSet = mapper.readerFor(DataSet.class).readValue(parser);
        dataSet.setMetadata(metadata);
        // get the actions to apply (no preparation ==> dataset export ==> no actions)
        final String actions = getActions(preparationId, previousVersion, version);
        final PreparationMessage preparation = getPreparation(preparationId);
        preparation.setSteps(getMatchingSteps(preparation.getSteps(), previousVersion, version));
        LOGGER.debug("Running optimized strategy for preparation {} @ step #{}", preparationId, version);
        // create tee to broadcast to cache + service output
        final TransformationCacheKey key = // 
        cacheKeyGenerator.generateContentKey(// 
        dataSetId, // 
        preparationId, // 
        version, // 
        parameters.getExportType(), // 
        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);
    }
}
Also used : ExportFormat(org.talend.dataprep.format.export.ExportFormat) StringUtils(org.apache.commons.lang.StringUtils) 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) ArrayList(java.util.ArrayList) CacheKeyGenerator(org.talend.dataprep.cache.CacheKeyGenerator) TransformationMetadataCacheKey(org.talend.dataprep.cache.TransformationMetadataCacheKey) DataSetMetadata(org.talend.dataprep.api.dataset.DataSetMetadata) 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) Preparation(org.talend.dataprep.api.preparation.Preparation) ExportParameters(org.talend.dataprep.api.export.ExportParameters) Logger(org.slf4j.Logger) 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) IOException(java.io.IOException) Step(org.talend.dataprep.api.preparation.Step) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) ContentCache(org.talend.dataprep.cache.ContentCache) CSVFormat(org.talend.dataprep.transformation.format.CSVFormat) List(java.util.List) Component(org.springframework.stereotype.Component) TransformationCacheKey(org.talend.dataprep.cache.TransformationCacheKey) InputStream(java.io.InputStream) 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) ExportFormat(org.talend.dataprep.format.export.ExportFormat) DataSetMetadata(org.talend.dataprep.api.dataset.DataSetMetadata) TDPException(org.talend.dataprep.exception.TDPException) IOException(java.io.IOException) 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 62 with TDPException

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

the class FileUpgradeTaskRepository method applied.

/**
 * @see UpgradeTaskRepository#applied(String, UpgradeTaskId)
 */
@Override
public void applied(String targetId, UpgradeTaskId id) {
    AppliedUpgradeTask task = new AppliedUpgradeTask(id);
    File file = new File(getRootFolder(targetId), id.getUniqueKey() + ".json");
    try {
        mapper.writerFor(AppliedUpgradeTask.class).writeValue(file, task);
    } catch (IOException e) {
        throw new TDPException(UNEXPECTED_EXCEPTION, e);
    }
    LOG.debug("{} for {} saved here {}", task, targetId, file.getPath());
}
Also used : TDPException(org.talend.dataprep.exception.TDPException) AppliedUpgradeTask(org.talend.dataprep.upgrade.repository.model.AppliedUpgradeTask) IOException(java.io.IOException) File(java.io.File)

Example 63 with TDPException

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

the class FileSystemDataSetMetadataRepository method save.

@Override
public void save(DataSetMetadata metadata) {
    String id = metadata.getId();
    ReentrantReadWriteLock lock = locks.getLock(id);
    final File file = getFile(id);
    lock.writeLock().lock();
    try (GZIPOutputStream output = new GZIPOutputStream(new FileOutputStream(file))) {
        mapper.writer().writeValue(output, metadata);
    } catch (IOException e) {
        LOG.error("Error saving {}", metadata, e);
        throw new TDPException(DataSetErrorCodes.UNABLE_TO_STORE_DATASET_METADATA, e, ExceptionContext.build().put("id", metadata.getId()));
    } finally {
        lock.writeLock().unlock();
    }
}
Also used : TDPException(org.talend.dataprep.exception.TDPException) GZIPOutputStream(java.util.zip.GZIPOutputStream) ReentrantReadWriteLock(java.util.concurrent.locks.ReentrantReadWriteLock)

Example 64 with TDPException

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

the class FolderService method list.

/**
 * Get folders. If parentId is supplied, it will be used as filter.
 *
 * @param parentId the parent folder id parameter
 * @return direct sub folders for the given id.
 */
// @formatter:off
@RequestMapping(value = "/folders", method = GET)
@ApiOperation(value = "List children folders of the parameter if null list root children.", notes = "List all child folders of the one as parameter")
@Timed
public Stream<Folder> list(@RequestParam(required = false) @ApiParam(value = "Parent id filter.") String parentId, @RequestParam(defaultValue = "lastModificationDate") @ApiParam(value = "Sort key (by name or date).") Sort sort, @RequestParam(defaultValue = "desc") @ApiParam(value = "Order for sort key (desc or asc).") Order order) {
    // @formatter:on
    Stream<Folder> children;
    if (parentId != null) {
        if (!folderRepository.exists(parentId)) {
            throw new TDPException(FOLDER_NOT_FOUND, build().put("id", parentId));
        }
        children = folderRepository.children(parentId);
    } else {
        // This will list all folders
        children = folderRepository.searchFolders("", false);
    }
    final AtomicInteger folderCount = new AtomicInteger();
    // update the number of preparations in each children
    children = children.peek(f -> {
        final long count = folderRepository.count(f.getId(), PREPARATION);
        f.setNbPreparations(count);
        folderCount.addAndGet(1);
    });
    LOGGER.info("Found {} children for parentId: {}", folderCount.get(), parentId);
    // sort the folders
    return children.sorted(getFolderComparator(sort, order));
}
Also used : TDPException(org.talend.dataprep.exception.TDPException) PathVariable(org.springframework.web.bind.annotation.PathVariable) RequestParam(org.springframework.web.bind.annotation.RequestParam) TDPException(org.talend.dataprep.exception.TDPException) PREPARATION(org.talend.dataprep.api.folder.FolderContentType.PREPARATION) PUT(org.springframework.web.bind.annotation.RequestMethod.PUT) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ApiParam(io.swagger.annotations.ApiParam) FOLDER_NOT_FOUND(org.talend.dataprep.exception.error.FolderErrorCodes.FOLDER_NOT_FOUND) GET(org.springframework.web.bind.annotation.RequestMethod.GET) RequestBody(org.springframework.web.bind.annotation.RequestBody) ApiOperation(io.swagger.annotations.ApiOperation) ExceptionContext.build(org.talend.daikon.exception.ExceptionContext.build) ExceptionContext(org.talend.daikon.exception.ExceptionContext) Folder(org.talend.dataprep.api.folder.Folder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) StreamSupport(java.util.stream.StreamSupport) Api(io.swagger.annotations.Api) FolderRepository(org.talend.dataprep.folder.store.FolderRepository) SortAndOrderHelper.getFolderComparator(org.talend.dataprep.util.SortAndOrderHelper.getFolderComparator) Logger(org.slf4j.Logger) DELETE(org.springframework.web.bind.annotation.RequestMethod.DELETE) Order(org.talend.dataprep.util.SortAndOrderHelper.Order) HttpResponseContext(org.talend.dataprep.http.HttpResponseContext) Sort(org.talend.dataprep.util.SortAndOrderHelper.Sort) FolderTreeNode(org.talend.dataprep.api.folder.FolderTreeNode) RestController(org.springframework.web.bind.annotation.RestController) HttpStatus(org.springframework.http.HttpStatus) Collectors.toList(java.util.stream.Collectors.toList) List(java.util.List) Stream(java.util.stream.Stream) Security(org.talend.dataprep.security.Security) Timed(org.talend.dataprep.metrics.Timed) FolderInfo(org.talend.dataprep.api.folder.FolderInfo) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Folder(org.talend.dataprep.api.folder.Folder) Timed(org.talend.dataprep.metrics.Timed) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 65 with TDPException

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

the class StreamModuleTest method shouldHaveCorrectJSONWithTDPFailure.

@Test
public void shouldHaveCorrectJSONWithTDPFailure() throws Exception {
    // Given
    Iterator<String> failedIterator = new Iterator<String>() {

        int i = 0;

        @Override
        public boolean hasNext() {
            return i < 2;
        }

        @Override
        public String next() {
            if (i <= 0) {
                i++;
                return "string1";
            } else {
                throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION);
            }
        }
    };
    final Stream<String> stringStream = stream(spliterator(failedIterator, 2, 0), false);
    // When
    final StringWriter writer = new StringWriter();
    try {
        mapper.writeValue(writer, stringStream);
    } catch (IOException e) {
    // Ignored
    }
    // Then
    assertThat(writer.toString(), sameJSONAs("[\"string1\"]"));
}
Also used : TDPException(org.talend.dataprep.exception.TDPException) StringWriter(java.io.StringWriter) Iterator(java.util.Iterator) IOException(java.io.IOException) Test(org.junit.Test) ServiceBaseTest(org.talend.ServiceBaseTest)

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