org.alfresco.service.namespace.NamespaceException Java Examples

The following examples show how to use org.alfresco.service.namespace.NamespaceException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: XMLTransferManifestReader.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * @param namespaceURI
 * @return the prefix
 */
public Collection<String> getPrefixes(String namespaceURI) throws NamespaceException
{
    Collection<String> prefixes = new HashSet<String>();

    for(HashMap<String, String> namespace : namespaces)
    {
        for(Entry<String, String> entry : namespace.entrySet())
        {
            if (namespaceURI.equals(entry.getValue()))
            {
                prefixes.add(entry.getKey());
            }
        }
    }

    return prefixes;
}
 
Example #2
Source File: JSONConversionComponent.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * 
 * @param nodeRef NodeRef
 * @param useShortQNames boolean
 * @return JSONObject
 */
@SuppressWarnings("unchecked")
protected JSONObject propertiesToJSON(NodeRef nodeRef, Map<QName, Serializable> properties, boolean useShortQNames)
{
    JSONObject propertiesJSON = new JSONObject();
    
    for (QName propertyName : properties.keySet())
    {
        try
        {
            String key = nameToString(propertyName, useShortQNames);
            Serializable value = properties.get(propertyName);
            
            propertiesJSON.put(key, propertyToJSON(nodeRef, propertyName, key, value));
        }
        catch (NamespaceException ne)
        {
            // ignore properties that do not have a registered namespace
            if (logger.isDebugEnabled())
                logger.debug("Ignoring property '" + propertyName + "' as its namespace is not registered");
        }
    }
    
    return propertiesJSON;
}
 
Example #3
Source File: WorkflowQNameConverter.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static QName convertNameToQName(String name, NamespacePrefixResolver prefixResolver)
{
    if (name.indexOf(QName.NAMESPACE_BEGIN)==0)
    {
        return QName.createQName(name);
    }
    String qName = name;
    if (name.indexOf(QName.NAMESPACE_PREFIX)==-1)
    {
        if (name.indexOf('_')==-1)
        {
            return QName.createQName(NamespaceService.DEFAULT_URI, name);
        }
        qName = name.replaceFirst("_", ":");
    }
    try
    {
        return QName.createQName(qName, prefixResolver);
    }
    catch (NamespaceException ne)
    {
        return QName.createQName(NamespaceService.DEFAULT_URI, name);
    }
}
 
Example #4
Source File: AbstractRenderingEngine.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Sets the default rendition content property.
 * 
 * @param prop String
 */
public void setDefaultRenditionContentProp(String prop)
{
    QName qname;
    try
    {
        qname = QName.createQName(prop);
    }
    catch (NamespaceException nx)
    {
        if (logger.isErrorEnabled())
        {
            logger.error("Error when setting default rendition content property: ", nx);
        }
        throw nx;
    }

    if (logger.isInfoEnabled())
    {
        logger.info("Using default rendition content property: " + qname);
    }
    this.defaultRenditionContentProp = qname;
}
 
Example #5
Source File: AbstractRenderingEngine.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * Sets the default rendition-node type.
 * 
 * @param type String
 */
public void setDefaultRenditionNodeType(String type)
{
    QName qname;
    try
    {
        qname = QName.createQName(type);
    }
    catch (NamespaceException nx)
    {
        if (logger.isErrorEnabled())
        {
            logger.error("Error when setting default rendition node type: ", nx);
        }
        throw nx;
    }

    if (logger.isInfoEnabled())
    {
        logger.info("Using default rendition node type: " + qname);
    }
    this.defaultRenditionNodeType = qname;
}
 
Example #6
Source File: NodeInfoFactory.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
private String getName(QName qName)
{
    String name = null;
    
    try
    {
        name = qName.toPrefixString(namespaceService);
    }
    catch (NamespaceException e)
    {
        name = qName.toPrefixString();
    }
    name = ISO9075.decode(name);
    
    return name;
}
 
