Search in sources :

Example 1 with StringUtils.split

use of org.apache.commons.lang3.StringUtils.split in project oap by oaplatform.

the class SchemaPath method traverse.

public static Result traverse(SchemaAST root, String path) {
    SchemaAST schemaAST = root;
    val additionalProperties = new MutableObject<Boolean>(null);
    final Supplier<Result> empty = () -> new Result(Optional.empty(), Optional.ofNullable(additionalProperties.getValue()));
    for (val item : StringUtils.split(path, '.')) {
        if (schemaAST instanceof ObjectSchemaAST) {
            val objectSchemaAST = (ObjectSchemaAST) schemaAST;
            schemaAST = objectSchemaAST.properties.get(item);
            objectSchemaAST.additionalProperties.ifPresent(additionalProperties::setValue);
            if (schemaAST == null)
                return empty.get();
        } else if (schemaAST instanceof ArraySchemaAST) {
            if (!"items".equals(item))
                return empty.get();
            schemaAST = ((ArraySchemaAST) schemaAST).items;
        } else {
            return empty.get();
        }
    }
    return new Result(Optional.of(schemaAST), Optional.ofNullable(additionalProperties.getValue()));
}
Also used : lombok.val(lombok.val) ArraySchemaAST(oap.json.schema.validator.array.ArraySchemaAST) ObjectSchemaAST(oap.json.schema.validator.object.ObjectSchemaAST) ObjectSchemaAST(oap.json.schema.validator.object.ObjectSchemaAST) ArraySchemaAST(oap.json.schema.validator.array.ArraySchemaAST) MutableObject(org.apache.commons.lang3.mutable.MutableObject)

Example 2 with StringUtils.split

use of org.apache.commons.lang3.StringUtils.split in project oap by oaplatform.

the class JavaCTemplate method addPathOr.

