Search in sources :

Example 1 with ParserException

use of org.codice.ddf.parser.ParserException in project ddf by codice.

the class RegistryStoreImpl method update.

@Override
public UpdateResponse update(UpdateRequest request) throws IngestException {
    if (request.getUpdates().stream().map(e -> RegistryUtility.getRegistryId(e.getValue())).anyMatch(Objects::isNull)) {
        throw new IngestException("One or more of the metacards is not a registry metacard");
    }
    Map<String, Metacard> updatedMetacards = request.getUpdates().stream().collect(Collectors.toMap(e -> RegistryUtility.getRegistryId(e.getValue()), Map.Entry::getValue));
    Map<String, Metacard> origMetacards = ((OperationTransaction) request.getPropertyValue(Constants.OPERATION_TRANSACTION_KEY)).getPreviousStateMetacards().stream().collect(Collectors.toMap(RegistryUtility::getRegistryId, e -> e));
    //update the new metacards with the id from the orig so that they can be found on the remote system
    try {
        for (Map.Entry<String, Metacard> entry : updatedMetacards.entrySet()) {
            setMetacardExtID(entry.getValue(), origMetacards.get(entry.getKey()).getId());
        }
    } catch (ParserException e) {
        throw new IngestException("Could not update metacards id", e);
    }
    return super.update(request);
}
Also used : CreateRequest(ddf.catalog.operation.CreateRequest) UnsupportedQueryException(ddf.catalog.source.UnsupportedQueryException) LoggerFactory(org.slf4j.LoggerFactory) TagsFilterDelegate(ddf.catalog.filter.delegate.TagsFilterDelegate) Locale(java.util.Locale) Map(java.util.Map) DeleteRequestImpl(ddf.catalog.operation.impl.DeleteRequestImpl) URI(java.net.URI) Bundle(org.osgi.framework.Bundle) Converter(com.thoughtworks.xstream.converters.Converter) ImmutableSet(com.google.common.collect.ImmutableSet) RegistryUtility(org.codice.ddf.registry.common.metacard.RegistryUtility) SourceResponseImpl(ddf.catalog.operation.impl.SourceResponseImpl) SourceMonitor(ddf.catalog.source.SourceMonitor) ParserException(org.codice.ddf.parser.ParserException) AbstractCswStore(org.codice.ddf.spatial.ogc.csw.catalog.common.source.AbstractCswStore) Collectors(java.util.stream.Collectors) BundleContext(org.osgi.framework.BundleContext) Serializable(java.io.Serializable) Objects(java.util.Objects) SecureCxfClientFactory(org.codice.ddf.cxf.SecureCxfClientFactory) DeleteRequest(ddf.catalog.operation.DeleteRequest) List(java.util.List) ExternalIdentifierType(oasis.names.tc.ebxml_regrep.xsd.rim._3.ExternalIdentifierType) ConfigurationAdmin(org.osgi.service.cm.ConfigurationAdmin) RegistryObjectMetacardType(org.codice.ddf.registry.common.metacard.RegistryObjectMetacardType) UpdateResponse(ddf.catalog.operation.UpdateResponse) Dictionary(java.util.Dictionary) QueryRequestImpl(ddf.catalog.operation.impl.QueryRequestImpl) HashMap(java.util.HashMap) DeleteResponse(ddf.catalog.operation.DeleteResponse) OperationTransaction(ddf.catalog.operation.OperationTransaction) MetaTypeInformation(org.osgi.service.metatype.MetaTypeInformation) ArrayList(java.util.ArrayList) MetacardMarshaller(org.codice.ddf.registry.schemabindings.helper.MetacardMarshaller) Configuration(org.osgi.service.cm.Configuration) CreateResponse(ddf.catalog.operation.CreateResponse) CollectionUtils(org.apache.commons.collections.CollectionUtils) Constants(ddf.catalog.Constants) Metacard(ddf.catalog.data.Metacard) SecurityConstants(ddf.security.SecurityConstants) QueryRequest(ddf.catalog.operation.QueryRequest) UpdateRequest(ddf.catalog.operation.UpdateRequest) EncryptionService(ddf.security.encryption.EncryptionService) RegistryConstants(org.codice.ddf.registry.common.RegistryConstants) Result(ddf.catalog.data.Result) CreateRequestImpl(ddf.catalog.operation.impl.CreateRequestImpl) QueryImpl(ddf.catalog.operation.impl.QueryImpl) Logger(org.slf4j.Logger) RegistryPackageType(oasis.names.tc.ebxml_regrep.xsd.rim._3.RegistryPackageType) IngestException(ddf.catalog.source.IngestException) RegistryStore(org.codice.ddf.registry.api.internal.RegistryStore) CswSourceConfiguration(org.codice.ddf.spatial.ogc.csw.catalog.common.CswSourceConfiguration) IOException(java.io.IOException) CreateResponseImpl(ddf.catalog.operation.impl.CreateResponseImpl) MetaTypeService(org.osgi.service.metatype.MetaTypeService) Consumer(java.util.function.Consumer) Query(ddf.catalog.operation.Query) SourceResponse(ddf.catalog.operation.SourceResponse) Filter(org.opengis.filter.Filter) Collections(java.util.Collections) FrameworkUtil(org.osgi.framework.FrameworkUtil) OperationTransaction(ddf.catalog.operation.OperationTransaction) ParserException(org.codice.ddf.parser.ParserException) Metacard(ddf.catalog.data.Metacard) Objects(java.util.Objects) IngestException(ddf.catalog.source.IngestException) Map(java.util.Map) HashMap(java.util.HashMap)

