Search in sources :

Example 31 with Value

use of org.springframework.beans.factory.annotation.Value in project data-prep by Talend.

the class DataSetAPI method getPreparation.

/**
 * Return the list of preparation using a dataset
 *
 * @param id the wanted dataset.
 * @return the list of preparation using the dataset
 */
@RequestMapping(value = "/api/datasets/{id}/preparations", method = GET, produces = APPLICATION_JSON_VALUE)
@ApiOperation(value = "Get the list of preparation using a dataset by the dataset id.", produces = APPLICATION_JSON_VALUE, notes = "Get the list of preparation using a dataset by the dataset id.")
@Timed
public List<DatasetDetailsDTO.Preparation> getPreparation(@ApiParam(value = "Id of the data set to get") @PathVariable(value = "id") String id) {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Requesting preparations using dataset #{} (pool: {})...", id, getConnectionStats());
    }
    try {
        DatasetDetailsDTO details = datasetClient.getDataSetDetails(id);
        // Add the related preparations list to the given dataset metadata.
        final PreparationSearchByDataSetId getPreparations = getCommand(PreparationSearchByDataSetId.class, details.getId());
        List<DatasetDetailsDTO.Preparation> preps = new ArrayList<>();
        // 
        toStream(PreparationDTO.class, mapper, getPreparations).filter(p -> p.getSteps() != null).forEach(p -> preps.add(new DatasetDetailsDTO.Preparation(p.getId(), p.getName(), (long) p.getSteps().size(), p.getLastModificationDate())));
        return preps;
    } finally {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Request preparations using dataset #{} (pool: {}) done.", id, getConnectionStats());
        }
    }
}
Also used : PathVariable(org.springframework.web.bind.annotation.PathVariable) RequestParam(org.springframework.web.bind.annotation.RequestParam) UpdateDataSet(org.talend.dataprep.api.service.command.dataset.UpdateDataSet) StringUtils.containsIgnoreCase(org.apache.commons.lang3.StringUtils.containsIgnoreCase) PUT(org.springframework.web.bind.annotation.RequestMethod.PUT) Autowired(org.springframework.beans.factory.annotation.Autowired) ApiParam(io.swagger.annotations.ApiParam) SetFavorite(org.talend.dataprep.api.service.command.dataset.SetFavorite) DatasetDetailsDTO(org.talend.dataprep.api.dataset.DatasetDetailsDTO) CommandHelper.toStream(org.talend.dataprep.command.CommandHelper.toStream) DatasetDTO(org.talend.dataprep.api.dataset.DatasetDTO) TEXT_PLAIN_VALUE(org.springframework.http.MediaType.TEXT_PLAIN_VALUE) CommandHelper.toStreaming(org.talend.dataprep.command.CommandHelper.toStreaming) SemanticDomain(org.talend.dataprep.api.dataset.statistics.SemanticDomain) ApiOperation(io.swagger.annotations.ApiOperation) DataSetMetadata(org.talend.dataprep.api.dataset.DataSetMetadata) DataSet(org.talend.dataprep.api.dataset.DataSet) CertificationState(org.talend.dataprep.dataset.adapter.Dataset.CertificationState) Order(org.talend.dataprep.util.SortAndOrderHelper.Order) MediaType(org.springframework.http.MediaType) UpdateColumn(org.talend.dataprep.api.service.command.dataset.UpdateColumn) PublicAPI(org.talend.dataprep.security.PublicAPI) StreamingResponseBody(org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody) Collectors(java.util.stream.Collectors) RestController(org.springframework.web.bind.annotation.RestController) DataSetPreview(org.talend.dataprep.api.service.command.dataset.DataSetPreview) List(java.util.List) HystrixCommand(com.netflix.hystrix.HystrixCommand) StringUtils.isNotBlank(org.apache.commons.lang3.StringUtils.isNotBlank) Stream(java.util.stream.Stream) GetDataSetColumnTypes(org.talend.dataprep.api.service.command.dataset.GetDataSetColumnTypes) RequestHeader(org.springframework.web.bind.annotation.RequestHeader) PreparationList(org.talend.dataprep.api.service.command.preparation.PreparationList) CopyDataSet(org.talend.dataprep.api.service.command.dataset.CopyDataSet) GenericCommand(org.talend.dataprep.command.GenericCommand) SuggestLookupActions(org.talend.dataprep.api.service.command.transformation.SuggestLookupActions) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) Callable(java.util.concurrent.Callable) CreateOrUpdateDataSet(org.talend.dataprep.api.service.command.dataset.CreateOrUpdateDataSet) SortAndOrderHelper(org.talend.dataprep.util.SortAndOrderHelper) GET(org.springframework.web.bind.annotation.RequestMethod.GET) PreparationSearchByDataSetId(org.talend.dataprep.api.service.command.preparation.PreparationSearchByDataSetId) DatasetClient(org.talend.dataprep.dataset.adapter.DatasetClient) ArrayList(java.util.ArrayList) Value(org.springframework.beans.factory.annotation.Value) CONTENT_TYPE(org.springframework.http.HttpHeaders.CONTENT_TYPE) Charset(java.nio.charset.Charset) CompatibleDataSetList(org.talend.dataprep.api.service.command.dataset.CompatibleDataSetList) POST(org.springframework.web.bind.annotation.RequestMethod.POST) DataSetGetImportParameters(org.talend.dataprep.api.service.command.dataset.DataSetGetImportParameters) DELETE(org.springframework.web.bind.annotation.RequestMethod.DELETE) CreateDataSet(org.talend.dataprep.api.service.command.dataset.CreateDataSet) Sort(org.talend.dataprep.util.SortAndOrderHelper.Sort) APPLICATION_JSON_VALUE(org.springframework.http.MediaType.APPLICATION_JSON_VALUE) StringsHelper(org.talend.dataprep.util.StringsHelper) ActionForm(org.talend.dataprep.api.action.ActionForm) PreparationDTO(org.talend.dataprep.api.preparation.PreparationDTO) DataSetDelete(org.talend.dataprep.api.service.command.dataset.DataSetDelete) CERTIFIED(org.talend.dataprep.dataset.adapter.Dataset.CertificationState.CERTIFIED) ResponseEntity(org.springframework.http.ResponseEntity) CommandHelper(org.talend.dataprep.command.CommandHelper) EncodingSupport(org.talend.dataprep.configuration.EncodingSupport) Timed(org.talend.dataprep.metrics.Timed) InputStream(java.io.InputStream) DatasetDetailsDTO(org.talend.dataprep.api.dataset.DatasetDetailsDTO) ArrayList(java.util.ArrayList) PreparationSearchByDataSetId(org.talend.dataprep.api.service.command.preparation.PreparationSearchByDataSetId) Timed(org.talend.dataprep.metrics.Timed) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 32 with Value

