Search in sources :

Example 51 with Attribute

use of ddf.catalog.data.Attribute in project ddf by codice.

the class TransactionRequestConverter method parseUpdateAction.

private UpdateAction parseUpdateAction(HierarchicalStreamReader reader, UnmarshallingContext context) {
    Map<String, String> xmlnsAttributeToUriMappings = getXmlnsAttributeToUriMappingsFromContext(context);
    Map<String, String> prefixToUriMappings = getPrefixToUriMappingsFromXmlnsAttributes(xmlnsAttributeToUriMappings);
    String typeName = StringUtils.defaultIfEmpty(reader.getAttribute(CswConstants.TYPE_NAME_PARAMETER), CswConstants.CSW_RECORD);
    String handle = StringUtils.defaultIfEmpty(reader.getAttribute(CswConstants.HANDLE_PARAMETER), "");
    // Move down to the content of the <Update>.
    reader.moveDown();
    UpdateAction updateAction;
    // Do we have a list of <RecordProperty> elements or a new <csw:Record>?
    if (reader.getNodeName().contains("RecordProperty")) {
        Map<String, Serializable> cswRecordProperties = new HashMap<>();
        while (reader.getNodeName().contains("RecordProperty")) {
            String cswField;
            Serializable newValue = null;
            // Move down to the <Name>.
            reader.moveDown();
            if (reader.getNodeName().contains("Name")) {
                String attribute = reader.getValue();
                cswField = CswRecordConverter.getCswAttributeFromAttributeName(attribute);
            } else {
                throw new ConversionException("Missing Parameter Value: missing a Name in a RecordProperty.");
            }
            // Move back up to the <RecordProperty>.
            reader.moveUp();
            String attrName = DefaultCswRecordMap.getDefaultMetacardFieldForPrefixedString(cswField);
            cswRecordProperties.put(attrName, null);
            // Is there a <Value>?
            while (reader.hasMoreChildren()) {
                // Move down to the <Value>.
                reader.moveDown();
                if (reader.getNodeName().contains("Value")) {
                    newValue = getRecordPropertyValue(reader, attrName);
                } else {
                    throw new ConversionException("Invalid Parameter Value: invalid element in a RecordProperty.");
                }
                Serializable currentValue = cswRecordProperties.get(attrName);
                if (currentValue != null) {
                    if (currentValue instanceof List) {
                        ((List) currentValue).add(newValue);
                    } else {
                        LinkedList<Serializable> list = new LinkedList<>();
                        list.add(currentValue);
                        list.add(newValue);
                        cswRecordProperties.put(attrName, list);
                    }
                } else {
                    cswRecordProperties.put(attrName, newValue);
                }
                // Back to the <RecordProperty>.
                reader.moveUp();
            }
            // Back to the <Update>, look for the next <RecordProperty>.
            reader.moveUp();
            if (!reader.hasMoreChildren()) {
                // Constraint, which is required.
                throw new ConversionException("Missing Parameter Value: missing a Constraint.");
            }
            // What's the next element in the <Update>?
            reader.moveDown();
        }
        // Now there should be a <Constraint> element.
        if (reader.getNodeName().contains("Constraint")) {
            StringWriter writer = new StringWriter();
            XStreamAttributeCopier.copyXml(reader, writer, xmlnsAttributeToUriMappings);
            QueryConstraintType constraint = getElementFromXml(writer.toString(), QueryConstraintType.class);
            // For any CSW attributes that map to basic metacard attributes (e.g. title,
            // modified date, etc.), update the basic metacard attributes as well.
            Map<String, String> cswToMetacardAttributeNames = DefaultCswRecordMap.getDefaultCswRecordMap().getCswToMetacardAttributeNames();
            Map<String, Serializable> cswRecordPropertiesWithMetacardAttributes = new HashMap<>(cswRecordProperties);
            for (Entry<String, Serializable> recordProperty : cswRecordProperties.entrySet()) {
                String cswAttributeName = recordProperty.getKey();
                // basic metacard attribute.
                if (cswToMetacardAttributeNames.containsKey(cswAttributeName)) {
                    String metacardAttrName = cswToMetacardAttributeNames.get(cswAttributeName);
                    // If this basic metacard attribute hasn't already been set, set it.
                    if (!cswRecordPropertiesWithMetacardAttributes.containsKey(metacardAttrName)) {
                        Attribute metacardAttr = cswRecordConverter.getMetacardAttributeFromCswAttribute(cswAttributeName, recordProperty.getValue(), metacardAttrName);
                        cswRecordPropertiesWithMetacardAttributes.put(metacardAttrName, metacardAttr.getValue());
                    }
                }
            }
            updateAction = new UpdateAction(cswRecordPropertiesWithMetacardAttributes, typeName, handle, constraint, prefixToUriMappings);
        } else {
            throw new ConversionException("Missing Parameter Value: missing a Constraint.");
        }
    } else {
        context.put(CswConstants.TRANSFORMER_LOOKUP_KEY, TransformerManager.ID);
        context.put(CswConstants.TRANSFORMER_LOOKUP_VALUE, typeName);
        Metacard metacard = (Metacard) context.convertAnother(null, MetacardImpl.class, delegatingTransformer);
        updateAction = new UpdateAction(metacard, typeName, handle);
        // Move back to the <Update>.
        reader.moveUp();
    }
    return updateAction;
}
Also used : ConversionException(com.thoughtworks.xstream.converters.ConversionException) Serializable(java.io.Serializable) UpdateAction(org.codice.ddf.spatial.ogc.csw.catalog.common.transaction.UpdateAction) HashMap(java.util.HashMap) Attribute(ddf.catalog.data.Attribute) LinkedList(java.util.LinkedList) QueryConstraintType(net.opengis.cat.csw.v_2_0_2.QueryConstraintType) MetacardImpl(ddf.catalog.data.impl.MetacardImpl) Metacard(ddf.catalog.data.Metacard) StringWriter(java.io.StringWriter) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) List(java.util.List)