Example 2 with ParserException

use of org.codice.ddf.parser.ParserException in project ddf by codice.

the class IdentificationPlugin method updateIdentifiers.

private void updateIdentifiers(Metacard metacard, boolean create) throws StopProcessingException {
    boolean extOriginFound = false;
    boolean extRegIdFound = false;
    String metacardID = metacard.getId();
    String registryID = RegistryUtility.getRegistryId(metacard);
    String systemRegId = System.getProperty(RegistryConstants.REGISTRY_ID_PROPERTY);
    try {
        RegistryPackageType registryPackage = metacardMarshaller.getRegistryPackageFromMetacard(metacard);
        List<ExternalIdentifierType> extIdList = new ArrayList<>();
        //check if external ids are already present
        if (registryPackage.isSetExternalIdentifier()) {
            List<ExternalIdentifierType> currentExtIdList = registryPackage.getExternalIdentifier();
            for (ExternalIdentifierType extId : currentExtIdList) {
                extId.setRegistryObject(registryID);
                if (extId.getId().equals(RegistryConstants.REGISTRY_MCARD_ID_LOCAL)) {
                    if (isInternal(metacard) && create) {
                        metacard.setAttribute(new AttributeImpl(RegistryObjectMetacardType.REMOTE_METACARD_ID, extId.getValue()));
                    }
                    extId.setValue(metacardID);
                } else if (extId.getId().equals(RegistryConstants.REGISTRY_MCARD_ID_ORIGIN)) {
                    extOriginFound = true;
                } else if (extId.getId().equals(RegistryConstants.REGISTRY_ID_ORIGIN)) {
                    if (!systemRegId.equals(extId.getValue()) && isInternal(metacard)) {
                        metacard.setAttribute(new AttributeImpl(RegistryObjectMetacardType.REMOTE_REGISTRY_ID, extId.getValue()));
                    }
                    extId.setValue(systemRegId);
                    extRegIdFound = true;
                }
                extIdList.add(extId);
            }
            if (!extOriginFound) {
                extIdList.add(createExternalIdentifier(RegistryConstants.REGISTRY_MCARD_ID_ORIGIN, registryID, RegistryConstants.REGISTRY_METACARD_ID_CLASS, metacardID));
            }
            if (!extRegIdFound) {
                extIdList.add(createExternalIdentifier(RegistryConstants.REGISTRY_ID_ORIGIN, registryID, RegistryConstants.REGISTRY_ID_CLASS, systemRegId));
            }
        } else {
            extIdList.add(createExternalIdentifier(RegistryConstants.REGISTRY_MCARD_ID_LOCAL, registryID, RegistryConstants.REGISTRY_METACARD_ID_CLASS, metacardID));
            extIdList.add(createExternalIdentifier(RegistryConstants.REGISTRY_MCARD_ID_ORIGIN, registryID, RegistryConstants.REGISTRY_METACARD_ID_CLASS, metacardID));
            extIdList.add(createExternalIdentifier(RegistryConstants.REGISTRY_ID_ORIGIN, registryID, RegistryConstants.REGISTRY_ID_CLASS, systemRegId));
        }
        registryPackage.setExternalIdentifier(extIdList);
        metacardMarshaller.setMetacardRegistryPackage(metacard, registryPackage);
    } catch (ParserException e) {
        throw new StopProcessingException("Unable to access Registry Metadata. Parser exception caught");
    }
}
Also used : ParserException(org.codice.ddf.parser.ParserException) RegistryPackageType(oasis.names.tc.ebxml_regrep.xsd.rim._3.RegistryPackageType) AttributeImpl(ddf.catalog.data.impl.AttributeImpl) ArrayList(java.util.ArrayList) ExternalIdentifierType(oasis.names.tc.ebxml_regrep.xsd.rim._3.ExternalIdentifierType) StopProcessingException(ddf.catalog.plugin.StopProcessingException)