use of org.springframework.beans.factory.annotation.Value in project data-prep by Talend.

the class XlsSchemaParser method guessColumnType.

/**
 * @param colId the column id.
 * @param columnRows all rows with previously guessed type: key=row number, value= guessed type
 * @param averageHeaderSize
 * @return
 */
private Type guessColumnType(Integer colId, SortedMap<Integer, String> columnRows, int averageHeaderSize) {
    // calculate number per type
    Map<String, Long> perTypeNumber = columnRows.tailMap(averageHeaderSize).values().stream().collect(Collectors.groupingBy(w -> w, Collectors.counting()));
    OptionalLong maxOccurrence = perTypeNumber.values().stream().mapToLong(Long::longValue).max();
    if (!maxOccurrence.isPresent()) {
        return ANY;
    }
    List<String> duplicatedMax = new ArrayList<>();
    perTypeNumber.forEach((type1, aLong) -> {
        if (aLong >= maxOccurrence.getAsLong()) {
            duplicatedMax.add(type1);
        }
    });
    String guessedType;
    if (duplicatedMax.size() == 1) {
        guessedType = duplicatedMax.get(0);
    } else {
        // as we have more than one type we guess ANY
        guessedType = ANY.getName();
    }
    LOGGER.debug("guessed type for column #{} is {}", colId, guessedType);
    return Type.get(guessedType);
}
Also used : CellType(org.apache.poi.ss.usermodel.CellType) TDPException(org.talend.dataprep.exception.TDPException) DataSetErrorCodes(org.talend.dataprep.exception.error.DataSetErrorCodes) PushbackInputStream(java.io.PushbackInputStream) LoggerFactory(org.slf4j.LoggerFactory) Schema(org.talend.dataprep.schema.Schema) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) STRING(org.talend.dataprep.api.type.Type.STRING) Value(org.springframework.beans.factory.annotation.Value) OptionalLong(java.util.OptionalLong) HSSFDateUtil(org.apache.poi.hssf.usermodel.HSSFDateUtil) ExceptionContext(org.talend.daikon.exception.ExceptionContext) Service(org.springframework.stereotype.Service) Markers(org.talend.dataprep.log.Markers) DATE(org.talend.dataprep.api.type.Type.DATE) Map(java.util.Map) DataprepBundle.message(org.talend.dataprep.i18n.DataprepBundle.message) Cell(org.apache.poi.ss.usermodel.Cell) ANY(org.talend.dataprep.api.type.Type.ANY) WorkbookFactory(org.apache.poi.ss.usermodel.WorkbookFactory) Sheet(org.apache.poi.ss.usermodel.Sheet) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) BOOLEAN(org.talend.dataprep.api.type.Type.BOOLEAN) NUMERIC(org.talend.dataprep.api.type.Type.NUMERIC) IOException(java.io.IOException) SchemaParser(org.talend.dataprep.schema.SchemaParser) StreamingReader(org.talend.dataprep.schema.xls.streaming.StreamingReader) Collectors(java.util.stream.Collectors) FormulaEvaluator(org.apache.poi.ss.usermodel.FormulaEvaluator) FileMagic(org.apache.poi.poifs.filesystem.FileMagic) List(java.util.List) Workbook(org.apache.poi.ss.usermodel.Workbook) Type(org.talend.dataprep.api.type.Type) TreeMap(java.util.TreeMap) Marker(org.slf4j.Marker) StreamingSheet(org.talend.dataprep.schema.xls.streaming.StreamingSheet) Row(org.apache.poi.ss.usermodel.Row) CommonErrorCodes(org.talend.dataprep.exception.error.CommonErrorCodes) Collections(java.util.Collections) SortedMap(java.util.SortedMap) InputStream(java.io.InputStream) ColumnMetadata(org.talend.dataprep.api.dataset.ColumnMetadata) OptionalLong(java.util.OptionalLong) ArrayList(java.util.ArrayList) OptionalLong(java.util.OptionalLong)