Example #7
Source File: AbstractDictionaryRegistry.java    From alfresco-data-model with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected void addPrefixImpl(String prefix, String uri)
{
	urisCacheRWLock.readLock().lock();
	try
	{
  if(!urisCache.contains(uri))
  {
      throw new NamespaceException("Namespace URI " + uri + " does not exist");
  }
  if (prefixesCache.containsKey(prefix))
     {
         throw new NamespaceException(
                 String.format("Namespace prefix '%s' is already in use for URI '%s' so cannot be registered for URI '%s'",
                         prefix,
                         prefixesCache.get(prefix),
                         uri));
     }
  prefixesCache.put(prefix,  uri);
    }
    finally
    {
    	urisCacheRWLock.readLock().unlock();
    }
}
 
Example #8
Source File: ISO9075.java    From alfresco-data-model with GNU Lesser General Public License v3.0 6 votes vote down vote up
public static String getXPathName(QName qName, NamespacePrefixResolver nspr)
{

    Collection<String> prefixes = nspr.getPrefixes(qName.getNamespaceURI());
    if (prefixes.size() == 0)
    {
        throw new NamespaceException("A namespace prefix is not registered for uri " + qName.getNamespaceURI());
    }
    String prefix = prefixes.iterator().next();
    if (prefix.equals(NamespaceService.DEFAULT_PREFIX))
    {
        return ISO9075.encode(qName.getLocalName());
    }
    else
    {
        return prefix + ":" + ISO9075.encode(qName.getLocalName());
    }

}
 
Example #9
Source File: DiffModelTest.java    From alfresco-data-model with GNU Lesser General Public License v3.0 6 votes vote down vote up
public void testDuplicateModels()
{
    ByteArrayInputStream byteArrayInputStream1 = new ByteArrayInputStream(AbstractModelTest.MODEL1_XML.getBytes());
    ByteArrayInputStream byteArrayInputStream2 = new ByteArrayInputStream(MODEL1_DUPLICATED_XML.getBytes());

    M2Model model1 = M2Model.createModel(byteArrayInputStream1);
    dictionaryDAO.putModel(model1);

    M2Model model2 = M2Model.createModel(byteArrayInputStream2);

    try
    {
        dictionaryDAO.putModel(model2);
        fail("This model with this URI has already been defined");
    }
    catch (NamespaceException exception)
    {
        // Ignore since we where expecting this
    }
}
 
Example #10
Source File: AbstractDictionaryRegistry.java    From alfresco-data-model with GNU Lesser General Public License v3.0 6 votes vote down vote up
protected void addURIImpl(String uri)
{
    if(hasURI(uri))
    {
        throw new NamespaceException("URI " + uri + " has already been defined");
    }

    urisCacheRWLock.writeLock().lock();
    try
    {
    	urisCache.add(uri);
    }
    finally
    {
    	urisCacheRWLock.writeLock().unlock();
    }
}
 
Example #11
Source File: XMLTransferRequsiteReader.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * @param namespaceURI
 * @return the prefix
 */
public Collection<String> getPrefixes(String namespaceURI) throws NamespaceException
{
    Collection<String> prefixes = new HashSet<String>();
    
    for(HashMap<String, String> namespace : namespaces)
    {
        for(Entry<String, String> entry : namespace.entrySet())
        {
            if (namespaceURI.equals(entry.getValue()))
            {
                prefixes.add(entry.getKey());
            }           
        }
    }
 
    return prefixes;
}
 
Example #12
Source File: AlfrescoSolrDataModel.java    From SearchServices with GNU Lesser General Public License v3.0 6 votes vote down vote up
private Set<String> validateModel(M2Model model)
{
    try
    {
        dictionaryDAO.getCompiledModel(QName.createQName(model.getName(), namespaceDAO));
    }
    catch (DictionaryException | NamespaceException exception)
    {
        // No model to diff
        return Collections.emptySet();
    }

    // namespace unknown - no model
    List<M2ModelDiff> modelDiffs = dictionaryDAO.diffModelIgnoringConstraints(model);
    return modelDiffs.stream()
            .filter(diff -> diff.getDiffType().equals(M2ModelDiff.DIFF_UPDATED))
            .map(diff ->
                    String.format("Model not updated: %s Failed to validate model update - found non-incrementally updated %s '%s'",
                            model.getName(),
                            diff.getElementType(),
                            diff.getElementName()))
            .collect(Collectors.toSet());
}
 