private void addPathOr(Class<T> clazz, String delimiter, StringBuilder c, AtomicInteger num, FieldStack fields, boolean last, AtomicInteger tab, String[] orPath, int orIndex, TLine line) throws NoSuchFieldException, NoSuchMethodException {
    val currentPath = orPath[orIndex].trim();
    val m = mapper.get(currentPath);
    if (m != null) {
        printDefaultValue(tab(c, tab), m.get(), line);
    } else {
        int sp = 0;
        StringBuilder newPath = new StringBuilder("s.");
        MutableObject<Type> lc = new MutableObject<>(clazz);
        AtomicInteger psp = new AtomicInteger(0);
        AtomicInteger opts = new AtomicInteger(0);
        while (sp >= 0) {
            sp = currentPath.indexOf('.', sp + 1);
            if (sp > 0) {
                Pair<Type, String> pnp = fields.computeIfAbsent(currentPath.substring(0, sp), Try.map((key) -> {
                    String prefix = StringUtils.trim(psp.get() > 1 ? key.substring(0, psp.get() - 1) : "");
                    String suffix = StringUtils.trim(key.substring(psp.get()));
                    boolean optional = isOptional(lc.getValue());
                    Type declaredFieldType = getDeclaredFieldOrFunctionType(optional ? getOptionalArgumentType(lc.getValue()) : lc.getValue(), suffix);
                    String classType = toJavaType(declaredFieldType);
                    String field = "field" + num.incrementAndGet();
                    Optional<Pair<Type, String>> rfP = Optional.ofNullable(fields.get(prefix));
                    String rf = rfP.map(p -> p._2 + (optional ? ".get()" : "") + "." + suffix).orElse("s." + key);
                    if (optional) {
                        tab(c, tab).append("if( ").append(rfP.map(p -> p._2).orElse("s")).append(".isPresent() ) {\n");
                        opts.incrementAndGet();
                        tabInc(tab);
                        fields.up();
                    }
                    tab(c, tab).append(" ").append(classType).append(" ").append(field).append(" = ").append(rf).append(";\n");
                    lc.setValue(declaredFieldType);
                    return __(lc.getValue(), field);
                }));
                newPath = new StringBuilder(pnp._2 + ".");
                lc.setValue(pnp._1);
                psp.set(sp + 1);
            } else {
                newPath.append(currentPath.substring(psp.get()));
            }
        }
        int in = newPath.toString().lastIndexOf('.');
        String pField = in > 0 ? newPath.substring(0, in) : newPath.toString();
        String cField = newPath.substring(in + 1);
        boolean isJoin = cField.startsWith("{");
        String[] cFields = isJoin ? StringUtils.split(cField.substring(1, cField.length() - 1), ',') : new String[] { cField };
        Type parentClass = lc.getValue();
        boolean isOptionalParent = isOptional(parentClass) && !cField.startsWith("isPresent");
        String optField = null;
        if (isOptionalParent) {
            opts.incrementAndGet();
            tab(c, tab).append("if( ").append(pField).append(".isPresent() ) {\n");
            fields.up();
            tabInc(tab);
            parentClass = getOptionalArgumentType(parentClass);
            optField = "opt" + num.incrementAndGet();
            tab(c, tab).append(" ").append(toJavaType(parentClass)).append(" ").append(optField).append(" = ").append(pField).append(".get();\n");
        }
        for (int i = 0; i < cFields.length; i++) {
            cField = StringUtils.trim(cFields[i]);
            Optional<Join> join = isJoin ? Optional.of(new Join(i, cFields.length)) : Optional.empty();
            if (cField.startsWith("\"")) {
                tab(c.append("\n"), tab);
                map.map(c, String.class, line, cField, delimiter, join);
            } else {
                if (isOptionalParent) {
                    newPath = new StringBuilder(in > 0 ? optField + "." + cField : cField);
                } else {
                    newPath = new StringBuilder(in > 0 ? pField + "." + cField : "s." + cField);
                }
                Type cc = in > 0 ? getDeclaredFieldOrFunctionType(parentClass, cField) : parentClass;
                add(c, num, newPath.toString(), cc, parentClass, true, tab, orPath, orIndex, clazz, delimiter, fields, last || (i < cFields.length - 1), line, join);
            }
        }
        c.append("\n");
        for (int i = 0; i < opts.get(); i++) {
            fields.down();
            tabDec(tab);
            tab(c, tab).append("} else {\n");
            fields.up();
            tabInc(tab);
            if (orIndex + 1 < orPath.length) {
                addPathOr(clazz, delimiter, c, num, fields, last, new AtomicInteger(tab.get() + 2), orPath, orIndex + 1, line);
            } else {
                printDefaultValue(c, line.defaultValue, line);
                if (!map.ignoreDefaultValue())
                    printDelimiter(delimiter, c, last, tab);
            }
            tabDec(tab);
            fields.down();
            tab(c, tab).append("}\n");
        }
    }
}
Also used : lombok.val(lombok.val) Pair(oap.util.Pair) SneakyThrows(lombok.SneakyThrows) BiFunction(java.util.function.BiFunction) Pair.__(oap.util.Pair.__) HashMap(java.util.HashMap) StringUtils(org.apache.commons.lang3.StringUtils) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Stack(java.util.Stack) ClassUtils(org.apache.commons.lang3.ClassUtils) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) StringEscapeUtils(org.apache.commons.lang3.StringEscapeUtils) MutableObject(org.apache.commons.lang3.mutable.MutableObject) Path(java.nio.file.Path) Types.isPrimitive(oap.reflect.Types.isPrimitive) Types.getOptionalArgumentType(oap.reflect.Types.getOptionalArgumentType) lombok.val(lombok.val) Collectors.joining(java.util.stream.Collectors.joining) Slf4j(lombok.extern.slf4j.Slf4j) Try(oap.util.Try) List(java.util.List) Types.toJavaType(oap.reflect.Types.toJavaType) MemoryClassLoader(oap.tools.MemoryClassLoader) StringReader(java.io.StringReader) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) Optional(java.util.Optional) BufferedReader(java.io.BufferedReader) Optional(java.util.Optional) Types.getOptionalArgumentType(oap.reflect.Types.getOptionalArgumentType) Types.toJavaType(oap.reflect.Types.toJavaType) ParameterizedType(java.lang.reflect.ParameterizedType) Type(java.lang.reflect.Type) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MutableObject(org.apache.commons.lang3.mutable.MutableObject)

Example 3 with StringUtils.split

use of org.apache.commons.lang3.StringUtils.split in project eol-globi-data by jhpoelen.

the class StudyImporterForHurlbert method importInteraction.

