Search in sources :

Example 36 with StringUtils.isEmpty

use of org.apache.commons.lang3.StringUtils.isEmpty in project cuba by cuba-platform.

the class ScreenNavigationHandler method doHandle.

@Override
public boolean doHandle(NavigationState requestedState, AppUI ui) {
    UrlChangeHandler urlChangeHandler = ui.getUrlChangeHandler();
    if (urlChangeHandler.isEmptyState(requestedState) || !isScreenChanged(requestedState, ui)) {
        return false;
    }
    String requestedRoute = requestedState.getNestedRoute();
    if (StringUtils.isEmpty(requestedRoute)) {
        log.info("Unable to handle state with empty route '{}'", requestedState);
        urlChangeHandler.revertNavigationState();
        return true;
    }
    String[] routeParts = { requestedRoute };
    if (windowConfig.findWindowInfoByRoute(requestedRoute) == null) {
        routeParts = requestedRoute.split("/");
    }
    if (routeParts.length > MAX_SUB_ROUTES) {
        log.info("Unable to perform navigation to requested state '{}'. Only {} sub routes are supported", requestedRoute, MAX_SUB_ROUTES);
        urlChangeHandler.revertNavigationState();
        return true;
    }
    List<Pair<String, WindowInfo>> routeWindowInfos = Arrays.stream(routeParts).map(subRoute -> new Pair<>(subRoute, windowConfig.findWindowInfoByRoute(subRoute))).collect(Collectors.toList());
    for (Pair<String, WindowInfo> entry : routeWindowInfos) {
        WindowInfo routeWindowInfo = entry.getSecond();
        if (routeWindowInfo == null) {
            log.info("No registered screen found for route: '{}'", entry.getFirst());
            urlChangeHandler.revertNavigationState();
            handle404(entry.getFirst(), ui);
            return true;
        }
        if (urlChangeHandler.shouldRedirect(routeWindowInfo)) {
            urlChangeHandler.redirect(requestedState);
            return true;
        }
        if (urlChangeHandler.isRootRoute(routeWindowInfo)) {
            log.info("Unable navigate to '{}' as nested screen", routeWindowInfo.getId());
            urlChangeHandler.revertNavigationState();
            return true;
        }
    }
    return navigate(requestedState, ui, routeWindowInfos);
}
Also used : java.util(java.util) PermissionType(com.haulmont.cuba.security.entity.PermissionType) LoggerFactory(org.slf4j.LoggerFactory) ParamsMap(com.haulmont.bali.util.ParamsMap) Screen(com.haulmont.cuba.gui.screen.Screen) StringUtils(org.apache.commons.lang3.StringUtils) MetaClass(com.haulmont.chile.core.model.MetaClass) Scope(org.springframework.context.annotation.Scope) com.haulmont.cuba.core.global(com.haulmont.cuba.core.global) Inject(javax.inject.Inject) Pair(com.haulmont.bali.datastruct.Pair) UrlChangeHandler(com.haulmont.cuba.web.sys.navigation.UrlChangeHandler) AppUI(com.haulmont.cuba.web.AppUI) MapScreenOptions(com.haulmont.cuba.gui.screen.MapScreenOptions) BeanDefinition(org.springframework.beans.factory.config.BeanDefinition) OpenMode(com.haulmont.cuba.gui.screen.OpenMode) Nullable(javax.annotation.Nullable) LegacyFrame(com.haulmont.cuba.gui.screen.compatibility.LegacyFrame) EditorScreen(com.haulmont.cuba.gui.screen.EditorScreen) MapUtils(org.apache.commons.collections4.MapUtils) Order(org.springframework.core.annotation.Order) WindowInfo(com.haulmont.cuba.gui.config.WindowInfo) UrlIdSerializer(com.haulmont.cuba.web.sys.navigation.UrlIdSerializer) Logger(org.slf4j.Logger) MetaProperty(com.haulmont.chile.core.model.MetaProperty) NotFoundScreen(com.haulmont.cuba.web.app.ui.navigation.notfoundwindow.NotFoundScreen) FrameOwner(com.haulmont.cuba.gui.screen.FrameOwner) Collectors(java.util.stream.Collectors) NavigationState(com.haulmont.cuba.gui.navigation.NavigationState) NEW_ENTITY_ID(com.haulmont.cuba.web.sys.WebUrlRouting.NEW_ENTITY_ID) WindowParams(com.haulmont.cuba.gui.WindowParams) Component(org.springframework.stereotype.Component) UrlParamsChangedEvent(com.haulmont.cuba.gui.navigation.UrlParamsChangedEvent) EntityOp(com.haulmont.cuba.security.entity.EntityOp) WindowConfig(com.haulmont.cuba.gui.config.WindowConfig) WebWindow(com.haulmont.cuba.web.gui.WebWindow) EditorTypeExtractor(com.haulmont.cuba.web.sys.navigation.EditorTypeExtractor) Entity(com.haulmont.cuba.core.entity.Entity) UiControllerUtils(com.haulmont.cuba.gui.screen.UiControllerUtils) UrlChangeHandler(com.haulmont.cuba.web.sys.navigation.UrlChangeHandler) Pair(com.haulmont.bali.datastruct.Pair) WindowInfo(com.haulmont.cuba.gui.config.WindowInfo)

