Skip to content

Commit

Permalink
Move various util classes to prism-api
Browse files Browse the repository at this point in the history
E.g. JavaTypeConverter, XmlTypeConverter, XsdTypeMapper, PrismUtil.
These need to be cleaned up!

Also moved CloneUtil.
  • Loading branch information
mederly committed Dec 4, 2018
1 parent 29df3d6 commit 808ff84
Show file tree
Hide file tree
Showing 13 changed files with 336 additions and 322 deletions.
Expand Up @@ -41,6 +41,7 @@
* many scripting languages (e.g. perl) where the programmer does not really care about the type
* and the type conversion is done automatically.
*
* TODO clean this up as it is now part of prism-api!
* @author Radovan Semancik
*/
public class JavaTypeConverter {
Expand Down
@@ -0,0 +1,225 @@
/*
* Copyright (c) 2010-2018 Evolveum
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.evolveum.midpoint.prism.util;

import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.prism.delta.ItemDelta;
import com.evolveum.midpoint.prism.match.MatchingRule;
import com.evolveum.midpoint.prism.polystring.PolyString;
import com.evolveum.midpoint.prism.xml.XsdTypeMapper;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.prism.xml.ns._public.types_3.PolyStringType;
import org.apache.commons.lang.StringUtils;

import javax.xml.namespace.QName;
import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Collectors;

/**
* TODO clean this up as it is part of prism-api!
*
* @author semancik
*/
public class PrismUtil {

public static <T> void recomputeRealValue(T realValue, PrismContext prismContext) {
if (realValue == null) {
return;
}
// TODO: switch to Recomputable interface instead of PolyString
if (realValue instanceof PolyString && prismContext != null) {
PolyString polyStringVal = (PolyString)realValue;
// Always recompute. Recompute is cheap operation and this avoids a lot of bugs
polyStringVal.recompute(prismContext.getDefaultPolyStringNormalizer());
}
}

public static <T> void recomputePrismPropertyValue(PrismPropertyValue<T> pValue, PrismContext prismContext) {
if (pValue == null) {
return;
}
recomputeRealValue(pValue.getValue(), prismContext);
}

// /**
// * Super-mega-giga-ultra hack. This is used to "fortify" XML namespace declaration in a non-standard way.
// * It is useful in case that someone will try some stupid kind of schema-less XML normalization that removes
// * "unused" XML namespace declaration. The declarations are usually used, but they are used inside QName values
// * that the dumb normalization cannot see. Therefore this fortification places XML namespace declaration in
// * a explicit XML elements. That can be reconstructed later by using unfortification method below.
// */
// public static void fortifyNamespaceDeclarations(Element definitionElement) {
// for(Element childElement: DOMUtil.listChildElements(definitionElement)) {
// fortifyNamespaceDeclarations(definitionElement, childElement);
// }
// }
//
// private static void fortifyNamespaceDeclarations(Element definitionElement, Element childElement) {
// Document doc = definitionElement.getOwnerDocument();
// NamedNodeMap attributes = childElement.getAttributes();
// for(int i=0; i<attributes.getLength(); i++) {
// Attr attr = (Attr)attributes.item(i);
// if (DOMUtil.isNamespaceDefinition(attr)) {
// String prefix = DOMUtil.getNamespaceDeclarationPrefix(attr);
// String namespace = DOMUtil.getNamespaceDeclarationNamespace(attr);
// Element namespaceElement = doc.createElementNS(PrismConstants.A_NAMESPACE.getNamespaceURI(), PrismConstants.A_NAMESPACE.getLocalPart());
// namespaceElement.setAttribute(PrismConstants.A_NAMESPACE_PREFIX, prefix);
// namespaceElement.setAttribute(PrismConstants.A_NAMESPACE_URL, namespace);
// definitionElement.insertBefore(namespaceElement, childElement);
// }
// }
// }
//
// public static void unfortifyNamespaceDeclarations(Element definitionElement) {
// Map<String,String> namespaces = new HashMap<>();
// for(Element childElement: DOMUtil.listChildElements(definitionElement)) {
// if (PrismConstants.A_NAMESPACE.equals(DOMUtil.getQName(childElement))) {
// String prefix = childElement.getAttribute(PrismConstants.A_NAMESPACE_PREFIX);
// String namespace = childElement.getAttribute(PrismConstants.A_NAMESPACE_URL);
// namespaces.put(prefix, namespace);
// definitionElement.removeChild(childElement);
// } else {
// unfortifyNamespaceDeclarations(definitionElement, childElement, namespaces);
// namespaces = new HashMap<>();
// }
// }
// }
//
// private static void unfortifyNamespaceDeclarations(Element definitionElement, Element childElement,
// Map<String, String> namespaces) {
// for (Entry<String, String> entry: namespaces.entrySet()) {
// String prefix = entry.getKey();
// String namespace = entry.getValue();
// String declaredNamespace = DOMUtil.getNamespaceDeclarationForPrefix(childElement, prefix);
// if (declaredNamespace == null) {
// DOMUtil.setNamespaceDeclaration(childElement, prefix, namespace);
// } else if (!namespace.equals(declaredNamespace)) {
// throw new IllegalStateException("Namespace declaration with prefix '"+prefix+"' that was used to declare "+
// "namespace '"+namespace+"' is now used for namespace '"+declaredNamespace+"', cannot unfortify.");
// }
// }
// }

public static boolean isEmpty(PolyStringType value) {
return value == null || StringUtils.isEmpty(value.getOrig()) && StringUtils.isEmpty(value.getNorm());
}

// public static PrismUnmarshaller getXnodeProcessor(@NotNull PrismContext prismContext) {
// return ((PrismContextImpl) prismContext).getPrismUnmarshaller();
// }

public static <T,X> PrismPropertyValue<X> convertPropertyValue(PrismPropertyValue<T> srcVal,
PrismPropertyDefinition<T> srcDef, PrismPropertyDefinition<X> targetDef,
PrismContext prismContext) {
if (targetDef.getTypeName().equals(srcDef.getTypeName())) {
return (PrismPropertyValue<X>) srcVal;
} else {
Class<X> expectedJavaType = XsdTypeMapper.toJavaType(targetDef.getTypeName());
X convertedRealValue = JavaTypeConverter.convert(expectedJavaType, srcVal.getValue());
return prismContext.itemFactory().createPrismPropertyValue(convertedRealValue);
}
}

public static <T,X> PrismProperty<X> convertProperty(PrismProperty<T> srcProp, PrismPropertyDefinition<X> targetDef,
PrismContext prismContext) throws SchemaException {
if (targetDef.getTypeName().equals(srcProp.getDefinition().getTypeName())) {
return (PrismProperty<X>) srcProp;
} else {
PrismProperty<X> targetProp = targetDef.instantiate();
Class<X> expectedJavaType = XsdTypeMapper.toJavaType(targetDef.getTypeName());
for (PrismPropertyValue<T> srcPVal: srcProp.getValues()) {
X convertedRealValue = JavaTypeConverter.convert(expectedJavaType, srcPVal.getValue());
targetProp.add(prismContext.itemFactory().createPrismPropertyValue(convertedRealValue));
}
return targetProp;
}
}

public static <O extends Objectable> void setDeltaOldValue(PrismObject<O> oldObject, ItemDelta<?,?> itemDelta) {
if (oldObject == null) {
return;
}
Item<PrismValue, ItemDefinition> itemOld = oldObject.findItem(itemDelta.getPath());
if (itemOld != null) {
itemDelta.setEstimatedOldValues((Collection) PrismValueCollectionsUtil.cloneCollection(itemOld.getValues()));
}
}

public static <O extends Objectable> void setDeltaOldValue(PrismObject<O> oldObject, Collection<? extends ItemDelta> itemDeltas) {
for(ItemDelta itemDelta: itemDeltas) {
setDeltaOldValue(oldObject, itemDelta);
}
}

public static <T> boolean equals(T a, T b, MatchingRule<T> matchingRule) throws SchemaException {
if (a == null && b == null) {
return true;
}
if (a == null || b == null) {
return false;
}
if (matchingRule == null) {
if (a instanceof byte[]) {
if (b instanceof byte[]) {
return Arrays.equals((byte[])a, (byte[])b);
} else {
return false;
}
} else {
return a.equals(b);
}
} else {
return matchingRule.match(a, b);
}
}

// for diagnostic purposes
public static String serializeQuietly(PrismContext prismContext, Object object) {
if (object == null) {
return null;
}
if (object instanceof Collection) {
return ((Collection<?>) object).stream()
.map(o -> serializeQuietly(prismContext, o))
.collect(Collectors.joining("; "));
}
try {
PrismSerializer<String> serializer = prismContext.xmlSerializer();
if (object instanceof Item) {
return serializer.serialize((Item) object);
} else {
return serializer.serializeRealValue(object, new QName("value"));
}
} catch (Throwable t) {
return "Couldn't serialize (" + t.getMessage() + "): " + object;
}
}

// for diagnostic purposes
public static Object serializeQuietlyLazily(PrismContext prismContext, Object object) {
if (object == null) {
return null;
}
return new Object() {
@Override
public String toString() {
return serializeQuietly(prismContext, object);
}
};
}

}
Expand Up @@ -36,6 +36,8 @@
* need much more now. If more complex thing will be needed, we will extend the
* implementation later.
*
* TODO clean this up as it is now part of prism-api!
*
* @author Radovan Semancik
*/
public class XmlTypeConverter {
Expand All @@ -55,14 +57,17 @@ private static DatatypeFactory getDatatypeFactory() {
return datatypeFactory;
}

@Deprecated // do NOT use form the outside of prism
public static boolean canConvert(Class<?> clazz) {
return (XsdTypeMapper.getJavaToXsdMapping(clazz) != null);
}

@Deprecated // do NOT use form the outside of prism
public static boolean canConvert(QName xsdType) {
return (XsdTypeMapper.getXsdToJavaMapping(xsdType) != null);
}

// TODO consider moving this to better place
public static boolean isMatchingType(Class<?> expectedClass, Class<?> actualClass) {
if (expectedClass.isAssignableFrom(actualClass)) {
return true;
Expand Down
Expand Up @@ -19,7 +19,7 @@
import com.evolveum.midpoint.prism.path.ItemName;
import com.evolveum.midpoint.prism.polystring.PolyString;
import com.evolveum.midpoint.prism.schema.SchemaRegistry;
import com.evolveum.midpoint.prism.util.PrismUtil;
import com.evolveum.midpoint.prism.util.PrismUtilInternal;
import com.evolveum.midpoint.prism.xml.XmlTypeConverter;
import com.evolveum.midpoint.prism.xnode.*;
import com.evolveum.midpoint.util.DOMUtil;
Expand Down Expand Up @@ -492,7 +492,7 @@ private <T> PrimitiveXNodeImpl<T> createPrimitiveXNode(T val, QName type) {

@NotNull
private XNodeImpl createExpressionXNode(@NotNull ExpressionWrapper expression) throws SchemaException {
return PrismUtil.serializeExpression(expression, beanMarshaller);
return PrismUtilInternal.serializeExpression(expression, beanMarshaller);
}

@NotNull
Expand Down
Expand Up @@ -19,6 +19,7 @@
import com.evolveum.midpoint.prism.schema.PrismSchema;
import com.evolveum.midpoint.prism.schema.SchemaRegistry;
import com.evolveum.midpoint.prism.util.PrismUtil;
import com.evolveum.midpoint.prism.util.PrismUtilInternal;
import com.evolveum.midpoint.prism.xnode.*;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.QNameUtil;
Expand Down Expand Up @@ -375,7 +376,7 @@ private <T> PrismPropertyValue<T> parsePropertyValue(@NotNull XNodeImpl node,
if (realValue == null) {
// Be careful here. Expression element can be legal sub-element of complex properties.
// Therefore parse expression only if there is no legal value.
ExpressionWrapper expression = PrismUtil.parseExpression(node, prismContext);
ExpressionWrapper expression = PrismUtilInternal.parseExpression(node, prismContext);
if (expression != null) {
PrismPropertyValue<T> ppv = new PrismPropertyValueImpl<>(null, prismContext, null, null, expression);
return ppv;
Expand Down
Expand Up @@ -24,6 +24,7 @@
import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.query.*;
import com.evolveum.midpoint.prism.util.PrismUtilInternal;
import com.evolveum.midpoint.prism.xnode.*;
import com.evolveum.prism.xml.ns._public.query_3.PagingType;
import com.evolveum.prism.xml.ns._public.query_3.QueryType;
Expand All @@ -34,7 +35,6 @@
import org.apache.commons.lang.StringUtils;

import com.evolveum.midpoint.prism.query.OrgFilter.Scope;
import com.evolveum.midpoint.prism.util.PrismUtil;
import com.evolveum.midpoint.util.DOMUtil;
import com.evolveum.midpoint.util.QNameUtil;
import com.evolveum.midpoint.util.exception.SchemaException;
Expand Down Expand Up @@ -527,7 +527,7 @@ private <C extends Containerable> RefFilter parseRefFilter(MapXNodeImpl clauseXM
private ExpressionWrapper parseExpression(MapXNodeImpl xmap) throws SchemaException {
Entry<QName, XNodeImpl> expressionEntry = xmap.getSingleEntryThatDoesNotMatch(
ELEMENT_VALUE, ELEMENT_MATCHING, ELEMENT_ANCHOR_START, ELEMENT_ANCHOR_END, ELEMENT_PATH);
return PrismUtil.parseExpression(expressionEntry, prismContext);
return PrismUtilInternal.parseExpression(expressionEntry, prismContext);
}

private <C extends Containerable> SubstringFilter parseSubstringFilter(MapXNodeImpl clauseXMap, PrismContainerDefinition<C> pcd,
Expand Down Expand Up @@ -889,7 +889,7 @@ private <V extends PrismValue, D extends ItemDefinition> MapXNodeImpl serializeV

ExpressionWrapper xexpression = filter.getExpression();
if (xexpression != null) {
map.merge(PrismUtil.serializeExpression(xexpression, xnodeSerializer));
map.merge(PrismUtilInternal.serializeExpression(xexpression, xnodeSerializer));
}

return map;
Expand Down
Expand Up @@ -18,7 +18,6 @@

import com.evolveum.midpoint.prism.lex.dom.DomLexicalProcessor;
import com.evolveum.midpoint.prism.marshaller.XNodeProcessorUtil;
import com.evolveum.midpoint.prism.util.PrismUtil;
import com.evolveum.midpoint.prism.xnode.*;
import com.evolveum.midpoint.util.exception.SchemaException;
import com.evolveum.midpoint.util.logging.Trace;
Expand Down Expand Up @@ -95,10 +94,14 @@ public <T> void parseProtectedType(ProtectedDataType<T> protectedType, MapXNode

@Override
public Element serializeSingleElementMapToElement(MapXNode filterClauseXNode) throws SchemaException {
DomLexicalProcessor domParser = PrismUtil.getDomParser(prismContext);
DomLexicalProcessor domParser = getDomParser(prismContext);
return domParser.serializeSingleElementMapToElement(filterClauseXNode);
}

private static DomLexicalProcessor getDomParser(@NotNull PrismContext prismContext) {
return ((PrismContextImpl) prismContext).getParserDom();
}

@Override
public void setXNodeType(XNode node, QName explicitTypeName, boolean explicitTypeDeclaration) {
((XNodeImpl) node).setTypeQName(explicitTypeName);
Expand Down
Expand Up @@ -24,6 +24,7 @@
import com.evolveum.midpoint.prism.util.CloneUtil;
import com.evolveum.midpoint.prism.util.PrismPrettyPrinter;
import com.evolveum.midpoint.prism.util.PrismUtil;
import com.evolveum.midpoint.prism.util.PrismUtilInternal;
import com.evolveum.midpoint.prism.xnode.XNode;
import com.evolveum.midpoint.prism.xnode.XNodeImpl;
import com.evolveum.midpoint.util.DOMUtil;
Expand All @@ -38,19 +39,14 @@
import com.evolveum.prism.xml.ns._public.types_3.RawType;
import com.evolveum.prism.xml.ns._public.types_3.SchemaDefinitionType;
import org.apache.commons.lang.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jvnet.jaxb2_commons.lang.Equals;
import org.w3c.dom.Element;

import javax.xml.bind.JAXBElement;
import javax.xml.namespace.QName;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.stream.Collectors;

/**
* @author lazyman
Expand Down Expand Up @@ -181,7 +177,7 @@ public void applyDefinition(ItemDefinition definition) throws SchemaException {
if (value == null) {
// Be careful here. Expression element can be legal sub-element of complex properties.
// Therefore parse expression only if there is no legal value.
expression = PrismUtil.parseExpression(rawElement, prismContext);
expression = PrismUtilInternal.parseExpression(rawElement, prismContext);
}
rawElement = null;
}
Expand Down

0 comments on commit 808ff84

Please sign in to comment.