protected void importInteraction(Set<String> regions, Set<String> locales, Set<String> habitats, Record record, Study study, String preyTaxonName, String predatorName) throws StudyImporterException {
    try {
        Taxon predatorTaxon = new TaxonImpl(predatorName);
        Specimen predatorSpecimen = nodeFactory.createSpecimen(study, predatorTaxon);
        setBasisOfRecordAsLiterature(predatorSpecimen);
        Taxon preyTaxon = new TaxonImpl(preyTaxonName);
        String preyNameId = StringUtils.trim(columnValueOrNull(record, "Prey_Name_ITIS_ID"));
        if (NumberUtils.isDigits(preyNameId)) {
            preyTaxon.setExternalId(TaxonomyProvider.ITIS.getIdPrefix() + preyNameId);
        }
        Specimen preySpecimen = nodeFactory.createSpecimen(study, preyTaxon);
        setBasisOfRecordAsLiterature(preySpecimen);
        String preyStage = StringUtils.trim(columnValueOrNull(record, "Prey_Stage"));
        if (StringUtils.isNotBlank(preyStage)) {
            Term lifeStage = nodeFactory.getOrCreateLifeStage("HULBERT:" + StringUtils.replace(preyStage, " ", "_"), preyStage);
            preySpecimen.setLifeStage(lifeStage);
        }
        String preyPart = StringUtils.trim(columnValueOrNull(record, "Prey_Part"));
        if (StringUtils.isNotBlank(preyPart)) {
            Term term = nodeFactory.getOrCreateBodyPart("HULBERT:" + StringUtils.replace(preyPart, " ", "_"), preyPart);
            preySpecimen.setBodyPart(term);
        }
        Date date = addCollectionDate(record, study);
        nodeFactory.setUnixEpochProperty(predatorSpecimen, date);
        nodeFactory.setUnixEpochProperty(preySpecimen, date);
        LocationImpl location = new LocationImpl(null, null, null, null);
        String longitude = columnValueOrNull(record, "Longitude_dd");
        String latitude = columnValueOrNull(record, "Latitude_dd");
        if (NumberUtils.isNumber(latitude) && NumberUtils.isNumber(longitude)) {
            try {
                LatLng latLng = LocationUtil.parseLatLng(latitude, longitude);
                String altitude = columnValueOrNull(record, "Altitude_mean_m");
                Double altitudeD = NumberUtils.isNumber(altitude) ? Double.parseDouble(altitude) : null;
                location = new LocationImpl(latLng.getLat(), latLng.getLng(), altitudeD, null);
            } catch (InvalidLocationException e) {
                getLogger().warn(study, "found invalid (lat,lng) pair: (" + latitude + "," + longitude + ")");
            }
        }
        String locationRegion = columnValueOrNull(record, "Location_Region");
        String locationSpecific = columnValueOrNull(record, "Location_Specific");
        location.setLocality(StringUtils.join(Arrays.asList(locationRegion, locationSpecific), ":"));
        Location locationNode = nodeFactory.getOrCreateLocation(location);
        String habitat_type = columnValueOrNull(record, "Habitat_type");
        List<Term> habitatList = Arrays.stream(StringUtils.split(StringUtils.defaultIfBlank(habitat_type, ""), ";")).map(StringUtils::trim).map(habitat -> new TermImpl(idForHabitat(habitat), habitat)).collect(Collectors.toList());
        nodeFactory.addEnvironmentToLocation(locationNode, habitatList);
        preySpecimen.caughtIn(locationNode);
        predatorSpecimen.caughtIn(locationNode);
        predatorSpecimen.ate(preySpecimen);
    } catch (NodeFactoryException e) {
        throw new StudyImporterException("failed to create interaction between [" + predatorName + "] and [" + preyTaxonName + "]", e);
    }
}
Also used : TsvParser(com.univocity.parsers.tsv.TsvParser) DateUtil(org.eol.globi.util.DateUtil) StringUtils(org.apache.commons.lang.StringUtils) CitationUtil(org.globalbioticinteractions.dataset.CitationUtil) Arrays(java.util.Arrays) Record(com.univocity.parsers.common.record.Record) Term(org.eol.globi.domain.Term) Specimen(org.eol.globi.domain.Specimen) Location(org.eol.globi.domain.Location) Date(java.util.Date) TermImpl(org.eol.globi.domain.TermImpl) LocationImpl(org.eol.globi.domain.LocationImpl) HashMap(java.util.HashMap) StudyImpl(org.eol.globi.domain.StudyImpl) HashSet(java.util.HashSet) TaxonImpl(org.eol.globi.domain.TaxonImpl) Map(java.util.Map) LatLng(org.eol.globi.geo.LatLng) TaxonomyProvider(org.eol.globi.domain.TaxonomyProvider) Taxon(org.eol.globi.domain.Taxon) InvalidLocationException(org.eol.globi.util.InvalidLocationException) DateTime(org.joda.time.DateTime) Set(java.util.Set) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) TsvParserSettings(com.univocity.parsers.tsv.TsvParserSettings) List(java.util.List) NumberUtils(org.apache.commons.lang3.math.NumberUtils) Log(org.apache.commons.logging.Log) LogFactory(org.apache.commons.logging.LogFactory) Study(org.eol.globi.domain.Study) StringEscapeUtils(org.apache.commons.lang.StringEscapeUtils) ArrayUtils(org.apache.commons.lang.ArrayUtils) InputStream(java.io.InputStream) InvalidLocationException(org.eol.globi.util.InvalidLocationException) Taxon(org.eol.globi.domain.Taxon) TaxonImpl(org.eol.globi.domain.TaxonImpl) Term(org.eol.globi.domain.Term) Date(java.util.Date) TermImpl(org.eol.globi.domain.TermImpl) Specimen(org.eol.globi.domain.Specimen) StringUtils(org.apache.commons.lang.StringUtils) LocationImpl(org.eol.globi.domain.LocationImpl) LatLng(org.eol.globi.geo.LatLng) Location(org.eol.globi.domain.Location)