Example 37 with StringUtils.isEmpty

use of org.apache.commons.lang3.StringUtils.isEmpty in project mxisd by kamax-io.

the class ExecAuthStore method authenticate.

@Override
public ExecAuthResult authenticate(_MatrixID uId, String password) {
    Objects.requireNonNull(uId);
    Objects.requireNonNull(password);
    log.info("Performing authentication for {}", uId.getId());
    ExecAuthResult result = new ExecAuthResult();
    result.setId(new UserID(UserIdType.Localpart, uId.getLocalPart()));
    Processor<ExecAuthResult> p = new Processor<>(cfg);
    p.addTokenMapper(cfg.getToken().getLocalpart(), uId::getLocalPart);
    p.addTokenMapper(cfg.getToken().getDomain(), uId::getDomain);
    p.addTokenMapper(cfg.getToken().getMxid(), uId::getId);
    p.addTokenMapper(cfg.getToken().getPassword(), () -> password);
    p.addJsonInputTemplate(tokens -> {
        RestAuthRequestJson json = new RestAuthRequestJson();
        json.setLocalpart(tokens.getLocalpart());
        json.setDomain(tokens.getDomain());
        json.setMxid(tokens.getMxid());
        json.setPassword(tokens.getPassword());
        return json;
    });
    p.addInputTemplate(PlainType, tokens -> tokens.getLocalpart() + System.lineSeparator() + tokens.getDomain() + System.lineSeparator() + tokens.getMxid() + System.lineSeparator() + tokens.getPassword() + System.lineSeparator());
    p.withExitHandler(pr -> result.setExitStatus(pr.getExitValue()));
    p.withSuccessHandler(pr -> result.setSuccess(true));
    p.withSuccessDefault(o -> result);
    p.addSuccessMapper(JsonType, output -> {
        JsonObject data = GsonUtil.getObj(GsonUtil.parseObj(output), "auth");
        GsonUtil.findPrimitive(data, "success").map(JsonPrimitive::getAsBoolean).ifPresent(result::setSuccess);
        GsonUtil.findObj(data, "profile").flatMap(profile -> GsonUtil.findString(profile, "display_name")).ifPresent(v -> result.getProfile().setDisplayName(v));
        return result;
    });
    p.addSuccessMapper(PlainType, output -> {
        String[] lines = output.split("\\R");
        if (lines.length > 2) {
            throw new InternalServerError("Exec auth command returned more than 2 lines (" + lines.length + ")");
        }
        result.setSuccess(Optional.ofNullable(StringUtils.isEmpty(lines[0]) ? null : lines[0]).map(v -> StringUtils.equalsAnyIgnoreCase(v, "true", "1")).orElse(result.isSuccess()));
        if (lines.length == 2) {
            Optional.ofNullable(StringUtils.isEmpty(lines[1]) ? null : lines[1]).ifPresent(v -> result.getProfile().setDisplayName(v));
        }
        return result;
    });
    p.withFailureHandler(pr -> result.setSuccess(false));
    p.withFailureDefault(o -> result);
    return p.execute();
}
Also used : JsonObject(com.google.gson.JsonObject) GsonUtil(io.kamax.matrix.json.GsonUtil) Logger(org.slf4j.Logger) AuthenticatorProvider(io.kamax.mxisd.auth.provider.AuthenticatorProvider) RestAuthRequestJson(io.kamax.mxisd.backend.rest.RestAuthRequestJson) LoggerFactory(org.slf4j.LoggerFactory) io.kamax.matrix._MatrixID(io.kamax.matrix._MatrixID) StringUtils(org.apache.commons.lang3.StringUtils) Objects(java.util.Objects) InternalServerError(io.kamax.mxisd.exception.InternalServerError) ExecConfig(io.kamax.mxisd.config.ExecConfig) UserID(io.kamax.mxisd.UserID) Optional(java.util.Optional) UserIdType(io.kamax.mxisd.UserIdType) JsonPrimitive(com.google.gson.JsonPrimitive) RestAuthRequestJson(io.kamax.mxisd.backend.rest.RestAuthRequestJson) UserID(io.kamax.mxisd.UserID) JsonObject(com.google.gson.JsonObject) InternalServerError(io.kamax.mxisd.exception.InternalServerError)

