Search in sources :

Example 1 with StringUtils.isNotEmpty

use of org.apache.commons.lang3.StringUtils.isNotEmpty in project nifi by apache.

the class Notify method onTrigger.

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    final ComponentLog logger = getLogger();
    final PropertyValue signalIdProperty = context.getProperty(RELEASE_SIGNAL_IDENTIFIER);
    final PropertyValue counterNameProperty = context.getProperty(SIGNAL_COUNTER_NAME);
    final PropertyValue deltaProperty = context.getProperty(SIGNAL_COUNTER_DELTA);
    final String attributeCacheRegex = context.getProperty(ATTRIBUTE_CACHE_REGEX).getValue();
    final Integer bufferCount = context.getProperty(SIGNAL_BUFFER_COUNT).asInteger();
    // the cache client used to interact with the distributed cache.
    final AtomicDistributedMapCacheClient cache = context.getProperty(DISTRIBUTED_CACHE_SERVICE).asControllerService(AtomicDistributedMapCacheClient.class);
    final WaitNotifyProtocol protocol = new WaitNotifyProtocol(cache);
    final Map<String, SignalBuffer> signalBuffers = new HashMap<>();
    for (int i = 0; i < bufferCount; i++) {
        final FlowFile flowFile = session.get();
        if (flowFile == null) {
            break;
        }
        // Signal id is computed from attribute 'RELEASE_SIGNAL_IDENTIFIER' with expression language support
        final String signalId = signalIdProperty.evaluateAttributeExpressions(flowFile).getValue();
        // if the computed value is null, or empty, we transfer the flow file to failure relationship
        if (StringUtils.isBlank(signalId)) {
            logger.error("FlowFile {} has no attribute for given Release Signal Identifier", new Object[] { flowFile });
            // set 'notified' attribute
            session.transfer(session.putAttribute(flowFile, NOTIFIED_ATTRIBUTE_NAME, String.valueOf(false)), REL_FAILURE);
            continue;
        }
        String counterName = counterNameProperty.evaluateAttributeExpressions(flowFile).getValue();
        if (StringUtils.isEmpty(counterName)) {
            counterName = WaitNotifyProtocol.DEFAULT_COUNT_NAME;
        }
        int delta = 1;
        if (deltaProperty.isSet()) {
            final String deltaStr = deltaProperty.evaluateAttributeExpressions(flowFile).getValue();
            try {
                delta = Integer.parseInt(deltaStr);
            } catch (final NumberFormatException e) {
                logger.error("Failed to calculate delta for FlowFile {} due to {}", new Object[] { flowFile, e }, e);
                session.transfer(session.putAttribute(flowFile, NOTIFIED_ATTRIBUTE_NAME, String.valueOf(false)), REL_FAILURE);
                continue;
            }
        }
        if (!signalBuffers.containsKey(signalId)) {
            signalBuffers.put(signalId, new SignalBuffer());
        }
        final SignalBuffer signalBuffer = signalBuffers.get(signalId);
        if (StringUtils.isNotEmpty(attributeCacheRegex)) {
            flowFile.getAttributes().entrySet().stream().filter(e -> (!e.getKey().equals("uuid") && e.getKey().matches(attributeCacheRegex))).forEach(e -> signalBuffer.attributesToCache.put(e.getKey(), e.getValue()));
        }
        signalBuffer.incrementDelta(counterName, delta);
        signalBuffer.flowFiles.add(flowFile);
        if (logger.isDebugEnabled()) {
            logger.debug("Cached release signal identifier {} counterName {} from FlowFile {}", new Object[] { signalId, counterName, flowFile });
        }
    }
    signalBuffers.forEach((signalId, signalBuffer) -> {
        // retry after yielding for a while.
        try {
            protocol.notify(signalId, signalBuffer.deltas, signalBuffer.attributesToCache);
            signalBuffer.flowFiles.forEach(flowFile -> session.transfer(session.putAttribute(flowFile, NOTIFIED_ATTRIBUTE_NAME, String.valueOf(true)), REL_SUCCESS));
        } catch (IOException e) {
            throw new RuntimeException(String.format("Unable to communicate with cache when processing %s due to %s", signalId, e), e);
        }
    });
}
Also used : StandardValidators(org.apache.nifi.processor.util.StandardValidators) CapabilityDescription(org.apache.nifi.annotation.documentation.CapabilityDescription) ResultType(org.apache.nifi.expression.AttributeExpression.ResultType) HashMap(java.util.HashMap) EventDriven(org.apache.nifi.annotation.behavior.EventDriven) ComponentLog(org.apache.nifi.logging.ComponentLog) StringUtils(org.apache.commons.lang3.StringUtils) PropertyDescriptor(org.apache.nifi.components.PropertyDescriptor) ProcessException(org.apache.nifi.processor.exception.ProcessException) ArrayList(java.util.ArrayList) PropertyValue(org.apache.nifi.components.PropertyValue) HashSet(java.util.HashSet) Relationship(org.apache.nifi.processor.Relationship) Map(java.util.Map) Requirement(org.apache.nifi.annotation.behavior.InputRequirement.Requirement) AtomicDistributedMapCacheClient(org.apache.nifi.distributed.cache.client.AtomicDistributedMapCacheClient) FlowFile(org.apache.nifi.flowfile.FlowFile) ProcessContext(org.apache.nifi.processor.ProcessContext) Set(java.util.Set) IOException(java.io.IOException) ProcessSession(org.apache.nifi.processor.ProcessSession) WritesAttribute(org.apache.nifi.annotation.behavior.WritesAttribute) SeeAlso(org.apache.nifi.annotation.documentation.SeeAlso) List(java.util.List) InputRequirement(org.apache.nifi.annotation.behavior.InputRequirement) SupportsBatching(org.apache.nifi.annotation.behavior.SupportsBatching) AbstractProcessor(org.apache.nifi.processor.AbstractProcessor) Tags(org.apache.nifi.annotation.documentation.Tags) Collections(java.util.Collections) FlowFile(org.apache.nifi.flowfile.FlowFile) HashMap(java.util.HashMap) PropertyValue(org.apache.nifi.components.PropertyValue) IOException(java.io.IOException) ComponentLog(org.apache.nifi.logging.ComponentLog) AtomicDistributedMapCacheClient(org.apache.nifi.distributed.cache.client.AtomicDistributedMapCacheClient)