Example 3 with ParserException

use of org.codice.ddf.parser.ParserException in project ddf by codice.

the class XmlParser method marshal.

private void marshal(ParserConfigurator configurator, Consumer<Marshaller> marshallerConsumer) throws ParserException {
    JAXBContext jaxbContext = getContext(configurator.getContextPath(), configurator.getClassLoader());
    ClassLoader tccl = Thread.currentThread().getContextClassLoader();
    try {
        Thread.currentThread().setContextClassLoader(configurator.getClassLoader());
        Marshaller marshaller = jaxbContext.createMarshaller();
        if (configurator.getAdapter() != null) {
            marshaller.setAdapter(configurator.getAdapter());
        }
        if (configurator.getHandler() != null) {
            marshaller.setEventHandler(configurator.getHandler());
        }
        for (Map.Entry<String, Object> propRow : configurator.getProperties().entrySet()) {
            marshaller.setProperty(propRow.getKey(), propRow.getValue());
        }
        marshallerConsumer.accept(marshaller);
    } catch (RuntimeException e) {
        LOGGER.debug("Error marshalling ", e);
        throw new ParserException("Error marshalling ", e);
    } catch (JAXBException e) {
        LOGGER.debug("Error marshalling ", e);
        throw new ParserException("Error marshalling", e);
    } finally {
        Thread.currentThread().setContextClassLoader(tccl);
    }
}
Also used : ParserException(org.codice.ddf.parser.ParserException) Marshaller(javax.xml.bind.Marshaller) JAXBException(javax.xml.bind.JAXBException) JAXBContext(javax.xml.bind.JAXBContext) Map(java.util.Map)

Example 4 with ParserException

use of org.codice.ddf.parser.ParserException in project ddf by codice.

the class UPBSTValidator method validateToken.

/**
     * Validate a Token using the given TokenValidatorParameters.
     *
     * @param tokenParameters
     * @return TokenValidatorResponse
     */