Example #13
Source File: QNameFieldProcessor.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
protected Field generateTypedField(String fieldName, FormCreationData formData, ContentModelItemData<?> typedData)
{
    Field field = null;
    try
    {
        QName fullName = getFullName(fieldName);
        boolean isForcedField = formData.isForcedField(fieldName);
        field = generateField(fullName, typedData, isForcedField);
    }
    catch (NamespaceException ne)
    {
        // ignore fields with an invalid namespace - the model may no longer be present in the repository
    }
    return field;
}
 
Example #14
Source File: RegistryServiceImpl.java    From alfresco-repository with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
public void addProperty(RegistryKey key, Serializable value)
{
    if (key.getProperty() == null)
    {
        throw new IllegalArgumentException("Registry values must be added using paths that contain property names: " + key);
    }
    // Check the namespace being used in the key
    String namespaceUri = key.getNamespaceUri();
    if (!namespaceService.getURIs().contains(namespaceUri))
    {
        throw new NamespaceException("Unable to add a registry value with an unregistered namespace: " + namespaceUri);
    }
    
    // Get the path, with creation support
    Pair<NodeRef, QName> keyPair = getPath(key, true);
    // We know that the node exists, so just set the value
    nodeService.setProperty(keyPair.getFirst(), keyPair.getSecond(), value);
    // Done
    if (logger.isDebugEnabled())
    {
        logger.debug("Added value to registry: \n" +
                "   Key:   " + key + "\n" +
                "   Value: " + value);
    }
}
 
Example #15
Source File: TenantDictionaryRegistryImpl.java    From alfresco-data-model with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void addURI(String uri)
{
	if(getParent().hasURI(uri))
	{
		throw new NamespaceException("URI " + uri + " has already been defined");
	}
	addURIImpl(uri);
}
 
Example #16
Source File: CompiledModel.java    From alfresco-data-model with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Create a local namespace prefix resolver containing the namespaces defined and imported
 * in the model
 * 
 * @param model model definition
 * @param namespaceDAO  namespace DAO
 * @return the local namespace prefix resolver
 */
private NamespacePrefixResolver createLocalPrefixResolver(M2Model model, NamespaceDAO namespaceDAO)
{
    // Retrieve set of existing URIs for validation purposes
    Collection<String> uris = namespaceDAO.getURIs();
    
    // Create a namespace prefix resolver based on imported and defined
    // namespaces within the model
    DynamicNamespacePrefixResolver prefixResolver = new DynamicNamespacePrefixResolver(null);
    for (M2Namespace imported : model.getImports())
    {
        String uri = imported.getUri();
        if (!uris.contains(uri))
        {
            throw new NamespaceException("URI " + uri + " cannot be imported as it is not defined (with prefix " + imported.getPrefix());
        }
        if(model.getNamespace(uri) != null)
        {
            throw new NamespaceException("URI " + uri + " cannot be imported as it is already contained in the model's namespaces");
        }
        prefixResolver.registerNamespace(imported.getPrefix(), uri);
    }
    for (M2Namespace defined : model.getNamespaces())
    {
        prefixResolver.registerNamespace(defined.getPrefix(), defined.getUri());
    }
    return prefixResolver;
}
 
Example #17
Source File: TenantDictionaryRegistryImpl.java    From alfresco-data-model with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override
public void addPrefix(String prefix, String uri)
{
	if(getParent().hasPrefix(prefix))
	{
		throw new NamespaceException("Prefix " + prefix + " has already been defined");
	}
	addPrefixImpl(prefix, uri);
}
 
Example #18
Source File: ShortQNameMethod.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @see freemarker.template.TemplateMethodModel#exec(java.util.List)
 */