Example 38 with StringUtils.isEmpty

use of org.apache.commons.lang3.StringUtils.isEmpty in project data-prep by Talend.

the class ResourceLoaderContentCache method getResource.

private DeletableResource getResource(ContentCacheKey key) {
    try {
        final DeletableResource[] patternMatches = resolver.getResources(CACHE_PREFIX + key.getKey() + "*");
        final DeletableResource[] directMatches = resolver.getResources(CACHE_PREFIX + key.getKey());
        final DeletableResource[] resources = new DeletableResource[patternMatches.length + directMatches.length];
        System.arraycopy(patternMatches, 0, resources, 0, patternMatches.length);
        System.arraycopy(directMatches, 0, resources, patternMatches.length, directMatches.length);
        if (resources.length <= 0) {
            return null;
        } else {
            // resources.length > 0
            final Optional<DeletableResource> reduce = stream(resources).reduce(maxBy((r1, r2) -> {
                final String suffix1 = substringAfterLast(r1.getFilename(), ".");
                final String suffix2 = substringAfterLast(r2.getFilename(), ".");
                if (StringUtils.isEmpty(suffix1) || StringUtils.isEmpty(suffix2)) {
                    return 0;
                }
                final long i1 = parseLong(suffix1);
                final long i2 = parseLong(suffix2);
                return Long.compare(i1, i2);
            }));
            return reduce.filter(r -> {
                if (!r.exists()) {
                    return false;
                }
                final String suffix = StringUtils.substringAfterLast(r.getFilename(), ".");
                if (NumberUtils.isCreatable(suffix)) {
                    final long time = parseLong(suffix);
                    return time > System.currentTimeMillis();
                } else {
                    return true;
                }
            }).orElse(null);
        }
    } catch (IOException e) {
        throw new TDPException(CommonErrorCodes.UNEXPECTED_EXCEPTION, e);
    }
}
Also used : VolumeMetered(org.talend.dataprep.metrics.VolumeMetered) TDPException(org.talend.dataprep.exception.TDPException) ContentCacheKey(org.talend.dataprep.cache.ContentCacheKey) LoggerFactory(org.slf4j.LoggerFactory) Autowired(org.springframework.beans.factory.annotation.Autowired) StringUtils(org.apache.commons.lang3.StringUtils) BinaryOperator.maxBy(java.util.function.BinaryOperator.maxBy) OutputStream(java.io.OutputStream) ConditionalOnBean(org.springframework.boot.autoconfigure.condition.ConditionalOnBean) Logger(org.slf4j.Logger) StringUtils.substringAfterLast(org.apache.commons.lang3.StringUtils.substringAfterLast) DeletableResource(org.talend.daikon.content.DeletableResource) Optional.ofNullable(java.util.Optional.ofNullable) Predicate(java.util.function.Predicate) IOException(java.io.IOException) ContentCache(org.talend.dataprep.cache.ContentCache) Component(org.springframework.stereotype.Component) ContentServiceEnabled(org.talend.daikon.content.ContentServiceEnabled) NumberUtils(org.apache.commons.lang3.math.NumberUtils) Optional(java.util.Optional) CommonErrorCodes(org.talend.dataprep.exception.error.CommonErrorCodes) ResourceResolver(org.talend.daikon.content.ResourceResolver) Long.parseLong(java.lang.Long.parseLong) Arrays.stream(java.util.Arrays.stream) Timed(org.talend.dataprep.metrics.Timed) InputStream(java.io.InputStream) TDPException(org.talend.dataprep.exception.TDPException) DeletableResource(org.talend.daikon.content.DeletableResource) IOException(java.io.IOException)