public TokenValidatorResponse validateToken(TokenValidatorParameters tokenParameters) {
    LOGGER.trace("Validating UPBST Token");
    if (parser == null) {
        throw new IllegalStateException("XMLParser must be configured.");
    }
    if (failedLoginDelayer == null) {
        throw new IllegalStateException("Failed Login Delayer must be configured");
    }
    STSPropertiesMBean stsProperties = tokenParameters.getStsProperties();
    Crypto sigCrypto = stsProperties.getSignatureCrypto();
    CallbackHandler callbackHandler = stsProperties.getCallbackHandler();
    RequestData requestData = new RequestData();
    requestData.setSigVerCrypto(sigCrypto);
    requestData.setWssConfig(WSSConfig.getNewInstance());
    requestData.setCallbackHandler(callbackHandler);
    TokenValidatorResponse response = new TokenValidatorResponse();
    ReceivedToken validateTarget = tokenParameters.getToken();
    validateTarget.setState(STATE.INVALID);
    response.setToken(validateTarget);
    if (!validateTarget.isBinarySecurityToken()) {
        return response;
    }
    BinarySecurityTokenType binarySecurityType = (BinarySecurityTokenType) validateTarget.getToken();
    // Test the encoding type
    String encodingType = binarySecurityType.getEncodingType();
    if (!UPAuthenticationToken.BASE64_ENCODING.equals(encodingType)) {
        LOGGER.trace("Bad encoding type attribute specified: {}", encodingType);
        return response;
    }
    UPAuthenticationToken usernameToken = getUsernameTokenFromTarget(validateTarget);
    if (usernameToken == null) {
        return response;
    }
    UsernameTokenType usernameTokenType = getUsernameTokenType(usernameToken);
    // Marshall the received JAXB object into a DOM Element
    Element usernameTokenElement = null;
    JAXBElement<UsernameTokenType> tokenType = new JAXBElement<>(QNameConstants.USERNAME_TOKEN, UsernameTokenType.class, usernameTokenType);
    Document doc = DOMUtils.createDocument();
    Element rootElement = doc.createElement("root-element");
    List<String> ctxPath = new ArrayList<>(1);
    ctxPath.add(UsernameTokenType.class.getPackage().getName());
    ParserConfigurator configurator = parser.configureParser(ctxPath, UPBSTValidator.class.getClassLoader());
    try {
        parser.marshal(configurator, tokenType, rootElement);
    } catch (ParserException ex) {
        LOGGER.info("Unable to parse username token", ex);
        return response;
    }
    usernameTokenElement = (Element) rootElement.getFirstChild();
    //
    // Validate the token
    //
    WSSConfig wssConfig = WSSConfig.getNewInstance();
    try {
        boolean allowNamespaceQualifiedPasswordTypes = requestData.isAllowNamespaceQualifiedPasswordTypes();
        UsernameToken ut = new UsernameToken(usernameTokenElement, allowNamespaceQualifiedPasswordTypes, new BSPEnforcer());
        // The parsed principal is set independent whether validation is successful or not
        response.setPrincipal(new CustomTokenPrincipal(ut.getName()));
        if (ut.getPassword() == null) {
            return response;
        }
        String tokenId = String.format("%s:%s:%s", usernameToken.getUsername(), usernameToken.getPassword(), usernameToken.getRealm());
        // See if the UsernameToken is stored in the cache
        int hash = tokenId.hashCode();
        SecurityToken secToken = null;
        if (tokenParameters.getTokenStore() != null) {
            secToken = tokenParameters.getTokenStore().getToken(Integer.toString(hash));
            if (secToken != null && secToken.getTokenHash() != hash) {
                secToken = null;
            } else if (secToken != null) {
                validateTarget.setState(STATE.VALID);
            }
        }
        if (secToken == null) {
            Credential credential = new Credential();
            credential.setUsernametoken(ut);
            if (usernameToken.getRealm() != null && !"*".equals(usernameToken.getRealm())) {
                Validator validator = validators.get(usernameToken.getRealm());
                if (validator != null) {
                    try {
                        validator.validate(credential, requestData);
                        validateTarget.setState(STATE.VALID);
                        LOGGER.debug("Validated user against realm {}", usernameToken.getRealm());
                    } catch (WSSecurityException ex) {
                        LOGGER.debug("Not able to validate user against realm {}", usernameToken.getRealm());
                    }
                }
            } else {
                Set<Map.Entry<String, Validator>> entries = validators.entrySet();
                for (Map.Entry<String, Validator> entry : entries) {
                    try {
                        entry.getValue().validate(credential, requestData);
                        validateTarget.setState(STATE.VALID);
                        LOGGER.debug("Validated user against realm {}", entry.getKey());
                        break;
                    } catch (WSSecurityException ex) {
                        LOGGER.debug("Not able to validate user against realm {}", entry.getKey());
                    }
                }
            }
        }
        Principal principal = createPrincipal(ut.getName(), ut.getPassword(), ut.getPasswordType(), ut.getNonce(), ut.getCreated());
        // Store the successfully validated token in the cache
        if (tokenParameters.getTokenStore() != null && secToken == null && STATE.VALID.equals(validateTarget.getState())) {
            secToken = new SecurityToken(ut.getID());
            secToken.setToken(ut.getElement());
            int hashCode = tokenId.hashCode();
            String identifier = Integer.toString(hashCode);
            secToken.setTokenHash(hashCode);
            tokenParameters.getTokenStore().add(identifier, secToken);
        }
        response.setPrincipal(principal);
        response.setTokenRealm(null);
        validateTarget.setPrincipal(principal);
    } catch (WSSecurityException ex) {
        LOGGER.debug("Unable to validate token.", ex);
    }
    if (response.getToken().getState() != STATE.VALID) {
        failedLoginDelayer.delay(response.getToken().getPrincipal().getName());
    }
    return response;
}
Also used : CallbackHandler(javax.security.auth.callback.CallbackHandler) JAXBElement(javax.xml.bind.JAXBElement) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) UsernameToken(org.apache.wss4j.dom.message.token.UsernameToken) AttributedString(org.apache.cxf.ws.security.sts.provider.model.secext.AttributedString) PasswordString(org.apache.cxf.ws.security.sts.provider.model.secext.PasswordString) Document(org.w3c.dom.Document) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) BinarySecurityTokenType(org.apache.cxf.ws.security.sts.provider.model.secext.BinarySecurityTokenType) WSSConfig(org.apache.wss4j.dom.engine.WSSConfig) RequestData(org.apache.wss4j.dom.handler.RequestData) UPAuthenticationToken(org.codice.ddf.security.handler.api.UPAuthenticationToken) ReceivedToken(org.apache.cxf.sts.request.ReceivedToken) ParserException(org.codice.ddf.parser.ParserException) Credential(org.apache.wss4j.dom.validate.Credential) UsernameTokenType(org.apache.cxf.ws.security.sts.provider.model.secext.UsernameTokenType) BSPEnforcer(org.apache.wss4j.common.bsp.BSPEnforcer) WSSecurityException(org.apache.wss4j.common.ext.WSSecurityException) JAXBElement(javax.xml.bind.JAXBElement) SecurityToken(org.apache.cxf.ws.security.tokenstore.SecurityToken) ParserConfigurator(org.codice.ddf.parser.ParserConfigurator) Crypto(org.apache.wss4j.common.crypto.Crypto) STSPropertiesMBean(org.apache.cxf.sts.STSPropertiesMBean) TokenValidatorResponse(org.apache.cxf.sts.token.validator.TokenValidatorResponse) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Validator(org.apache.wss4j.dom.validate.Validator) JAASUsernameTokenValidator(org.apache.wss4j.dom.validate.JAASUsernameTokenValidator) TokenValidator(org.apache.cxf.sts.token.validator.TokenValidator) CustomTokenPrincipal(org.apache.wss4j.common.principal.CustomTokenPrincipal) Principal(java.security.Principal)