Example 2 with StringUtils.isNotEmpty

use of org.apache.commons.lang3.StringUtils.isNotEmpty in project flow by vaadin.

the class ComponentGenerator method generateClassSource.

/*
     * Gets the JavaClassSource object (note, the license is added externally to
     * the source, since JavaClassSource doesn't support adding a comment to the
     * beginning of the file).
     */
private JavaClassSource generateClassSource(ComponentMetadata metadata, String basePackage) {
    String targetPackage = basePackage;
    String baseUrl = metadata.getBaseUrl();
    if (StringUtils.isNotBlank(baseUrl)) {
        // this is a fugly way to remove that
        if (baseUrl.contains("/src/")) {
            baseUrl = baseUrl.replace("/src/", "/");
        }
        String subPackage = ComponentGeneratorUtils.convertFilePathToPackage(baseUrl);
        if (StringUtils.isNotBlank(subPackage)) {
            int firstDot = subPackage.indexOf('.');
            if (firstDot > 0) {
                String firstSegment = subPackage.substring(0, firstDot);
                String lastSegment = subPackage.substring(firstDot + 1);
                subPackage = lastSegment.replace(".", "");
                if (!"vaadin".equals(firstSegment)) {
                    subPackage = firstSegment + "." + subPackage;
                }
            }
            targetPackage += "." + subPackage;
        }
    }
    JavaClassSource javaClass = Roaster.create(JavaClassSource.class);
    javaClass.setPackage(targetPackage).setPublic().setAbstract(abstractClass).setName(getGeneratedClassName(metadata.getTag()));
    if (metadata.getParentTagName() != null) {
        javaClass.setSuperType(getGeneratedClassName(metadata.getParentTagName()) + GENERIC_TYPE_DECLARATION);
    } else {
        javaClass.setSuperType(Component.class);
        addInterfaces(metadata, javaClass);
    }
    javaClass.addTypeVariable().setName(GENERIC_TYPE).setBounds(javaClass.getName() + GENERIC_TYPE_DECLARATION);
    addClassAnnotations(metadata, javaClass);
    Map<String, MethodSource<JavaClassSource>> propertyToGetterMap = new HashMap<String, MethodSource<JavaClassSource>>();
    if (metadata.getProperties() != null) {
        generateEventsForPropertiesWithNotify(metadata);
        generateGettersAndSetters(metadata, javaClass, propertyToGetterMap);
    }
    if (metadata.getMethods() != null) {
        metadata.getMethods().stream().filter(function -> !ExclusionRegistry.isMethodExcluded(metadata.getTag(), function.getName())).forEach(function -> generateMethodFor(javaClass, function));
    }
    if (metadata.getEvents() != null) {
        metadata.getEvents().stream().filter(event -> !ExclusionRegistry.isEventExcluded(metadata.getTag(), event.getName())).forEach(event -> generateEventListenerFor(javaClass, metadata, event, propertyToGetterMap));
    }
    if (metadata.getSlots() != null && !metadata.getSlots().isEmpty()) {
        generateAdders(metadata, javaClass);
    }
    if (StringUtils.isNotEmpty(metadata.getDescription())) {
        addMarkdownJavaDoc(metadata.getDescription(), javaClass.getJavaDoc());
    }
    generateConstructors(javaClass);
    return javaClass;
}
Also used : Component(com.vaadin.flow.component.Component) Registration(com.vaadin.flow.shared.Registration) LoggerFactory(org.slf4j.LoggerFactory) ComponentFunctionData(com.vaadin.generator.metadata.ComponentFunctionData) ComponentBasicType(com.vaadin.generator.metadata.ComponentBasicType) StringUtils(org.apache.commons.lang3.StringUtils) ParameterSource(org.jboss.forge.roaster.model.source.ParameterSource) BehaviorRegistry(com.vaadin.generator.registry.BehaviorRegistry) ClassUtils(org.apache.commons.lang3.ClassUtils) Generated(javax.annotation.Generated) Roaster(org.jboss.forge.roaster.Roaster) ComponentPropertyData(com.vaadin.generator.metadata.ComponentPropertyData) Map(java.util.Map) Element(com.vaadin.flow.dom.Element) Synchronize(com.vaadin.flow.component.Synchronize) HasComponents(com.vaadin.flow.component.HasComponents) MethodSource(org.jboss.forge.roaster.model.source.MethodSource) Visibility(org.jboss.forge.roaster.model.Visibility) HasStyle(com.vaadin.flow.component.HasStyle) JavaDocSource(org.jboss.forge.roaster.model.source.JavaDocSource) Collection(java.util.Collection) Set(java.util.Set) Objects(java.util.Objects) List(java.util.List) JsonSerializable(com.vaadin.flow.component.JsonSerializable) JavaClassSource(org.jboss.forge.roaster.model.source.JavaClassSource) ComponentPropertyBaseData(com.vaadin.generator.metadata.ComponentPropertyBaseData) Optional(java.util.Optional) ComponentEventListener(com.vaadin.flow.component.ComponentEventListener) HasValue(com.vaadin.flow.component.HasValue) ComponentGenerationException(com.vaadin.generator.exception.ComponentGenerationException) HashMap(java.util.HashMap) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) DomEvent(com.vaadin.flow.component.DomEvent) Tag(com.vaadin.flow.component.Tag) Properties(java.util.Properties) JsonParser(com.fasterxml.jackson.core.JsonParser) Files(java.nio.file.Files) EventData(com.vaadin.flow.component.EventData) ComponentObjectType(com.vaadin.generator.metadata.ComponentObjectType) UTF_8(java.nio.charset.StandardCharsets.UTF_8) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) PropertyNameRemapRegistry(com.vaadin.generator.registry.PropertyNameRemapRegistry) IOException(java.io.IOException) ExclusionRegistry(com.vaadin.generator.registry.ExclusionRegistry) ComponentEvent(com.vaadin.flow.component.ComponentEvent) File(java.io.File) HtmlImport(com.vaadin.flow.component.dependency.HtmlImport) JsonFactory(com.fasterxml.jackson.core.JsonFactory) ComponentMetadata(com.vaadin.generator.metadata.ComponentMetadata) ComponentType(com.vaadin.generator.metadata.ComponentType) JsonObject(elemental.json.JsonObject) ComponentEventData(com.vaadin.generator.metadata.ComponentEventData) HasText(com.vaadin.flow.component.HasText) NotSupported(com.vaadin.flow.component.NotSupported) Collections(java.util.Collections) InputStream(java.io.InputStream) HashMap(java.util.HashMap) MethodSource(org.jboss.forge.roaster.model.source.MethodSource) JavaClassSource(org.jboss.forge.roaster.model.source.JavaClassSource)

