Search in sources :

Example 1 with Strings

use of org.apache.flink.shaded.guava30.com.google.common.base.Strings in project CzechIdMng by bcvsolutions.

the class AbstractSynchronizationExecutor method fillExtendedAttributes.

/**
 * Fill extended attribute for given entity. Entity must be persisted first.
 *
 * @param mappedAttributes
 * @param uid
 * @param icAttributes
 * @param dto
 * @param create (is create or update entity situation)
 * @param context
 * @return
 */
@SuppressWarnings("unchecked")
protected IdmFormInstanceDto fillExtendedAttributes(List<SysSystemAttributeMappingDto> mappedAttributes, String uid, List<IcAttribute> icAttributes, DTO dto, boolean create, SynchronizationContext context) {
    IdmFormInstanceDto formInstanceDto = new IdmFormInstanceDto();
    IdmFormDefinitionDto formDefinitionDto = formService.getDefinition(context.getEntityType().getExtendedAttributeOwnerType());
    formInstanceDto.setFormDefinition(formDefinitionDto);
    mappedAttributes.stream().filter(attribute -> {
        // Skip disabled attributes
        // Only for extended attributes
        boolean fastResult = !attribute.isDisabledAttribute() && attribute.isExtendedAttribute();
        if (!fastResult) {
            return false;
        }
        // Can be value set by attribute strategy?
        return this.canSetValue(uid, attribute, dto, create);
    }).forEach(attribute -> {
        String attributeProperty = attribute.getIdmPropertyName();
        Object transformedValue = getValueByMappedAttribute(attribute, icAttributes, context);
        // Save to extended attribute
        if (!formService.isFormable(dto.getClass())) {
            String message = MessageFormat.format("Entity [{0}] is not instance of formable entity!", dto.getId());
            throw new ProvisioningException(AccResultCode.SYNCHRONIZATION_ERROR_DURING_SYNC_ITEM, ImmutableMap.of("uid", uid, "message", message));
        }
        SystemEntityType entityType = context.getEntityType();
        Assert.notNull(entityType, "Entity type is requierd!");
        IdmFormAttributeDto defAttribute = formService.getDefinition(entityType.getExtendedAttributeOwnerType()).getMappedAttributeByCode(attributeProperty);
        if (defAttribute == null) {
            // eav definition could be changed
            String message = MessageFormat.format("Form attribute definition [{0}] was not found!", attributeProperty);
            throw new ProvisioningException(AccResultCode.SYNCHRONIZATION_ERROR_DURING_SYNC_ITEM, ImmutableMap.of("uid", uid, "message", message));
        }
        List<Serializable> values;
        if (transformedValue instanceof List<?>) {
            // TODO: Convert List GuardedStrings to Strings!
            ((List<?>) transformedValue).stream().forEach(value -> {
                if (value != null && !(value instanceof Serializable)) {
                    String message = MessageFormat.format("Value [{0}] is not serializable for the attribute [{1}] and UID [{2}]!", value, attribute, uid);
                    throw new ProvisioningException(AccResultCode.SYNCHRONIZATION_ERROR_DURING_SYNC_ITEM, ImmutableMap.of("uid", uid, "message", message));
                }
            });
            values = ((List<Serializable>) transformedValue);
        } else {
            // Convert GuardedString to string
            values = Lists.newArrayList(transformedValue instanceof GuardedString ? ((GuardedString) transformedValue).asString() : (Serializable) transformedValue);
        }
        if (!context.isEntityDifferent()) {
            List<IdmFormValueDto> previousValues = formService.getValues(dto.getId(), entityType.getEntityType(), defAttribute);
            if (defAttribute.isConfidential() && previousValues != null) {
                previousValues.forEach(formValue -> {
                    formValue.setValue(formService.getConfidentialPersistentValue(formValue));
                });
            }
            List<IdmFormValueDto> newValues = values.stream().filter(value -> value != null).map(value -> {
                IdmFormValueDto formValue = new IdmFormValueDto(defAttribute);
                formValue.setValue(value);
                return formValue;
            }).collect(Collectors.toList());
            boolean isEavValuesSame = this.isEavValuesSame(newValues, previousValues);
            if (!isEavValuesSame) {
                context.setIsEntityDifferent(true);
                addToItemLog(context.getLogItem(), MessageFormat.format("Value of EAV attribute [{0}] was changed. First change was detected -> entity in IdM will be updated.", attributeProperty));
            }
        }
        if (context.isEntityDifferent()) {
            List<IdmFormValueDto> formValues = values.stream().map(value -> {
                IdmFormValueDto formValue = new IdmFormValueDto(defAttribute);
                formValue.setValue(value);
                return formValue;
            }).collect(Collectors.toList());
            formInstanceDto.getValues().addAll(formValues);
        }
    });
    return formInstanceDto;
}
Also used : IdmFormInstanceDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormInstanceDto) DtoUtils(eu.bcvsolutions.idm.core.api.utils.DtoUtils) IcNotFilter(eu.bcvsolutions.idm.ic.filter.impl.IcNotFilter) IdmFormAttributeDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormAttributeDto) ZonedDateTime(java.time.ZonedDateTime) Autowired(org.springframework.beans.factory.annotation.Autowired) AttributeValueWrapperDto(eu.bcvsolutions.idm.acc.dto.AttributeValueWrapperDto) SysSystemEntityDto(eu.bcvsolutions.idm.acc.dto.SysSystemEntityDto) EntityAccountDto(eu.bcvsolutions.idm.acc.dto.EntityAccountDto) ConfigurationService(eu.bcvsolutions.idm.core.api.service.ConfigurationService) FormService(eu.bcvsolutions.idm.core.eav.api.service.FormService) SysSystemAttributeMapping_(eu.bcvsolutions.idm.acc.entity.SysSystemAttributeMapping_) GroovyScriptService(eu.bcvsolutions.idm.core.api.service.GroovyScriptService) CoreEvent(eu.bcvsolutions.idm.core.api.event.CoreEvent) Pair(org.apache.commons.lang3.tuple.Pair) AccAccountDto(eu.bcvsolutions.idm.acc.dto.AccAccountDto) EntityAccountService(eu.bcvsolutions.idm.acc.service.api.EntityAccountService) Map(java.util.Map) SynchronizationUnlinkedActionType(eu.bcvsolutions.idm.acc.domain.SynchronizationUnlinkedActionType) AbstractSysSyncConfigDto(eu.bcvsolutions.idm.acc.dto.AbstractSysSyncConfigDto) IcSyncTokenImpl(eu.bcvsolutions.idm.ic.impl.IcSyncTokenImpl) Loggable(eu.bcvsolutions.idm.core.api.domain.Loggable) IcFilter(eu.bcvsolutions.idm.ic.filter.api.IcFilter) Set(java.util.Set) PageRequest(org.springframework.data.domain.PageRequest) ReconciliationMissingAccountActionType(eu.bcvsolutions.idm.acc.domain.ReconciliationMissingAccountActionType) IntrospectionException(java.beans.IntrospectionException) Serializable(java.io.Serializable) InvocationTargetException(java.lang.reflect.InvocationTargetException) AttributeMapping(eu.bcvsolutions.idm.acc.domain.AttributeMapping) SynchronizationSituationType(eu.bcvsolutions.idm.acc.domain.SynchronizationSituationType) IcConnectorObject(eu.bcvsolutions.idm.ic.api.IcConnectorObject) Lazy(org.springframework.context.annotation.Lazy) GuardedString(eu.bcvsolutions.idm.core.security.api.domain.GuardedString) AccResultCode(eu.bcvsolutions.idm.acc.domain.AccResultCode) FormableDto(eu.bcvsolutions.idm.core.api.dto.FormableDto) IcConnectorFacade(eu.bcvsolutions.idm.ic.service.api.IcConnectorFacade) IcSyncResultsHandler(eu.bcvsolutions.idm.ic.api.IcSyncResultsHandler) SynchronizationEventType(eu.bcvsolutions.idm.acc.event.SynchronizationEventType) SysSystemEntityService(eu.bcvsolutions.idm.acc.service.api.SysSystemEntityService) Session(org.hibernate.Session) ValueWrapper(eu.bcvsolutions.idm.core.api.config.cache.domain.ValueWrapper) ArrayList(java.util.ArrayList) Strings(com.google.common.base.Strings) AbstractDto(eu.bcvsolutions.idm.core.api.dto.AbstractDto) Lists(com.google.common.collect.Lists) SysSyncConfig(eu.bcvsolutions.idm.acc.entity.SysSyncConfig) IcResultsHandler(eu.bcvsolutions.idm.ic.filter.api.IcResultsHandler) WorkflowProcessInstanceService(eu.bcvsolutions.idm.core.workflow.service.WorkflowProcessInstanceService) SynchronizationLinkedActionType(eu.bcvsolutions.idm.acc.domain.SynchronizationLinkedActionType) SysSystemEntityFilter(eu.bcvsolutions.idm.acc.dto.filter.SysSystemEntityFilter) IcObjectClass(eu.bcvsolutions.idm.ic.api.IcObjectClass) IcOrFilter(eu.bcvsolutions.idm.ic.filter.impl.IcOrFilter) EventResult(eu.bcvsolutions.idm.core.api.event.EventResult) IdmFormInstanceDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormInstanceDto) AccModuleDescriptor(eu.bcvsolutions.idm.acc.AccModuleDescriptor) SysSyncActionLogDto(eu.bcvsolutions.idm.acc.dto.SysSyncActionLogDto) SysSchemaObjectClass_(eu.bcvsolutions.idm.acc.entity.SysSchemaObjectClass_) IcFilterBuilder(eu.bcvsolutions.idm.ic.filter.impl.IcFilterBuilder) CoreException(eu.bcvsolutions.idm.core.api.exception.CoreException) IcConnectorKey(eu.bcvsolutions.idm.ic.api.IcConnectorKey) IdmCacheManager(eu.bcvsolutions.idm.core.api.service.IdmCacheManager) Throwables(com.google.common.base.Throwables) SysSyncLogDto(eu.bcvsolutions.idm.acc.dto.SysSyncLogDto) IcAttribute(eu.bcvsolutions.idm.ic.api.IcAttribute) EntityManager(javax.persistence.EntityManager) VariableScope(org.activiti.engine.delegate.VariableScope) BaseFilter(eu.bcvsolutions.idm.core.api.dto.filter.BaseFilter) IdmFormDefinitionDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormDefinitionDto) SynchronizationContext(eu.bcvsolutions.idm.acc.domain.SynchronizationContext) SysSystemAttributeMappingDto(eu.bcvsolutions.idm.acc.dto.SysSystemAttributeMappingDto) SynchronizationEntityExecutor(eu.bcvsolutions.idm.acc.service.api.SynchronizationEntityExecutor) SysSyncLogFilter(eu.bcvsolutions.idm.acc.dto.filter.SysSyncLogFilter) BaseDto(eu.bcvsolutions.idm.core.api.dto.BaseDto) SysSyncActionLogService(eu.bcvsolutions.idm.acc.service.api.SysSyncActionLogService) EntityEventManager(eu.bcvsolutions.idm.core.api.service.EntityEventManager) OperationResultType(eu.bcvsolutions.idm.acc.domain.OperationResultType) SysSchemaAttributeDto(eu.bcvsolutions.idm.acc.dto.SysSchemaAttributeDto) IcSyncDeltaTypeEnum(eu.bcvsolutions.idm.ic.impl.IcSyncDeltaTypeEnum) ProvisioningException(eu.bcvsolutions.idm.acc.exception.ProvisioningException) IdmFormValueDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormValueDto) AbstractSchedulableTaskExecutor(eu.bcvsolutions.idm.core.scheduler.api.service.AbstractSchedulableTaskExecutor) SynchronizationMissingEntityActionType(eu.bcvsolutions.idm.acc.domain.SynchronizationMissingEntityActionType) ProvisioningConfiguration(eu.bcvsolutions.idm.acc.config.domain.ProvisioningConfiguration) ProcessInstance(org.activiti.engine.runtime.ProcessInstance) SysSyncConfigService(eu.bcvsolutions.idm.acc.service.api.SysSyncConfigService) Pageable(org.springframework.data.domain.Pageable) SysSyncLogService(eu.bcvsolutions.idm.acc.service.api.SysSyncLogService) ImmutableMap(com.google.common.collect.ImmutableMap) ReadWriteDtoService(eu.bcvsolutions.idm.core.api.service.ReadWriteDtoService) SysSchemaObjectClassDto(eu.bcvsolutions.idm.acc.dto.SysSchemaObjectClassDto) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) List(java.util.List) EntityAccountFilter(eu.bcvsolutions.idm.acc.dto.filter.EntityAccountFilter) AccAccountService(eu.bcvsolutions.idm.acc.service.api.AccAccountService) ExceptionUtils(eu.bcvsolutions.idm.core.api.utils.ExceptionUtils) AccountType(eu.bcvsolutions.idm.acc.domain.AccountType) Optional(java.util.Optional) AccAccountFilter(eu.bcvsolutions.idm.acc.dto.filter.AccAccountFilter) SysSchemaObjectClassService(eu.bcvsolutions.idm.acc.service.api.SysSchemaObjectClassService) IcConnectorConfiguration(eu.bcvsolutions.idm.ic.api.IcConnectorConfiguration) HashMap(java.util.HashMap) IcObjectClassImpl(eu.bcvsolutions.idm.ic.impl.IcObjectClassImpl) SysSystemDto(eu.bcvsolutions.idm.acc.dto.SysSystemDto) MessageFormat(java.text.MessageFormat) HashSet(java.util.HashSet) ProcessEngine(org.activiti.engine.ProcessEngine) SysSystemMappingService(eu.bcvsolutions.idm.acc.service.api.SysSystemMappingService) ConfidentialStorage(eu.bcvsolutions.idm.core.api.service.ConfidentialStorage) SynchronizationActionType(eu.bcvsolutions.idm.acc.domain.SynchronizationActionType) SystemEntityType(eu.bcvsolutions.idm.acc.domain.SystemEntityType) CollectionUtils(org.apache.commons.collections.CollectionUtils) EntityUtils(eu.bcvsolutions.idm.core.api.utils.EntityUtils) CorrelationFilter(eu.bcvsolutions.idm.core.api.dto.filter.CorrelationFilter) IcSyncDelta(eu.bcvsolutions.idm.ic.api.IcSyncDelta) IcAndFilter(eu.bcvsolutions.idm.ic.filter.impl.IcAndFilter) IcAttributeImpl(eu.bcvsolutions.idm.ic.impl.IcAttributeImpl) Codeable(eu.bcvsolutions.idm.core.api.domain.Codeable) SysSystemService(eu.bcvsolutions.idm.acc.service.api.SysSystemService) ImmutablePair(org.apache.commons.lang3.tuple.ImmutablePair) SysSchemaAttributeService(eu.bcvsolutions.idm.acc.service.api.SysSchemaAttributeService) SysSystemAttributeMappingFilter(eu.bcvsolutions.idm.acc.dto.filter.SysSystemAttributeMappingFilter) SysSyncActionLogFilter(eu.bcvsolutions.idm.acc.dto.filter.SysSyncActionLogFilter) SynchronizationService(eu.bcvsolutions.idm.acc.service.api.SynchronizationService) DateTimeFormatter(java.time.format.DateTimeFormatter) SysSystemMappingDto(eu.bcvsolutions.idm.acc.dto.SysSystemMappingDto) ProvisioningService(eu.bcvsolutions.idm.acc.service.api.ProvisioningService) IcFilterOperationType(eu.bcvsolutions.idm.ic.domain.IcFilterOperationType) SysSyncItemLogService(eu.bcvsolutions.idm.acc.service.api.SysSyncItemLogService) IcSyncToken(eu.bcvsolutions.idm.ic.api.IcSyncToken) SysSystemAttributeMappingService(eu.bcvsolutions.idm.acc.service.api.SysSystemAttributeMappingService) SysSyncItemLogDto(eu.bcvsolutions.idm.acc.dto.SysSyncItemLogDto) Assert(org.springframework.util.Assert) StringUtils(org.springframework.util.StringUtils) Serializable(java.io.Serializable) SystemEntityType(eu.bcvsolutions.idm.acc.domain.SystemEntityType) IdmFormDefinitionDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormDefinitionDto) GuardedString(eu.bcvsolutions.idm.core.security.api.domain.GuardedString) GuardedString(eu.bcvsolutions.idm.core.security.api.domain.GuardedString) IdmFormAttributeDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormAttributeDto) ProvisioningException(eu.bcvsolutions.idm.acc.exception.ProvisioningException) IcConnectorObject(eu.bcvsolutions.idm.ic.api.IcConnectorObject) ArrayList(java.util.ArrayList) List(java.util.List) IdmFormValueDto(eu.bcvsolutions.idm.core.eav.api.dto.IdmFormValueDto)