public Object exec(List args) throws TemplateModelException
{
    String result = null;
    
    if (args.size() == 1)
    {
        // arg 0 can be either wrapped QName object or a String 
        String arg0String = null;
        Object arg0 = args.get(0);
        if (arg0 instanceof BeanModel)
        {
            arg0String = ((BeanModel)arg0).getWrappedObject().toString();
        }
        else if (arg0 instanceof TemplateScalarModel)
        {
            arg0String = ((TemplateScalarModel)arg0).getAsString();
        }

        try
        {
        result = createQName(arg0String).toPrefixString(services.getNamespaceService());
    }
        catch (NamespaceException e) 
        {
            // not valid qname -> return original value
            result = arg0String;
        }
    }
    
    return result != null ? result : "";
}
 
Example #19
Source File: QueryParserUtils.java    From alfresco-data-model with GNU Lesser General Public License v3.0 5 votes vote down vote up
public static String matchURI(NamespacePrefixResolver namespacePrefixResolver, String prefix)
{
    HashSet<String> prefixes = new HashSet<String>(namespacePrefixResolver.getPrefixes());
    if (prefixes.contains(prefix))
    {
        return namespacePrefixResolver.getNamespaceURI(prefix);
    }
    String match = null;
    for (String candidate : prefixes)
    {
        if (candidate.equalsIgnoreCase(prefix))
        {
            if (match == null)
            {
                match = candidate;
            }
            else
            {

                throw new NamespaceException("Ambiguous namespace prefix " + prefix);

            }
        }
    }
    if (match == null)
    {
        return null;
    }
    else
    {
        return namespacePrefixResolver.getNamespaceURI(match);
    }
}
 
Example #20
Source File: DictionaryDAOTest.java    From alfresco-data-model with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * ACE-5120: Dictionary should not allow duplication of namespace prefixes
 */
@Test
public void testNamespaceClashResultsInSensibleError()
{
    TenantService tenantService = new SingleTServiceImpl();

    DictionaryDAOImpl dictionaryDAO = new DictionaryDAOImpl();
    dictionaryDAO.setTenantService(tenantService);
    initDictionaryCaches(dictionaryDAO, tenantService);
    
    DictionaryBootstrap bootstrap = new DictionaryBootstrap();
    List<String> bootstrapModels = new ArrayList<String>();
    
    bootstrapModels.add("alfresco/model/dictionaryModel.xml");
    bootstrapModels.add(TEST_MODEL);
    bootstrapModels.add(TEST_NS_CLASH_MODEL);

    bootstrap.setModels(bootstrapModels);
    bootstrap.setDictionaryDAO(dictionaryDAO);
    bootstrap.setTenantService(tenantService);

    try
    {
        bootstrap.bootstrap();
        fail("Expected "+NamespaceException.class.getName()+" to be thrown, but it was not.");
    }
    catch (NamespaceException e)
    {
        System.out.println(e.getMessage());
        // Good!
    }
}
 
Example #21
Source File: NodeBrowserPost.java    From alfresco-remote-api with GNU Lesser General Public License v3.0 5 votes vote down vote up
public String getPrefixedName()
{
    try
    {
        return prefixString != null ? prefixString : (prefixString = name.toPrefixString(getNamespaceService()));
    }
    catch(NamespaceException e)
    {
        return name.getLocalName();
    }
}
 
Example #22
Source File: BeanPropertiesMapper.java    From alfresco-mvc with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize the mapping metadata for the given class.
 * 
 * @param mappedClass the mapped class.
 */