Example 3 with StringUtils.isNotEmpty

use of org.apache.commons.lang3.StringUtils.isNotEmpty in project pentaho-platform by pentaho.

the class PentahoWebContextFilter method getActiveThemeVar.

// region get Environment Variables
private String getActiveThemeVar(HttpServletRequest request) {
    IPentahoSession session = getSession();
    String activeTheme = (String) session.getAttribute("pentaho-user-theme");
    String ua = request.getHeader("User-Agent");
    // check if we're coming from a mobile device, if so, lock to system default (ruby)
    if (StringUtils.isNotEmpty(ua) && ua.matches(".*(?i)(iPad|iPod|iPhone|Android).*")) {
        activeTheme = PentahoSystem.getSystemSetting("default-theme", "ruby");
    }
    if (activeTheme == null) {
        IUserSettingService settingsService = getUserSettingsService();
        try {
            activeTheme = settingsService.getUserSetting("pentaho-user-theme", null).getSettingValue();
        } catch (Exception ignored) {
        // the user settings service is not valid in the agile-bi deployment of the server
        }
        if (activeTheme == null) {
            activeTheme = PentahoSystem.getSystemSetting("default-theme", "ruby");
        }
    }
    return activeTheme;
}
Also used : IUserSettingService(org.pentaho.platform.api.usersettings.IUserSettingService) IPentahoSession(org.pentaho.platform.api.engine.IPentahoSession) ServletException(javax.servlet.ServletException) ConcurrentException(org.apache.commons.lang3.concurrent.ConcurrentException) IOException(java.io.IOException)