Example 52 with Attribute

use of ddf.catalog.data.Attribute in project ddf by codice.

the class MetacardEditEndpoint method setAttribute.

@PUT
@Path("/{id}/{attribute}")
@Consumes(MediaType.TEXT_PLAIN)
public Response setAttribute(@Context HttpServletResponse response, @PathParam("id") String id, @PathParam("attribute") String attribute, String value) throws Exception {
    Metacard metacard = endpointUtil.getMetacard(id);
    if (metacard == null) {
        return Response.status(404).build();
    }
    Attribute metacardAttribute = metacard.getAttribute(attribute);
    Optional<AttributeDescriptor> attributeDescriptor = attributeRegistry.lookup(attribute);
    if (!attributeDescriptor.isPresent()) {
        /* Could not find attribute descriptor for requested attribute */
        return Response.status(404).build();
    }
    AttributeDescriptor descriptor = attributeDescriptor.get();
    if (descriptor.isMultiValued()) {
        if (metacardAttribute == null || metacardAttribute.getValues() == null) {
            metacard.setAttribute(new AttributeImpl(attribute, Collections.singletonList(value)));
        } else {
            List<Serializable> values = new ArrayList<>(metacardAttribute.getValues());
            if (!values.contains(value)) {
                values.add(value);
            }
            metacard.setAttribute(new AttributeImpl(attribute, values));
        }
    } else {
        // not multivalued
        metacard.setAttribute(new AttributeImpl(attribute, value));
    }
    catalogFramework.update(new UpdateRequestImpl(id, metacard));
    Map<String, Object> responseMap = getResponseMap(attribute, metacard.getAttribute(attribute), descriptor);
    return Response.ok(endpointUtil.getJson(responseMap), MediaType.APPLICATION_JSON).build();
}
Also used : Metacard(ddf.catalog.data.Metacard) Serializable(java.io.Serializable) Attribute(ddf.catalog.data.Attribute) AttributeImpl(ddf.catalog.data.impl.AttributeImpl) ArrayList(java.util.ArrayList) AttributeDescriptor(ddf.catalog.data.AttributeDescriptor) UpdateRequestImpl(ddf.catalog.operation.impl.UpdateRequestImpl) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) PUT(javax.ws.rs.PUT)

Example 53 with Attribute

use of ddf.catalog.data.Attribute in project ddf by codice.

the class CqlResult method countMatches.