Example 5 with ParserException

use of org.codice.ddf.parser.ParserException in project ddf by codice.

the class RegistryTransformer method transform.

@Override
public Metacard transform(InputStream inputStream, String id) throws IOException, CatalogTransformerException {
    MetacardImpl metacard;
    try (TemporaryFileBackedOutputStream fileBackedOutputStream = new TemporaryFileBackedOutputStream()) {
        try {
            IOUtils.copy(inputStream, fileBackedOutputStream);
        } catch (IOException e) {
            throw new CatalogTransformerException("Unable to transform from CSW RIM Service Record to Metacard. Error reading input stream.", e);
        } finally {
            IOUtils.closeQuietly(inputStream);
        }
        try (InputStream inputStreamCopy = fileBackedOutputStream.asByteSource().openStream()) {
            metacard = (MetacardImpl) unmarshal(inputStreamCopy);
        } catch (ParserException e) {
            throw new CatalogTransformerException("Unable to transform from CSW RIM Service Record to Metacard. Parser exception caught", e);
        } catch (RegistryConversionException e) {
            throw new CatalogTransformerException("Unable to transform from CSW RIM Service Record to Metacard. Conversion exception caught", e);
        }
        if (metacard == null) {
            throw new CatalogTransformerException("Unable to transform from CSW RIM Service Record to Metacard.");
        } else if (StringUtils.isNotEmpty(id)) {
            metacard.setAttribute(Metacard.ID, id);
        }
        String xml;
        try (Reader reader = fileBackedOutputStream.asByteSource().asCharSource(Charsets.UTF_8).openStream()) {
            xml = CharStreams.toString(reader);
        }
        metacard.setAttribute(Metacard.METADATA, xml);
        metacard.setTags(Collections.singleton(RegistryConstants.REGISTRY_TAG));
    } catch (IOException e) {
        throw new CatalogTransformerException("Unable to transform from CSW RIM Service Record to Metacard. Error using file-backed stream.", e);
    }
    return metacard;
}
Also used : ParserException(org.codice.ddf.parser.ParserException) RegistryConversionException(org.codice.ddf.registry.converter.RegistryConversionException) TemporaryFileBackedOutputStream(org.codice.ddf.platform.util.TemporaryFileBackedOutputStream) InputStream(java.io.InputStream) Reader(java.io.Reader) CatalogTransformerException(ddf.catalog.transform.CatalogTransformerException) IOException(java.io.IOException) MetacardImpl(ddf.catalog.data.impl.MetacardImpl)

