use of com.evolvedbinary.j8fu.function.ConsumerE in project exist by eXist-db.
the class EXIUtils method getInputStream.
protected static InputStream getInputStream(Item item, XQueryContext context) throws XPathException, MalformedURLException, IOException {
switch(item.getType()) {
case Type.ANY_URI:
LOG.debug("Streaming xs:anyURI");
// anyURI provided
String url = item.getStringValue();
// Fix URL
if (url.startsWith("/")) {
url = "xmldb:exist://" + url;
}
return new URL(url).openStream();
case Type.ELEMENT:
case Type.DOCUMENT:
LOG.debug("Streaming element or document node");
/*
if (item instanceof NodeProxy) {
NodeProxy np = (NodeProxy) item;
String url = "xmldb:exist://" + np.getDocument().getBaseURI();
LOG.debug("Document detected, adding URL " + url);
streamSource.setSystemId(url);
}
*/
// Node provided
final ConsumerE<ConsumerE<Serializer, IOException>, IOException> withSerializerFn = fn -> {
final Serializer serializer = context.getBroker().borrowSerializer();
try {
fn.accept(serializer);
} finally {
context.getBroker().returnSerializer(serializer);
}
};
NodeValue node = (NodeValue) item;
return new NodeInputStream(context.getBroker().getBrokerPool(), withSerializerFn, node);
default:
LOG.error("Wrong item type {}", Type.getTypeName(item.getType()));
throw new XPathException("wrong item type " + Type.getTypeName(item.getType()));
}
}
use of com.evolvedbinary.j8fu.function.ConsumerE in project exist by eXist-db.
the class Configurator method configureByCurrent.
private static Configuration configureByCurrent(final Configurable instance, final Configuration configuration) throws ConfigurationException {
final AFields annotatedFields = getConfigurationAnnotatedFields(instance.getClass());
final Set<String> properties = configuration.getProperties();
if (properties.isEmpty()) {
return configuration;
}
// process simple types: String, int, long, boolean
for (final String property : properties) {
final AField annotatedField = annotatedFields.findByAnnotationValue(property);
if (annotatedField == null) {
LOG.warn("Unused property {} @{}", property, configuration.getName());
continue;
}
final Field field = annotatedField.getField();
field.setAccessible(true);
Object value = null;
final Class<?> fieldType = field.getType();
try {
final NewClass newClass = getAnnotation(field, NewClass.class);
if (newClass != null) {
value = org.exist.config.mapper.Constructor.load(newClass, instance, configuration.getConfiguration(property));
} else if (String.class == fieldType) {
// String
value = configuration.getProperty(property);
} else if (int.class == fieldType || Integer.class == fieldType) {
if (field.isAnnotationPresent(ConfigurationFieldSettings.class)) {
final String settings = field.getAnnotation(ConfigurationFieldSettings.class).value();
final SettingKey settingKey = SettingKey.forSettings(settings);
try {
if (settingKey == SettingKey.RADIX) {
final int radix = Integer.parseInt(settingKey.extractValueFromSettings(settings));
value = Integer.valueOf(configuration.getProperty(property), radix);
} else if (settingKey == SettingKey.OCTAL_STRING) {
value = Integer.valueOf(configuration.getProperty(property), 8);
} else {
value = Integer.valueOf(configuration.getProperty(property));
}
} catch (final NumberFormatException e) {
LOG.error(e.getMessage(), e);
// ignore
continue;
}
} else {
value = configuration.getPropertyInteger(property);
}
} else if (long.class == fieldType || Long.class == fieldType) {
// long or Long
value = configuration.getPropertyLong(property);
} else if (boolean.class == fieldType || Boolean.class == fieldType) {
// boolean or Boolean
value = configuration.getPropertyBoolean(property);
} else if (Map.class == fieldType) {
// Map
// skip contents, they will be processed as structure in the next loop on ConfigurationFieldAsElement
value = configuration.getPropertyMap(property);
} else if (List.class == fieldType) {
// List
// skip, will be processed as structure in the next loop on ConfigurationFieldAsElement
// TODO what about simple generic types?
} else if (XmldbURI.class == fieldType) {
// use annotation ConfigurationFieldClassMask
value = org.exist.xmldb.XmldbURI.create(configuration.getProperty(property));
} else {
Configuration conf = configuration.getConfiguration(property);
if (conf == null) {
conf = configuration;
}
value = create(conf, instance, fieldType);
if (value == null) {
value = configuration.getProperty(property);
}
}
if (value != null && !value.equals(field.get(instance))) {
Method method = searchForSetMethod(instance.getClass(), field);
if (method != null) {
try {
method.invoke(instance, value);
} catch (final InvocationTargetException e) {
LOG.warn(e);
method = null;
}
}
if (method == null) {
field.set(instance, value);
}
}
} catch (final IllegalArgumentException iae) {
final String msg = "Configuration error: " + EOL + " config: " + configuration.getName() + EOL + " property: " + property + EOL + " message: " + iae.getMessage();
LOG.error(msg, iae);
throw new ConfigurationException(msg, iae);
// return null; //XXX: throw configuration error
} catch (final IllegalAccessException iae) {
final String msg = "Security error: " + EOL + " config: " + configuration.getName() + EOL + " property: " + property + EOL + " message: " + iae.getMessage();
LOG.error(msg, iae);
throw new ConfigurationException(msg, iae);
// LOG.error("Security error: " + iae.getMessage(), iae);
// return null; //XXX: throw configuration error
}
}
// process simple structures: List
Field field = null;
try {
for (final AField<ConfigurationFieldAsElement> element : annotatedFields.getElements()) {
field = element.getField();
final Class<?> fieldType = field.getType();
if (List.class == fieldType) {
// List
final String confName = element.getAnnotation().value();
field.setAccessible(true);
List list = (List) field.get(instance);
final Optional<String> referenceBy;
List<Configuration> confs;
if (field.isAnnotationPresent(ConfigurationReferenceBy.class)) {
confs = configuration.getConfigurations(confName);
referenceBy = Optional.ofNullable(field.getAnnotation(ConfigurationReferenceBy.class).value());
} else {
confs = configuration.getConfigurations(confName);
referenceBy = Optional.empty();
}
if (list == null) {
// has to be raw type as we don't know what it should be.
list = new ArrayList(confs.size());
field.set(instance, list);
}
if (confs != null) {
// remove & update
// referencedBy -> index
final Map<String, Integer> removed = new HashMap<>();
for (int i = 0; i < list.size(); i++) {
final Object obj = list.get(i);
Configuration current_conf = null;
if (!(obj instanceof Configurable)) {
// TODO Surely we should log a problem here or throw an exception?
list.remove(i);
continue;
} else if (obj instanceof Reference) {
if (!referenceBy.isPresent()) {
LOG.error("illegal design '{}' [{}]", configuration.getName(), field);
list.remove(i);
continue;
} else {
final String name = ((Reference) obj).getName();
// Lookup for new configuration, update if found
final List<Configuration> applicableConfs = filter(confs, conf -> Optional.ofNullable(conf.getPropertyBoolean(referenceBy.get())).map(value -> !value.equals(name)).orElse(true));
if (applicableConfs.size() == confs.size()) {
LOG.debug("Configuration was removed, will attempt to replace object [{}].", obj);
final Field referee = getFieldRecursive(Optional.of(list.get(i).getClass()), referenceBy.get());
if (referee != null) {
referee.setAccessible(true);
removed.put((String) referee.get(list.remove(i)), i);
} else {
LOG.error("Could not lookup referenced field: {} against: {}", referenceBy.get(), list.get(i).getClass().getName());
list.remove(i);
}
} else {
confs = applicableConfs;
}
}
} else {
current_conf = ((Configurable) obj).getConfiguration();
}
if (current_conf == null) {
// skip internal stuff //TODO: static list
if (obj instanceof org.exist.security.internal.RealmImpl) {
continue;
}
if (list.size() > i) {
if (LOG.isDebugEnabled()) {
LOG.debug("No configured instance of [{}], will attempt to replace object...", obj);
}
final Field referee = getFieldRecursive(Optional.of(list.get(i).getClass()), referenceBy.get());
if (referee != null) {
referee.setAccessible(true);
removed.put((String) referee.get(list.remove(i)), i);
} else {
LOG.error("Could not lookup referenced field: {} against: {}", referenceBy.get(), list.get(i).getClass().getName());
list.remove(i);
}
}
continue;
}
// Lookup for new configuration, update if found
final Configuration final_current_conf = current_conf;
final List<Configuration> applicableConfs = filter(confs, conf -> !final_current_conf.equals(conf, referenceBy));
if (applicableConfs.size() == confs.size()) {
LOG.debug("Configuration was removed, will attempt to replace [{}].", obj);
if (list.size() > i) {
Configurable old = ((Configurable) list.remove(i));
String key = old.getConfiguration().getProperty(referenceBy.orElse(Configuration.ID));
if (key != null) {
removed.put(key, i);
}
}
} else {
confs = applicableConfs;
}
}
// create
for (final Configuration conf : confs) {
if (referenceBy.isPresent()) {
final String value = conf.getProperty(referenceBy.get());
if (value != null) {
final Optional<ConsumerE<String, ReflectiveOperationException>> updateFn = updateListFn(instance, confName, removed, value);
if (!updateFn.isPresent()) {
LOG.error("Could not insert configured object");
} else {
try {
updateFn.get().accept(value);
continue;
} catch (final ReflectiveOperationException e) {
LOG.warn("Could not update {} for configuration '{}' referenceBy '{}' for value '{}'", instance.getClass().getName(), conf.getName(), referenceBy.get(), value, e);
}
}
}
} else {
final Type genericType = field.getGenericType();
if (genericType != null) {
if ("java.util.List<java.lang.String>".equals(genericType.toString())) {
final String value = conf.getValue();
if (value != null) {
final Optional<ConsumerE<String, ReflectiveOperationException>> updateFn = updateListFn(instance, confName, removed, value);
if (!updateFn.isPresent()) {
LOG.error("Could not insert configured object");
} else {
try {
updateFn.get().accept(value);
continue;
} catch (final ReflectiveOperationException e) {
LOG.warn("Could not update {} for configuration '{}' for value '{}'", instance.getClass().getName(), conf.getName(), value, e);
}
}
}
}
}
// TODO: AddMethod with Configuration argument
}
final ConfigurationFieldClassMask annotation = getAnnotation(field, ConfigurationFieldClassMask.class);
if (annotation == null) {
final NewClass newClass = getAnnotation(field, NewClass.class);
if (newClass != null) {
final Object obj = org.exist.config.mapper.Constructor.load(newClass, instance, conf);
if (obj != null) {
list.add(obj);
}
} else {
LOG.error("Field '{}' must have '@org.exist.config.annotation.ConfigurationFieldClassMask' annotation [{}], skipping instance creation.", field.getName(), conf.getName());
}
continue;
}
final String id = conf.getProperty(Configuration.ID);
Object[] objs;
if (id == null) {
objs = new Object[] { "", "" };
} else {
objs = new Object[] { id.toLowerCase(), id };
}
final String clazzName = String.format(annotation.value(), objs);
final Configurable obj = create(conf, instance, clazzName);
if (obj != null) {
list.add(obj);
}
}
}
}
}
} catch (final IllegalArgumentException iae) {
final String msg = "Configuration error: " + EOL + " config: " + configuration.getName() + EOL + " field: " + field + EOL + " message: " + iae.getMessage();
LOG.error(msg, iae);
throw new ConfigurationException(msg, iae);
// LOG.error(iae.getMessage(), iae);
// return null;
} catch (final IllegalAccessException iae) {
final String msg = "Security error: " + EOL + " config: " + configuration.getName() + EOL + " field: " + field + EOL + " message: " + iae.getMessage();
LOG.error(msg, iae);
throw new ConfigurationException(msg, iae);
// LOG.error(iae.getMessage(), iae);
// return null;
}
return configuration;
}
use of com.evolvedbinary.j8fu.function.ConsumerE in project exist by eXist-db.
the class Shared method getStreamSource.
public static StreamSource getStreamSource(Item item, XQueryContext context) throws XPathException, IOException {
final StreamSource streamSource = new StreamSource();
if (item.getType() == Type.JAVA_OBJECT) {
LOG.debug("Streaming Java object");
final Object obj = ((JavaObjectValue) item).getObject();
if (!(obj instanceof File)) {
throw new XPathException("Passed java object should be a File");
}
final File inputFile = (File) obj;
final InputStream is = new FileInputStream(inputFile);
streamSource.setInputStream(is);
streamSource.setSystemId(inputFile.toURI().toURL().toString());
} else if (item.getType() == Type.ANY_URI) {
LOG.debug("Streaming xs:anyURI");
// anyURI provided
String url = item.getStringValue();
// Fix URL
if (url.startsWith("/")) {
url = "xmldb:exist://" + url;
}
final InputStream is = new URL(url).openStream();
streamSource.setInputStream(is);
streamSource.setSystemId(url);
} else if (item.getType() == Type.ELEMENT || item.getType() == Type.DOCUMENT) {
LOG.debug("Streaming element or document node");
if (item instanceof NodeProxy) {
final NodeProxy np = (NodeProxy) item;
final String url = "xmldb:exist://" + np.getOwnerDocument().getBaseURI();
LOG.debug("Document detected, adding URL {}", url);
streamSource.setSystemId(url);
}
// Node provided
final DBBroker broker = context.getBroker();
final ConsumerE<ConsumerE<Serializer, IOException>, IOException> withSerializerFn = fn -> {
final Serializer serializer = broker.borrowSerializer();
try {
fn.accept(serializer);
} finally {
broker.returnSerializer(serializer);
}
};
final NodeValue node = (NodeValue) item;
final InputStream is = new NodeInputStream(context.getBroker().getBrokerPool(), withSerializerFn, node);
streamSource.setInputStream(is);
} else if (item.getType() == Type.BASE64_BINARY || item.getType() == Type.HEX_BINARY) {
LOG.debug("Streaming base64 binary");
final BinaryValue binary = (BinaryValue) item;
final byte[] data = binary.toJavaObject(byte[].class);
final InputStream is = new UnsynchronizedByteArrayInputStream(data);
streamSource.setInputStream(is);
if (item instanceof Base64BinaryDocument) {
final Base64BinaryDocument b64doc = (Base64BinaryDocument) item;
final String url = "xmldb:exist://" + b64doc.getUrl();
LOG.debug("Base64BinaryDocument detected, adding URL {}", url);
streamSource.setSystemId(url);
}
} else {
LOG.error("Wrong item type {}", Type.getTypeName(item.getType()));
throw new XPathException("wrong item type " + Type.getTypeName(item.getType()));
}
return streamSource;
}
Aggregations