Example 2 with Strings

use of org.apache.flink.shaded.guava30.com.google.common.base.Strings in project fdb-record-layer by FoundationDB.

the class FDBRecordStoreTest method prefixPrimaryKeysWithNullByteAfterPrefix.

/**
 * If there are two primary keys that overlap in the just the right way, then one can have the representation
 * of one record's primary key be a strict prefix of the other record's. With older versions of the Record Layer,
 * this could lead to problems where attempting to load the record with the shorter key would also read data for
 * the record with the longer key. See <a href="https://github.com/FoundationDB/fdb-record-layer/issues/782">Issue #782</a>.
 *
 * <p>
 * This test is parameterized by format version because the fix involves being more particular about the range that
 * is scanned. In particular, the scan range is now only over those keys which are strict prefixes of the primary
 * key. This is fine as long as there aren't any data stored at that key. Prior to {@link FDBRecordStore#SAVE_UNSPLIT_WITH_SUFFIX_FORMAT_VERSION},
 * there could be data in that key was not true if {@code splitLongRecords} was {@code false}. Parameterizing here
 * tests those older configurations.
 * </p>
 *
 * @param formatVersion format version to use when running the test
 * @param splitLongRecords whether the test should split long records or not
 */
@ParameterizedTest(name = "prefixPrimaryKeysWithNullByteAfterPrefix [formatVersion = {0}, splitLongRecords = {1}]")
@MethodSource("formatVersionAndSplitArgs")
public void prefixPrimaryKeysWithNullByteAfterPrefix(int formatVersion, boolean splitLongRecords) throws Exception {
    final RecordMetaDataHook hook = metaData -> {
        metaData.setSplitLongRecords(splitLongRecords);
        metaData.getRecordType("MySimpleRecord").setPrimaryKey(field("str_value_indexed"));
    };
    final FDBRecordStore.Builder storeBuilder;
    // The primary key for record1 is a prefix of the primary key for record2, and the first byte in record2's primary
    // key is a null byte. Because FDB's Tuple layer null terminates its representation of strings, this means that
    // the keys used to store record1 forms a prefix of the keys storing record2. However, the null byte should be
    // escaped in such a way that it is possible to read only the keys for record1. This is necessary to properly load
    // the record by primary key.
    final TestRecords1Proto.MySimpleRecord record1 = TestRecords1Proto.MySimpleRecord.newBuilder().setStrValueIndexed("foo").setNumValue3Indexed(1066).build();
    final TestRecords1Proto.MySimpleRecord record2 = TestRecords1Proto.MySimpleRecord.newBuilder().setStrValueIndexed("foo\0bar").setNumValue3Indexed(1415).build();
    // Save the two records
    try (FDBRecordContext context = openContext()) {
        uncheckedOpenSimpleRecordStore(context, hook);
        storeBuilder = recordStore.asBuilder().setFormatVersion(formatVersion);
        final FDBRecordStore store = storeBuilder.create();
        store.saveRecord(record1);
        store.saveRecord(record2);
        commit(context);
    }
    // Load by scanning records
    try (FDBRecordContext context = openContext()) {
        final FDBRecordStore store = storeBuilder.setContext(context).open();
        final List<FDBStoredRecord<Message>> records = store.scanRecords(null, ScanProperties.FORWARD_SCAN).asList().get();
        assertThat(records, hasSize(2));
        assertEquals(record1, records.get(0).getRecord());
        assertEquals(record2, records.get(1).getRecord());
    }
    // Load by primary key
    try (FDBRecordContext context = openContext()) {
        final FDBRecordStore store = storeBuilder.setContext(context).open();
        FDBStoredRecord<Message> storedRecord1 = store.loadRecord(Tuple.from(record1.getStrValueIndexed()));
        assertNotNull(storedRecord1, "record1 was missing");
        assertEquals(record1, storedRecord1.getRecord());
        FDBStoredRecord<Message> storedRecord2 = store.loadRecord(Tuple.from(record2.getStrValueIndexed()));
        assertNotNull(storedRecord2, "record2 was missing");
        assertEquals(record2, storedRecord2.getRecord());
    }
    // Load by query
    try (FDBRecordContext context = openContext()) {
        final FDBRecordStore store = storeBuilder.setContext(context).open();
        final RecordQuery query = RecordQuery.newBuilder().setRecordType("MySimpleRecord").setFilter(Query.field("num_value_3_indexed").equalsParameter("num")).build();
        final RecordQueryPlan plan = store.planQuery(query);
        assertThat(plan, indexScan(allOf(indexName("MySimpleRecord$num_value_3_indexed"), bounds(hasTupleString("[EQUALS $num]")))));
        // Record 1
        List<FDBQueriedRecord<Message>> record1List = plan.execute(store, EvaluationContext.forBinding("num", 1066)).asList().get();
        assertThat(record1List, hasSize(1));
        FDBQueriedRecord<Message> queriedRecord1 = record1List.get(0);
        assertEquals(record1, queriedRecord1.getRecord());
        // Record 2
        List<FDBQueriedRecord<Message>> record2List = plan.execute(store, EvaluationContext.forBinding("num", 1415)).asList().get();
        assertThat(record2List, hasSize(1));
        FDBQueriedRecord<Message> queriedRecord2 = record2List.get(0);
        assertEquals(record2, queriedRecord2.getRecord());
    }
}
Also used : IndexEntry(com.apple.foundationdb.record.IndexEntry) DescriptorProtos(com.google.protobuf.DescriptorProtos) DELETE_INDEX_ENTRY(com.apple.foundationdb.record.provider.foundationdb.FDBStoreTimer.Events.DELETE_INDEX_ENTRY) Arrays(java.util.Arrays) PlanMatchers.bounds(com.apple.foundationdb.record.query.plan.match.PlanMatchers.bounds) RecordCoreStorageException(com.apple.foundationdb.record.RecordCoreStorageException) ByteBuffer(java.nio.ByteBuffer) RecordSerializer(com.apple.foundationdb.record.provider.common.RecordSerializer) RecordSerializationException(com.apple.foundationdb.record.provider.common.RecordSerializationException) IndexScanType(com.apple.foundationdb.record.IndexScanType) Tuple(com.apple.foundationdb.tuple.Tuple) Range(com.apple.foundationdb.Range) FDBError(com.apple.foundationdb.FDBError) RecordCoreException(com.apple.foundationdb.record.RecordCoreException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Expressions.concatenateFields(com.apple.foundationdb.record.metadata.Key.Expressions.concatenateFields) RecordMetaDataProto(com.apple.foundationdb.record.RecordMetaDataProto) RecordMetaDataOptionsProto(com.apple.foundationdb.record.RecordMetaDataOptionsProto) Is.is(org.hamcrest.core.Is.is) Expressions.concat(com.apple.foundationdb.record.metadata.Key.Expressions.concat) Tag(org.junit.jupiter.api.Tag) MethodSource(org.junit.jupiter.params.provider.MethodSource) TestRecords7Proto(com.apple.foundationdb.record.TestRecords7Proto) ByteArrayUtil(com.apple.foundationdb.tuple.ByteArrayUtil) Query(com.apple.foundationdb.record.query.expressions.Query) KeyExpression(com.apple.foundationdb.record.metadata.expressions.KeyExpression) TestRecords1Proto(com.apple.foundationdb.record.TestRecords1Proto) Matchers.allOf(org.hamcrest.Matchers.allOf) Set(java.util.Set) Collectors(java.util.stream.Collectors) TupleRange(com.apple.foundationdb.record.TupleRange) ByteString(com.google.protobuf.ByteString) Test(org.junit.jupiter.api.Test) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) KeySpacePath(com.apple.foundationdb.record.provider.foundationdb.keyspace.KeySpacePath) PlanMatchers.hasTupleString(com.apple.foundationdb.record.query.plan.match.PlanMatchers.hasTupleString) List(java.util.List) PlanMatchers.indexName(com.apple.foundationdb.record.query.plan.match.PlanMatchers.indexName) RecordMetaDataProvider(com.apple.foundationdb.record.RecordMetaDataProvider) EvaluationContext(com.apple.foundationdb.record.EvaluationContext) Matchers.equalTo(org.hamcrest.Matchers.equalTo) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) IndexTypes(com.apple.foundationdb.record.metadata.IndexTypes) TestRecordsWithHeaderProto(com.apple.foundationdb.record.TestRecordsWithHeaderProto) Matchers.greaterThan(org.hamcrest.Matchers.greaterThan) Matchers.containsString(org.hamcrest.Matchers.containsString) Assertions.assertThrows(org.junit.jupiter.api.Assertions.assertThrows) Assertions.fail(org.junit.jupiter.api.Assertions.fail) RecordMetaData(com.apple.foundationdb.record.RecordMetaData) TestNoUnionProto(com.apple.foundationdb.record.TestNoUnionProto) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) TestRecordsDuplicateUnionFields(com.apple.foundationdb.record.TestRecordsDuplicateUnionFields) DynamicMessage(com.google.protobuf.DynamicMessage) Descriptors(com.google.protobuf.Descriptors) PlanMatchers.indexScan(com.apple.foundationdb.record.query.plan.match.PlanMatchers.indexScan) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) CompletableFuture(java.util.concurrent.CompletableFuture) RecordQuery(com.apple.foundationdb.record.query.RecordQuery) RecordQueryPlan(com.apple.foundationdb.record.query.plan.plans.RecordQueryPlan) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Strings(com.google.common.base.Strings) ExecuteProperties(com.apple.foundationdb.record.ExecuteProperties) ScanProperties(com.apple.foundationdb.record.ScanProperties) RecordCursorIterator(com.apple.foundationdb.record.RecordCursorIterator) Matchers.lessThan(org.hamcrest.Matchers.lessThan) Assumptions.assumeTrue(org.junit.jupiter.api.Assumptions.assumeTrue) Matchers.hasSize(org.hamcrest.Matchers.hasSize) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Nonnull(javax.annotation.Nonnull) Expressions.field(com.apple.foundationdb.record.metadata.Key.Expressions.field) Nullable(javax.annotation.Nullable) Charsets(com.google.common.base.Charsets) IsolationLevel(com.apple.foundationdb.record.IsolationLevel) RecordMetaDataBuilder(com.apple.foundationdb.record.RecordMetaDataBuilder) Tags(com.apple.test.Tags) ScanComparisons(com.apple.foundationdb.record.query.plan.ScanComparisons) Assertions.assertSame(org.junit.jupiter.api.Assertions.assertSame) ExecutionException(java.util.concurrent.ExecutionException) Consumer(java.util.function.Consumer) Comparisons(com.apple.foundationdb.record.query.expressions.Comparisons) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) TestRecordsImportProto(com.apple.foundationdb.record.TestRecordsImportProto) Index(com.apple.foundationdb.record.metadata.Index) FDBException(com.apple.foundationdb.FDBException) Message(com.google.protobuf.Message) RecordCursor(com.apple.foundationdb.record.RecordCursor) Collections(java.util.Collections) SAVE_INDEX_ENTRY(com.apple.foundationdb.record.provider.foundationdb.FDBStoreTimer.Events.SAVE_INDEX_ENTRY) RecordQueryPlan(com.apple.foundationdb.record.query.plan.plans.RecordQueryPlan) TestRecords1Proto(com.apple.foundationdb.record.TestRecords1Proto) DynamicMessage(com.google.protobuf.DynamicMessage) Message(com.google.protobuf.Message) RecordQuery(com.apple.foundationdb.record.query.RecordQuery) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 3 with Strings