Example 33 with Value

use of org.springframework.beans.factory.annotation.Value in project data-prep by Talend.

the class DataSetService method preview.

/**
 * Returns preview of the the data set content for given id (first 100 rows). Service might return
 * {@link org.apache.http.HttpStatus#SC_ACCEPTED} if the data set exists but analysis is not yet fully
 * completed so content is not yet ready to be served.
 *
 * @param metadata If <code>true</code>, includes data set metadata information.
 * @param sheetName the sheet name to preview
 * @param dataSetId A data set id.
 */
@RequestMapping(value = "/datasets/{id}/preview", method = RequestMethod.GET)
@ApiOperation(value = "Get a data preview set by id", notes = "Get a data set preview content based on provided id. Not valid or non existing data set id returns empty content. Data set not in drat status will return a redirect 301")
@Timed
@ResponseBody
public DataSet preview(@RequestParam(defaultValue = "true") @ApiParam(name = "metadata", value = "Include metadata information in the response") boolean metadata, @RequestParam(defaultValue = "") @ApiParam(name = "sheetName", value = "Sheet name to preview") String sheetName, @PathVariable(value = "id") @ApiParam(name = "id", value = "Id of the requested data set") String dataSetId) {
    DataSetMetadata dataSetMetadata = dataSetMetadataRepository.get(dataSetId);
    if (dataSetMetadata == null) {
        HttpResponseContext.status(HttpStatus.NO_CONTENT);
        // No data set, returns empty content.
        return DataSet.empty();
    }
    if (!dataSetMetadata.isDraft()) {
        // Moved to get data set content operation
        HttpResponseContext.status(HttpStatus.MOVED_PERMANENTLY);
        HttpResponseContext.header("Location", "/datasets/" + dataSetId + "/content");
        // dataset not anymore a draft so preview doesn't make sense.
        return DataSet.empty();
    }
    if (StringUtils.isNotEmpty(sheetName)) {
        dataSetMetadata.setSheetName(sheetName);
    }
    // take care of previous data without schema parser result
    if (dataSetMetadata.getSchemaParserResult() != null) {
        // sheet not yet set correctly so use the first one
        if (StringUtils.isEmpty(dataSetMetadata.getSheetName())) {
            String theSheetName = dataSetMetadata.getSchemaParserResult().getSheetContents().get(0).getName();
            LOG.debug("preview for dataSetMetadata: {} with sheetName: {}", dataSetId, theSheetName);
            dataSetMetadata.setSheetName(theSheetName);
        }
        String theSheetName = dataSetMetadata.getSheetName();
        Optional<Schema.SheetContent> sheetContentFound = dataSetMetadata.getSchemaParserResult().getSheetContents().stream().filter(// 
        sheetContent -> theSheetName.equals(sheetContent.getName())).findFirst();
        if (!sheetContentFound.isPresent()) {
            HttpResponseContext.status(HttpStatus.NO_CONTENT);
            // No sheet found, returns empty content.
            return DataSet.empty();
        }
        List<ColumnMetadata> columnMetadatas = sheetContentFound.get().getColumnMetadatas();
        if (dataSetMetadata.getRowMetadata() == null) {
            dataSetMetadata.setRowMetadata(new RowMetadata(emptyList()));
        }
        dataSetMetadata.getRowMetadata().setColumns(columnMetadatas);
    } else {
        LOG.warn("dataset#{} has draft status but any SchemaParserResult", dataSetId);
    }
    // Build the result
    DataSet dataSet = new DataSet();
    if (metadata) {
        dataSet.setMetadata(conversionService.convert(dataSetMetadata, UserDataSetMetadata.class));
    }
    dataSet.setRecords(contentStore.stream(dataSetMetadata).limit(100));
    return dataSet;
}
Also used : VolumeMetered(org.talend.dataprep.metrics.VolumeMetered) RequestParam(org.springframework.web.bind.annotation.RequestParam) ImportBuilder(org.talend.dataprep.api.dataset.Import.ImportBuilder) FormatFamilyFactory(org.talend.dataprep.schema.FormatFamilyFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) ApiParam(io.swagger.annotations.ApiParam) StringUtils(org.apache.commons.lang3.StringUtils) TEXT_PLAIN_VALUE(org.springframework.http.MediaType.TEXT_PLAIN_VALUE) SortAndOrderHelper.getDataSetMetadataComparator(org.talend.dataprep.util.SortAndOrderHelper.getDataSetMetadataComparator) Collections.singletonList(java.util.Collections.singletonList) SemanticDomain(org.talend.dataprep.api.dataset.statistics.SemanticDomain) BeanConversionService(org.talend.dataprep.conversions.BeanConversionService) PipedInputStream(java.io.PipedInputStream) DistributedLock(org.talend.dataprep.lock.DistributedLock) Arrays.asList(java.util.Arrays.asList) Map(java.util.Map) DataprepBundle.message(org.talend.dataprep.i18n.DataprepBundle.message) UserData(org.talend.dataprep.api.user.UserData) TaskExecutor(org.springframework.core.task.TaskExecutor) MAX_STORAGE_MAY_BE_EXCEEDED(org.talend.dataprep.exception.error.DataSetErrorCodes.MAX_STORAGE_MAY_BE_EXCEEDED) DataSet(org.talend.dataprep.api.dataset.DataSet) LocalStoreLocation(org.talend.dataprep.api.dataset.location.LocalStoreLocation) FormatFamily(org.talend.dataprep.schema.FormatFamily) Resource(javax.annotation.Resource) Set(java.util.Set) DatasetUpdatedEvent(org.talend.dataprep.dataset.event.DatasetUpdatedEvent) RestController(org.springframework.web.bind.annotation.RestController) IOUtils(org.apache.commons.io.IOUtils) QuotaService(org.talend.dataprep.dataset.store.QuotaService) SecurityProxy(org.talend.dataprep.security.SecurityProxy) Stream(java.util.stream.Stream) StreamSupport.stream(java.util.stream.StreamSupport.stream) FlagNames(org.talend.dataprep.api.dataset.row.FlagNames) UNEXPECTED_CONTENT(org.talend.dataprep.exception.error.CommonErrorCodes.UNEXPECTED_CONTENT) Analyzers(org.talend.dataquality.common.inference.Analyzers) DatasetImportedEvent(org.talend.dataprep.dataset.event.DatasetImportedEvent) DataSetLocatorService(org.talend.dataprep.api.dataset.location.locator.DataSetLocatorService) Callable(java.util.concurrent.Callable) Schema(org.talend.dataprep.schema.Schema) ArrayList(java.util.ArrayList) Value(org.springframework.beans.factory.annotation.Value) RequestBody(org.springframework.web.bind.annotation.RequestBody) DataSetLocationService(org.talend.dataprep.api.dataset.location.DataSetLocationService) AnalyzerService(org.talend.dataprep.quality.AnalyzerService) UserDataRepository(org.talend.dataprep.user.store.UserDataRepository) Markers(org.talend.dataprep.log.Markers) Api(io.swagger.annotations.Api) DraftValidator(org.talend.dataprep.schema.DraftValidator) HttpResponseContext(org.talend.dataprep.http.HttpResponseContext) Sort(org.talend.dataprep.util.SortAndOrderHelper.Sort) IOException(java.io.IOException) PipedOutputStream(java.io.PipedOutputStream) FormatAnalysis(org.talend.dataprep.dataset.service.analysis.synchronous.FormatAnalysis) ContentAnalysis(org.talend.dataprep.dataset.service.analysis.synchronous.ContentAnalysis) SchemaAnalysis(org.talend.dataprep.dataset.service.analysis.synchronous.SchemaAnalysis) HttpStatus(org.springframework.http.HttpStatus) FilterService(org.talend.dataprep.api.filter.FilterService) Marker(org.slf4j.Marker) NullOutputStream(org.apache.commons.io.output.NullOutputStream) StatisticsAdapter(org.talend.dataprep.dataset.StatisticsAdapter) Timed(org.talend.dataprep.metrics.Timed) ColumnMetadata(org.talend.dataprep.api.dataset.ColumnMetadata) PathVariable(org.springframework.web.bind.annotation.PathVariable) DataSetMetadataBuilder(org.talend.dataprep.dataset.DataSetMetadataBuilder) DataSetErrorCodes(org.talend.dataprep.exception.error.DataSetErrorCodes) PUT(org.springframework.web.bind.annotation.RequestMethod.PUT) BiFunction(java.util.function.BiFunction) LoggerFactory(org.slf4j.LoggerFactory) DatasetDTO(org.talend.dataprep.api.dataset.DatasetDTO) SEMANTIC(org.talend.dataprep.quality.AnalyzerService.Analysis.SEMANTIC) ApiOperation(io.swagger.annotations.ApiOperation) UNABLE_TO_CREATE_OR_UPDATE_DATASET(org.talend.dataprep.exception.error.DataSetErrorCodes.UNABLE_TO_CREATE_OR_UPDATE_DATASET) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) DataSetRow(org.talend.dataprep.api.dataset.row.DataSetRow) StrictlyBoundedInputStream(org.talend.dataprep.dataset.store.content.StrictlyBoundedInputStream) DataSetMetadata(org.talend.dataprep.api.dataset.DataSetMetadata) UNSUPPORTED_CONTENT(org.talend.dataprep.exception.error.DataSetErrorCodes.UNSUPPORTED_CONTENT) TimeToLive(org.talend.dataprep.cache.ContentCache.TimeToLive) Order(org.talend.dataprep.util.SortAndOrderHelper.Order) Collections.emptyList(java.util.Collections.emptyList) Predicate(java.util.function.Predicate) PublicAPI(org.talend.dataprep.security.PublicAPI) RequestMethod(org.springframework.web.bind.annotation.RequestMethod) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) ContentCache(org.talend.dataprep.cache.ContentCache) INVALID_DATASET_NAME(org.talend.dataprep.exception.error.DataSetErrorCodes.INVALID_DATASET_NAME) List(java.util.List) Optional(java.util.Optional) Analyzer(org.talend.dataquality.common.inference.Analyzer) RequestHeader(org.springframework.web.bind.annotation.RequestHeader) Pattern(java.util.regex.Pattern) Security(org.talend.dataprep.security.Security) Spliterator(java.util.Spliterator) RowMetadata(org.talend.dataprep.api.dataset.RowMetadata) ComponentProperties(org.talend.dataprep.parameters.jsonschema.ComponentProperties) TDPException(org.talend.dataprep.exception.TDPException) JsonErrorCodeDescription(org.talend.dataprep.exception.json.JsonErrorCodeDescription) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) UNABLE_CREATE_DATASET(org.talend.dataprep.exception.error.DataSetErrorCodes.UNABLE_CREATE_DATASET) HashMap(java.util.HashMap) GET(org.springframework.web.bind.annotation.RequestMethod.GET) HashSet(java.util.HashSet) Import(org.talend.dataprep.api.dataset.Import) ExceptionContext.build(org.talend.daikon.exception.ExceptionContext.build) ExceptionContext(org.talend.daikon.exception.ExceptionContext) UpdateColumnParameters(org.talend.dataprep.dataset.service.api.UpdateColumnParameters) VersionService(org.talend.dataprep.api.service.info.VersionService) POST(org.springframework.web.bind.annotation.RequestMethod.POST) OutputStream(java.io.OutputStream) DataSetLocation(org.talend.dataprep.api.dataset.DataSetLocation) Logger(org.slf4j.Logger) LocaleContextHolder.getLocale(org.springframework.context.i18n.LocaleContextHolder.getLocale) UpdateDataSetCacheKey(org.talend.dataprep.dataset.service.cache.UpdateDataSetCacheKey) DataSetContentLimit(org.talend.dataprep.dataset.store.content.DataSetContentLimit) APPLICATION_JSON_VALUE(org.springframework.http.MediaType.APPLICATION_JSON_VALUE) ResponseBody(org.springframework.web.bind.annotation.ResponseBody) Certification(org.talend.dataprep.api.dataset.DataSetGovernance.Certification) Comparator(java.util.Comparator) InputStream(java.io.InputStream) ColumnMetadata(org.talend.dataprep.api.dataset.ColumnMetadata) DataSet(org.talend.dataprep.api.dataset.DataSet) RowMetadata(org.talend.dataprep.api.dataset.RowMetadata) DataSetMetadata(org.talend.dataprep.api.dataset.DataSetMetadata) Timed(org.talend.dataprep.metrics.Timed) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) ResponseBody(org.springframework.web.bind.annotation.ResponseBody)

