code
stringlengths 25
201k
| docstring
stringlengths 19
96.2k
| func_name
stringlengths 0
235
| language
stringclasses 1
value | repo
stringlengths 8
51
| path
stringlengths 11
314
| url
stringlengths 62
377
| license
stringclasses 7
values |
|---|---|---|---|---|---|---|---|
public static List<Path> listFiles(Path dir, String glob) throws IOException {
Preconditions.checkArgument(Files.isDirectory(dir), "%s is not a directory", dir);
List<String> globLevels;
if (glob == null || glob.isEmpty()) {
globLevels = Collections.singletonList("*");
} else {
globLevels = Arrays.asList(glob.split("/"));
}
Preconditions.checkState(!globLevels.isEmpty());
List<Path> paths = new ArrayList<>();
paths.add(dir);
for (String globLevel : globLevels) {
List<Path> newPaths = new ArrayList<>();
for (Path existingPath : paths) {
if (Files.isDirectory(existingPath)) {
try (DirectoryStream<Path> stream = Files.newDirectoryStream(existingPath, globLevel)) {
for (Path path : stream) {
if (!path.getFileName().toString().startsWith(".")) {
newPaths.add(path);
}
}
}
}
}
paths = newPaths;
}
Collections.sort(paths);
return paths;
}
|
@param dir directory to list
@param glob glob pattern for files that should be returned, which can span subdirectories
as in patterns like {@code * /*}
@return {@link Path}s, including both files and directories, matching the glob pattern.
No path containing an element whose name starts with "." is returned.
Returned paths are also ordered lexicographically.
@throws IOException if an error occurs while accessing the file system
|
listFiles
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/io/IOUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/io/IOUtils.java
|
Apache-2.0
|
public static void closeQuietly(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
} catch (IOException e) {
log.warn("Unable to close", e);
}
}
}
|
Closes a {@link Closeable} and logs the exception, if any. This is only suitable for closing
objects where a failure to close does not impact correctness -- for example, an input stream
that is already fully read, but not an output stream which may fail when flushing final
output.
@param closeable thing to close
|
closeQuietly
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/io/IOUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/io/IOUtils.java
|
Apache-2.0
|
public static int chooseFreePort() throws IOException {
try (ServerSocket socket = new ServerSocket(0, 0)) {
return socket.getLocalPort();
}
}
|
Binds to a free ephemeral port, and then releases it. The returned port is quite likely
to be free for use after this, but is not entirely guaranteed to be.
@return a (probably) free ephemeral port
@throws IOException if an error occurs while binding to a port
|
chooseFreePort
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/io/IOUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/io/IOUtils.java
|
Apache-2.0
|
public AutoLock autoLock() {
lock();
return this;
}
|
@return this, after calling {@link #lock()}
|
autoLock
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/lang/AutoLock.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/lang/AutoLock.java
|
Apache-2.0
|
public AutoLock autoReadLock() {
return readLock.autoLock();
}
|
@return the {@link ReadWriteLock#readLock()}, locked
|
autoReadLock
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/lang/AutoReadWriteLock.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/lang/AutoReadWriteLock.java
|
Apache-2.0
|
public static <T> Class<T> loadClass(String className) {
try {
@SuppressWarnings("unchecked")
Class<T> theClass = (Class<T>) forName(className);
return theClass;
} catch (ClassNotFoundException cnfe) {
throw new IllegalStateException("No valid " + className + " exists", cnfe);
}
}
|
@param className fully-qualified class name, which should be known to be available
@param <T> expected type of returned {@link Class}
@return {@link Class} for that named class
|
loadClass
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/lang/ClassUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/lang/ClassUtils.java
|
Apache-2.0
|
public static <T> Class<? extends T> loadClass(String className, Class<T> superClass) {
try {
return forName(className).asSubclass(superClass);
} catch (ClassNotFoundException cnfe) {
throw new IllegalStateException("No valid " + superClass + " binding exists", cnfe);
}
}
|
@param className fully-qualified class name, which should be known to be available
@param superClass reference type of returned {@link Class}
@param <T> type of returned {@link Class}
@return {@link Class} for that named class
|
loadClass
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/lang/ClassUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/lang/ClassUtils.java
|
Apache-2.0
|
public static <T> T loadInstanceOf(Class<T> clazz) {
return loadInstanceOf(clazz.getName(), clazz);
}
|
Like {@link #loadInstanceOf(String, Class)} where the reference returned is of the same type as
the class being loaded -- not any supertype.
@param clazz {@link Class} to make an instance of
@param <T> type of returned instance
@return instance of {@code clazz}
|
loadInstanceOf
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/lang/ClassUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/lang/ClassUtils.java
|
Apache-2.0
|
public static <T> T loadInstanceOf(String implClassName, Class<T> superClass) {
return loadInstanceOf(implClassName, superClass, NO_TYPES, NO_ARGS);
}
|
Like {@link #loadInstanceOf(String, Class, Class[], Object[])} for no-arg constructors.
@param implClassName implementation class name
@param superClass superclass or interface that the implementation extends
@param <T> type of returned instance
@return instance of {@code implClassName}
|
loadInstanceOf
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/lang/ClassUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/lang/ClassUtils.java
|
Apache-2.0
|
public static <T> T loadInstanceOf(String implClassName,
Class<T> superClass,
Class<?>[] constructorTypes,
Object[] constructorArgs) {
try {
Class<? extends T> configClass = loadClass(implClassName, superClass);
Constructor<? extends T> constructor = configClass.getConstructor(constructorTypes);
return constructor.newInstance(constructorArgs);
} catch (NoSuchMethodException | InstantiationException | IllegalAccessException e) {
throw new IllegalArgumentException("No valid " + superClass + " binding exists", e);
} catch (InvocationTargetException ite) {
throw new IllegalStateException("Could not instantiate " + superClass + " due to exception",
ite.getCause());
}
}
|
Loads and instantiates a named implementation class, a subclass of a given supertype,
whose constructor takes the given arguments.
@param implClassName implementation class name
@param superClass superclass or interface that the implementation extends
@param constructorTypes argument types of constructor to use
@param constructorArgs actual constructor arguments
@param <T> type of returned instance
@return instance of {@code implClassName}
|
loadInstanceOf
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/lang/ClassUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/lang/ClassUtils.java
|
Apache-2.0
|
public static void doInParallel(int numTasks, Consumer<Integer> task) {
doInParallel(numTasks, numTasks, false, task);
}
|
@param numTasks how many copies of {@code task} to run; all may be run simultaneously,
and a shared thread pool is used
@param task task to execute; takes an {@code Integer} argument that is the index of
the task that has been executed in [0, numTasks)
|
doInParallel
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/lang/ExecUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/lang/ExecUtils.java
|
Apache-2.0
|
public static void doInParallel(int numTasks,
int parallelism,
boolean privatePool,
Consumer<Integer> task) {
Preconditions.checkArgument(numTasks >= 1);
Preconditions.checkArgument(parallelism >= 1);
Objects.requireNonNull(task);
IntStream range = IntStream.range(0, numTasks);
IntStream taskIndices = parallelism > 1 ? range.parallel() : range;
if (parallelism > 1 && privatePool) {
ForkJoinPool pool = new ForkJoinPool(parallelism);
try {
pool.submit(() -> taskIndices.forEach(task::accept)).get();
} catch (InterruptedException e) {
throw new IllegalStateException(e);
} catch (ExecutionException e) {
throw new IllegalStateException(e.getCause());
} finally {
pool.shutdown();
}
} else {
taskIndices.forEach(task::accept);
}
}
|
@param numTasks how many copies of {@code task} to run
@param parallelism maximum how many tasks to run simultaneously
@param privatePool whether to create and use a new private thread pool; otherwise
a shared pool is used. No parallelism or pool is used if {@code parallelism} is 1
@param task task to execute; takes an {@code Integer} argument that is the index of
the task that has been executed in [0, numTasks)
|
doInParallel
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/lang/ExecUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/lang/ExecUtils.java
|
Apache-2.0
|
public static <T,R> R collectInParallel(int numTasks,
int parallelism,
boolean privatePool,
Function<Integer,T> task,
Collector<? super T,?,R> collector) {
Preconditions.checkArgument(numTasks >= 1);
Preconditions.checkArgument(parallelism >= 1);
Objects.requireNonNull(task);
Objects.requireNonNull(collector);
IntStream range = IntStream.range(0, numTasks);
IntStream taskIndices = parallelism > 1 ? range.parallel() : range;
if (parallelism > 1 && privatePool) {
ForkJoinPool pool = new ForkJoinPool(parallelism);
try {
return pool.submit(() -> taskIndices.mapToObj(task::apply).collect(collector)).get();
} catch (InterruptedException e) {
throw new IllegalStateException(e);
} catch (ExecutionException e) {
throw new IllegalStateException(e.getCause());
} finally {
pool.shutdown();
}
} else {
return taskIndices.mapToObj(task::apply).collect(collector);
}
}
|
@param numTasks how many copies of {@code task} to run
@param parallelism maximum how many tasks to run simultaneously
@param privatePool whether to create and use a new private thread pool; otherwise
a shared pool is used. No parallelism or pool is used if {@code parallelism} is 1
@param task task to execute; takes an {@code Integer} argument that is the index of
the task that has been executed in [0, numTasks) and returns some value
@param collector instance used to collect results into the return value
@param <T> type produced by each task
@param <R> type produced by {@code collector} from task results
@return result of collecting individual task results
|
collectInParallel
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/lang/ExecUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/lang/ExecUtils.java
|
Apache-2.0
|
public static void closeAtShutdown(Closeable closeable) {
if (SHUTDOWN_HOOK.addCloseable(closeable)) {
try {
Runtime.getRuntime().addShutdownHook(new Thread(SHUTDOWN_HOOK, "OryxShutdownHookThread"));
} catch (IllegalStateException ise) {
log.warn("Can't close {} at shutdown since shutdown is in progress", closeable);
}
}
}
|
Adds a shutdown hook that tries to call {@link Closeable#close()} on the given argument
at JVM shutdown.
@param closeable thing to close
|
closeAtShutdown
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/lang/JVMUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/lang/JVMUtils.java
|
Apache-2.0
|
public static long getUsedMemory() {
Runtime runtime = Runtime.getRuntime();
return runtime.totalMemory() - runtime.freeMemory();
}
|
@return approximate heap used, in bytes
|
getUsedMemory
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/lang/JVMUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/lang/JVMUtils.java
|
Apache-2.0
|
@Override
public void run() {
triggered = true;
synchronized (closeAtShutdown) {
closeAtShutdown.forEach(IOUtils::closeQuietly);
}
}
|
Intended for use with {@link Runtime#addShutdownHook(Thread)} or similar mechanisms, this is a
{@link Runnable} that is configured with a list of {@link Closeable}s that are to be closed
at shutdown, when its {@link #run()} is called.
|
run
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/lang/OryxShutdownHook.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/lang/OryxShutdownHook.java
|
Apache-2.0
|
public boolean addCloseable(Closeable closeable) {
Objects.requireNonNull(closeable);
Preconditions.checkState(!triggered, "Can't add closeable %s; already shutting down", closeable);
synchronized (closeAtShutdown) {
boolean wasFirst = closeAtShutdown.isEmpty();
closeAtShutdown.push(closeable);
return wasFirst;
}
}
|
@param closeable object to close at shutdown
@return {@code true} iff this is the first object to be registered
@throws IllegalStateException if already shutting down
|
addCloseable
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/lang/OryxShutdownHook.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/lang/OryxShutdownHook.java
|
Apache-2.0
|
@Override
public void increment(double datum) {
increment(datum, 1.0);
}
|
@param datum new datum to add to the mean, with weight 1
|
increment
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/math/DoubleWeightedMean.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/math/DoubleWeightedMean.java
|
Apache-2.0
|
public static Solver getSolver(double[] packed) {
if (packed == null) {
return null;
}
int dim = (int) Math.round((Math.sqrt(8.0 * packed.length + 1.0) - 1.0) / 2.0);
double[][] unpacked = new double[dim][dim];
int offset = 0;
for (int col = 0; col < dim; col++) {
double[] unpackedCol = unpacked[col];
for (int row = col; row < dim; row++) {
unpacked[row][col] = unpackedCol[row] = packed[offset++];
}
}
return getSolver(unpacked);
}
|
@param packed dense lower-triangular matrix A, represented in BLAS packed column-major form
@return solver for the system Ax = b
|
getSolver
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/math/LinearSystemSolver.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/math/LinearSystemSolver.java
|
Apache-2.0
|
static Solver getSolver(double[][] data) {
if (data == null) {
return null;
}
RealMatrix M = new Array2DRowRealMatrix(data, false);
double infNorm = M.getNorm();
double singularityThreshold = infNorm * SINGULARITY_THRESHOLD_RATIO;
RRQRDecomposition decomposition = new RRQRDecomposition(M, singularityThreshold);
DecompositionSolver solver = decomposition.getSolver();
if (solver.isNonSingular()) {
return new Solver(solver);
}
// Otherwise try to report apparent rank
int apparentRank = decomposition.getRank(0.01); // Better value?
log.warn("{} x {} matrix is near-singular (threshold {}). Add more data or decrease the " +
"number of features, to <= about {}",
M.getRowDimension(),
M.getColumnDimension(),
singularityThreshold,
apparentRank);
throw new SingularMatrixSolverException(apparentRank, "Apparent rank: " + apparentRank);
}
|
@param data dense matrix represented in row-major form
@return solver for the system Ax = b
|
getSolver
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/math/LinearSystemSolver.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/math/LinearSystemSolver.java
|
Apache-2.0
|
public int getApparentRank() {
return apparentRank;
}
|
Throws when a system can't be solved because the input matrix is singular or
near-singular. Encapsulates its apparent rank too.
|
getApparentRank
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/math/SingularMatrixSolverException.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/math/SingularMatrixSolverException.java
|
Apache-2.0
|
public static double dot(float[] x, float[] y) {
int length = x.length;
double dot = 0.0;
for (int i = 0; i < length; i++) {
dot += (double) x[i] * y[i];
}
return dot;
}
|
@return dot product of the two given arrays
@param x one array
@param y the other array
|
dot
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/math/VectorMath.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/math/VectorMath.java
|
Apache-2.0
|
public static double cosineSimilarity(float[] x, float[] y, double normY) {
int length = x.length;
double dot = 0.0;
double totalXSq = 0.0;
for (int i = 0; i < length; i++) {
double xi = x[i];
totalXSq += xi * xi;
dot += xi * y[i];
}
return dot / (Math.sqrt(totalXSq) * normY);
}
|
Computes cosine similarity of values in two given arrays, when the norm of one array is
known in advance, which is a not-uncommon case.
@param x one array
@param y the other array
@param normY norm of y
@return cosine similarity = dot(x,y) / (norm(x) * norm(y))
|
cosineSimilarity
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/math/VectorMath.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/math/VectorMath.java
|
Apache-2.0
|
public static double[] transposeTimesSelf(Collection<float[]> M) {
if (M == null || M.isEmpty()) {
return null;
}
int features = M.iterator().next().length;
double[] result = new double[features * (features + 1) / 2];
double[] vectorD = new double[features];
for (float[] vector : M) {
// Unfortunately need to copy into a double[]
for (int i = 0; i < vector.length; i++) {
vectorD[i] = vector[i];
}
blas.dspr("L", features, 1.0, vectorD, 1, result);
}
return result;
}
|
@param M tall, skinny matrix
@return MT * M as a dense lower-triangular matrix, represented in packed row-major form.
|
transposeTimesSelf
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/math/VectorMath.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/math/VectorMath.java
|
Apache-2.0
|
public static double[] parseVector(String[] values) {
double[] doubles = new double[values.length];
for (int i = 0; i < values.length; i++) {
doubles[i] = Double.parseDouble(values[i]);
}
return doubles;
}
|
@param values numeric values as {@link String}s
@return values parsed as {@code double[]}
|
parseVector
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/math/VectorMath.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/math/VectorMath.java
|
Apache-2.0
|
public static float[] randomVectorF(int features, RandomGenerator random) {
float[] vector = new float[features];
for (int i = 0; i < features; i++) {
vector[i] = (float) random.nextGaussian();
}
return vector;
}
|
@param features dimension of vector
@param random random number generator
@return vector whose direction from the origin is chosen uniformly at random, but which is not normalized
|
randomVectorF
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/math/VectorMath.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/math/VectorMath.java
|
Apache-2.0
|
public static PMML buildSkeletonPMML() {
String formattedDate =
new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZZ", Locale.ENGLISH).format(new Date());
Header header = new Header()
.setTimestamp(new Timestamp().addContent(formattedDate))
.setApplication(new Application("Oryx"));
return new PMML(VERSION, header, null);
}
|
@return {@link PMML} with common {@link Header} fields like {@link Application},
{@link Timestamp}, and version filled out
|
buildSkeletonPMML
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/pmml/PMMLUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/pmml/PMMLUtils.java
|
Apache-2.0
|
public static void write(PMML pmml, Path path) throws IOException {
try (OutputStream out = Files.newOutputStream(path)) {
write(pmml, out);
}
}
|
@param pmml {@link PMML} model to write
@param path file to write the model to
@throws IOException if an error occurs while writing the model to storage
|
write
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/pmml/PMMLUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/pmml/PMMLUtils.java
|
Apache-2.0
|
public static void write(PMML pmml, OutputStream out) throws IOException {
try {
PMMLUtil.marshal(pmml, out);
} catch (JAXBException e) {
throw new IOException(e);
}
}
|
@param pmml {@link PMML} model to write
@param out stream to write the model to
@throws IOException if an error occurs while writing the model to storage
|
write
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/pmml/PMMLUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/pmml/PMMLUtils.java
|
Apache-2.0
|
public static PMML read(Path path) throws IOException {
try (InputStream in = Files.newInputStream(path)) {
return read(in);
}
}
|
@param path file to read PMML from
@return {@link PMML} model file from path
@throws IOException if an error occurs while reading the model from storage
|
read
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/pmml/PMMLUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/pmml/PMMLUtils.java
|
Apache-2.0
|
public static PMML read(InputStream in) throws IOException {
try {
return PMMLUtil.unmarshal(in);
} catch (JAXBException | SAXException e) {
throw new IOException(e);
}
}
|
@param in stream to read PMML from
@return {@link PMML} model file from stream
@throws IOException if an error occurs while reading the model from the stream
|
read
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/pmml/PMMLUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/pmml/PMMLUtils.java
|
Apache-2.0
|
public static String toString(PMML pmml) {
try (StringWriter out = new StringWriter()) {
// v JAXBUtil.marshalPMML but need to set compact, non-pretty output
Marshaller marshaller = JAXBUtil.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.FALSE);
marshaller.marshal(pmml, new StreamResult(out));
return out.toString();
} catch (JAXBException | IOException e) {
// IOException should not be possible; JAXBException would only happen with XML
// config problems.
throw new IllegalStateException(e);
}
}
|
@param pmml model
@return model serialized as an XML document as a string
|
toString
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/pmml/PMMLUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/pmml/PMMLUtils.java
|
Apache-2.0
|
public static PMML fromString(String pmmlString) throws IOException {
try {
SAXSource transformed = SAXUtil.createFilteredSource(
new ByteArrayInputStream(pmmlString.getBytes(StandardCharsets.UTF_8)),
new ImportFilter());
return JAXBUtil.unmarshalPMML(transformed);
} catch (JAXBException | SAXException e) {
throw new IOException(e);
}
}
|
@param pmmlString PMML model encoded as an XML doc in a string
@return {@link PMML} object representing the model
@throws IOException if XML can't be unserialized
|
fromString
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/pmml/PMMLUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/pmml/PMMLUtils.java
|
Apache-2.0
|
private static long getTestSeed() {
String seedString = System.getProperty("oryx.test.seed", "1234567890123456789");
try {
return Long.parseLong(seedString);
} catch (NumberFormatException nfe) {
return Long.parseLong(seedString, 16);
}
}
|
Manages random number generation. Allows resetting RNGs to a known state for testing.
|
getTestSeed
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/random/RandomManager.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/random/RandomManager.java
|
Apache-2.0
|
public static RandomGenerator getRandom(long seed) {
// Don't track these or use the test seed as the caller has manually specified
// the seeding behavior
return new Well19937c(seed);
}
|
@param seed explicit seed for random number generator
@return a new, seeded {@link RandomGenerator}
|
getRandom
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/random/RandomManager.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/random/RandomManager.java
|
Apache-2.0
|
public static void useTestSeed() {
useTestSeed = true;
Collection<RandomGenerator> instances = INSTANCES.get();
if (instances != null) {
synchronized (instances) {
instances.forEach(random -> random.setSeed(TEST_SEED));
instances.clear();
}
INSTANCES.clear();
}
}
|
<em>Only call in test code.</em> Causes all known instances of {@link RandomGenerator},
and future ones, to be started from a fixed seed. This is useful for making
tests deterministic.
|
useTestSeed
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/random/RandomManager.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/random/RandomManager.java
|
Apache-2.0
|
public static Config getDefault() {
return DEFAULT_CONFIG;
}
|
Returns the default {@code Config} object for this app, based on config in the JAR file
or otherwise specified to the library.
@return default configuration
|
getDefault
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/settings/ConfigUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/settings/ConfigUtils.java
|
Apache-2.0
|
public static Config overlayOn(Map<String,?> overlay, Config underlying) {
StringBuilder configFileString = new StringBuilder();
overlay.forEach((k, v) -> configFileString.append(k).append('=').append(v).append('\n'));
String configFile = configFileString.toString();
log.debug("Overlaid config: \n{}", configFile);
return ConfigFactory.parseString(configFile).resolve().withFallback(underlying);
}
|
@param overlay map of key-value pairs to add to default config. The map is converted
to a string representation, as it were from a config file, and parsed accordingly.
@param underlying underlying config to overlay new settings on top of
@return default config but with key-value pairs added
|
overlayOn
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/settings/ConfigUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/settings/ConfigUtils.java
|
Apache-2.0
|
public static void set(Map<String,Object> overlay, String key, Path path) throws IOException {
Path finalPath = Files.exists(path, LinkOption.NOFOLLOW_LINKS) ?
path.toRealPath(LinkOption.NOFOLLOW_LINKS) :
path;
overlay.put(key, "\"" + finalPath.toUri() + "\"");
}
|
Helper to set a {@link Path} value correctly for use with {@link #overlayOn(Map,Config)}.
@param overlay key-value pairs to overlay on a {@link Config}
@param key key to set
@param path {@link Path} value
@throws IOException if {@link Path} can't be made canonical
|
set
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/settings/ConfigUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/settings/ConfigUtils.java
|
Apache-2.0
|
public static String serialize(Config config) {
return config.root().withOnlyKey("oryx").render(ConfigRenderOptions.concise());
}
|
@param config {@link Config} to serialize to a String
@return JSON-like representation of properties in the configuration, excluding those
inherited from the local JVM environment
|
serialize
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/settings/ConfigUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/settings/ConfigUtils.java
|
Apache-2.0
|
public static Config deserialize(String serialized) {
return ConfigFactory.parseString(serialized).resolve().withFallback(DEFAULT_CONFIG);
}
|
@param serialized serialized form of configuration as JSON-like data
@return {@link Config} from the serialized config
|
deserialize
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/settings/ConfigUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/settings/ConfigUtils.java
|
Apache-2.0
|
public static Properties keyValueToProperties(Object... keyValues) {
Preconditions.checkArgument(keyValues.length % 2 == 0);
Properties properties = new Properties();
for (int i = 0; i < keyValues.length - 1; i += 2) { // length must be even
properties.setProperty(keyValues[i].toString(), keyValues[i+1].toString());
}
return properties;
}
|
@param keyValues a sequence key1, value1, key2, value2, ... where the {@link #toString()}
of successive pairs are interpreted as key-value pairs
@return a {@link Properties} containing these key-value pairs
|
keyValueToProperties
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/settings/ConfigUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/settings/ConfigUtils.java
|
Apache-2.0
|
public static String joinPMMLDelimited(Iterable<?> elements) {
String rawResult = doJoinDelimited(elements, formatForDelimiter(' '));
// Must change "" into \"
return TWO_DOUBLE_QUOTE_ESC.matcher(rawResult).replaceAll(SLASH_QUOTE_ESC);
}
|
@param elements values to join by space to make one line of text
@return one line of text, formatted according to PMML quoting rules
(\" instead of "" for escaping quotes; ignore space surrounding values
|
joinPMMLDelimited
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/text/TextUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/text/TextUtils.java
|
Apache-2.0
|
public static String joinJSON(Iterable<?> elements) {
try {
return MAPPER.writeValueAsString(elements);
} catch (JsonProcessingException e) {
throw new IllegalArgumentException(e);
}
}
|
@param elements elements to be joined in a JSON string. May be any objects.
@return JSON representation of the list of objects
|
joinJSON
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/text/TextUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/text/TextUtils.java
|
Apache-2.0
|
public static <T> T readJSON(String json, Class<T> clazz) {
try {
return MAPPER.readValue(json, clazz);
} catch (IOException e) {
throw new IllegalStateException(e);
}
}
|
@param json JSON string
@param clazz Java type to interpret as
@param <T> type that should be parsed from JSON and returned
@return the JSON string, parsed into the given type
|
readJSON
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/text/TextUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/text/TextUtils.java
|
Apache-2.0
|
public static <T> T convertViaJSON(Object value, Class<T> clazz) {
return MAPPER.convertValue(value, clazz);
}
|
@param value value to convert
@param clazz desired type to interpret as
@param <T> type that should be parsed from JSON and returned
@return the given value, reinterpreted as the given type, as if serialized/deserialized
via JSON to perform the conversion
|
convertViaJSON
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/main/java/com/cloudera/oryx/common/text/TextUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/main/java/com/cloudera/oryx/common/text/TextUtils.java
|
Apache-2.0
|
public static void checkDiscreteProbability(int value, IntegerDistribution dist) {
double probAsExtreme = value <= dist.getNumericalMean() ?
dist.cumulativeProbability(value) :
(1.0 - dist.cumulativeProbability(value - 1));
assertTrue(value + " is not likely (" + probAsExtreme + " ) to differ from expected value " +
dist.getNumericalMean() + " by chance",
probAsExtreme >= 0.001);
}
|
Asserts that the probability of sampling a value as or more extreme than the given value,
from the given discrete distribution, is at least 0.001.
@param value sample value
@param dist discrete distribution
|
checkDiscreteProbability
|
java
|
OryxProject/oryx
|
framework/oryx-common/src/test/java/com/cloudera/oryx/common/OryxTest.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-common/src/test/java/com/cloudera/oryx/common/OryxTest.java
|
Apache-2.0
|
@Override
public void call(T ignored) throws IOException {
Path dataDirPath = new Path(dataDirString + "/*");
FileSystem fs = FileSystem.get(dataDirPath.toUri(), hadoopConf);
FileStatus[] inputPathStatuses = fs.globStatus(dataDirPath);
if (inputPathStatuses != null) {
long oldestTimeAllowed =
System.currentTimeMillis() - TimeUnit.MILLISECONDS.convert(maxAgeHours, TimeUnit.HOURS);
Arrays.stream(inputPathStatuses).filter(FileStatus::isDirectory).map(FileStatus::getPath).
filter(subdir -> {
Matcher m = dirTimestampPattern.matcher(subdir.getName());
return m.find() && Long.parseLong(m.group(1)) < oldestTimeAllowed;
}).forEach(subdir -> {
log.info("Deleting old data at {}", subdir);
try {
fs.delete(subdir, true);
} catch (IOException e) {
log.warn("Unable to delete {}; continuing", subdir, e);
}
});
}
}
|
Function that deletes old data, if applicable, at each batch interval.
@param <T> unused
|
call
|
java
|
OryxProject/oryx
|
framework/oryx-lambda/src/main/java/com/cloudera/oryx/lambda/DeleteOldDataFn.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-lambda/src/main/java/com/cloudera/oryx/lambda/DeleteOldDataFn.java
|
Apache-2.0
|
public static void closeAtShutdown(Closeable closeable) {
if (SHUTDOWN_HOOK.addCloseable(closeable)) {
try {
// Spark uses SHUTDOWN_HOOK_PRIORITY + 30; this tries to execute earlier
ShutdownHookManager.get().addShutdownHook(SHUTDOWN_HOOK, FileSystem.SHUTDOWN_HOOK_PRIORITY + 40);
} catch (IllegalStateException ise) {
log.warn("Can't close {} at shutdown since shutdown is in progress", closeable);
}
}
}
|
Adds a shutdown hook that tries to call {@link Closeable#close()} on the given argument
at JVM shutdown. This integrates with Hadoop's {@link ShutdownHookManager} in order to
better interact with Spark's usage of the same.
@param closeable thing to close
|
closeAtShutdown
|
java
|
OryxProject/oryx
|
framework/oryx-lambda/src/main/java/com/cloudera/oryx/lambda/HadoopUtils.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-lambda/src/main/java/com/cloudera/oryx/lambda/HadoopUtils.java
|
Apache-2.0
|
@Override
public void call(JavaRDD<T> javaRDD) {
OffsetRange[] ranges = ((HasOffsetRanges) javaRDD.rdd()).offsetRanges();
Map<Pair<String,Integer>,Long> newOffsets = new HashMap<>(ranges.length);
for (OffsetRange range : ranges) {
newOffsets.put(new Pair<>(range.topic(), range.partition()), range.untilOffset());
}
log.info("Updating offsets: {}", newOffsets);
KafkaUtils.setOffsets(inputTopicLockMaster, group, newOffsets);
}
|
@param javaRDD RDD whose underlying RDD must be an instance of {@code HasOffsetRanges},
such as {@code KafkaRDD}
|
call
|
java
|
OryxProject/oryx
|
framework/oryx-lambda/src/main/java/com/cloudera/oryx/lambda/UpdateOffsetsFn.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-lambda/src/main/java/com/cloudera/oryx/lambda/UpdateOffsetsFn.java
|
Apache-2.0
|
@Override
public void call(JavaPairRDD<K,M> newData, Time timestamp)
throws IOException, InterruptedException {
if (newData.isEmpty()) {
log.info("No data in current generation's RDD; nothing to do");
return;
}
log.info("Beginning update at {}", timestamp);
Configuration hadoopConf = sparkContext.hadoopConfiguration();
if (hadoopConf.getResource("core-site.xml") == null) {
log.warn("Hadoop config like core-site.xml was not found; " +
"is the Hadoop config directory on the classpath?");
}
JavaPairRDD<K,M> pastData;
Path inputPathPattern = new Path(dataDirString + "/*/part-*");
FileSystem fs = FileSystem.get(inputPathPattern.toUri(), hadoopConf);
FileStatus[] inputPathStatuses = fs.globStatus(inputPathPattern);
if (inputPathStatuses == null || inputPathStatuses.length == 0) {
log.info("No past data at path(s) {}", inputPathPattern);
pastData = null;
} else {
log.info("Found past data at path(s) like {}", inputPathStatuses[0].getPath());
Configuration updatedConf = new Configuration(hadoopConf);
updatedConf.set(FileInputFormat.INPUT_DIR, joinFSPaths(fs, inputPathStatuses));
@SuppressWarnings("unchecked")
JavaPairRDD<Writable,Writable> pastWritableData = (JavaPairRDD<Writable,Writable>)
sparkContext.newAPIHadoopRDD(updatedConf,
SequenceFileInputFormat.class,
keyWritableClass,
messageWritableClass);
pastData = pastWritableData.mapToPair(
new WritableToValueFunction<>(keyClass,
messageClass,
keyWritableClass,
messageWritableClass));
}
if (updateTopic == null || updateBroker == null) {
log.info("Not producing updates to update topic since none was configured");
updateInstance.runUpdate(sparkContext,
timestamp.milliseconds(),
newData,
pastData,
modelDirString,
null);
} else {
// This TopicProducer should not be async; sends one big model generally and
// needs to occur before other updates reliably rather than be buffered
try (TopicProducer<String,U> producer =
new TopicProducerImpl<>(updateBroker, updateTopic, false)) {
updateInstance.runUpdate(sparkContext,
timestamp.milliseconds(),
newData,
pastData,
modelDirString,
producer);
}
}
}
|
Framework for executing the batch layer update, and storing data to persistent storage,
in the context of a streaming framework.
@param <K> type of key read from input topic
@param <M> type of message read from input topic
@param <U> type of model message written
|
call
|
java
|
OryxProject/oryx
|
framework/oryx-lambda/src/main/java/com/cloudera/oryx/lambda/batch/BatchUpdateFunction.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-lambda/src/main/java/com/cloudera/oryx/lambda/batch/BatchUpdateFunction.java
|
Apache-2.0
|
@Override
public void call(JavaPairRDD<K,M> rdd, Time time) throws IOException {
if (rdd.isEmpty()) {
log.info("RDD was empty, not saving to HDFS");
} else {
String file = prefix + '-' + time.milliseconds() + '.' + suffix;
Path path = new Path(file);
FileSystem fs = FileSystem.get(path.toUri(), hadoopConf);
if (fs.exists(path)) {
log.warn("Saved data already existed, possibly from a failed job. Deleting {}", path);
fs.delete(path, true);
}
log.info("Saving RDD to HDFS at {}", file);
rdd.mapToPair(
new ValueToWritableFunction<>(keyClass, messageClass, keyWritableClass, messageWritableClass)
).saveAsNewAPIHadoopFile(
file,
keyWritableClass,
messageWritableClass,
SequenceFileOutputFormat.class,
hadoopConf);
}
}
|
Function that saves RDDs to HDFS -- only if they're non empty, to prevent creation
of many small empty files if data is infrequent but the model interval is short.
|
call
|
java
|
OryxProject/oryx
|
framework/oryx-lambda/src/main/java/com/cloudera/oryx/lambda/batch/SaveToHDFSFunction.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-lambda/src/main/java/com/cloudera/oryx/lambda/batch/SaveToHDFSFunction.java
|
Apache-2.0
|
@Override
public void runUpdate(JavaSparkContext sparkContext,
long timestamp,
JavaPairRDD<K,M> newData,
JavaPairRDD<K,M> pastData,
String modelDirString,
TopicProducer<String,U> modelUpdateTopic) {
scalaUpdate.configureUpdate(sparkContext.sc(),
timestamp,
newData.rdd(),
pastData == null ? null : pastData.rdd(),
modelDirString,
modelUpdateTopic);
}
|
Adapts a {@link ScalaBatchLayerUpdate} to be a Java {@link BatchLayerUpdate}.
@param <K> type of key read from input topic
@param <M> type of message read from input topic
@param <U> type of model message written
|
runUpdate
|
java
|
OryxProject/oryx
|
framework/oryx-lambda/src/main/java/com/cloudera/oryx/lambda/batch/ScalaBatchLayerUpdateAdapter.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-lambda/src/main/java/com/cloudera/oryx/lambda/batch/ScalaBatchLayerUpdateAdapter.java
|
Apache-2.0
|
@Override
public void call(JavaPairRDD<K,M> newData) throws IOException {
if (newData.isEmpty()) {
log.debug("RDD was empty");
} else {
Iterable<U> updates = modelManager.buildUpdates(newData);
if (updates != null) {
try (TopicProducer<String, U> producer = new TopicProducerImpl<>(updateBroker, updateTopic, true)) {
updates.forEach(update -> producer.send("UP", update));
}
}
}
}
|
Main Spark Streaming function for the speed layer that collects and publishes update to
a Kafka topic.
@param <K> type of key read from input topic
@param <M> type of message read from input topic
@param <U> type of update message read/written
|
call
|
java
|
OryxProject/oryx
|
framework/oryx-lambda/src/main/java/com/cloudera/oryx/lambda/speed/SpeedLayerUpdate.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-lambda/src/main/java/com/cloudera/oryx/lambda/speed/SpeedLayerUpdate.java
|
Apache-2.0
|
@Test
public void testDeleteOldData() throws Exception {
Path tempDir = getTempDir();
Path dataDir = tempDir.resolve("data");
Path modelDir = tempDir.resolve("model");
Map<String,Object> overlayConfig = new HashMap<>();
overlayConfig.put("oryx.batch.update-class", MockBatchUpdate.class.getName());
ConfigUtils.set(overlayConfig, "oryx.batch.storage.data-dir", dataDir);
ConfigUtils.set(overlayConfig, "oryx.batch.storage.model-dir", modelDir);
overlayConfig.put("oryx.batch.storage.max-age-data-hours", 0);
overlayConfig.put("oryx.batch.storage.max-age-model-hours", 0);
overlayConfig.put("oryx.batch.streaming.generation-interval-sec", GEN_INTERVAL_SEC);
Config config = ConfigUtils.overlayOn(overlayConfig, getConfig());
startMessaging();
startServerProduceConsumeTopics(config, DATA_TO_WRITE, WRITE_INTERVAL_MSEC);
assertEquals(0, IOUtils.listFiles(dataDir, "*").size());
assertEquals(0, IOUtils.listFiles(modelDir, "*").size());
}
|
Tests the effect of {@link com.cloudera.oryx.lambda.DeleteOldDataFn}.
|
testDeleteOldData
|
java
|
OryxProject/oryx
|
framework/oryx-lambda/src/test/java/com/cloudera/oryx/lambda/batch/DeleteOldDataIT.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-lambda/src/test/java/com/cloudera/oryx/lambda/batch/DeleteOldDataIT.java
|
Apache-2.0
|
@Override
public Response toResponse(OryxServingException exception) {
Response.ResponseBuilder response = Response.status(exception.getStatusCode());
if (exception.getMessage() != null) {
response = response.entity(exception.getMessage());
}
return response.build();
}
|
Maps {@link OryxServingException} types to an HTTP {@link Response}.
|
toResponse
|
java
|
OryxProject/oryx
|
framework/oryx-lambda-serving/src/main/java/com/cloudera/oryx/lambda/serving/OryxExceptionMapper.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-lambda-serving/src/main/java/com/cloudera/oryx/lambda/serving/OryxExceptionMapper.java
|
Apache-2.0
|
public synchronized void start() throws IOException {
if (id != null) {
log.info("Starting Serving Layer {}", id);
}
Preconditions.checkState(tomcat == null);
// Has to happen very early before Tomcat init:
System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true");
noSuchBaseDir = Files.createTempDirectory("Oryx");
noSuchBaseDir.toFile().deleteOnExit();
Tomcat tomcat = new Tomcat();
Connector connector = makeConnector();
configureTomcat(tomcat, connector);
configureEngine(tomcat.getEngine());
configureServer(tomcat.getServer());
configureHost(tomcat.getHost());
makeContext(tomcat, noSuchBaseDir);
try {
tomcat.start();
} catch (LifecycleException le) {
throw new IOException(le);
}
this.tomcat = tomcat;
}
|
Creates a new instance with the given configuration.
@param config configuration for the serving layer
|
start
|
java
|
OryxProject/oryx
|
framework/oryx-lambda-serving/src/main/java/com/cloudera/oryx/lambda/serving/ServingLayer.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-lambda-serving/src/main/java/com/cloudera/oryx/lambda/serving/ServingLayer.java
|
Apache-2.0
|
public void await() {
Server server;
synchronized (this) {
server = tomcat.getServer();
}
server.await(); // Can't do this with lock held
}
|
Blocks and waits until the server shuts down.
|
await
|
java
|
OryxProject/oryx
|
framework/oryx-lambda-serving/src/main/java/com/cloudera/oryx/lambda/serving/ServingLayer.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-lambda-serving/src/main/java/com/cloudera/oryx/lambda/serving/ServingLayer.java
|
Apache-2.0
|
protected final double getTestFraction() {
return testFraction;
}
|
A specialization of {@link BatchLayerUpdate} for machine learning-oriented
update processes. This implementation contains the framework for test/train split
for example, parameter optimization, and so on. Subclasses instead implement
methods like {@link #buildModel(JavaSparkContext,JavaRDD,List,Path)} to create a PMML model and
{@link #evaluate(JavaSparkContext,PMML,Path,JavaRDD,JavaRDD)} to evaluate a model from
held-out test data.
@param <M> type of message to read from the input topic
|
getTestFraction
|
java
|
OryxProject/oryx
|
framework/oryx-ml/src/main/java/com/cloudera/oryx/ml/MLUpdate.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-ml/src/main/java/com/cloudera/oryx/ml/MLUpdate.java
|
Apache-2.0
|
public boolean canPublishAdditionalModelData() {
return false;
}
|
@return {@code true} iff additional updates must be published along with the model; if
{@link #publishAdditionalModelData(JavaSparkContext, PMML, JavaRDD, JavaRDD, Path, TopicProducer)} must
be called. This is only applicable for special model types.
|
canPublishAdditionalModelData
|
java
|
OryxProject/oryx
|
framework/oryx-ml/src/main/java/com/cloudera/oryx/ml/MLUpdate.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-ml/src/main/java/com/cloudera/oryx/ml/MLUpdate.java
|
Apache-2.0
|
public void publishAdditionalModelData(JavaSparkContext sparkContext,
PMML pmml,
JavaRDD<M> newData,
JavaRDD<M> pastData,
Path modelParentPath,
TopicProducer<String, String> modelUpdateTopic) {
// Do nothing by default
}
|
Optionally, publish additional model-related information to the update topic,
after the model has been written. This is needed only in specific cases, like the
ALS algorithm, where the model serialization in PMML can't contain all of the info.
@param sparkContext active Spark Context
@param pmml model for which extra data should be written
@param newData data that has arrived in current interval
@param pastData all previously-known data (may be {@code null})
@param modelParentPath directory containing model files, if applicable
@param modelUpdateTopic message topic to write to
|
publishAdditionalModelData
|
java
|
OryxProject/oryx
|
framework/oryx-ml/src/main/java/com/cloudera/oryx/ml/MLUpdate.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-ml/src/main/java/com/cloudera/oryx/ml/MLUpdate.java
|
Apache-2.0
|
protected Pair<JavaRDD<M>,JavaRDD<M>> splitNewDataToTrainTest(JavaRDD<M> newData) {
RDD<M>[] testTrainRDDs = newData.rdd().randomSplit(
new double[]{1.0 - testFraction, testFraction},
RandomManager.getRandom().nextLong());
return new Pair<>(newData.wrapRDD(testTrainRDDs[0]),
newData.wrapRDD(testTrainRDDs[1]));
}
|
Default implementation which randomly splits new data into train/test sets.
This handles the case where {@link #getTestFraction()} is not 0 or 1.
@param newData data that has arrived in the current input batch
@return a {@link Pair} of train, test {@link RDD}s.
|
splitNewDataToTrainTest
|
java
|
OryxProject/oryx
|
framework/oryx-ml/src/main/java/com/cloudera/oryx/ml/MLUpdate.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-ml/src/main/java/com/cloudera/oryx/ml/MLUpdate.java
|
Apache-2.0
|
@Override
public Double getRandomValue(RandomDataGenerator rdg) {
return rdg.nextGaussian(around, step);
}
|
@param rdg random number generator to use
@return a hyperparameter value chosen from Normal(around, step)
|
getRandomValue
|
java
|
OryxProject/oryx
|
framework/oryx-ml/src/main/java/com/cloudera/oryx/ml/param/ContinuousAround.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-ml/src/main/java/com/cloudera/oryx/ml/param/ContinuousAround.java
|
Apache-2.0
|
@Override
public Integer getRandomValue(RandomDataGenerator rdg) {
return (int) Math.round(rdg.nextGaussian(around, step));
}
|
@param rdg random number generator to use
@return a hyperparameter value chosen from Normal(around, step) and rounded to the nearest integer
|
getRandomValue
|
java
|
OryxProject/oryx
|
framework/oryx-ml/src/main/java/com/cloudera/oryx/ml/param/DiscreteAround.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-ml/src/main/java/com/cloudera/oryx/ml/param/DiscreteAround.java
|
Apache-2.0
|
static List<List<?>> chooseHyperParameterCombos(List<HyperParamValues<?>> ranges, int howMany) {
// Put some reasonable upper limit on the number of combos
Preconditions.checkArgument(howMany > 0 && howMany <= MAX_COMBOS);
int numParams = ranges.size();
int perParam = chooseValuesPerHyperParam(ranges, howMany);
if (numParams == 0 || perParam == 0) {
return Collections.singletonList(Collections.emptyList());
}
int howManyCombos = 1;
List<List<?>> paramRanges = new ArrayList<>(numParams);
for (HyperParamValues<?> range : ranges) {
List<?> values = range.getTrialValues(perParam);
paramRanges.add(values);
howManyCombos *= values.size();
}
List<List<?>> allCombinations = new ArrayList<>(howManyCombos);
for (int combo = 0; combo < howManyCombos; combo++) {
List<Object> combination = new ArrayList<>(numParams);
for (int param = 0; param < numParams; param++) {
int whichValueToTry = combo;
for (int i = 0; i < param; i++) {
whichValueToTry /= paramRanges.get(i).size();
}
whichValueToTry %= paramRanges.get(param).size();
combination.add(paramRanges.get(param).get(whichValueToTry));
}
allCombinations.add(combination);
}
if (howMany >= howManyCombos) {
Collections.shuffle(allCombinations);
return allCombinations;
}
RandomDataGenerator rdg = new RandomDataGenerator(RandomManager.getRandom());
int[] indices = rdg.nextPermutation(howManyCombos, howMany);
List<List<?>> result = new ArrayList<>(indices.length);
for (int i = 0; i < indices.length; i++) {
result.add(allCombinations.get(i));
}
Collections.shuffle(result);
return result;
}
|
@param ranges ranges of hyperparameters to try, one per hyperparameters
@param howMany how many combinations of hyperparameters to return
@return combinations of concrete hyperparameter values. For example, for 5 parameters each
with 3 values to try, the total number of combinations returned could be up to pow(3,5)
or 243. The number could be less if the ranges do not actually have that many distinct
values. If {@code howMany} is smaller than the total number of combinations, a random
subset of all combinations are returned. The order is shuffled randomly. If no parameters
are specified or {@code perParam} is 0, a single empty combination is returned.
|
chooseHyperParameterCombos
|
java
|
OryxProject/oryx
|
framework/oryx-ml/src/main/java/com/cloudera/oryx/ml/param/GridSearch.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-ml/src/main/java/com/cloudera/oryx/ml/param/GridSearch.java
|
Apache-2.0
|
private static int chooseValuesPerHyperParam(List<? extends HyperParamValues<?>> ranges, int candidates) {
if (ranges.isEmpty()) {
return 0;
}
int valuesPerHyperParam = 0;
long lastTotal;
long total = 0;
do {
valuesPerHyperParam++;
lastTotal = total;
total = 1;
for (HyperParamValues<?> range : ranges) {
total *= Math.min(valuesPerHyperParam, range.getNumDistinctValues());
}
// Keep going until values-per-hyperparam is enough to generate enough candidates,
// but stop early if it won't increase anyway because there aren't enough distinct values
} while (total < candidates && total > lastTotal);
return valuesPerHyperParam;
}
|
@param ranges ranges of hyperparameters to try, one per hyperparameters
@param candidates minimum number of candidates to be built
@return smallest value such that picking that many values from each hyperparameter would result
in at least the requested minimum number of candidate combinations
|
chooseValuesPerHyperParam
|
java
|
OryxProject/oryx
|
framework/oryx-ml/src/main/java/com/cloudera/oryx/ml/param/GridSearch.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-ml/src/main/java/com/cloudera/oryx/ml/param/GridSearch.java
|
Apache-2.0
|
static List<List<?>> chooseHyperParameterCombos(Collection<? extends HyperParamValues<?>> ranges, int howMany) {
Preconditions.checkArgument(howMany > 0);
int numParams = ranges.size();
if (numParams == 0) {
return Collections.singletonList(Collections.emptyList());
}
RandomDataGenerator rdg = new RandomDataGenerator(RandomManager.getRandom());
List<List<?>> allCombinations = new ArrayList<>(howMany);
for (int i = 0; i < howMany; i++) {
List<Object> combination = new ArrayList<>(numParams);
for (HyperParamValues<?> range : ranges) {
combination.add(range.getRandomValue(rdg));
}
allCombinations.add(combination);
}
return allCombinations;
}
|
@param ranges ranges of hyperparameters to try, one per hyperparameters
@param howMany how many combinations of hyperparameters to return
@return combinations of concrete hyperparameter values
|
chooseHyperParameterCombos
|
java
|
OryxProject/oryx
|
framework/oryx-ml/src/main/java/com/cloudera/oryx/ml/param/RandomSearch.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-ml/src/main/java/com/cloudera/oryx/ml/param/RandomSearch.java
|
Apache-2.0
|
@Override
public T getRandomValue(RandomDataGenerator rdg) {
return values.get(rdg.nextInt(0, values.size() - 1));
}
|
@param rdg random number generator to use
@return a value chosen at random from given values
|
getRandomValue
|
java
|
OryxProject/oryx
|
framework/oryx-ml/src/main/java/com/cloudera/oryx/ml/param/Unordered.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-ml/src/main/java/com/cloudera/oryx/ml/param/Unordered.java
|
Apache-2.0
|
@Test
public void testMLUpdate() throws Exception {
Path tempDir = getTempDir();
Path modelDir = tempDir.resolve("model");
Map<String,Object> overlayConfig = new HashMap<>();
overlayConfig.put("oryx.batch.update-class", MockMLUpdate.class.getName());
ConfigUtils.set(overlayConfig, "oryx.batch.storage.data-dir", tempDir.resolve("data"));
ConfigUtils.set(overlayConfig, "oryx.batch.storage.model-dir", modelDir);
overlayConfig.put("oryx.batch.streaming.generation-interval-sec", GEN_INTERVAL_SEC);
overlayConfig.put("oryx.ml.eval.threshold", DATA_TO_WRITE * 2); // Won't pass
Config config = ConfigUtils.overlayOn(overlayConfig, getConfig());
startMessaging();
startServerProduceConsumeTopics(config, DATA_TO_WRITE, WRITE_INTERVAL_MSEC);
assertTrue(IOUtils.listFiles(modelDir, "*").isEmpty());
}
|
Tests {@link MLUpdate} threshold, where model doesn't pass threshold.
|
testMLUpdate
|
java
|
OryxProject/oryx
|
framework/oryx-ml/src/test/java/com/cloudera/oryx/ml/ThresholdIT.java
|
https://github.com/OryxProject/oryx/blob/master/framework/oryx-ml/src/test/java/com/cloudera/oryx/ml/ThresholdIT.java
|
Apache-2.0
|
public Enum<?> make(String value) {
return make(value, 0,
EMPTY_CLASS_ARRAY, EMPTY_OBJECT_ARRAY);
}
|
Make a new enum instance, without adding it to the values
array and using the default ordinal of 0.
|
make
|
java
|
kiooeht/ModTheSpire
|
src/main/java/com/evacipated/cardcrawl/modthespire/EnumBusterReflect.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/com/evacipated/cardcrawl/modthespire/EnumBusterReflect.java
|
MIT
|
public Enum<?> make(String value, int ordinal) {
return make(value, ordinal,
EMPTY_CLASS_ARRAY, EMPTY_OBJECT_ARRAY);
}
|
Make a new enum instance with the given ordinal.
|
make
|
java
|
kiooeht/ModTheSpire
|
src/main/java/com/evacipated/cardcrawl/modthespire/EnumBusterReflect.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/com/evacipated/cardcrawl/modthespire/EnumBusterReflect.java
|
MIT
|
public Enum<?> make(String value, int ordinal,
Class[] additionalTypes, Object[] additional) {
try {
undoStack.push(new Memento());
ConstructorAccessor ca = findConstructorAccessor(
additionalTypes, clazz);
return constructEnum(clazz, ca, value,
ordinal, additional);
} catch (Exception e) {
throw new IllegalArgumentException(
"Could not create enum", e);
}
}
|
Make a new enum instance with the given value, ordinal and
additional parameters. The additionalTypes is used to match
the constructor accurately.
|
make
|
java
|
kiooeht/ModTheSpire
|
src/main/java/com/evacipated/cardcrawl/modthespire/EnumBusterReflect.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/com/evacipated/cardcrawl/modthespire/EnumBusterReflect.java
|
MIT
|
public void addByValue(Enum<?> e) {
try {
undoStack.push(new Memento());
Field valuesField = findValuesField();
// we get the current Enum[]
Enum<?>[] values = values();
for (int i = 0; i < values.length; i++) {
Enum<?> value = values[i];
if (value.name().equals(e.name())) {
setOrdinal(e, value.ordinal());
values[i] = e;
replaceConstant(e);
return;
}
}
// we did not find it in the existing array, thus
// append it to the array
Enum<?>[] newValues =
Arrays.copyOf(values, values.length + 1);
newValues[newValues.length - 1] = e;
ReflectionHelper.setStaticFinalField(
valuesField, newValues);
int ordinal = newValues.length - 1;
setOrdinal(e, ordinal);
addSwitchCase();
} catch (Exception ex) {
throw new IllegalArgumentException(
"Could not set the enum", ex);
}
}
|
This method adds the given enum into the array
inside the enum class. If the enum already
contains that particular value, then the value
is overwritten with our enum. Otherwise it is
added at the end of the array.
In addition, if there is a constant field in the
enum class pointing to an enum with our value,
then we replace that with our enum instance.
The ordinal is either set to the existing position
or to the last value.
Warning: This should probably never be called,
since it can cause permanent changes to the enum
values. Use only in extreme conditions.
@param e the enum to add
|
addByValue
|
java
|
kiooeht/ModTheSpire
|
src/main/java/com/evacipated/cardcrawl/modthespire/EnumBusterReflect.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/com/evacipated/cardcrawl/modthespire/EnumBusterReflect.java
|
MIT
|
public boolean deleteByValue(Enum<?> e) {
if (e == null) throw new NullPointerException();
try {
undoStack.push(new Memento());
// we get the current E[]
Enum<?>[] values = values();
for (int i = 0; i < values.length; i++) {
Enum<?> value = values[i];
if (value.name().equals(e.name())) {
Enum<?>[] newValues =
Arrays.copyOf(values, values.length - 1);
System.arraycopy(values, i + 1, newValues, i,
values.length - i - 1);
for (int j = i; j < newValues.length; j++) {
setOrdinal(newValues[j], j);
}
Field valuesField = findValuesField();
ReflectionHelper.setStaticFinalField(
valuesField, newValues);
removeSwitchCase(i);
blankOutConstant(e);
return true;
}
}
} catch (Exception ex) {
throw new IllegalArgumentException(
"Could not set the enum", ex);
}
return false;
}
|
We delete the enum from the values array and set the
constant pointer to null.
@param e the enum to delete from the type.
@return true if the enum was found and deleted;
false otherwise
|
deleteByValue
|
java
|
kiooeht/ModTheSpire
|
src/main/java/com/evacipated/cardcrawl/modthespire/EnumBusterReflect.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/com/evacipated/cardcrawl/modthespire/EnumBusterReflect.java
|
MIT
|
public void restore() {
while (undo()) {
//
}
}
|
Undo the state right back to the beginning when the
EnumBuster was created.
|
restore
|
java
|
kiooeht/ModTheSpire
|
src/main/java/com/evacipated/cardcrawl/modthespire/EnumBusterReflect.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/com/evacipated/cardcrawl/modthespire/EnumBusterReflect.java
|
MIT
|
public void sync(int fps) {
if (fps <= 0) return;
if (!initialised) initialise();
try {
// sleep until the average sleep time is greater than the time remaining till nextFrame
for (long t0 = getTime(), t1; (nextFrame - t0) > sleepDurations.avg(); t0 = t1) {
Thread.sleep(1);
sleepDurations.add((t1 = getTime()) - t0); // update average sleep time
}
// slowly dampen sleep average if too high to avoid yielding too much
sleepDurations.dampenForLowResTicker();
// yield until the average yield time is greater than the time remaining till nextFrame
for (long t0 = getTime(), t1; (nextFrame - t0) > yieldDurations.avg(); t0 = t1) {
Thread.yield();
yieldDurations.add((t1 = getTime()) - t0); // update average yield time
}
} catch (InterruptedException e) {
}
// schedule next frame, drop frame(s) if already too late for next frame
nextFrame = Math.max(nextFrame + NANOS_IN_SECOND / fps, getTime());
}
|
An accurate sync method that will attempt to run at a constant frame rate.
It should be called once every frame.
@param fps - the desired frame rate, in frames per second
|
sync
|
java
|
kiooeht/ModTheSpire
|
src/main/java/com/evacipated/cardcrawl/modthespire/patches/lwjgl3/Sync.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/com/evacipated/cardcrawl/modthespire/patches/lwjgl3/Sync.java
|
MIT
|
public boolean accept (ClassInfo classInfo, ClassFinder classFinder)
{
boolean accepted = true;
for (ClassFilter filter : filters)
{
accepted = filter.accept (classInfo, classFinder);
if (! accepted)
break;
}
return accepted;
}
|
<p>Determine whether a class name is to be accepted or not, based on
the contained filters. The class name is accepted if any one of the
contained filters accepts it. This method stops looping over the
contained filters as soon as it encounters one whose
{@link ClassFilter#accept accept()} method returns
<tt>false</tt> (implementing a "short-circuited AND" operation.)</p>
<p>If the set of contained filters is empty, then this method
returns <tt>true</tt>.</p>
@param classInfo the {@link ClassInfo} object to test
@param classFinder the invoking {@link ClassFinder} object
@return <tt>true</tt> if the name matches, <tt>false</tt> if it doesn't
|
accept
|
java
|
kiooeht/ModTheSpire
|
src/main/java/org/clapper/util/classutil/AndClassFilter.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/org/clapper/util/classutil/AndClassFilter.java
|
MIT
|
public void addClassPath()
{
String path = null;
try
{
path = System.getProperty ("java.class.path");
}
catch (Exception ex)
{
path= "";
log.error ("Unable to get class path", ex);
}
StringTokenizer tok = new StringTokenizer (path, File.pathSeparator);
while (tok.hasMoreTokens())
add (new File (tok.nextToken()));
}
|
Add the contents of the system classpath for classes.
|
addClassPath
|
java
|
kiooeht/ModTheSpire
|
src/main/java/org/clapper/util/classutil/ClassFinder.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/org/clapper/util/classutil/ClassFinder.java
|
MIT
|
public boolean add (File file)
{
boolean added = false;
if (ClassUtil.fileCanContainClasses (file))
{
String absPath = file.getAbsolutePath();
if (placesToSearch.get (absPath) == null)
{
placesToSearch.put (absPath, file);
if (isJar (absPath))
loadJarClassPathEntries (file);
}
added = true;
}
return added;
}
|
Add a jar file, zip file or directory to the list of places to search
for classes.
@param file the jar file, zip file or directory
@return <tt>true</tt> if the file was suitable for adding;
<tt>false</tt> if it was not a jar file, zip file, or
directory.
|
add
|
java
|
kiooeht/ModTheSpire
|
src/main/java/org/clapper/util/classutil/ClassFinder.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/org/clapper/util/classutil/ClassFinder.java
|
MIT
|
public int add (File[] files)
{
int totalAdded = 0;
for (File file : files)
{
if (add (file))
totalAdded++;
}
return totalAdded;
}
|
Add an array jar files, zip files and/or directories to the list of
places to search for classes.
@param files the array of jar files, zip files and/or directories.
The array can contain a mixture of all of the above.
@return the total number of items from the array that were actually
added. (Elements that aren't jars, zip files or directories
are skipped.)
|
add
|
java
|
kiooeht/ModTheSpire
|
src/main/java/org/clapper/util/classutil/ClassFinder.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/org/clapper/util/classutil/ClassFinder.java
|
MIT
|
public int add (Collection<File> files)
{
int totalAdded = 0;
for (File file : files)
{
if (add (file))
totalAdded++;
}
return totalAdded;
}
|
Add a <tt>Collection</tt> of jar files, zip files and/or directories
to the list of places to search for classes.
@param files the collection of jar files, zip files and/or directories.
@return the total number of items from the collection that were actually
added. (Elements that aren't jars, zip files or directories
are skipped.)
|
add
|
java
|
kiooeht/ModTheSpire
|
src/main/java/org/clapper/util/classutil/ClassFinder.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/org/clapper/util/classutil/ClassFinder.java
|
MIT
|
public void clear()
{
placesToSearch.clear();
foundClasses.clear();
}
|
Clear the finder's notion of where to search.
|
clear
|
java
|
kiooeht/ModTheSpire
|
src/main/java/org/clapper/util/classutil/ClassFinder.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/org/clapper/util/classutil/ClassFinder.java
|
MIT
|
public int findClasses (Collection<ClassInfo> classes)
{
return findClasses (classes, null);
}
|
Find all classes in the search areas, implicitly accepting all of
them.
@param classes where to store the resulting matches
@return the number of matched classes added to the collection
|
findClasses
|
java
|
kiooeht/ModTheSpire
|
src/main/java/org/clapper/util/classutil/ClassFinder.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/org/clapper/util/classutil/ClassFinder.java
|
MIT
|
public int findClasses (Collection<ClassInfo> classes,
ClassFilter filter)
{
int total = 0;
foundClasses.clear();
// Load all the classes first.
for (File file : placesToSearch.values())
{
String name = file.getPath();
log.info ("Finding classes in " + name);
if (isJar (name))
processJar (name, foundClasses);
else if (isZip (name))
processZip (name, foundClasses);
else
processDirectory (file, foundClasses);
}
log.info ("Loaded " + foundClasses.size() + " classes.");
// Next, weed out the ones we don't want.
for (ClassInfo classInfo : foundClasses.values())
{
String className = classInfo.getClassName();
String locationName = classInfo.getClassLocation().getPath();
log.debug ("Looking at " + locationName + " (" + className + ")");
if ((filter == null) || (filter.accept (classInfo, this)))
{
log.debug ("Filter accepted " + className);
total++;
classes.add (classInfo);
}
else
{
log.debug ("Filter rejected " + className);
}
}
log.info ("Returning " + total + " total classes");
foundClasses.clear();
return total;
}
|
Search all classes in the search areas, keeping only those that
pass the specified filter.
@param classes where to store the resulting matches
@param filter the filter, or null for no filter
@return the number of matched classes added to the collection
|
findClasses
|
java
|
kiooeht/ModTheSpire
|
src/main/java/org/clapper/util/classutil/ClassFinder.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/org/clapper/util/classutil/ClassFinder.java
|
MIT
|
public int findAllSuperClasses (ClassInfo classInfo,
Map<String,ClassInfo> superClasses)
{
int total = 0;
String superClassName = classInfo.getSuperClassName();
if (superClassName != null)
{
ClassInfo superClassInfo = foundClasses.get (superClassName);
if (superClassInfo != null)
{
superClasses.put (superClassName, superClassInfo);
total++;
total += findAllSuperClasses (superClassInfo, superClasses);
}
}
return total;
}
|
Intended to be called only from a {@link ClassFilter} object's
{@link ClassFilter#accept accept()} method, this method attempts to
find all the superclasses (except <tt>java.lang.Object</tt>for a
given class, by checking all the currently-loaded class data.
@param classInfo the {@link ClassInfo} objects for the class
@param superClasses where to store the {@link ClassInfo} objects
for the superclasses. The map is indexed by
class name.
@return the number of superclasses found
|
findAllSuperClasses
|
java
|
kiooeht/ModTheSpire
|
src/main/java/org/clapper/util/classutil/ClassFinder.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/org/clapper/util/classutil/ClassFinder.java
|
MIT
|
public String getClassName()
{
return className;
}
|
Get the class name.
@return the class name
|
getClassName
|
java
|
kiooeht/ModTheSpire
|
src/main/java/org/clapper/util/classutil/ClassInfo.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/org/clapper/util/classutil/ClassInfo.java
|
MIT
|
public String getSuperClassName()
{
return superClassName;
}
|
Get the parent (super) class name, if any. Returns null if the
superclass is <tt>java.lang.Object</tt>. Note: To find other
ancestor classes, use {@link ClassFinder#findAllSuperClasses}.
@return the super class name, or null
@see ClassFinder#findAllSuperClasses
|
getSuperClassName
|
java
|
kiooeht/ModTheSpire
|
src/main/java/org/clapper/util/classutil/ClassInfo.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/org/clapper/util/classutil/ClassInfo.java
|
MIT
|
public String[] getInterfaces()
{
return implementedInterfaces;
}
|
Get the names of all <i>directly</i> implemented interfaces. To find
indirectly implemented interfaces, use
{@link ClassFinder#findAllInterfaces}.
@return an array of the names of all directly implemented interfaces,
or null if there are none
@see ClassFinder#findAllInterfaces
|
getInterfaces
|
java
|
kiooeht/ModTheSpire
|
src/main/java/org/clapper/util/classutil/ClassInfo.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/org/clapper/util/classutil/ClassInfo.java
|
MIT
|
public int getModifier()
{
return modifier;
}
|
Get the Reflection API-based modifier bitfield for the class. Use
<tt>java.lang.reflect.Modifier</tt> to decode this bitfield.
@return the modifier
|
getModifier
|
java
|
kiooeht/ModTheSpire
|
src/main/java/org/clapper/util/classutil/ClassInfo.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/org/clapper/util/classutil/ClassInfo.java
|
MIT
|
public File getClassLocation()
{
return locationFound;
}
|
Get the location (the jar file, zip file or directory) where the
class was found.
@return where the class was found
|
getClassLocation
|
java
|
kiooeht/ModTheSpire
|
src/main/java/org/clapper/util/classutil/ClassInfo.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/org/clapper/util/classutil/ClassInfo.java
|
MIT
|
public Set<FieldInfo> getFields()
{
return fields;
}
|
Get the set of fields in the class.
@return the set of fields, if any.
|
getFields
|
java
|
kiooeht/ModTheSpire
|
src/main/java/org/clapper/util/classutil/ClassInfo.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/org/clapper/util/classutil/ClassInfo.java
|
MIT
|
public Set<MethodInfo> getMethods()
{
return methods;
}
|
Get the set of methods in the class.
@return the set of methods, if any
|
getMethods
|
java
|
kiooeht/ModTheSpire
|
src/main/java/org/clapper/util/classutil/ClassInfo.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/org/clapper/util/classutil/ClassInfo.java
|
MIT
|
public String toString()
{
StringBuilder buf = new StringBuilder();
if ((modifier & Modifier.PUBLIC) != 0)
buf.append ("public ");
if ((modifier & Modifier.ABSTRACT) != 0)
buf.append ("abstract ");
if ((modifier & Modifier.INTERFACE) != 0)
buf.append ("interface ");
else
buf.append ("class ");
buf.append (className);
String sep = " ";
if (implementedInterfaces.length > 0)
{
buf.append (" implements");
for (String intf : implementedInterfaces)
{
buf.append (sep);
buf.append (intf);
}
}
if ((superClassName != null) &&
(! superClassName.equals ("java.lang.Object")))
{
buf.append (sep);
buf.append ("extends ");
buf.append (superClassName);
}
return (buf.toString());
}
|
Get a string representation of this object.
@return the string representation
|
toString
|
java
|
kiooeht/ModTheSpire
|
src/main/java/org/clapper/util/classutil/ClassInfo.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/org/clapper/util/classutil/ClassInfo.java
|
MIT
|
private String translateInternalClassName(String internalName)
{
return internalName.replaceAll("/", ".");
}
|
Translate an internal class/interface name to an external one.
@param internalName the internal JVM name, from the ASM API
@return the external name
|
translateInternalClassName
|
java
|
kiooeht/ModTheSpire
|
src/main/java/org/clapper/util/classutil/ClassInfo.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/org/clapper/util/classutil/ClassInfo.java
|
MIT
|
private void setClassFields(String name,
String superClassName,
String[] interfaces,
int asmAccessMask,
File location)
{
this.className = translateInternalClassName(name);
this.locationFound = location;
if ((superClassName != null) &&
(! superClassName.equals ("java/lang/Object")))
{
this.superClassName = translateInternalClassName(superClassName);
}
if (interfaces != null)
{
this.implementedInterfaces = new String[interfaces.length];
for (int i = 0; i < interfaces.length; i++)
{
this.implementedInterfaces[i] =
translateInternalClassName(interfaces[i]);
}
}
modifier = convertAccessMaskToModifierMask(asmAccessMask);
}
|
Set the fields in this object.
@param name the class name
@param superClassName the parent class name, or null
@param interfaces the names of interfaces the class implements,
or null
@param asmAccessMask ASM API's access mask for the class
@param location File (jar, zip) or directory where class was found
|
setClassFields
|
java
|
kiooeht/ModTheSpire
|
src/main/java/org/clapper/util/classutil/ClassInfo.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/org/clapper/util/classutil/ClassInfo.java
|
MIT
|
private int convertAccessMaskToModifierMask(int asmAccessMask)
{
int modifier = 0;
// Convert the ASM access info into Reflection API modifiers.
if ((asmAccessMask & Opcodes.ACC_FINAL) != 0)
modifier |= Modifier.FINAL;
if ((asmAccessMask & Opcodes.ACC_NATIVE) != 0)
modifier |= Modifier.NATIVE;
if ((asmAccessMask & Opcodes.ACC_INTERFACE) != 0)
modifier |= Modifier.INTERFACE;
if ((asmAccessMask & Opcodes.ACC_ABSTRACT) != 0)
modifier |= Modifier.ABSTRACT;
if ((asmAccessMask & Opcodes.ACC_PRIVATE) != 0)
modifier |= Modifier.PRIVATE;
if ((asmAccessMask & Opcodes.ACC_PROTECTED) != 0)
modifier |= Modifier.PROTECTED;
if ((asmAccessMask & Opcodes.ACC_PUBLIC) != 0)
modifier |= Modifier.PUBLIC;
if ((asmAccessMask & Opcodes.ACC_STATIC) != 0)
modifier |= Modifier.STATIC;
if ((asmAccessMask & Opcodes.ACC_STRICT) != 0)
modifier |= Modifier.STRICT;
if ((asmAccessMask & Opcodes.ACC_SYNCHRONIZED) != 0)
modifier |= Modifier.SYNCHRONIZED;
if ((asmAccessMask & Opcodes.ACC_TRANSIENT) != 0)
modifier |= Modifier.TRANSIENT;
if ((asmAccessMask & Opcodes.ACC_VOLATILE) != 0)
modifier |= Modifier.VOLATILE;
return modifier;
}
|
Convert an ASM access mask to a reflection Modifier mask.
@param asmAccessMask the ASM access mask
@return the Modifier mask
|
convertAccessMaskToModifierMask
|
java
|
kiooeht/ModTheSpire
|
src/main/java/org/clapper/util/classutil/ClassInfo.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/org/clapper/util/classutil/ClassInfo.java
|
MIT
|
public File getClassLocation()
{
return location;
}
|
Get the location (the jar file, zip file or directory) containing
the classes processed by this visitor.
@return where the class was found
|
getClassLocation
|
java
|
kiooeht/ModTheSpire
|
src/main/java/org/clapper/util/classutil/ClassInfoClassVisitor.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/org/clapper/util/classutil/ClassInfoClassVisitor.java
|
MIT
|
public boolean add (File file)
{
boolean added = false;
String fileName = file.getPath();
try
{
if (ClassUtil.fileCanContainClasses (file))
{
if (file.isDirectory() && (! fileName.endsWith ("/")))
{
fileName = fileName + "/";
file = new File(fileName);
}
urlList.add(file.toURI().toURL());
added = true;
}
}
catch (MalformedURLException ex)
{
log.error ("Unexpected exception", ex);
}
if (! added)
{
log.debug ("Skipping non-jar, non-zip, non-directory \"" +
fileName +
"\"");
}
return added;
}
|
Add a jar file, zip file or directory to the list of places the
not-yet-constructed class loader will search. If the directory or
file does not exist, or isn't a jar file, zip file, or directory,
this method just ignores it and returns <tt>false</tt>.
@param file the jar file, zip file or directory
@return <tt>true</tt> if the file was suitable for adding;
<tt>false</tt> if it was not a jar file, zip file, or
directory.
|
add
|
java
|
kiooeht/ModTheSpire
|
src/main/java/org/clapper/util/classutil/ClassLoaderBuilder.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/org/clapper/util/classutil/ClassLoaderBuilder.java
|
MIT
|
public int add (File[] files)
{
int total = 0;
for (File f : files)
{
if (add (f))
total++;
}
return total;
}
|
Add an array of jar files, zip files or directories to the list of
places the not-yet-constructed class loader will search. If the
directory or file does not exist, or isn't a jar file, zip file, or
directory, this method just ignores it and returns <tt>false</tt>.
@param files the array
@return the number of entries from the array that were actually added
|
add
|
java
|
kiooeht/ModTheSpire
|
src/main/java/org/clapper/util/classutil/ClassLoaderBuilder.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/org/clapper/util/classutil/ClassLoaderBuilder.java
|
MIT
|
public int add (Collection<File> files)
{
int total = 0;
for (File f : files)
{
if (add (f))
total++;
}
return total;
}
|
Add a <tt>Collection</tt> of jar files, zip files or directories to
the list of places the not-yet-constructed class loader will search.
If the directory or file does not exist, or isn't a jar file, zip
file, or directory, this method just ignores it and returns
<tt>false</tt>.
@param files the collection
@return the number of entries from the collection that were
actually added
|
add
|
java
|
kiooeht/ModTheSpire
|
src/main/java/org/clapper/util/classutil/ClassLoaderBuilder.java
|
https://github.com/kiooeht/ModTheSpire/blob/master/src/main/java/org/clapper/util/classutil/ClassLoaderBuilder.java
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.