Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance. Project price only 1 $
You can buy this project and download/modify it how often you want.
/*
*
* *
* * * Copyright 2015 Skymind,Inc.
* * *
* * * 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 org.canova.api.conf;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Serializable;
import java.io.Writer;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import org.canova.api.util.ReflectionUtils;
import org.canova.api.util.StringUtils;
import org.canova.api.writable.Writable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;
/**
* Provides access to configuration parameters.
*
*
Resources
*
*
Configurations are specified by resources. A resource contains a set of
* name/value pairs as XML data. Each resource is named by either a
* String. If named by a String,
* then the classpath is examined for a file with that name. If named by a
* Path, then the local filesystem is examined directly, without
* referring to the classpath.
*
*
Unless explicitly turned off, Hadoop by default specifies two
* resources, loaded in-order from the classpath:
core-site.xml: Site-specific configuration for a given hadoop
* installation.
*
* Applications may add additional resources, which are loaded
* subsequent to these resources in the order they are added.
*
*
Final Parameters
*
*
Configuration parameters may be declared final.
* Once a resource declares a value final, no subsequently-loaded
* resource can alter that value.
* For example, one might define a final parameter with:
*
*
* When conf.get("tempdir") is called, then ${basedir}
* will be resolved to another property in this Configuration, while
* ${user.name} would then ordinarily be resolved to the value
* of the System property with that name.
*/
public class Configuration implements Iterable>,
Writable, Serializable {
private static final Logger LOG =
LoggerFactory.getLogger(Configuration.class);
private boolean quietmode = true;
/**
* List of configuration resources.
*/
private ArrayList
.
* If no such property is specified, or if the specified value is not a valid
* Pattern, then DefaultValue is returned.
*
* @param name property name
* @param defaultValue default value
* @return property value as a compiled Pattern, or defaultValue
*/
public Pattern getPattern(String name, Pattern defaultValue) {
String valString = get(name);
if (null == valString || "".equals(valString)) {
return defaultValue;
}
try {
return Pattern.compile(valString);
} catch (PatternSyntaxException pse) {
LOG.warn("Regular expression '" + valString + "' for property '" +
name + "' not valid. Using default", pse);
return defaultValue;
}
}
/**
* Set the given property to Pattern.
* If the pattern is passed as null, sets the empty pattern which results in
* further calls to getPattern(...) returning the default value.
*
* @param name property name
* @param pattern new value
*/
public void setPattern(String name, Pattern pattern) {
if (null == pattern) {
set(name, null);
} else {
set(name, pattern.pattern());
}
}
@Override
public void write(DataOutput out) throws IOException {
}
@Override
public void readFields(DataInput in) throws IOException {
}
/**
* A class that represents a set of positive integer ranges. It parses
* strings of the form: "2-3,5,7-" where ranges are separated by comma and
* the lower/upper bounds are separated by dash. Either the lower or upper
* bound may be omitted meaning all values up to or over. So the string
* above means 2, 3, 5, and 7, 8, 9, ...
*/
public static class IntegerRanges {
private static class Range {
int start;
int end;
}
List ranges = new ArrayList();
public IntegerRanges() {
}
public IntegerRanges(String newValue) {
StringTokenizer itr = new StringTokenizer(newValue, ",");
while (itr.hasMoreTokens()) {
String rng = itr.nextToken().trim();
String[] parts = rng.split("-", 3);
if (parts.length < 1 || parts.length > 2) {
throw new IllegalArgumentException("integer range badly formed: " +
rng);
}
Range r = new Range();
r.start = convertToInt(parts[0], 0);
if (parts.length == 2) {
r.end = convertToInt(parts[1], Integer.MAX_VALUE);
} else {
r.end = r.start;
}
if (r.start > r.end) {
throw new IllegalArgumentException("IntegerRange from " + r.start +
" to " + r.end + " is invalid");
}
ranges.add(r);
}
}
/**
* Convert a string to an int treating empty strings as the default value.
* @param value the string value
* @param defaultValue the value for if the string is empty
* @return the desired integer
*/
private static int convertToInt(String value, int defaultValue) {
String trim = value.trim();
if (trim.length() == 0) {
return defaultValue;
}
return Integer.parseInt(trim);
}
/**
* Is the given value in the set of ranges
* @param value the value to check
* @return is the value in the ranges?
*/
public boolean isIncluded(int value) {
for(Range r: ranges) {
if (r.start <= value && value <= r.end) {
return true;
}
}
return false;
}
@Override
public String toString() {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Range r: ranges) {
if (first) {
first = false;
} else {
result.append(',');
}
result.append(r.start);
result.append('-');
result.append(r.end);
}
return result.toString();
}
}
/**
* Parse the given attribute as a set of integer ranges
* @param name the attribute name
* @param defaultValue the default value if it is not set
* @return a new set of ranges from the configured value
*/
public IntegerRanges getRange(String name, String defaultValue) {
return new IntegerRanges(get(name, defaultValue));
}
/**
* Get the comma delimited values of the name property as
* a collection of Strings.
* If no such property is specified then empty collection is returned.
*
* This is an optimized version of {@link #getStrings(String)}
*
* @param name property name.
* @return property value as a collection of Strings.
*/
public Collection getStringCollection(String name) {
String valueString = get(name);
return StringUtils.getStringCollection(valueString);
}
/**
* Get the comma delimited values of the name property as
* an array of Strings.
* If no such property is specified then null is returned.
*
* @param name property name.
* @return property value as an array of Strings,
* or null.
*/
public String[] getStrings(String name) {
String valueString = get(name);
return StringUtils.getStrings(valueString);
}
/**
* Get the comma delimited values of the name property as
* an array of Strings.
* If no such property is specified then default value is returned.
*
* @param name property name.
* @param defaultValue The default value
* @return property value as an array of Strings,
* or default value.
*/
public String[] getStrings(String name, String... defaultValue) {
String valueString = get(name);
if (valueString == null) {
return defaultValue;
} else {
return StringUtils.getStrings(valueString);
}
}
/**
* Get the comma delimited values of the name property as
* a collection of Strings, trimmed of the leading and trailing whitespace.
* If no such property is specified then empty Collection is returned.
*
* @param name property name.
* @return property value as a collection of Strings, or empty Collection
*/
public Collection getTrimmedStringCollection(String name) {
String valueString = get(name);
if (null == valueString) {
return Collections.emptyList();
}
return StringUtils.getTrimmedStringCollection(valueString);
}
/**
* Get the comma delimited values of the name property as
* an array of Strings, trimmed of the leading and trailing whitespace.
* If no such property is specified then an empty array is returned.
*
* @param name property name.
* @return property value as an array of trimmed Strings,
* or empty array.
*/
public String[] getTrimmedStrings(String name) {
String valueString = get(name);
return StringUtils.getTrimmedStrings(valueString);
}
/**
* Get the comma delimited values of the name property as
* an array of Strings, trimmed of the leading and trailing whitespace.
* If no such property is specified then default value is returned.
*
* @param name property name.
* @param defaultValue The default value
* @return property value as an array of trimmed Strings,
* or default value.
*/
public String[] getTrimmedStrings(String name, String... defaultValue) {
String valueString = get(name);
if (null == valueString) {
return defaultValue;
} else {
return StringUtils.getTrimmedStrings(valueString);
}
}
/**
* Set the array of string values for the name property as
* as comma delimited values.
*
* @param name property name.
* @param values The values
*/
public void setStrings(String name, String... values) {
set(name, StringUtils.arrayToString(values));
}
/**
* Load a class by name.
*
* @param name the class name.
* @return the class object.
* @throws ClassNotFoundException if the class is not found.
*/
public Class> getClassByName(String name) throws ClassNotFoundException {
Map> map = CACHE_CLASSES.get(classLoader);
if (map == null) {
Map> newMap = new ConcurrentHashMap<>();
map = CACHE_CLASSES.putIfAbsent(classLoader, newMap);
if (map == null) {
map = newMap;
}
}
Class clazz = map.get(name);
if (clazz == null) {
clazz = Class.forName(name, true, classLoader);
if (clazz != null) {
map.put(name, clazz);
}
}
return clazz;
}
/**
* Get the value of the name property
* as an array of Class.
* The value of the property specifies a list of comma separated class names.
* If no such property is specified, then defaultValue is
* returned.
*
* @param name the property name.
* @param defaultValue default value.
* @return property value as a Class[],
* or defaultValue.
*/
public Class>[] getClasses(String name, Class> ... defaultValue) {
String[] classnames = getStrings(name);
if (classnames == null)
return defaultValue;
try {
Class>[] classes = new Class>[classnames.length];
for(int i = 0; i < classnames.length; i++) {
classes[i] = getClassByName(classnames[i]);
}
return classes;
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
/**
* Get the value of the name property as a Class.
* If no such property is specified, then defaultValue is
* returned.
*
* @param name the class name.
* @param defaultValue default value.
* @return property value as a Class,
* or defaultValue.
*/
public Class> getClass(String name, Class> defaultValue) {
String valueString = get(name);
if (valueString == null)
return defaultValue;
try {
return getClassByName(valueString);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
/**
* Get the value of the name property as a Class
* implementing the interface specified by xface.
*
* If no such property is specified, then defaultValue is
* returned.
*
* An exception is thrown if the returned class does not implement the named
* interface.
*
* @param name the class name.
* @param defaultValue default value.
* @param xface the interface implemented by the named class.
* @return property value as a Class,
* or defaultValue.
*/
public Class extends U> getClass(String name,
Class extends U> defaultValue,
Class xface) {
try {
Class> theClass = getClass(name, defaultValue);
if (theClass != null && !xface.isAssignableFrom(theClass))
throw new RuntimeException(theClass+" not "+xface.getName());
else if (theClass != null)
return theClass.asSubclass(xface);
else
return null;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Get the value of the name property as a List
* of objects implementing the interface specified by xface.
*
* An exception is thrown if any of the classes does not exist, or if it does
* not implement the named interface.
*
* @param name the property name.
* @param xface the interface implemented by the classes named by
* name.
* @return a List of objects implementing xface.
*/
@SuppressWarnings("unchecked")
public List getInstances(String name, Class xface) {
List ret = new ArrayList<>();
Class>[] classes = getClasses(name);
for (Class> cl: classes) {
if (!xface.isAssignableFrom(cl)) {
throw new RuntimeException(cl + " does not implement " + xface);
}
ret.add((U) ReflectionUtils.newInstance(cl, this));
}
return ret;
}
/**
* Set the value of the name property to the name of a
* theClass implementing the given interface xface.
*
* An exception is thrown if theClass does not implement the
* interface xface.
*
* @param name property name.
* @param theClass property value.
* @param xface the interface implemented by the named class.
*/
public void setClass(String name, Class> theClass, Class> xface) {
if (!xface.isAssignableFrom(theClass))
throw new RuntimeException(theClass+" not "+xface.getName());
set(name, theClass.getName());
}
/**
* Get a local file name under a directory named in dirsProp with
* the given path. If dirsProp contains multiple directories,
* then one is chosen based on path's hash code. If the selected
* directory does not exist, an attempt is made to create it.
*
* @param dirsProp directory in which to locate the file.
* @param path file-path.
* @return local file under the directory with the given path.
*/
public File getFile(String dirsProp, String path)
throws IOException {
String[] dirs = getStrings(dirsProp);
int hashCode = path.hashCode();
for (int i = 0; i < dirs.length; i++) { // try each local dir
int index = (hashCode+i & Integer.MAX_VALUE) % dirs.length;
File file = new File(dirs[index], path);
File dir = file.getParentFile();
if (dir.exists() || dir.mkdirs()) {
return file;
}
}
throw new IOException("No valid local directories in property: "+dirsProp);
}
/**
* Get the {@link URL} for the named resource.
*
* @param name resource name.
* @return the url for the named resource.
*/
public URL getResource(String name) {
return classLoader.getResource(name);
}
/**
* Get an input stream attached to the configuration resource with the
* given name.
*
* @param name configuration resource name.
* @return an input stream attached to the resource.
*/
public InputStream getConfResourceAsInputStream(String name) {
try {
URL url= getResource(name);
if (url == null) {
LOG.info(name + " not found");
return null;
} else {
LOG.info("found resource " + name + " at " + url);
}
return url.openStream();
} catch (Exception e) {
return null;
}
}
/**
* Get a {@link Reader} attached to the configuration resource with the
* given name.
*
* @param name configuration resource name.
* @return a reader attached to the resource.
*/
public Reader getConfResourceAsReader(String name) {
try {
URL url= getResource(name);
if (url == null) {
LOG.info(name + " not found");
return null;
} else {
LOG.info("found resource " + name + " at " + url);
}
return new InputStreamReader(url.openStream());
} catch (Exception e) {
return null;
}
}
private synchronized Properties getProps() {
if (properties == null) {
properties = new Properties();
loadResources(properties, resources, quietmode);
if (overlay!= null) {
properties.putAll(overlay);
if (storeResource) {
for (Map.Entry