private void countMatches(Set<SearchTerm> searchTerms, Metacard mc) {
    List<String> textAttributes = mc.getMetacardType().getAttributeDescriptors().stream().filter(CqlResult::isTextAttribute).filter(Objects::nonNull).map(descriptor -> mc.getAttribute(descriptor.getName())).filter(Objects::nonNull).map(attribute -> Optional.ofNullable(attribute.getValue())).filter(Optional::isPresent).map(Optional::get).map(Object::toString).collect(Collectors.toList());
    List<SearchTerm> terms = searchTerms.stream().filter(term -> !"*".equals(term.getTerm())).collect(Collectors.toList());
    int totalTokens = 0;
    for (String value : textAttributes) {
        BufferedReader reader = new BufferedReader(new StringReader(value.toLowerCase()));
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                String[] tokens = line.split("[\\s\\p{Punct}]+");
                for (String token : tokens) {
                    totalTokens++;
                    for (SearchTerm term : terms) {
                        if (term.match(token)) {
                            matches.put(term.getTerm(), matches.getOrDefault(term.getTerm(), 0) + 1);
                        }
                    }
                }
            }
        } catch (IOException e) {
            LOGGER.debug("Unable to read line", e);
        }
        matches.put("*", totalTokens);
    }
}
Also used : ValidationRule(org.locationtech.spatial4j.context.jts.ValidationRule) ShapeReader(org.locationtech.spatial4j.io.ShapeReader) UnsupportedQueryException(ddf.catalog.source.UnsupportedQueryException) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) FilterAdapter(ddf.catalog.filter.FilterAdapter) StringUtils(org.apache.commons.lang3.StringUtils) AttributeType(ddf.catalog.data.AttributeType) Action(ddf.action.Action) DistanceUtils(org.locationtech.spatial4j.distance.DistanceUtils) ImmutableList(com.google.common.collect.ImmutableList) Metacard(ddf.catalog.data.Metacard) Map(java.util.Map) MetacardImpl(ddf.catalog.data.impl.MetacardImpl) QueryRequest(ddf.catalog.operation.QueryRequest) ParseException(java.text.ParseException) Result(ddf.catalog.data.Result) DateTimeFormat(org.joda.time.format.DateTimeFormat) JtsSpatialContextFactory(org.locationtech.spatial4j.context.jts.JtsSpatialContextFactory) Logger(org.slf4j.Logger) AttributeDescriptor(ddf.catalog.data.AttributeDescriptor) PropertyJsonMetacardTransformer(ddf.catalog.transformer.metacard.propertyjson.PropertyJsonMetacardTransformer) WktQueryDelegate(org.codice.ddf.catalog.ui.query.delegate.WktQueryDelegate) DateTimeFormatter(org.joda.time.format.DateTimeFormatter) ImmutableMap(com.google.common.collect.ImmutableMap) DateTime(org.joda.time.DateTime) Set(java.util.Set) IOException(java.io.IOException) Shape(org.locationtech.spatial4j.shape.Shape) Collectors(java.util.stream.Collectors) SpatialContextFactory(org.locationtech.spatial4j.context.SpatialContextFactory) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) Objects(java.util.Objects) Query(ddf.catalog.operation.Query) List(java.util.List) Attribute(ddf.catalog.data.Attribute) StringReader(java.io.StringReader) SearchTerm(org.codice.ddf.catalog.ui.query.delegate.SearchTerm) Optional(java.util.Optional) ActionRegistry(ddf.action.ActionRegistry) BufferedReader(java.io.BufferedReader) SpatialContext(org.locationtech.spatial4j.context.SpatialContext) Optional(java.util.Optional) BufferedReader(java.io.BufferedReader) StringReader(java.io.StringReader) IOException(java.io.IOException) SearchTerm(org.codice.ddf.catalog.ui.query.delegate.SearchTerm)

Example 54 with Attribute

use of ddf.catalog.data.Attribute in project ddf by codice.

the class MetacardEditEndpoint method setBinaryAttribute.