Example 4 with StringUtils.split

use of org.apache.commons.lang3.StringUtils.split in project molgenis by molgenis.

the class RestService method convertMref.

private List<?> convertMref(Attribute attr, Object paramValue) {
    List<?> value;
    if (paramValue != null) {
        List<?> mrefParamValues;
        if (paramValue instanceof String) {
            mrefParamValues = asList(StringUtils.split((String) paramValue, ','));
        } else if (paramValue instanceof List<?>) {
            mrefParamValues = (List<?>) paramValue;
        } else {
            throw new MolgenisDataException(format("Attribute [%s] value is of type [%s] instead of [%s] or [%s]", attr.getName(), paramValue.getClass().getSimpleName(), String.class.getSimpleName(), List.class.getSimpleName()));
        }
        EntityType mrefEntity = attr.getRefEntity();
        Attribute mrefEntityIdAttr = mrefEntity.getIdAttribute();
        value = mrefParamValues.stream().map(mrefParamValue -> toEntityValue(mrefEntityIdAttr, mrefParamValue, null)).map(mrefIdValue -> entityManager.getReference(mrefEntity, mrefIdValue)).collect(toList());
    } else {
        value = emptyList();
    }
    return value;
}
Also used : EntityType(org.molgenis.data.meta.model.EntityType) IdGenerator(org.molgenis.data.populate.IdGenerator) ONE_TO_MANY(org.molgenis.data.meta.AttributeType.ONE_TO_MANY) StringUtils(org.apache.commons.lang3.StringUtils) Attribute(org.molgenis.data.meta.model.Attribute) FileStore(org.molgenis.data.file.FileStore) FileDownloadController(org.molgenis.core.ui.file.FileDownloadController) FileMetaFactory(org.molgenis.data.file.model.FileMetaFactory) Service(org.springframework.stereotype.Service) Arrays.asList(java.util.Arrays.asList) Map(java.util.Map) Objects.requireNonNull(java.util.Objects.requireNonNull) Nonnull(javax.annotation.Nonnull) Nullable(javax.annotation.Nullable) Collectors.toSet(java.util.stream.Collectors.toSet) POPULATE(org.molgenis.data.EntityManager.CreationMode.POPULATE) AttributeType(org.molgenis.data.meta.AttributeType) ServletUriComponentsBuilder(org.springframework.web.servlet.support.ServletUriComponentsBuilder) Collections.emptyList(java.util.Collections.emptyList) Set(java.util.Set) IOException(java.io.IOException) Instant(java.time.Instant) MolgenisDateFormat(org.molgenis.data.util.MolgenisDateFormat) EntityType(org.molgenis.data.meta.model.EntityType) FILENAME(org.molgenis.data.file.model.FileMetaMetaData.FILENAME) String.format(java.lang.String.format) UnexpectedEnumException(org.molgenis.util.UnexpectedEnumException) FileMeta(org.molgenis.data.file.model.FileMeta) FILE_META(org.molgenis.data.file.model.FileMetaMetaData.FILE_META) DateTimeParseException(java.time.format.DateTimeParseException) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList) Stream(java.util.stream.Stream) StreamSupport.stream(java.util.stream.StreamSupport.stream) LocalDate(java.time.LocalDate) DataService(org.molgenis.data.DataService) MultipartFile(org.springframework.web.multipart.MultipartFile) MolgenisDataException(org.molgenis.data.MolgenisDataException) EntityManager(org.molgenis.data.EntityManager) Entity(org.molgenis.data.Entity) UriComponents(org.springframework.web.util.UriComponents) MolgenisDataException(org.molgenis.data.MolgenisDataException) Attribute(org.molgenis.data.meta.model.Attribute) Arrays.asList(java.util.Arrays.asList) Collections.emptyList(java.util.Collections.emptyList) List(java.util.List) Collectors.toList(java.util.stream.Collectors.toList)