use of org.apache.flink.shaded.guava30.com.google.common.base.Strings in project timbuctoo by HuygensING.

the class RelatedDatableRangeFacetDescription method filter.

@Override
@SuppressWarnings("unchecked")
public void filter(GraphTraversal<Vertex, Vertex> graphTraversal, List<FacetValue> facets) {
    Optional<FacetValue> first = facets.stream().filter(facetValue -> Objects.equals(facetValue.getName(), facetName)).findFirst();
    if (!first.isPresent()) {
        return;
    }
    FacetValue facetValue = first.get();
    if (!(facetValue instanceof DateRangeFacetValue)) {
        return;
    }
    // pad the strings to make them parsable
    String lowerLimitString = Strings.padStart("" + ((DateRangeFacetValue) facetValue).getLowerLimit(), 8, '0').substring(0, 4);
    String upperLimitString = Strings.padStart("" + ((DateRangeFacetValue) facetValue).getUpperLimit(), 8, '0').substring(0, 4);
    try {
        Range<Date> range = Range.closed(FILTER_FORMAT.parse(lowerLimitString), FILTER_FORMAT.parse(upperLimitString));
        graphTraversal.where(__.bothE(relations).otherV().has(propertyName, P.test((o1, o2) -> {
            Datable datable = getDatable("" + o1);
            if (!datable.isValid()) {
                return false;
            }
            Range<Date> range1 = (Range<Date>) o2;
            return range1.contains(datable.getFromDate()) || range1.contains(datable.getToDate());
        }, range)));
    } catch (ParseException e) {
        LOG.error("Cannot parse date", e);
    }
}
Also used : Logger(org.slf4j.Logger) Date(java.util.Date) Range(com.google.common.collect.Range) DatableRangeFacetGetter(nl.knaw.huygens.timbuctoo.search.description.facet.helpers.DatableRangeFacetGetter) LoggerFactory(org.slf4j.LoggerFactory) SimpleDateFormat(java.text.SimpleDateFormat) org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__(org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__) Vertex(org.apache.tinkerpop.gremlin.structure.Vertex) StringUtils(org.apache.commons.lang3.StringUtils) GraphTraversal(org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal) Objects(java.util.Objects) Strings(com.google.common.base.Strings) FacetValue(nl.knaw.huygens.timbuctoo.search.FacetValue) List(java.util.List) DateRangeFacetValue(nl.knaw.huygens.timbuctoo.server.mediatypes.v2.search.DateRangeFacetValue) Datable(nl.knaw.huygens.timbuctoo.model.Datable) Optional(java.util.Optional) ParseException(java.text.ParseException) P(org.apache.tinkerpop.gremlin.process.traversal.P) RelatedPropertyValueGetter(nl.knaw.huygens.timbuctoo.search.description.facet.helpers.RelatedPropertyValueGetter) DateRangeFacetValue(nl.knaw.huygens.timbuctoo.server.mediatypes.v2.search.DateRangeFacetValue) FacetValue(nl.knaw.huygens.timbuctoo.search.FacetValue) DateRangeFacetValue(nl.knaw.huygens.timbuctoo.server.mediatypes.v2.search.DateRangeFacetValue) ParseException(java.text.ParseException) Range(com.google.common.collect.Range) Date(java.util.Date) Datable(nl.knaw.huygens.timbuctoo.model.Datable)