@SuppressFBWarnings
@PUT
@Path("/{id}/{attribute}")
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
public Response setBinaryAttribute(@Context HttpServletResponse response, @PathParam("id") String id, @PathParam("attribute") String attribute, byte[] value) throws Exception {
    Metacard metacard = endpointUtil.getMetacard(id);
    if (metacard == null) {
        return Response.status(404).build();
    }
    Attribute metacardAttribute = metacard.getAttribute(attribute);
    Optional<AttributeDescriptor> attributeDescriptor = attributeRegistry.lookup(attribute);
    if (!attributeDescriptor.isPresent()) {
        /* Could not find attribute descriptor for requested attribute */
        response.setStatus(404);
        return Response.status(404).build();
    }
    AttributeDescriptor descriptor = attributeDescriptor.get();
    if (!descriptor.getType().getAttributeFormat().equals(AttributeType.AttributeFormat.BINARY)) {
        return Response.status(400).build();
    }
    if (descriptor.isMultiValued()) {
        List<Serializable> values;
        if (metacardAttribute == null) {
            values = new ArrayList<>();
        } else {
            values = metacardAttribute.getValues();
        }
        if (!values.contains(value)) {
            values.add(value);
        }
        metacard.setAttribute(new AttributeImpl(attribute, values));
    } else {
        metacard.setAttribute(new AttributeImpl(attribute, value));
    }
    catalogFramework.update(new UpdateRequestImpl(id, metacard));
    Map<String, Object> responseMap = getResponseMap(attribute, metacard.getAttribute(attribute), descriptor);
    return Response.ok(endpointUtil.getJson(response), MediaType.APPLICATION_JSON).build();
}
Also used : Metacard(ddf.catalog.data.Metacard) Serializable(java.io.Serializable) Attribute(ddf.catalog.data.Attribute) AttributeImpl(ddf.catalog.data.impl.AttributeImpl) AttributeDescriptor(ddf.catalog.data.AttributeDescriptor) UpdateRequestImpl(ddf.catalog.operation.impl.UpdateRequestImpl) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) SuppressFBWarnings(edu.umd.cs.findbugs.annotations.SuppressFBWarnings) PUT(javax.ws.rs.PUT)

Example 55 with Attribute

use of ddf.catalog.data.Attribute in project ddf by codice.

the class EndpointUtil method getMetacardMap.

public Map<String, Object> getMetacardMap(Metacard metacard) {
    Set<AttributeDescriptor> attributeDescriptors = metacard.getMetacardType().getAttributeDescriptors();
    Map<String, Object> result = new HashMap<>();
    for (AttributeDescriptor descriptor : attributeDescriptors) {
        if (metacard.getAttribute(descriptor.getName()) == null) {
            if (descriptor.isMultiValued()) {
                result.put(descriptor.getName(), Collections.emptyList());
            } else {
                result.put(descriptor.getName(), null);
            }
            continue;
        }
        if (Metacard.THUMBNAIL.equals(descriptor.getName())) {
            if (metacard.getThumbnail() != null) {
                result.put(descriptor.getName(), Base64.getEncoder().encodeToString(metacard.getThumbnail()));
            } else {
                result.put(descriptor.getName(), null);
            }
            continue;
        }
        if (descriptor.getType().getAttributeFormat().equals(AttributeType.AttributeFormat.DATE)) {
            Attribute attribute = metacard.getAttribute(descriptor.getName());
            if (descriptor.isMultiValued()) {
                result.put(descriptor.getName(), attribute.getValues().stream().map(this::parseDate).collect(Collectors.toList()));
            } else {
                result.put(descriptor.getName(), parseDate(attribute.getValue()));
            }
        }
        if (descriptor.isMultiValued()) {
            result.put(descriptor.getName(), metacard.getAttribute(descriptor.getName()).getValues());
        } else {
            result.put(descriptor.getName(), metacard.getAttribute(descriptor.getName()).getValue());
        }
    }
    return result;
}
Also used : HashMap(java.util.HashMap) InjectableAttribute(ddf.catalog.data.InjectableAttribute) Attribute(ddf.catalog.data.Attribute) AttributeDescriptor(ddf.catalog.data.AttributeDescriptor)

Aggregations

Attribute (ddf.catalog.data.Attribute)103 Metacard (ddf.catalog.data.Metacard)39 Test (org.junit.Test)37 ArrayList (java.util.ArrayList)30 AttributeImpl (ddf.catalog.data.impl.AttributeImpl)29 AttributeDescriptor (ddf.catalog.data.AttributeDescriptor)26 Serializable (java.io.Serializable)23 MetacardImpl (ddf.catalog.data.impl.MetacardImpl)15 HashMap (java.util.HashMap)15 Result (ddf.catalog.data.Result)14 List (java.util.List)14 MetacardType (ddf.catalog.data.MetacardType)11 QueryResponse (ddf.catalog.operation.QueryResponse)11 Date (java.util.Date)11 Map (java.util.Map)11 HashSet (java.util.HashSet)10 Optional (java.util.Optional)8 Set (java.util.Set)8 Filter (org.opengis.filter.Filter)8 UpdateRequestImpl (ddf.catalog.operation.impl.UpdateRequestImpl)7