release version 1.10.0

This commit is contained in:
2024-10-07 18:42:55 +03:00
parent 2034182607
commit a5088587f7
1501 changed files with 28818 additions and 59966 deletions

View File

@ -3,7 +3,7 @@
<parent>
<groupId>ru.entaxy.esb.platform.runtime</groupId>
<artifactId>base</artifactId>
<version>1.9.0</version>
<version>1.10.0</version>
</parent>
<groupId>ru.entaxy.esb.platform.runtime.base</groupId>
<artifactId>base-support</artifactId>
@ -17,11 +17,16 @@
ru.entaxy.platform.base.support.xml,
ru.entaxy.platform.base.support.osgi,
ru.entaxy.platform.base.support.osgi.bundle,
ru.entaxy.platform.base.support.osgi.feature,
ru.entaxy.platform.base.support.osgi.service,
ru.entaxy.platform.base.support.osgi.tracker,
ru.entaxy.platform.base.support.osgi.tracker.filter,
ru.entaxy.platform.base.support.osgi.filter
ru.entaxy.platform.base.support.osgi.filter,
ru.entaxy.platform.base.support.karaf.shell
</bundle.osgi.export.pkg>
<bundle.osgi.private.pkg>
org.apache.felix.gogo.runtime.threadio
</bundle.osgi.private.pkg>
</properties>
<dependencies>
@ -48,8 +53,29 @@
<artifactId>commons-codec</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<groupId>ru.entaxy.bundles-repacked</groupId>
<artifactId>ru.entaxy.bundles-repacked.com.google.code.gson-2.8.5.entaxy</artifactId>
<version>${gson.version}-ENTAXY</version>
</dependency>
<dependency>
<groupId>org.apache.karaf.shell</groupId>
<artifactId>org.apache.karaf.shell.core</artifactId>
<version>${karaf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.karaf.features</groupId>
<artifactId>org.apache.karaf.features.core</artifactId>
<version>${karaf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.karaf.bundle</groupId>
<artifactId>org.apache.karaf.bundle.core</artifactId>
<version>${karaf.version}</version>
</dependency>
<dependency>
<groupId>org.fusesource.jansi</groupId>
<artifactId>jansi</artifactId>
<version>1.18</version>
</dependency>
</dependencies>
</project>

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* base-support
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
@ -33,6 +33,7 @@ import java.util.Dictionary;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
@ -49,243 +50,256 @@ import org.apache.commons.lang3.StringUtils;
*
*/
public class CommonUtils {
public static final String GUID_0 = "00000000-0000-0000-0000-000000000000";
public static final String GUID_f = "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF";
public static final String NULL_GUID_ = GUID_0;
public static final String PACKET_TYPE_PARAM_NAME = "packetType";
public static class Path {
public static final String DEFAULT_SEPARATOR = "/";
protected String separator = DEFAULT_SEPARATOR;
protected List<String> data = new ArrayList<>();
public static Path create() {
return new Path();
}
public static boolean isAbsolute(String path) {
return isAbsolute(path, DEFAULT_SEPARATOR);
}
public static boolean isAbsolute(String path, String separator) {
if (!isValid(path))
return false;
return path.trim().startsWith(separator);
}
public Path() {
super();
}
public Path separator(String newSeparator) {
if (newSeparator!=null)
this.separator = newSeparator;
return this;
}
public Path construct(String...fragments) {
data.clear();
return append(fragments);
}
public Path append(String...fragments) {
if (fragments==null)
return this;
for (int i = 0; i < fragments.length; i++) {
String string = fragments[i];
if (isValid(string)) {
String[] splitted = StringUtils.split(string, separator);
for (int j = 0; j < splitted.length; j++) {
String string2 = splitted[j];
if (isValid(string2) && isValid(string2.trim()))
data.add(string2.trim());
}
}
}
return this;
};
public String relational() {
return StringUtils.join(data, separator);
}
public String absolute() {
return separator + relational();
}
public Iterator<String> fragmentsIterator() {
return data.iterator();
}
public ListIterator<String> fragmentsListIterator() {
return data.listIterator();
}
public List<String> pathHierarchy(){
return pathHierarchy(true);
}
public List<String> pathHierarchy(boolean absolute){
List<String> result = new ArrayList<>();
if (data.isEmpty())
return result;
result.add((absolute?separator:"") + data.get(0));
for (int i=1; i<data.size(); i++)
result.add(result.get(i-1) + separator + data.get(i));
return result;
}
public Iterator<String> iterator() {
return pathHierarchy().iterator();
}
public ListIterator<String> listIterator() {
return pathHierarchy().listIterator();
}
}
/**
* Generates UUID
*
* @return
*/
public static String getUUID(){
return UUID.randomUUID().toString().toLowerCase().replace("-", "");
}
/**
* Generates UUID consisting of specified char
* @param c
* @return
*/
public static String getUUID(char c) {
return StringUtils.leftPad("", 32, c);
}
/**
* Generates GUID
*
* @return
*/
public static String getGUID(){
return UUID.randomUUID().toString().toUpperCase();
}
public static final String GUID_0 = "00000000-0000-0000-0000-000000000000";
public static final String GUID_f = "FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF";
public static final String NULL_GUID_ = GUID_0;
/**
* Generates GUID consisting of specified char
* @param c
* @return
*/
public static String getGUID(char c) {
return uid2guid(StringUtils.leftPad("", 32, c));
}
/**
* Converts UUID to GUID
* @param uid
* @return
*/
public static String uid2guid(String uid){
return uid.replaceFirst("(.{8})(.{4})(.{4})(.{4})(.{8})", "$1-$2-$3-$4-$5").toUpperCase();
}
/**
* Converts GUID to UUID
* @param uid
* @return
*/
public static String guid2uid(String guid){
return guid.toLowerCase().replace("-", "");
}
/**
* Checks if the string is not null and has something inside after trim
*
* @param s
* @return
*/
public static boolean isValid(String s){
if (s==null)
return false;
return s.trim().length()>0;
}
/**
*
* @param s string to examine
* @param def default value
* @return s if isValid(s), otherwise def
*/
public static String getValid(String s, String def){
return isValid(s)?s:def;
}
public static String padLeft(String data, int length){
return padLeft(data, length, ' ');
}
public static String padRight(String data, int length){
return padRight(data, length, ' ');
}
public static final String PACKET_TYPE_PARAM_NAME = "packetType";
public static String padBoth(String data, int length){
return padBoth(data, length, ' ');
}
public static class Path {
public static String padLeft(String data, int length, Character c){
String val = data;
if (data==null)
val = "";
while (val.length()<length)
val = c + val;
return val;
}
public static String padRight(String data, int length, Character c){
String val = data;
if (data==null)
val = "";
while (val.length()<length)
val = val + c;
return val;
}
public static final String DEFAULT_SEPARATOR = "/";
public static String padBoth(String data, int length, Character c){
String val = data;
boolean left = true;
if (data==null)
val = "";
while (val.length()<length){
if (left)
val = c + val;
else
val = val + c;
left = !left;
}
return val;
}
protected String separator = DEFAULT_SEPARATOR;
protected List<String> data = new ArrayList<>();
public static void stream2file(InputStream input, String file) throws Exception {
File f = new File(file);
FileOutputStream output = new FileOutputStream(f);
IOUtils.copy(input, output);
output.close();
}
public static <K, V> Map<K, V> addDictionaryToMap(Dictionary<K, V> source, Map<K, V> sink) {
for (Enumeration<K> keys = source.keys(); keys.hasMoreElements();) {
K key = keys.nextElement();
sink.put(key, source.get(key));
}
return sink;
}
public static <K, V> Map<K, V> getDictionaryAsMap(Dictionary<K, V> source) {
Map<K, V> result = new HashMap<>();
CommonUtils.addDictionaryToMap(source, result);
return result;
}
public static Path create() {
return new Path();
}
public static boolean isAbsolute(String path) {
return isAbsolute(path, DEFAULT_SEPARATOR);
}
public static boolean isAbsolute(String path, String separator) {
if (!isValid(path))
return false;
return path.trim().startsWith(separator);
}
public Path() {
super();
}
public Path separator(String newSeparator) {
if (newSeparator != null)
this.separator = newSeparator;
return this;
}
public Path construct(String... fragments) {
data.clear();
return append(fragments);
}
public Path append(String... fragments) {
if (fragments == null)
return this;
for (int i = 0; i < fragments.length; i++) {
String string = fragments[i];
if (isValid(string)) {
String[] splitted = StringUtils.split(string, separator);
for (int j = 0; j < splitted.length; j++) {
String string2 = splitted[j];
if (isValid(string2) && isValid(string2.trim()))
data.add(string2.trim());
}
}
}
return this;
};
public String relational() {
return StringUtils.join(data, separator);
}
public String absolute() {
return separator + relational();
}
public Iterator<String> fragmentsIterator() {
return data.iterator();
}
public ListIterator<String> fragmentsListIterator() {
return data.listIterator();
}
public List<String> pathHierarchy() {
return pathHierarchy(true);
}
public List<String> pathHierarchy(boolean absolute) {
List<String> result = new ArrayList<>();
if (data.isEmpty())
return result;
result.add((absolute ? separator : "") + data.get(0));
for (int i = 1; i < data.size(); i++)
result.add(result.get(i - 1) + separator + data.get(i));
return result;
}
public Iterator<String> iterator() {
return pathHierarchy().iterator();
}
public ListIterator<String> listIterator() {
return pathHierarchy().listIterator();
}
}
/**
* Generates UUID
*
* @return
*/
public static String getUUID() {
return UUID.randomUUID().toString().toLowerCase().replace("-", "");
}
/**
* Generates UUID consisting of specified char
*
* @param c
* @return
*/
public static String getUUID(char c) {
return StringUtils.leftPad("", 32, c);
}
/**
* Generates GUID
*
* @return
*/
public static String getGUID() {
return UUID.randomUUID().toString().toUpperCase();
}
/**
* Generates GUID consisting of specified char
*
* @param c
* @return
*/
public static String getGUID(char c) {
return uid2guid(StringUtils.leftPad("", 32, c));
}
/**
* Converts UUID to GUID
*
* @param uid
* @return
*/
public static String uid2guid(String uid) {
return uid.replaceFirst("(.{8})(.{4})(.{4})(.{4})(.{8})", "$1-$2-$3-$4-$5").toUpperCase();
}
/**
* Converts GUID to UUID
*
* @param uid
* @return
*/
public static String guid2uid(String guid) {
return guid.toLowerCase().replace("-", "");
}
/**
* Checks if the string is not null and has something inside after trim
*
* @param s
* @return
*/
public static boolean isValid(String s) {
if (s == null)
return false;
return s.trim().length() > 0;
}
/**
*
* @param s string to examine
* @param def default value
* @return s if isValid(s), otherwise def
*/
public static String getValid(String s, String def) {
return isValid(s) ? s : def;
}
public static String padLeft(String data, int length) {
return padLeft(data, length, ' ');
}
public static String padRight(String data, int length) {
return padRight(data, length, ' ');
}
public static String padBoth(String data, int length) {
return padBoth(data, length, ' ');
}
public static String padLeft(String data, int length, Character c) {
String val = data;
if (data == null)
val = "";
while (val.length() < length)
val = c + val;
return val;
}
public static String padRight(String data, int length, Character c) {
String val = data;
if (data == null)
val = "";
while (val.length() < length)
val = val + c;
return val;
}
public static String padBoth(String data, int length, Character c) {
String val = data;
boolean left = true;
if (data == null)
val = "";
while (val.length() < length) {
if (left)
val = c + val;
else
val = val + c;
left = !left;
}
return val;
}
public static void stream2file(InputStream input, String file) throws Exception {
File f = new File(file);
try (FileOutputStream output = new FileOutputStream(f)) {
IOUtils.copy(input, output);
}
}
public static <K, V> Map<K, V> addDictionaryToMap(Dictionary<K, V> source, Map<K, V> sink) {
for (Enumeration<K> keys = source.keys(); keys.hasMoreElements();) {
K key = keys.nextElement();
sink.put(key, source.get(key));
}
return sink;
}
public static <K, V> Map<K, V> getDictionaryAsMap(Dictionary<K, V> source) {
Map<K, V> result = new HashMap<>();
CommonUtils.addDictionaryToMap(source, result);
return result;
}
public static <V> Map<String, V> prefixMap(Map<String, V> map, String prefix) {
Map<String, V> result = new LinkedHashMap<>();
for (Map.Entry<String, V> entry : map.entrySet())
result.put(String.format("%s%s", prefix, entry.getKey()), entry.getValue());
return result;
}
}

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* test-producers
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
@ -25,54 +25,53 @@
*/
package ru.entaxy.platform.base.support;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
public class DependencySorter {
public static interface DependencyProvider<T> {
List<T> getDependencies(T inspectedObject);
}
public static <T> List<T> getSortedList(List<T> origin, DependencyProvider<T> provider) throws Exception {
List<T> result = new LinkedList<>();
// add independent objects
result.addAll(
origin.stream().filter(obj -> provider.getDependencies(obj).isEmpty())
.collect(Collectors.toList())
);
while (result.size() < origin.size()) {
List<T> nextObjects = origin.stream().filter(obj->!result.contains(obj))
.filter(obj->result.containsAll(provider.getDependencies(obj)))
.collect(Collectors.toList());
if (nextObjects.isEmpty())
// TODO create more informative exception
throw new UnsatisfiedDependenciesException(
origin.stream().filter(obj->!result.contains(obj))
.collect(Collectors.toList())
);
result.addAll(nextObjects);
}
return result;
}
public static interface DependencyProvider<T> {
List<T> getDependencies(T inspectedObject);
}
public static <T> List<T> getSortedList(List<T> origin, DependencyProvider<T> provider) throws Exception {
List<T> result = new LinkedList<>();
// add independent objects
result.addAll(
origin.stream().filter(obj -> provider.getDependencies(obj).isEmpty())
.collect(Collectors.toList()));
while (result.size() < origin.size()) {
List<T> nextObjects = origin.stream().filter(obj -> !result.contains(obj))
.filter(obj -> result.containsAll(provider.getDependencies(obj)))
.collect(Collectors.toList());
if (nextObjects.isEmpty())
// TODO create more informative exception
throw new UnsatisfiedDependenciesException(
origin.stream().filter(obj -> !result.contains(obj))
.collect(Collectors.toList()));
result.addAll(nextObjects);
}
return result;
}
@SuppressWarnings("serial")
public static class UnsatisfiedDependenciesException extends Exception {
protected List<Object> objects;
public UnsatisfiedDependenciesException(List<?> list) {
super("Contains unsatisfied dependencies");
this.objects = new ArrayList(list);
}
public List<Object> getObjects() {
return objects;
}
}
@SuppressWarnings("serial")
public static class UnsatisfiedDependenciesException extends Exception {
protected List<Object> objects;
public UnsatisfiedDependenciesException(List<?> list) {
super("Contains unsatisfied dependencies");
this.objects.addAll(list);
}
public List<Object> getObjects() {
return objects;
}
}
}

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* base-support
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* base-support
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* base-support
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* base-support
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
@ -30,44 +30,63 @@ import java.util.Map;
import org.osgi.framework.Bundle;
import org.osgi.framework.wiring.BundleCapability;
import org.osgi.framework.wiring.BundleRevision;
import org.osgi.framework.wiring.BundleWiring;
public class BundleCapabilityHelper extends CapabilityHelper {
protected Bundle bundle;
public BundleCapabilityHelper(Bundle bundle) {
super();
this.bundle = bundle;
setMultipleNamespacesSupported(true);
load();
}
@Override
protected void load() {
BundleWiring bundleWiring = bundle.adapt(BundleWiring.class);
if (bundleWiring == null)
return;
List<BundleCapability> capabilities = bundleWiring.getCapabilities(null);
for (BundleCapability cap: capabilities) {
CapabilityDescriptorImpl descriptor = new CapabilityDescriptorImpl();
descriptor.namespace(cap.getNamespace());
for (Map.Entry<String, Object> attr: cap.getAttributes().entrySet())
descriptor.attribute(attr.getKey(), attr.getValue());
addProvidedCapability(descriptor);
}
}
public CapabilityDescriptor findObjectDeclaration(String objectId, String objectType) {
if (this.providedCapabilities == null)
return null;
if (this.providedCapabilities.get(objectType) == null)
return null;
for (CapabilityDescriptor desc: this.providedCapabilities.get(objectType))
if (objectId.equals(desc.getAttributes().getOrDefault("objectId", "").toString()))
return desc;
return null;
}
protected Bundle bundle;
protected boolean isLoaded = false;
public BundleCapabilityHelper(Bundle bundle) {
super();
this.bundle = bundle;
setMultipleNamespacesSupported(true);
load();
}
@Override
protected void load() {
List<BundleCapability> capabilities = null;
BundleWiring bundleWiring = bundle.adapt(BundleWiring.class);
if (bundleWiring != null) {
capabilities = bundleWiring.getCapabilities(null);
} else {
BundleRevision bundleRevision = bundle.adapt(BundleRevision.class);
if (bundleRevision != null) {
capabilities = bundleRevision.getDeclaredCapabilities(null);
}
}
if (capabilities == null)
return;
for (BundleCapability cap : capabilities) {
CapabilityDescriptorImpl descriptor = new CapabilityDescriptorImpl();
descriptor.namespace(cap.getNamespace());
for (Map.Entry<String, Object> attr : cap.getAttributes().entrySet())
descriptor.attribute(attr.getKey(), attr.getValue());
addProvidedCapability(descriptor);
}
isLoaded = true;
}
public CapabilityDescriptor findObjectDeclaration(String objectId, String objectType) {
if (this.providedCapabilities == null)
return null;
if (this.providedCapabilities.get(objectType) == null)
return null;
for (CapabilityDescriptor desc : this.providedCapabilities.get(objectType))
if (objectId.equals(desc.getAttributes().getOrDefault("objectId", "").toString()))
return desc;
return null;
}
public boolean isLoaded() {
return isLoaded;
}
}

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* artifact-management
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
@ -25,42 +25,53 @@
*/
package ru.entaxy.platform.base.support.osgi.bundle;
import org.osgi.resource.Capability;
import java.util.Map;
import org.osgi.resource.Capability;
public interface CapabilityDescriptor extends Capability {
public static final String HEADER_PROVIDE_CAPABILITY = "Provide-Capability";
public static final String HEADER_REQUIRE_CAPABILITY = "Require-Capability";
public static interface ATTRIBUTE_TYPES {
public static final String STRING = "String";
public static final String VERSION = "Version";
public static final String LONG = "Long";
public static final String DOUBLE = "Double";
public static final String LIST = "List";
public static String TYPED_LIST(String itemType) {
return LIST + "<" + itemType + ">";
}
public static final String HEADER_PROVIDE_CAPABILITY = "Provide-Capability";
public static final String HEADER_REQUIRE_CAPABILITY = "Require-Capability";
public static boolean isList(String itemType) {
return (itemType!=null) && (itemType.startsWith(LIST));
}
public static interface ATTRIBUTE_TYPES {
public static final String STRING = "String";
public static final String VERSION = "Version";
public static final String LONG = "Long";
public static final String DOUBLE = "Double";
public static final String LIST = "List";
public static String TYPED_LIST(String itemType) {
return LIST + "<" + itemType + ">";
}
public static boolean isList(String itemType) {
return (itemType != null) && (itemType.startsWith(LIST));
}
public static String itemType(String listType) {
if (!isList(listType))
return null;
return listType.substring(listType.indexOf("<"), listType.indexOf(">"));
}
}
/**
* Get attributes as they exist without extracting and transforming
*
* @return map of attributes
*/
public Map<String, Object> getRawAttributes();
public CapabilityDescriptor namespace(String namespace);
public CapabilityDescriptor attributes(Map<String, Object> attributes);
public CapabilityDescriptor attribute(String name, Object value);
public CapabilityDescriptor attribute(String name, Object value, String type);
public static String itemType(String listType) {
if (!isList(listType))
return null;
return listType.substring(listType.indexOf("<"), listType.indexOf(">"));
}
}
public CapabilityDescriptor namespace(String namespace);
public CapabilityDescriptor attributes(Map<String, Object> attributes);
public CapabilityDescriptor attribute(String name, Object value);
public CapabilityDescriptor attribute(String name, Object value, String type);
}

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* artifact-management
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
@ -25,6 +25,11 @@
*/
package ru.entaxy.platform.base.support.osgi.bundle;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -37,130 +42,178 @@ import ru.entaxy.platform.base.support.CommonUtils;
public class CapabilityDescriptorImpl implements CapabilityDescriptor {
protected String namespace;
protected Map<String, String> directives = new HashMap<>();
protected Map<String, AttributeDescriptor> attributes = new HashMap<>();
private static class AttributeDescriptor {
String type;
Object value;
public AttributeDescriptor(Object value) {
this(value, CapabilityTypeHelper.getTypeName(value));
}
public AttributeDescriptor(Object value, String type) {
this.type = type;
this.value = value==null?"":value; //.toString();
}
public String getValueAsString() {
if (value == null)
return null;
if (CapabilityDescriptor.ATTRIBUTE_TYPES.isList(type))
return CapabilityTypeHelper.getListAsString((List<?>)value);
if (CapabilityDescriptor.ATTRIBUTE_TYPES.STRING.equals(type))
return "\"" + value.toString() + "\"";
return value.toString();
}
}
public CapabilityDescriptorImpl() {
// TODO Auto-generated constructor stub
}
protected String namespace;
public CapabilityDescriptorImpl(String namespace) {
this();
namespace(namespace);
}
public String getAttributesAsString() {
return this.attributes.entrySet().stream()
.map(entry->
entry.getKey()
+ /* (!ATTRIBUTE_TYPES.STRING.equals(entry.getValue().type)?(*/":" + entry.getValue().type/* ):"") */
+ "=" + entry.getValue().getValueAsString())
.collect(Collectors.joining(";"));
}
@Override
public String getNamespace() {
return this.namespace;
}
protected Map<String, String> directives = new HashMap<>();
protected Map<String, AttributeDescriptor> attributes = new HashMap<>();
@Override
public Map<String, String> getDirectives() {
return this.directives;
}
private static class AttributeDescriptor {
@Override
public Map<String, Object> getAttributes() {
Map<String, Object> result = new HashMap<>();
for (Map.Entry<String, AttributeDescriptor> entry: this.attributes.entrySet())
result.put(entry.getKey(), entry.getValue().value);
return result;
}
public static final String MARKER_BASE64 = "@BASE64";
@Override
public Resource getResource() {
// not implemented
return null;
}
private static final CharsetEncoder ENCODER = StandardCharsets.ISO_8859_1.newEncoder();
@Override
public CapabilityDescriptor namespace(String namespace) {
this.namespace = namespace;
return this;
}
private static final Encoder BASE64_ENCODER = Base64.getEncoder();
@Override
public CapabilityDescriptor attribute(String name, Object value) {
this.attributes.put(name, new AttributeDescriptor(value));
return this;
}
private static final Decoder BASE64_DECODER = Base64.getDecoder();
@Override
public CapabilityDescriptor attribute(String name, Object value, String type) {
this.attributes.put(name, new AttributeDescriptor(value, type));
return this;
}
public CapabilityDescriptor parseAttribute(String attributeData) {
String nameType = attributeData.substring(0, attributeData.indexOf("="));
if (!CommonUtils.isValid(nameType))
return this;
String[] nameTypeSplit = nameType.split(":");
String name = nameTypeSplit[0].trim();
String type = (nameTypeSplit.length > 1?nameTypeSplit[1]:CapabilityDescriptor.ATTRIBUTE_TYPES.STRING);
if (!CommonUtils.isValid(type))
type = CapabilityDescriptor.ATTRIBUTE_TYPES.STRING;
type = type.trim();
String value = attributeData.substring(attributeData.indexOf("=")+1);
if (!CommonUtils.isValid(value))
value = "";
value = value.trim();
Object typedValue = CapabilityTypeHelper.getTypedValue(type, value);
this.attribute(name, typedValue, type);
return this;
}
String type;
Object value;
@Override
public CapabilityDescriptor attributes(Map<String, Object> attributes) {
if (attributes == null)
return this;
for (Entry<String, Object> entry: attributes.entrySet()) {
this.attribute(entry.getKey(), entry.getValue());
}
return this;
}
public AttributeDescriptor(Object value) {
this(value, CapabilityTypeHelper.getTypeName(value));
}
public AttributeDescriptor(Object value, String type) {
this.type = type;
this.value = value == null ? "" : value; // .toString();
}
public String getPackedStringValue(String data) {
if (ENCODER.canEncode(data))
return data;
return BASE64_ENCODER.encodeToString(data.getBytes()).concat(MARKER_BASE64);
}
public String getUnpackedStringValue(String data) {
if (data.endsWith(MARKER_BASE64))
return new String(BASE64_DECODER.decode(data.substring(0, data.length() - MARKER_BASE64.length())));
return data;
}
public Object getValue() {
if (!CapabilityDescriptor.ATTRIBUTE_TYPES.STRING.equals(type))
return value;
return getUnpackedStringValue(value.toString());
}
public String getValueAsString() {
if (value == null)
return null;
if (CapabilityDescriptor.ATTRIBUTE_TYPES.isList(type))
return CapabilityTypeHelper.getListAsString((List<?>) value);
if (CapabilityDescriptor.ATTRIBUTE_TYPES.STRING.equals(type))
return "\"" + getPackedStringValue(value.toString()) + "\"";
return value.toString();
}
public String getRawValueAsString() {
if (value == null)
return null;
if (CapabilityDescriptor.ATTRIBUTE_TYPES.isList(type))
return CapabilityTypeHelper.getListAsString((List<?>) value);
if (CapabilityDescriptor.ATTRIBUTE_TYPES.STRING.equals(type))
return "\"" + value.toString() + "\"";
return value.toString();
}
}
public CapabilityDescriptorImpl() {
// TODO Auto-generated constructor stub
}
public CapabilityDescriptorImpl(String namespace) {
this();
namespace(namespace);
}
public String getAttributesAsString() {
return this.attributes.entrySet().stream()
.map(entry -> entry.getKey()
+ /* (!ATTRIBUTE_TYPES.STRING.equals(entry.getValue().type)?( */":" + entry.getValue().type/*
* )
* :
* "")
*/
+ "=" + entry.getValue().getValueAsString())
.collect(Collectors.joining(";"));
}
@Override
public String getNamespace() {
return this.namespace;
}
@Override
public Map<String, String> getDirectives() {
return this.directives;
}
@Override
public Map<String, Object> getAttributes() {
Map<String, Object> result = new HashMap<>();
for (Map.Entry<String, AttributeDescriptor> entry : this.attributes.entrySet())
result.put(entry.getKey(), entry.getValue().getValue());
return result;
}
@Override
public Map<String, Object> getRawAttributes() {
Map<String, Object> result = new HashMap<>();
for (Map.Entry<String, AttributeDescriptor> entry : this.attributes.entrySet())
result.put(entry.getKey(), entry.getValue().value);
return result;
}
@Override
public Resource getResource() {
// not implemented
return null;
}
@Override
public CapabilityDescriptor namespace(String namespace) {
this.namespace = namespace;
return this;
}
@Override
public CapabilityDescriptor attribute(String name, Object value) {
this.attributes.put(name, new AttributeDescriptor(value));
return this;
}
@Override
public CapabilityDescriptor attribute(String name, Object value, String type) {
this.attributes.put(name, new AttributeDescriptor(value, type));
return this;
}
public CapabilityDescriptor parseAttribute(String attributeData) {
String nameType = attributeData.substring(0, attributeData.indexOf("="));
if (!CommonUtils.isValid(nameType))
return this;
String[] nameTypeSplit = nameType.split(":");
String name = nameTypeSplit[0].trim();
String type = (nameTypeSplit.length > 1 ? nameTypeSplit[1] : CapabilityDescriptor.ATTRIBUTE_TYPES.STRING);
if (!CommonUtils.isValid(type))
type = CapabilityDescriptor.ATTRIBUTE_TYPES.STRING;
type = type.trim();
String value = attributeData.substring(attributeData.indexOf("=") + 1);
if (!CommonUtils.isValid(value))
value = "";
value = value.trim();
Object typedValue = CapabilityTypeHelper.getTypedValue(type, value);
this.attribute(name, typedValue, type);
return this;
}
@Override
public CapabilityDescriptor attributes(Map<String, Object> attributes) {
if (attributes == null)
return this;
for (Entry<String, Object> entry : attributes.entrySet()) {
this.attribute(entry.getKey(), entry.getValue());
}
return this;
}
}

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* test-producers
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
@ -28,130 +28,144 @@ package ru.entaxy.platform.base.support.osgi.bundle;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import ru.entaxy.platform.base.support.CommonUtils;
public class CapabilityHelper {
protected boolean isMultipleNamespacesSupported = false;
protected Map<String, CapabilityDescriptorImpl> requiredCapabilities = new HashMap<>();
protected Map<String, List<CapabilityDescriptorImpl>> providedCapabilities = new HashMap<>();
public CapabilityHelper() {
super();
}
protected boolean isMultipleNamespacesSupported = false;
protected void load() {
/* String existing = this.manifest.getCustomAttributes().get(CapabilityDescriptor.HEADER_PROVIDE_CAPABILITY);
if (CommonUtils.isValid(existing)) {
List<CapabilityDescriptorImpl> list = parse(existing);
for (CapabilityDescriptorImpl c: list)
addProvidedCapability(c);
}
existing = this.manifest.getCustomAttributes().get(CapabilityDescriptor.HEADER_REQUIRE_CAPABILITY);
if (CommonUtils.isValid(existing)) {
List<CapabilityDescriptorImpl> list = parse(existing);
for (CapabilityDescriptorImpl c: list)
addRequiredCapability(c);
} */
}
protected void addProvidedCapability(CapabilityDescriptorImpl capabilityDescriptorImpl) {
if (capabilityDescriptorImpl == null)
return;
if (!isMultipleNamespacesSupported) {
this.providedCapabilities.put(capabilityDescriptorImpl.getNamespace()
, Collections.singletonList(capabilityDescriptorImpl));
} else {
if (!this.providedCapabilities.containsKey(capabilityDescriptorImpl.getNamespace()))
this.providedCapabilities.put(capabilityDescriptorImpl.getNamespace()
, Collections.singletonList(capabilityDescriptorImpl));
else
this.providedCapabilities.get(capabilityDescriptorImpl.getNamespace())
.add(capabilityDescriptorImpl);
}
}
protected Map<String, CapabilityDescriptorImpl> requiredCapabilities = new HashMap<>();
protected Map<String, List<CapabilityDescriptorImpl>> providedCapabilities = new HashMap<>();
protected Set<String> osgiCapabilities = new HashSet<>();
protected void addRequiredCapability(CapabilityDescriptorImpl capabilityDescriptorImpl) {
if (capabilityDescriptorImpl == null)
return;
this.requiredCapabilities.put(capabilityDescriptorImpl.getNamespace(), capabilityDescriptorImpl);
}
protected List<CapabilityDescriptorImpl> parse(String capabilities) {
List<CapabilityDescriptorImpl> result = new ArrayList<>();
String[] caps = capabilities.split(",");
for (int i=0; i< caps.length; i++)
if (CommonUtils.isValid(caps[i])) {
result.add(parseCapability(caps[i]));
}
return result;
}
protected CapabilityDescriptorImpl parseCapability(String capability) {
String[] parsed = capability.split(";");
CapabilityDescriptorImpl result = new CapabilityDescriptorImpl(parsed[0].trim());
for (int i=1; i<parsed.length; i++) {
result.parseAttribute(parsed[i]);
}
return result;
}
public List<CapabilityDescriptor> getProvidedCapabilities(){
return this.providedCapabilities.values().stream()
.flatMap(List::stream)
.map(c -> (CapabilityDescriptor)c)
.collect(Collectors.toList());
}
public CapabilityHelper() {
super();
osgiCapabilities.add("osgi.identity");
osgiCapabilities.add("osgi.wiring.bundle");
osgiCapabilities.add("osgi.wiring.host");
}
public List<CapabilityDescriptor> getProvidedCapabilities(String namesoace){
if (!this.providedCapabilities.containsKey(namesoace))
return new ArrayList<>();
return this.providedCapabilities.get(namesoace)
.stream()
.map(c -> (CapabilityDescriptor)c)
.collect(Collectors.toList());
}
public List<CapabilityDescriptor> getRequiredCapabilities(){
return this.requiredCapabilities.values().stream()
.map(c -> (CapabilityDescriptor)c)
.collect(Collectors.toList());
}
public boolean isCapabilityProvided(String namespace) {
return this.providedCapabilities.containsKey(namespace);
}
protected void load() {
/*
* String existing =
* this.manifest.getCustomAttributes().get(CapabilityDescriptor.HEADER_PROVIDE_CAPABILITY);
* if (CommonUtils.isValid(existing)) { List<CapabilityDescriptorImpl> list =
* parse(existing); for (CapabilityDescriptorImpl c: list) addProvidedCapability(c); }
* existing =
* this.manifest.getCustomAttributes().get(CapabilityDescriptor.HEADER_REQUIRE_CAPABILITY);
* if (CommonUtils.isValid(existing)) { List<CapabilityDescriptorImpl> list =
* parse(existing); for (CapabilityDescriptorImpl c: list) addRequiredCapability(c); }
*/
}
public boolean isCapabilityRequired(String namespace) {
return this.requiredCapabilities.containsKey(namespace);
}
public CapabilityDescriptor provideCapability(String namespace) {
CapabilityDescriptorImpl desc = new CapabilityDescriptorImpl(namespace);
addProvidedCapability(desc);
return desc;
}
protected void addProvidedCapability(CapabilityDescriptorImpl capabilityDescriptorImpl) {
if (capabilityDescriptorImpl == null)
return;
if (!isMultipleNamespacesSupported) {
this.providedCapabilities.put(capabilityDescriptorImpl.getNamespace(),
Collections.singletonList(capabilityDescriptorImpl));
} else {
if (!this.providedCapabilities.containsKey(capabilityDescriptorImpl.getNamespace()))
this.providedCapabilities.put(capabilityDescriptorImpl.getNamespace(), new ArrayList<>());
this.providedCapabilities.get(capabilityDescriptorImpl.getNamespace())
.add(capabilityDescriptorImpl);
}
}
public CapabilityDescriptor requireCapability(String namespace) {
if (!this.requiredCapabilities.containsKey(namespace))
this.requiredCapabilities.put(namespace, new CapabilityDescriptorImpl(namespace));
return this.requiredCapabilities.get(namespace);
}
public boolean isMultipleNamespacesSupported() {
return isMultipleNamespacesSupported;
}
public void setMultipleNamespacesSupported(boolean isMultipleNamespacesSupported) {
this.isMultipleNamespacesSupported = isMultipleNamespacesSupported;
}
protected void addRequiredCapability(CapabilityDescriptorImpl capabilityDescriptorImpl) {
if (capabilityDescriptorImpl == null)
return;
this.requiredCapabilities.put(capabilityDescriptorImpl.getNamespace(), capabilityDescriptorImpl);
}
protected List<CapabilityDescriptorImpl> parse(String capabilities) {
List<CapabilityDescriptorImpl> result = new ArrayList<>();
String[] caps = capabilities.split(",");
for (int i = 0; i < caps.length; i++)
if (CommonUtils.isValid(caps[i])) {
result.add(parseCapability(caps[i]));
}
return result;
}
protected CapabilityDescriptorImpl parseCapability(String capability) {
String[] parsed = capability.split(";");
CapabilityDescriptorImpl result = new CapabilityDescriptorImpl(parsed[0].trim());
for (int i = 1; i < parsed.length; i++) {
if (!CommonUtils.isValid(parsed[i]))
continue;
result.parseAttribute(parsed[i]);
}
return result;
}
public List<CapabilityDescriptor> getProvidedCapabilities() {
return this.providedCapabilities.values().stream()
.flatMap(List::stream)
.map(c -> (CapabilityDescriptor) c)
.collect(Collectors.toList());
}
public List<CapabilityDescriptor> getEntaxyObjectsProvidedCapabilities() {
return this.providedCapabilities.entrySet().stream()
.filter(e -> !osgiCapabilities.contains(e.getKey()))
.map(e -> e.getValue())
.flatMap(List::stream)
.map(c -> (CapabilityDescriptor) c)
.collect(Collectors.toList());
}
public List<CapabilityDescriptor> getProvidedCapabilities(String namespace) {
if (!this.providedCapabilities.containsKey(namespace))
return new ArrayList<>();
return this.providedCapabilities.get(namespace)
.stream()
.map(c -> (CapabilityDescriptor) c)
.collect(Collectors.toList());
}
public List<CapabilityDescriptor> getRequiredCapabilities() {
return this.requiredCapabilities.values().stream()
.map(c -> (CapabilityDescriptor) c)
.collect(Collectors.toList());
}
public boolean isCapabilityProvided(String namespace) {
return this.providedCapabilities.containsKey(namespace);
}
public boolean isCapabilityRequired(String namespace) {
return this.requiredCapabilities.containsKey(namespace);
}
public CapabilityDescriptor provideCapability(String namespace) {
CapabilityDescriptorImpl desc = new CapabilityDescriptorImpl(namespace);
addProvidedCapability(desc);
return desc;
}
public CapabilityDescriptor requireCapability(String namespace) {
if (!this.requiredCapabilities.containsKey(namespace))
this.requiredCapabilities.put(namespace, new CapabilityDescriptorImpl(namespace));
return this.requiredCapabilities.get(namespace);
}
public boolean isMultipleNamespacesSupported() {
return isMultipleNamespacesSupported;
}
public void setMultipleNamespacesSupported(boolean isMultipleNamespacesSupported) {
this.isMultipleNamespacesSupported = isMultipleNamespacesSupported;
}
}

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* test-producers
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* system-commons
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* system-commons
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* system-commons
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* system-commons
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* profile-management
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* profile-management
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* profile-management
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* profile-management
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* profile-management
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* base-support
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* profile-management
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* base-support
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property

View File

@ -2,7 +2,7 @@
* ~~~~~~licensing~~~~~~
* base-support
* ==========
* Copyright (C) 2020 - 2023 EmDev LLC
* Copyright (C) 2020 - 2024 EmDev LLC
* ==========
* You may not use this file except in accordance with the License Terms of the Copyright
* Holder located at: https://entaxy.ru/eula . All copyrights, all intellectual property
@ -38,16 +38,20 @@ import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Result;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
/*import net.sf.saxon.TransformerFactoryImpl;
import net.sf.saxon.lib.NamespaceConstant;
*/
/*
* import net.sf.saxon.TransformerFactoryImpl; import net.sf.saxon.lib.NamespaceConstant;
*/
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
@ -56,195 +60,255 @@ import org.xml.sax.InputSource;
import ru.entaxy.platform.base.support.CommonUtils;
public class CommonXMLUtils {
// GETTING DOCUMENT
public static Document getDocument(URL url) throws Exception{
return getDocument(url.openStream());
}
public static Document getDocument(InputStream stream) throws Exception {
return getDocument(false, stream);
}
public static Document getDocument(boolean namespaceAware, InputStream stream) throws Exception {
InputSource is = new InputSource(stream);
return getDocument(namespaceAware, is);
}
public static Document newDocument(boolean namespaceAware) throws Exception{
return getDocument(namespaceAware, (File)null);
}
public static Document getDocument(boolean namespaceAware, String path) throws Exception{
return getDocument(namespaceAware, CommonUtils.isValid(path)?(new File(path)):null);
}
public static Document getDocument(boolean namespaceAware, File file) throws Exception{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(namespaceAware);
DocumentBuilder db = dbf.newDocumentBuilder();
if (file!=null)
return db.parse(file);
else
return db.newDocument();
}
public static Document newDocument() throws Exception {
return newDocument(false);
}
public static Document getDocument(String path) throws Exception{
return getDocument(false, path);
}
public static Document parseString(boolean namespaceAware, String xmlData) throws Exception{
public static final Logger log = LoggerFactory.getLogger(CommonXMLUtils.class);
private static final String XML_SAX_EXTERNAL_GENERAL_ENTITIES =
"http://xml.org/sax/features/external-general-entities";
private static final String XML_SAX_EXTERNAL_PARAMETER_ENTITIES =
"http://xml.org/sax/features/external-parameter-entities";
// GETTING DOCUMENT
public static Document getDocument(URL url) throws Exception {
return getDocument(url.openStream());
}
public static Document getDocument(InputStream stream) throws Exception {
return getDocument(false, stream);
}
public static Document getDocument(boolean namespaceAware, InputStream stream) throws Exception {
InputSource is = new InputSource(stream);
return getDocument(namespaceAware, is);
}
public static Document newDocument(boolean namespaceAware) throws Exception {
return getDocument(namespaceAware, (File) null);
}
public static Document getDocument(boolean namespaceAware, String path) throws Exception {
return getDocument(namespaceAware, CommonUtils.isValid(path) ? (new File(path)) : null);
}
public static Document getDocument(boolean namespaceAware, File file) throws Exception {
DocumentBuilderFactory dbf = newDocumentBuilderFactoryInstance();
dbf.setNamespaceAware(namespaceAware);
DocumentBuilder db = dbf.newDocumentBuilder();
if (file != null)
return db.parse(file);
else
return db.newDocument();
}
public static Document newDocument() throws Exception {
return newDocument(false);
}
public static Document getDocument(String path) throws Exception {
return getDocument(false, path);
}
public static Document parseString(boolean namespaceAware, String xmlData) throws Exception {
InputSource is = new InputSource(new StringReader(xmlData));
return getDocument(namespaceAware, is);
}
public static Document getDocument(InputSource source) throws Exception {
return getDocument(false, source);
}
public static Document getDocument(boolean namespaceAware, InputSource source) throws Exception {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
}
public static Document getDocument(InputSource source) throws Exception {
return getDocument(false, source);
}
public static Document getDocument(boolean namespaceAware, InputSource source) throws Exception {
DocumentBuilderFactory factory = newDocumentBuilderFactoryInstance();
factory.setNamespaceAware(namespaceAware);
DocumentBuilder builder = factory.newDocumentBuilder();
Document d = builder.parse( source );
return d;
}
public static String doc2string(Document doc) throws Exception{
//set up a transformer
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
Document d = builder.parse(source);
return d;
}
//create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
String xmlString = sw.toString();
public static DocumentBuilderFactory newDocumentBuilderFactoryInstance() {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
return xmlString;
}
public static String node2string(Node node) throws Exception {
Transformer t = TransformerFactory.newInstance().newTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter sw = new StringWriter();
t.transform(new DOMSource(node), new StreamResult(sw));
return sw.toString();
}
// SAVING DOCUMENT
public static void saveDocument(Document doc, String path) throws Exception{
File file = new File(path);
saveDocument(doc, file);
}
// Disable external entities declarations
try {
factory.setFeature(XML_SAX_EXTERNAL_GENERAL_ENTITIES, false);
factory.setFeature(XML_SAX_EXTERNAL_PARAMETER_ENTITIES, false);
} catch (ParserConfigurationException e) {
// log.warn(e.getMessage(), e);
log.warn(e.getMessage());
}
public static void saveDocument(Document doc, File file) throws Exception{
DOMSource source = new DOMSource(doc);
Result result = new StreamResult(file);
Transformer xformer = TransformerFactory.newInstance().newTransformer();
return factory;
}
public static TransformerFactory newTransformerFactoryInstance() {
System.setProperty("javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
TransformerFactory transformerFactory = TransformerFactory.newInstance();
// Disable external entities declarations
try {
transformerFactory.setFeature(XML_SAX_EXTERNAL_GENERAL_ENTITIES, false);
transformerFactory.setFeature(XML_SAX_EXTERNAL_PARAMETER_ENTITIES, false);
} catch (TransformerConfigurationException e) {
// log.warn(e.getMessage(), e);
log.warn(e.getMessage());
}
return transformerFactory;
}
public static String doc2string(Document doc) throws Exception {
// set up a transformer
TransformerFactory transfac = newTransformerFactoryInstance();
Transformer trans = transfac.newTransformer();
trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
trans.setOutputProperty(OutputKeys.INDENT, "yes");
// create string from xml tree
StringWriter sw = new StringWriter();
StreamResult result = new StreamResult(sw);
DOMSource source = new DOMSource(doc);
trans.transform(source, result);
String xmlString = sw.toString();
return xmlString;
}
public static String node2string(Node node) throws Exception {
TransformerFactory transfac = newTransformerFactoryInstance();
Transformer t = transfac.newTransformer();
t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
StringWriter sw = new StringWriter();
t.transform(new DOMSource(node), new StreamResult(sw));
return sw.toString();
}
// SAVING DOCUMENT
public static void saveDocument(Document doc, String path) throws Exception {
File file = new File(path);
saveDocument(doc, file);
}
public static void saveDocument(Document doc, File file) throws Exception {
DOMSource source = new DOMSource(doc);
Result result = new StreamResult(file);
TransformerFactory transfac = newTransformerFactoryInstance();
Transformer xformer = transfac.newTransformer();
xformer.transform(source, result);
}
// MARSHAL
public static void jaxbMarshal(JAXBContext context, JAXBElement<?> object, Node node) throws Exception{
Marshaller m = context.createMarshaller();
jaxbMarshall(m, object, node);
}
public static void jaxbMarshall(Marshaller m, JAXBElement<?> object, Node node) throws Exception{
if (node==null || node.getNodeType()!=Node.ELEMENT_NODE)
throw new IllegalArgumentException("Node is not Element");
m.marshal(object, node);
}
public static String jaxbMarshall(JAXBContext context, JAXBElement<?> object) throws Exception{
String result = null;
Marshaller m = context.createMarshaller();
StringWriter sw = new StringWriter();
m.marshal(object, sw);
result = sw.toString();
return result;
}
// UNMARSHAL
/**
*
* @param context
* @param node
* @param classMap
* @return
* @throws Exception
*/
public static JAXBElement<?> jaxbUnmarshall(JAXBContext context, Node node, HashMap<String, Class<? extends Object>> classMap) throws Exception{
Unmarshaller um = context.createUnmarshaller();
return jaxbUnmarshall(um, node, classMap);
}
public static JAXBElement<?> jaxbUnmarshall(Unmarshaller um, Node node, HashMap<String, Class<? extends Object>> classMap) throws Exception{
if (node.getNodeType()!=Node.ELEMENT_NODE)
throw new IllegalArgumentException("Node is not Element");
String nodeName = node.getNodeName();
String[] s = nodeName.split(":");
nodeName = s[s.length-1];
Class<?> objectClass = classMap.get(nodeName.toLowerCase());
if (objectClass==null)
throw new IllegalArgumentException("Node name " +nodeName+ " not found in map " + classMap.toString());
Object obj = um.unmarshal(node, objectClass);
return (JAXBElement<?>)obj;
}
public static JAXBElement<?> jaxbUnmarshall(Class<?> type, Document doc) throws Exception{
JAXBContext context = JAXBContext.newInstance(
type.getPackage().getName(), type.getClassLoader());
NodeList list = doc.getChildNodes();
Node node = null;
for (int i=0; i<list.getLength(); i++){
if (list.item(i).getNodeType() == Node.ELEMENT_NODE){
node = list.item(i);
break;
}
}
if (node == null)
throw new Exception("Root element not found in document");
return jaxbUnmarshall(context.createUnmarshaller(), node, type);
}
public static JAXBElement<?> jaxbUnmarshall(Class<?> type, Node node) throws Exception{
JAXBContext context = JAXBContext.newInstance(
type.getPackage().getName(), type.getClassLoader());
return jaxbUnmarshall(context.createUnmarshaller(), node, type);
}
public static JAXBElement<?> jaxbUnmarshall(JAXBContext context, Node node, Class<?> type) throws Exception{
return jaxbUnmarshall(context.createUnmarshaller(), node, type);
}
public static JAXBElement<?> jaxbUnmarshall(Unmarshaller um, Node node, Class<?> type) throws Exception{
Object obj = um.unmarshal(node, type);
return (JAXBElement<?>)obj;
}
// XSLT
}
// MARSHAL
public static void jaxbMarshal(JAXBContext context, JAXBElement<?> object, Node node) throws Exception {
Marshaller m = context.createMarshaller();
jaxbMarshall(m, object, node);
}
public static void jaxbMarshall(Marshaller m, JAXBElement<?> object, Node node) throws Exception {
if (node == null || node.getNodeType() != Node.ELEMENT_NODE)
throw new IllegalArgumentException("Node is not Element");
m.marshal(object, node);
}
public static String jaxbMarshall(JAXBContext context, JAXBElement<?> object) throws Exception {
String result = null;
Marshaller m = context.createMarshaller();
StringWriter sw = new StringWriter();
m.marshal(object, sw);
result = sw.toString();
return result;
}
// UNMARSHAL
/**
*
* @param context
* @param node
* @param classMap
* @return
* @throws Exception
*/
public static JAXBElement<?> jaxbUnmarshall(JAXBContext context, Node node,
HashMap<String, Class<? extends Object>> classMap) throws Exception {
Unmarshaller um = context.createUnmarshaller();
return jaxbUnmarshall(um, node, classMap);
}
public static JAXBElement<?> jaxbUnmarshall(Unmarshaller um, Node node,
HashMap<String, Class<? extends Object>> classMap) throws Exception {
if (node.getNodeType() != Node.ELEMENT_NODE)
throw new IllegalArgumentException("Node is not Element");
String nodeName = node.getNodeName();
String[] s = nodeName.split(":");
nodeName = s[s.length - 1];
Class<?> objectClass = classMap.get(nodeName.toLowerCase());
if (objectClass == null)
throw new IllegalArgumentException("Node name " + nodeName + " not found in map " + classMap.toString());
Object obj = um.unmarshal(node, objectClass);
return (JAXBElement<?>) obj;
}
public static JAXBElement<?> jaxbUnmarshall(Class<?> type, Document doc) throws Exception {
JAXBContext context = JAXBContext.newInstance(
type.getPackage().getName(), type.getClassLoader());
NodeList list = doc.getChildNodes();
Node node = null;
for (int i = 0; i < list.getLength(); i++) {
if (list.item(i).getNodeType() == Node.ELEMENT_NODE) {
node = list.item(i);
break;
}
}
if (node == null)
throw new Exception("Root element not found in document");
return jaxbUnmarshall(context.createUnmarshaller(), node, type);
}
public static JAXBElement<?> jaxbUnmarshall(Class<?> type, Node node) throws Exception {
JAXBContext context = JAXBContext.newInstance(
type.getPackage().getName(), type.getClassLoader());
return jaxbUnmarshall(context.createUnmarshaller(), node, type);
}
public static JAXBElement<?> jaxbUnmarshall(JAXBContext context, Node node, Class<?> type) throws Exception {
return jaxbUnmarshall(context.createUnmarshaller(), node, type);
}
public static JAXBElement<?> jaxbUnmarshall(Unmarshaller um, Node node, Class<?> type) throws Exception {
Object obj = um.unmarshal(node, type);
return (JAXBElement<?>) obj;
}
// XSLT
/*
public static void transform(URL input, URL xslt, Result result) throws Exception {
TransformerFactory factory = TransformerFactory.newInstance("net.sf.saxon.TransformerFactoryImpl",TransformerFactoryImpl.class.getClassLoader());
Source xsltS = new StreamSource(xslt.openStream());
Transformer transformer = factory.newTransformer(xsltS);
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
InputStream is = input.openStream();
TransformerFactory factory = TransformerFactory.newInstance("net.sf.saxon.TransformerFactoryImpl",TransformerFactoryImpl.class.getClassLoader());
Source inputS = new StreamSource(is);
transformer.transform(inputS, result);
Source xsltS = new StreamSource(xslt.openStream());
Transformer transformer = factory.newTransformer(xsltS);
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(OutputKeys.STANDALONE, "yes");
InputStream is = input.openStream();
Source inputS = new StreamSource(is);
transformer.transform(inputS, result);
}
*/
// XPath
*/
// XPath
/* public static XPath createXPath() throws Exception {
XPathFactory factory = XPathFactory.newInstance(NamespaceConstant.OBJECT_MODEL_SAXON,
"net.sf.saxon.xpath.XPathFactoryImpl", net.sf.saxon.xpath.XPathFactoryImpl.class.getClassLoader());
XPath xpath = factory.newXPath();
return xpath;
return xpath;
}
public static String getStringXPathResult(org.w3c.dom.Node node, String expression) throws Exception {