Example 4 with Strings

use of org.apache.flink.shaded.guava30.com.google.common.base.Strings in project arctic-sea by 52North.

the class AbstractCapabilitiesBaseTypeDecoder method parseMetadata.

// private Set<OwsDomainMetadata> parseDomainMetadata(DomainMetadataType[]
// metadata) {
// return
// Optional.ofNullable(metadata).map(Arrays::stream).orElseGet(Stream::empty).map(this::parseDomainMetadata)
// .filter(Objects::nonNull).collect(toSet());
// }
private OwsMetadata parseMetadata(MetadataType metadata) {
    if (metadata == null) {
        return null;
    }
    URI href = Optional.ofNullable(metadata.getHref()).map(Strings::emptyToNull).map(URI::create).orElse(null);
    URI role = Optional.ofNullable(metadata.getRole()).map(Strings::emptyToNull).map(URI::create).orElse(null);
    URI arcrole = Optional.ofNullable(metadata.getArcrole()).map(Strings::emptyToNull).map(URI::create).orElse(null);
    Show show = Optional.ofNullable(metadata.getShow()).map(Object::toString).map(Show::valueOf).orElse(null);
    Actuate actuate = Optional.ofNullable(metadata.getActuate()).map(Object::toString).map(Actuate::valueOf).orElse(null);
    URI about = Optional.ofNullable(metadata.getAbout()).map(Strings::emptyToNull).map(URI::create).orElse(null);
    String title = metadata.getTitle();
    return new OwsMetadata(href, role, arcrole, title, show, actuate, about);
}
Also used : Actuate(org.n52.shetland.w3c.xlink.Actuate) OwsMetadata(org.n52.shetland.ogc.ows.OwsMetadata) Show(org.n52.shetland.w3c.xlink.Show) XmlObject(org.apache.xmlbeans.XmlObject) LocalizedString(org.n52.janmayen.i18n.LocalizedString) MultilingualString(org.n52.janmayen.i18n.MultilingualString) OwsLanguageString(org.n52.shetland.ogc.ows.OwsLanguageString) URI(java.net.URI) Strings(com.google.common.base.Strings)