Example 5 with StringUtils.split

use of org.apache.commons.lang3.StringUtils.split in project spring-roo by spring-projects.

the class RepositoryJpaCustomImplMetadataProviderImpl method buildFieldNamesMap.

/**
 * Build a Map<String, String> with field names and "path" field names
 * and adds it to the typesFieldMaps Map.
 *
 * @param entity
 * @param projection
 * @param entityProjectionAnnotation
 * @param typesFieldMaps
 */
private void buildFieldNamesMap(JavaType entity, JavaType projection, AnnotationMetadata entityProjectionAnnotation, Map<JavaType, List<Pair<String, String>>> typesFieldMaps) {
    List<Pair<String, String>> projectionFieldNames = new ArrayList<Pair<String, String>>();
    if (!typesFieldMaps.containsKey(projection)) {
        AnnotationAttributeValue<?> projectionFields = entityProjectionAnnotation.getAttribute("fields");
        if (projectionFields != null) {
            @SuppressWarnings("unchecked") List<StringAttributeValue> values = (List<StringAttributeValue>) projectionFields.getValue();
            // Get entity name as a variable name for building constructor expression
            String entityVariableName = StringUtils.uncapitalize(entity.getSimpleTypeName());
            for (StringAttributeValue field : values) {
                String[] splittedByDot = StringUtils.split(field.getValue(), ".");
                StringBuffer propertyName = new StringBuffer();
                for (int i = 0; i < splittedByDot.length; i++) {
                    if (i == 0) {
                        propertyName.append(splittedByDot[i]);
                    } else {
                        propertyName.append(StringUtils.capitalize(splittedByDot[i]));
                    }
                }
                String pathName = entityVariableName.concat(".").concat(field.getValue());
                projectionFieldNames.add(Pair.of(propertyName.toString(), pathName));
                typesFieldMaps.put(projection, projectionFieldNames);
            }
        }
    }
}
Also used : ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) StringAttributeValue(org.springframework.roo.classpath.details.annotations.StringAttributeValue) Pair(org.apache.commons.lang3.tuple.Pair)

Aggregations

List (java.util.List)6 Map (java.util.Map)5 StringUtils (org.apache.commons.lang3.StringUtils)5 Set (java.util.Set)4 IOException (java.io.IOException)3 HashMap (java.util.HashMap)3 HashSet (java.util.HashSet)3 Collectors (java.util.stream.Collectors)3 ArrayList (java.util.ArrayList)2 Arrays (java.util.Arrays)2 Optional (java.util.Optional)2 Function (java.util.function.Function)2 Supplier (java.util.function.Supplier)2 Stream (java.util.stream.Stream)2 lombok.val (lombok.val)2 MutableObject (org.apache.commons.lang3.mutable.MutableObject)2 LinePoint (blue.components.lines.LinePoint)1 GenericInstrument (blue.orchestra.GenericInstrument)1 TypeReference (com.fasterxml.jackson.core.type.TypeReference)1 Record (com.univocity.parsers.common.record.Record)1