Aggregations

ParserException (org.codice.ddf.parser.ParserException)17 ArrayList (java.util.ArrayList)7 ParserConfigurator (org.codice.ddf.parser.ParserConfigurator)7 IOException (java.io.IOException)5 Map (java.util.Map)5 ByteArrayOutputStream (java.io.ByteArrayOutputStream)4 JAXBElement (javax.xml.bind.JAXBElement)4 RegistryPackageType (oasis.names.tc.ebxml_regrep.xsd.rim._3.RegistryPackageType)4 InputStream (java.io.InputStream)3 UsernameTokenType (org.apache.cxf.ws.security.sts.provider.model.secext.UsernameTokenType)3 Metacard (ddf.catalog.data.Metacard)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)2 Principal (java.security.Principal)2 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)2 CallbackHandler (javax.security.auth.callback.CallbackHandler)2 JAXBContext (javax.xml.bind.JAXBContext)2 ExternalIdentifierType (oasis.names.tc.ebxml_regrep.xsd.rim._3.ExternalIdentifierType)2 STSPropertiesMBean (org.apache.cxf.sts.STSPropertiesMBean)2 ReceivedToken (org.apache.cxf.sts.request.ReceivedToken)2 TokenValidator (org.apache.cxf.sts.token.validator.TokenValidator)2