Example 5 with Strings

use of org.apache.flink.shaded.guava30.com.google.common.base.Strings in project arctic-sea by 52North.

the class AbstractCapabilitiesBaseTypeDecoder method parse.

private <T extends OwsDomainMetadata> T parse(BiFunction<URI, String, T> fun, DomainMetadataType metadata) {
    if (metadata == null) {
        return null;
    }
    URI reference = Optional.ofNullable(metadata.getReference()).map(Strings::emptyToNull).map(URI::create).orElse(null);
    String value = metadata.getStringValue();
    return fun.apply(reference, value);
}
Also used : LocalizedString(org.n52.janmayen.i18n.LocalizedString) MultilingualString(org.n52.janmayen.i18n.MultilingualString) OwsLanguageString(org.n52.shetland.ogc.ows.OwsLanguageString) URI(java.net.URI) Strings(com.google.common.base.Strings)

Aggregations

Strings (com.google.common.base.Strings)23 List (java.util.List)14 ArrayList (java.util.ArrayList)9 Collectors (java.util.stream.Collectors)9 LoggerFactory (org.slf4j.LoggerFactory)6 Map (java.util.Map)5 LocalizedString (org.n52.janmayen.i18n.LocalizedString)5 MultilingualString (org.n52.janmayen.i18n.MultilingualString)5 OwsLanguageString (org.n52.shetland.ogc.ows.OwsLanguageString)5 Logger (org.slf4j.Logger)5 Lists (com.google.common.collect.Lists)4 URI (java.net.URI)4 Arrays (java.util.Arrays)4 Collections (java.util.Collections)4 Optional (java.util.Optional)4 Iterator (java.util.Iterator)3 Set (java.util.Set)3 Function (java.util.function.Function)3 Collectors.toList (java.util.stream.Collectors.toList)3 ImmutableList (com.google.common.collect.ImmutableList)2