Example 34 with Value

use of org.springframework.beans.factory.annotation.Value in project topcom-cloud by 545314690.

the class DataXUtil method setDataxLogPath.

@Value("${dataxLogPath:/home/topcom/dataxlog/ }")
public void setDataxLogPath(String dataxLogPath) {
    DataXUtil.dataxLogPath = dataxLogPath;
    File parentLogPath = new File(DataXUtil.dataxLogPath);
    if (!parentLogPath.exists()) {
        parentLogPath.mkdirs();
    }
}
Also used : File(java.io.File) Value(org.springframework.beans.factory.annotation.Value)

Example 35 with Value

use of org.springframework.beans.factory.annotation.Value in project ArachneCentralAPI by OHDSI.

the class BaseAnalysisController method doAddCommonEntityToAnalysis.

protected void doAddCommonEntityToAnalysis(T analysis, DataReference dataReference, IUser user, CommonAnalysisType analysisType, List<MultipartFile> files) throws IOException {
    files.stream().filter(f -> !CommonAnalysisType.COHORT.equals(analysisType) || !f.getName().endsWith(CommonFileUtils.OHDSI_JSON_EXT)).forEach(f -> {
        try {
            analysisService.saveFile(f, user, analysis, f.getName(), detectExecutable(analysisType, f), dataReference);
        } catch (IOException e) {
            LOGGER.error("Failed to save file", e);
        }
    });
    if (analysisType.equals(CommonAnalysisType.COHORT)) {
        final ByteArrayOutputStream out = new ByteArrayOutputStream();
        class StringContainer {

            String value = CommonAnalysisType.COHORT.getTitle();
        }
        final StringContainer generatedFileName = new StringContainer();
        try (final ZipOutputStream zos = new ZipOutputStream(out)) {
            files.forEach(file -> {
                try {
                    if (file.getName().endsWith(CommonFileUtils.OHDSI_SQL_EXT)) {
                        String statement = org.apache.commons.io.IOUtils.toString(file.getInputStream(), "UTF-8");
                        String renderedSql = SqlRender.renderSql(statement, null, null);
                        DBMSType[] dbTypes = new DBMSType[] { DBMSType.POSTGRESQL, DBMSType.ORACLE, DBMSType.MS_SQL_SERVER, DBMSType.REDSHIFT, DBMSType.PDW };
                        String baseName = FilenameUtils.getBaseName(file.getOriginalFilename());
                        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
                        for (final DBMSType dialect : dbTypes) {
                            final String sql = SqlTranslate.translateSql(renderedSql, DBMSType.MS_SQL_SERVER.getOhdsiDB(), dialect.getOhdsiDB());
                            final String fileName = baseName + "." + dialect.getLabel().replaceAll(" ", "-") + "." + extension;
                            ZipUtil.addZipEntry(zos, fileName, new ByteArrayInputStream(sql.getBytes("UTF-8")));
                        }
                        final String shortBaseName = baseName.replaceAll("\\.ohdsi", "");
                        if (!generatedFileName.value.contains(shortBaseName)) {
                            generatedFileName.value += "_" + shortBaseName;
                        }
                    } else {
                        String fileName = file.getName();
                        ZipUtil.addZipEntry(zos, fileName, file.getInputStream());
                    }
                } catch (IOException e) {
                    LOGGER.error("Failed to add file to archive", e);
                    throw new RuntimeIOException(e.getMessage(), e);
                }
            });
        }
        String fileName = generatedFileName.value + ".zip";
        final MultipartFile sqlArchive = new MockMultipartFile(fileName, fileName, "application/zip", out.toByteArray());
        analysisService.saveFile(sqlArchive, user, analysis, fileName, false, dataReference);
    }
}
Also used : Arrays(java.util.Arrays) RequestParam(org.springframework.web.bind.annotation.RequestParam) SqlTranslate(org.ohdsi.sql.SqlTranslate) Valid(javax.validation.Valid) CommentUtils.getRecentCommentables(com.odysseusinc.arachne.portal.util.CommentUtils.getRecentCommentables) AnalysisLockDTO(com.odysseusinc.arachne.portal.api.v1.dto.AnalysisLockDTO) BaseDataSourceService(com.odysseusinc.arachne.portal.service.BaseDataSourceService) Analysis(com.odysseusinc.arachne.portal.model.Analysis) Map(java.util.Map) Commentable(com.odysseusinc.arachne.portal.api.v1.dto.Commentable) Sort(org.springframework.data.domain.Sort) ImportedFile(com.odysseusinc.arachne.portal.util.ImportedFile) Resource(org.springframework.core.io.Resource) MessagingUtils(com.odysseusinc.arachne.portal.service.messaging.MessagingUtils) FieldError(org.springframework.validation.FieldError) SqlRender(org.ohdsi.sql.SqlRender) Set(java.util.Set) AnalysisFileDTO(com.odysseusinc.arachne.portal.api.v1.dto.AnalysisFileDTO) Page(org.springframework.data.domain.Page) MockMultipartFile(org.springframework.mock.web.MockMultipartFile) IUser(com.odysseusinc.arachne.portal.model.IUser) IOUtils(org.apache.commons.io.IOUtils) SimpMessagingTemplate(org.springframework.messaging.simp.SimpMessagingTemplate) RuntimeIOException(org.assertj.core.api.exception.RuntimeIOException) VALIDATION_ERROR(com.odysseusinc.arachne.commons.api.v1.dto.util.JsonResult.ErrorCode.VALIDATION_ERROR) ZipOutputStream(java.util.zip.ZipOutputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) DataReference(com.odysseusinc.arachne.portal.model.DataReference) BindingResult(org.springframework.validation.BindingResult) ArrayList(java.util.ArrayList) Value(org.springframework.beans.factory.annotation.Value) RequestBody(org.springframework.web.bind.annotation.RequestBody) ZipUtil(com.odysseusinc.arachne.portal.util.ZipUtil) SubmissionInsightDTO(com.odysseusinc.arachne.portal.api.v1.dto.SubmissionInsightDTO) NO_ERROR(com.odysseusinc.arachne.commons.api.v1.dto.util.JsonResult.ErrorCode.NO_ERROR) StreamSupport(java.util.stream.StreamSupport) CommonEntityRequestDTO(com.odysseusinc.arachne.commons.api.v1.dto.CommonEntityRequestDTO) IOException(java.io.IOException) GenericConversionService(org.springframework.core.convert.support.GenericConversionService) HttpUtils.putFileContentToResponse(com.odysseusinc.arachne.portal.util.HttpUtils.putFileContentToResponse) SubmissionInsightUpdateDTO(com.odysseusinc.arachne.portal.api.v1.dto.SubmissionInsightUpdateDTO) DataReferenceDTO(com.odysseusinc.arachne.portal.api.v1.dto.DataReferenceDTO) AnalysisFile(com.odysseusinc.arachne.portal.model.AnalysisFile) UpdateNotificationDTO(com.odysseusinc.arachne.portal.api.v1.dto.UpdateNotificationDTO) AnalysisUpdateDTO(com.odysseusinc.arachne.portal.api.v1.dto.AnalysisUpdateDTO) PathVariable(org.springframework.web.bind.annotation.PathVariable) AnalysisUnlockRequestDTO(com.odysseusinc.arachne.portal.api.v1.dto.AnalysisUnlockRequestDTO) Date(java.util.Date) PUT(org.springframework.web.bind.annotation.RequestMethod.PUT) URISyntaxException(java.net.URISyntaxException) LoggerFactory(org.slf4j.LoggerFactory) ApiOperation(io.swagger.annotations.ApiOperation) ByteArrayInputStream(java.io.ByteArrayInputStream) PERMISSION_DENIED(com.odysseusinc.arachne.commons.api.v1.dto.util.JsonResult.ErrorCode.PERMISSION_DENIED) AnalysisUnlockRequest(com.odysseusinc.arachne.portal.model.AnalysisUnlockRequest) ToPdfConverter(com.odysseusinc.arachne.portal.service.ToPdfConverter) BaseSubmissionService(com.odysseusinc.arachne.portal.service.submission.BaseSubmissionService) BaseAnalysisService(com.odysseusinc.arachne.portal.service.analysis.BaseAnalysisService) AnalysisDTO(com.odysseusinc.arachne.portal.api.v1.dto.AnalysisDTO) AlreadyExistException(com.odysseusinc.arachne.portal.exception.AlreadyExistException) CommonAnalysisType(com.odysseusinc.arachne.commons.api.v1.dto.CommonAnalysisType) UUID(java.util.UUID) ShortBaseAnalysisDTO(com.odysseusinc.arachne.portal.api.v1.dto.ShortBaseAnalysisDTO) Collectors(java.util.stream.Collectors) JMSException(javax.jms.JMSException) FileDTO(com.odysseusinc.arachne.portal.api.v1.dto.FileDTO) CommonFileUtils(com.odysseusinc.arachne.commons.utils.CommonFileUtils) List(java.util.List) Principal(java.security.Principal) DataReferenceService(com.odysseusinc.arachne.portal.service.DataReferenceService) AnalysisCreateDTO(com.odysseusinc.arachne.portal.api.v1.dto.AnalysisCreateDTO) AnalysisUnlockRequestStatus(com.odysseusinc.arachne.portal.model.AnalysisUnlockRequestStatus) FilenameUtils(org.apache.commons.io.FilenameUtils) SubmissionGroupDTO(com.odysseusinc.arachne.portal.api.v1.dto.SubmissionGroupDTO) NotUniqueException(com.odysseusinc.arachne.portal.exception.NotUniqueException) FileDtoContentHandler(com.odysseusinc.arachne.portal.api.v1.dto.converters.FileDtoContentHandler) ClassPathResource(org.springframework.core.io.ClassPathResource) RequestMapping(org.springframework.web.bind.annotation.RequestMapping) HashMap(java.util.HashMap) ObjectMessage(javax.jms.ObjectMessage) GET(org.springframework.web.bind.annotation.RequestMethod.GET) Submission(com.odysseusinc.arachne.portal.model.Submission) SubmissionGroupSearch(com.odysseusinc.arachne.portal.model.search.SubmissionGroupSearch) ValidationException(com.odysseusinc.arachne.portal.exception.ValidationException) JsonResult(com.odysseusinc.arachne.commons.api.v1.dto.util.JsonResult) ModelAttribute(org.springframework.web.bind.annotation.ModelAttribute) JmsTemplate(org.springframework.jms.core.JmsTemplate) ProducerConsumerTemplate(com.odysseusinc.arachne.commons.service.messaging.ProducerConsumerTemplate) POST(org.springframework.web.bind.annotation.RequestMethod.POST) SubmissionInsight(com.odysseusinc.arachne.portal.model.SubmissionInsight) LinkedList(java.util.LinkedList) UploadFileDTO(com.odysseusinc.arachne.portal.api.v1.dto.UploadFileDTO) DestinationResolver(org.springframework.jms.support.destination.DestinationResolver) ServiceNotAvailableException(com.odysseusinc.arachne.portal.exception.ServiceNotAvailableException) CommentTopic(com.odysseusinc.arachne.portal.model.CommentTopic) Logger(org.slf4j.Logger) DELETE(org.springframework.web.bind.annotation.RequestMethod.DELETE) DBMSType(com.odysseusinc.arachne.commons.types.DBMSType) HttpServletResponse(javax.servlet.http.HttpServletResponse) BaseDataNodeService(com.odysseusinc.arachne.portal.service.BaseDataNodeService) PermissionDeniedException(com.odysseusinc.arachne.portal.exception.PermissionDeniedException) OptionDTO(com.odysseusinc.arachne.commons.api.v1.dto.OptionDTO) NotExistException(com.odysseusinc.arachne.portal.exception.NotExistException) DataNode(com.odysseusinc.arachne.portal.model.DataNode) MultipartFile(org.springframework.web.multipart.MultipartFile) ImportService(com.odysseusinc.arachne.portal.service.ImportService) NotEmptyException(com.odysseusinc.arachne.portal.exception.NotEmptyException) SubmissionInsightService(com.odysseusinc.arachne.portal.service.submission.SubmissionInsightService) InputStream(java.io.InputStream) StringUtils(org.springframework.util.StringUtils) MockMultipartFile(org.springframework.mock.web.MockMultipartFile) RuntimeIOException(org.assertj.core.api.exception.RuntimeIOException) MockMultipartFile(org.springframework.mock.web.MockMultipartFile) MultipartFile(org.springframework.web.multipart.MultipartFile) ByteArrayInputStream(java.io.ByteArrayInputStream) ZipOutputStream(java.util.zip.ZipOutputStream) DBMSType(com.odysseusinc.arachne.commons.types.DBMSType) RuntimeIOException(org.assertj.core.api.exception.RuntimeIOException) IOException(java.io.IOException) ByteArrayOutputStream(java.io.ByteArrayOutputStream)

Aggregations

Value (org.springframework.beans.factory.annotation.Value)71 Autowired (org.springframework.beans.factory.annotation.Autowired)33 IOException (java.io.IOException)29 Collectors (java.util.stream.Collectors)29 List (java.util.List)24 Logger (org.slf4j.Logger)23 LoggerFactory (org.slf4j.LoggerFactory)23 PathVariable (org.springframework.web.bind.annotation.PathVariable)20 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)20 ArrayList (java.util.ArrayList)18 RequestParam (org.springframework.web.bind.annotation.RequestParam)18 Map (java.util.Map)17 Optional (java.util.Optional)17 HttpServletResponse (javax.servlet.http.HttpServletResponse)16 RestController (org.springframework.web.bind.annotation.RestController)16 RequestMethod (org.springframework.web.bind.annotation.RequestMethod)15 Stream (java.util.stream.Stream)14 HttpStatus (org.springframework.http.HttpStatus)14 ApiOperation (io.swagger.annotations.ApiOperation)13 ApiParam (io.swagger.annotations.ApiParam)12