Example 39 with StringUtils.isEmpty

use of org.apache.commons.lang3.StringUtils.isEmpty 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 40 with StringUtils.isEmpty

use of org.apache.commons.lang3.StringUtils.isEmpty in project iaf by ibissource.

the class FileSystemUtils method getFilteredStream.

public static <F> Stream<F> getFilteredStream(IBasicFileSystem<F> fileSystem, String folder, String wildCard, String excludeWildCard) throws FileSystemException, IOException {
    DirectoryStream<F> ds = fileSystem.listFiles(folder);
    if (ds == null) {
        return null;
    }
    Iterator<F> it = ds.iterator();
    if (it == null) {
        return null;
    }
    WildCardFilter wildcardfilter = StringUtils.isEmpty(wildCard) ? null : new WildCardFilter(wildCard);
    WildCardFilter excludeFilter = StringUtils.isEmpty(excludeWildCard) ? null : new WildCardFilter(excludeWildCard);
    return StreamSupport.stream(Spliterators.spliteratorUnknownSize(it, 0), false).filter(F -> (wildcardfilter == null || wildcardfilter.accept(null, fileSystem.getName((F) F))) && (excludeFilter == null || !excludeFilter.accept(null, fileSystem.getName((F) F)))).onClose(() -> {
        try {
            ds.close();
        } catch (IOException e) {
            throw Lombok.sneakyThrow(e);
        }
    });
}
Also used : Misc(nl.nn.adapterframework.util.Misc) Iterator(java.util.Iterator) Date(java.util.Date) Spliterators(java.util.Spliterators) LogUtil(nl.nn.adapterframework.util.LogUtil) IOException(java.io.IOException) Supplier(java.util.function.Supplier) StringUtils(org.apache.commons.lang3.StringUtils) WildCardFilter(nl.nn.adapterframework.util.WildCardFilter) DirectoryStream(java.nio.file.DirectoryStream) XmlBuilder(nl.nn.adapterframework.util.XmlBuilder) DateUtils(nl.nn.adapterframework.util.DateUtils) Stream(java.util.stream.Stream) Logger(org.apache.logging.log4j.Logger) FileSystemAction(nl.nn.adapterframework.filesystem.FileSystemActor.FileSystemAction) Map(java.util.Map) MessageContext(nl.nn.adapterframework.stream.MessageContext) StreamSupport(java.util.stream.StreamSupport) Lombok(lombok.Lombok) IOException(java.io.IOException) WildCardFilter(nl.nn.adapterframework.util.WildCardFilter)

Aggregations

StringUtils (org.apache.commons.lang3.StringUtils)76 List (java.util.List)53 Collectors (java.util.stream.Collectors)40 ArrayList (java.util.ArrayList)39 Map (java.util.Map)39 HashMap (java.util.HashMap)28 IOException (java.io.IOException)26 Collections (java.util.Collections)25 Set (java.util.Set)25 Logger (org.slf4j.Logger)25 Arrays (java.util.Arrays)24 LoggerFactory (org.slf4j.LoggerFactory)24 Optional (java.util.Optional)22 HashSet (java.util.HashSet)18 Collection (java.util.Collection)14 Autowired (org.springframework.beans.factory.annotation.Autowired)13 Objects (java.util.Objects)12 UUID (java.util.UUID)11 java.util (java.util)10 Component (org.springframework.stereotype.Component)10