Example 4 with StringUtils.isNotEmpty

use of org.apache.commons.lang3.StringUtils.isNotEmpty 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");
    }
    // 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) QuotaService(org.talend.dataprep.dataset.store.QuotaService) 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) 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) URLDecoder(java.net.URLDecoder) DataSetErrorCodes(org.talend.dataprep.exception.error.DataSetErrorCodes) PUT(org.springframework.web.bind.annotation.RequestMethod.PUT) LoggerFactory(org.slf4j.LoggerFactory) 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) 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) 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) Import(org.talend.dataprep.api.dataset.Import) ExceptionContext.build(org.talend.daikon.exception.ExceptionContext.build) ExceptionContext(org.talend.daikon.exception.ExceptionContext) Charset(java.nio.charset.Charset) 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) IOUtils(org.apache.commons.compress.utils.IOUtils) 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) EncodingSupport(org.talend.dataprep.configuration.EncodingSupport) 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 5 with StringUtils.isNotEmpty

use of org.apache.commons.lang3.StringUtils.isNotEmpty in project okta-sdk-java by okta.

the class AbstractOktaJavaClientCodegen method fromModel.

@Override
public CodegenModel fromModel(String name, Model model, Map<String, Model> allDefinitions) {
    CodegenModel codegenModel = super.fromModel(name, model, allDefinitions);
    // super add these imports, and we don't want that dependency
    codegenModel.imports.remove("ApiModel");
    if (model.getVendorExtensions().containsKey("x-baseType")) {
        String baseType = (String) model.getVendorExtensions().get("x-baseType");
        codegenModel.vendorExtensions.put("baseType", toModelName(baseType));
        codegenModel.imports.add(toModelName(baseType));
    }
    Collection<CodegenOperation> operations = (Collection<CodegenOperation>) codegenModel.vendorExtensions.get("operations");
    if (operations != null) {
        operations.forEach(op -> {
            if (op.returnType != null) {
                codegenModel.imports.add(op.returnType);
            }
            if (op.allParams != null) {
                op.allParams.stream().filter(param -> needToImport(param.dataType)).forEach(param -> codegenModel.imports.add(param.dataType));
            }
        });
    }
    // force alias == false (likely only relevant for Lists, but something changed in swagger 2.2.3 to require this)
    codegenModel.isAlias = false;
    String parent = (String) model.getVendorExtensions().get("x-okta-parent");
    if (StringUtils.isNotEmpty(parent)) {
        codegenModel.parent = toApiName(parent.substring(parent.lastIndexOf("/")));
        // figure out the resourceClass if this model has a parent
        String discriminatorRoot = getRootDiscriminator(name);
        if (discriminatorRoot != null) {
            model.getVendorExtensions().put("discriminatorRoot", discriminatorRoot);
        }
    }
    // We use '$ref' attributes with siblings, which isn't valid JSON schema (or swagger), so we need process
    // additional attributes from the raw schema
    Map<String, Object> modelDef = getRawSwaggerDefinition(name);
    codegenModel.vars.forEach(codegenProperty -> {
        Map<String, Object> rawPropertyMap = getRawSwaggerProperty(modelDef, codegenProperty.baseName);
        codegenProperty.isReadOnly = Boolean.TRUE.equals(rawPropertyMap.get("readOnly"));
    });
    return codegenModel;
}
Also used : CodegenOperation(io.swagger.codegen.CodegenOperation) SortedSet(java.util.SortedSet) LoggerFactory(org.slf4j.LoggerFactory) ModelImpl(io.swagger.models.ModelImpl) ArrayProperty(io.swagger.models.properties.ArrayProperty) StringUtils(org.apache.commons.lang3.StringUtils) Model(io.swagger.models.Model) Path(io.swagger.models.Path) Locale(java.util.Locale) Map(java.util.Map) JsonNode(com.fasterxml.jackson.databind.JsonNode) Operation(io.swagger.models.Operation) Property(io.swagger.models.properties.Property) RefModel(io.swagger.models.RefModel) Collection(java.util.Collection) Set(java.util.Set) Reader(java.io.Reader) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) ArrayNode(com.fasterxml.jackson.databind.node.ArrayNode) Response(io.swagger.models.Response) List(java.util.List) Optional(java.util.Optional) CodegenParameter(io.swagger.codegen.CodegenParameter) AbstractJavaCodegen(io.swagger.codegen.languages.AbstractJavaCodegen) Swagger(io.swagger.models.Swagger) BooleanUtils(org.apache.commons.lang3.BooleanUtils) HashMap(java.util.HashMap) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) TreeSet(java.util.TreeSet) Yaml(org.yaml.snakeyaml.Yaml) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) CodegenProperty(io.swagger.codegen.CodegenProperty) RefProperty(io.swagger.models.properties.RefProperty) Logger(org.slf4j.Logger) CodegenOperation(io.swagger.codegen.CodegenOperation) BodyParameter(io.swagger.models.parameters.BodyParameter) Iterator(java.util.Iterator) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) CodegenType(io.swagger.codegen.CodegenType) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) InputStreamReader(java.io.InputStreamReader) File(java.io.File) SwaggerException(io.swagger.parser.SwaggerException) CodegenModel(io.swagger.codegen.CodegenModel) HttpMethod(io.swagger.models.HttpMethod) Collections(java.util.Collections) Collection(java.util.Collection) CodegenModel(io.swagger.codegen.CodegenModel)

Aggregations

StringUtils (org.apache.commons.lang3.StringUtils)37 List (java.util.List)27 Map (java.util.Map)23 HashMap (java.util.HashMap)19 Collectors (java.util.stream.Collectors)18 IOException (java.io.IOException)17 ArrayList (java.util.ArrayList)16 Set (java.util.Set)14 LoggerFactory (org.slf4j.LoggerFactory)13 HashSet (java.util.HashSet)11 Optional (java.util.Optional)11 Logger (org.slf4j.Logger)11 Collections (java.util.Collections)10 File (java.io.File)9 Arrays (java.util.Arrays)8 Autowired (org.springframework.beans.factory.annotation.Autowired)8 java.util (java.util)7 Collection (java.util.Collection)7 Pattern (java.util.regex.Pattern)7 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)6