private void initialize(Class<T> mappedClass) {
	this.mappedClass = mappedClass;
	this.mappedFields = new HashMap<String, PropertyDescriptor>();
	this.mappedProperties = new HashSet<String>();
	this.mappedQNames = new HashMap<QName, PropertyDescriptor>();
	PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(mappedClass);
	for (PropertyDescriptor pd : pds) {
		if (pd.getWriteMethod() != null) {
			this.mappedFields.put(pd.getName().toLowerCase(), pd);
			String prefixName = prefixName(pd.getName());
			if (!pd.getName().toLowerCase().equals(prefixName)) {
				this.mappedFields.put(prefixName, pd);
			}
			this.mappedProperties.add(pd.getName());

			String prefixedString = prefixName.replaceFirst("_", ":");

			if (prefixedString.contains(":")) {
				try {
					QName qName = QName.createQName(prefixedString, namespaceService);
					if (dictionaryService.getProperty(qName) != null) {
						this.mappedQNames.put(qName, pd);
					}
				} catch (NamespaceException e) {
					LOGGER.warn("the property is not configured for this namespace", e);
					if (reportNamespaceException) {
						throw e;
					}
				}
			}
		}
	}

	afterInitialize();
}
 
Example #23
Source File: BeanPropertiesMapperTest.java    From alfresco-mvc with Apache License 2.0 5 votes vote down vote up
@Test
public void mapNodeProperties_withNonExistingProperty_reportException() {
	Assertions.assertThrows(NamespaceException.class, () -> {
		BeanPropertiesMapper<NonExistingNodeProperties> mapperWrong = new BeanPropertiesMapperBuilder<NonExistingNodeProperties>()
				.mappedClass(NonExistingNodeProperties.class).namespaceService(namespaceService)
				.dictionaryService(dictionaryService).reportNamespaceException(true).build();
		mapperWrong.mapNodeProperties(NODE_REF, ImmutableMap.of());
	});
}
 
Example #24
Source File: FacetQNameUtilsTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override public String getNamespaceURI(String prefix) throws NamespaceException
{
    if (prefixes.contains(prefix))
    { return "http://www.alfresco.org/model/foo/1.0"; }
    else
    { throw new NamespaceException("Unrecognised prefix: " + prefix); }
}
 
Example #25
Source File: FacetQNameUtilsTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Override public Collection<String> getPrefixes(String namespaceURI) throws NamespaceException
{
    if (uris.contains(namespaceURI))
    { return prefixes; }
    else
    { throw new NamespaceException("Unrecognised namespace: " + namespaceURI); }
}
 
Example #26
Source File: NodeResourceHelper.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Returns the QName in the format prefix:local, but in the exceptional case where there is no registered prefix
 * returns it in the form {uri}local.
 *
 * @param   k QName
 * @return  a String representing the QName in the format prefix:local or {uri}local.
 */
public String getQNamePrefixString(QName k)
{
    String key;
    try
    {
        key = k.toPrefixString(namespaceService);
    }
    catch (NamespaceException e)
    {
        key = k.toString();
    }
    return key;
}
 
Example #27
Source File: NodeChange.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * @return a new QName that has the prefix set or the original if it is unknown.
 */
private QName getPrefixedQName(QName qName)
{
    try
    {
        qName = qName.getPrefixedQName(namespaceService);
    }
    catch (NamespaceException e)
    {
        // ignore - go with what we have
    }
    return qName;
}
 
Example #28
Source File: XMLTransferManifestReader.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
* lookup the prefix for a URI e.g. TRANSFER_URI for xfer
*/
public String getNamespaceURI(String prefix) throws NamespaceException
{
    for(HashMap<String, String> namespace : namespaces)
    {
        String uri = namespace.get(prefix);
        if(uri != null)
        {
            return uri;
        }
    }
    return null;
}
 
Example #29
Source File: XMLTransferRequsiteReader.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
* lookup the prefix for a URI e.g. TRANSFER_URI for xfer
*/
public String getNamespaceURI(String prefix) throws NamespaceException
{ 
    for(HashMap<String, String> namespace : namespaces)
    {
        String uri = namespace.get(prefix);
        if(uri != null)
        {
            return uri;
        }
    }
    return null;
}
 
Example #30
Source File: FacetQNameUtilsTest.java    From alfresco-repository with GNU Lesser General Public License v3.0 4 votes vote down vote up
@Test (expected=NamespaceException.class)
public void shortFormQnameWithUnrecognisedPrefixFails() throws Exception
{
    FacetQNameUtils.createQName("illegal:localName", resolver);
}