answer
stringlengths 17
10.2M
|
|---|
package com.mebigfatguy.fbcontrib.detect;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.Constant;
import org.apache.bcel.classfile.ConstantClass;
import org.apache.bcel.classfile.ConstantPool;
import org.apache.bcel.classfile.ConstantUtf8;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.Type;
import com.mebigfatguy.fbcontrib.utils.BugType;
import com.mebigfatguy.fbcontrib.utils.SignatureUtils;
import com.mebigfatguy.fbcontrib.utils.TernaryPatcher;
import com.mebigfatguy.fbcontrib.utils.UnmodifiableSet;
import com.mebigfatguy.fbcontrib.utils.Values;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.BytecodeScanningDetector;
import edu.umd.cs.findbugs.OpcodeStack;
import edu.umd.cs.findbugs.OpcodeStack.CustomUserValue;
import edu.umd.cs.findbugs.OpcodeStack.Item;
import edu.umd.cs.findbugs.ba.ClassContext;
/**
* looks for uses of log4j or slf4j where the class specified when creating the
* logger is not the same as the class in which this logger is used. Also looks
* for using concatenation with slf4j logging rather than using the
* parameterized interface.
*/
@CustomUserValue
public class LoggerOddities extends BytecodeScanningDetector {
private static JavaClass THROWABLE_CLASS;
static {
try {
THROWABLE_CLASS = Repository.lookupClass("java/lang/Throwable");
} catch (ClassNotFoundException cnfe) {
THROWABLE_CLASS = null;
}
}
private static final Set<String> LOGGER_METHODS = UnmodifiableSet.create(
"trace",
"debug",
"info",
"warn",
"error",
"fatal"
);
private static final Pattern BAD_FORMATTING_ANCHOR = Pattern.compile("\\{[0-9]\\}");
private static final Pattern FORMATTER_ANCHOR = Pattern.compile("\\{\\}");
private final BugReporter bugReporter;
private OpcodeStack stack;
private String nameOfThisClass;
/**
* constructs a LO detector given the reporter to report bugs on.
*
* @param bugReporter
* the sync of bug reports
*/
public LoggerOddities(final BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
/**
* implements the visitor to discover what the class name is if it is a
* normal class, or the owning class, if the class is an anonymous class.
*
* @param classContext
* the context object of the currently parsed class
*/
@Override
public void visitClassContext(ClassContext classContext) {
try {
stack = new OpcodeStack();
nameOfThisClass = classContext.getJavaClass().getClassName();
int subclassIndex = nameOfThisClass.indexOf('$');
while (subclassIndex >= 0) {
String simpleName = nameOfThisClass.substring(subclassIndex + 1);
try {
Integer.parseInt(simpleName);
nameOfThisClass = nameOfThisClass.substring(0, subclassIndex);
subclassIndex = nameOfThisClass.indexOf('$');
} catch (NumberFormatException nfe) {
subclassIndex = -1;
}
}
nameOfThisClass = nameOfThisClass.replace('.', '/');
super.visitClassContext(classContext);
} finally {
stack = null;
}
}
/**
* implements the visitor to reset the stack
*
* @param obj
* the context object of the currently parsed code block
*/
@Override
public void visitCode(Code obj) {
stack.resetForMethodEntry(this);
Method m = getMethod();
if (Values.CONSTRUCTOR.equals(m.getName())) {
Type[] types = Type.getArgumentTypes(m.getSignature());
for (Type t : types) {
String parmSig = t.getSignature();
if ("Lorg/slf4j/Logger;".equals(parmSig) || "Lorg/apache/log4j/Logger;".equals(parmSig) || "Lorg/apache/commons/logging/Log;".equals(parmSig)) {
bugReporter.reportBug(new BugInstance(this, BugType.LO_SUSPECT_LOG_PARAMETER.name(), NORMAL_PRIORITY).addClass(this).addMethod(this));
}
}
}
super.visitCode(obj);
}
/**
* implements the visitor to look for calls to Logger.getLogger with the
* wrong class name
*
* @param seen
* the opcode of the currently parsed instruction
*/
@Override
public void sawOpcode(int seen) {
String ldcClassName = null;
String seenMethodName = null;
int exMessageReg = -1;
Integer arraySize = null;
try {
stack.precomputation(this);
if ((seen == LDC) || (seen == LDC_W)) {
Constant c = getConstantRefOperand();
if (c instanceof ConstantClass) {
ConstantPool pool = getConstantPool();
ldcClassName = ((ConstantUtf8) pool.getConstant(((ConstantClass) c).getNameIndex())).getBytes();
}
} else if (seen == INVOKESTATIC) {
lookForSuspectClasses();
} else if (((seen == INVOKEVIRTUAL) || (seen == INVOKEINTERFACE)) && (THROWABLE_CLASS != null)) {
String mthName = getNameConstantOperand();
if ("getName".equals(mthName)) {
if (stack.getStackDepth() >= 1) {
// Foo.class.getName() is being called, so we pass the
// name of the class to the current top of the stack
// (the name of the class is currently on the top of the
// stack, but won't be on the stack at all next opcode)
Item stackItem = stack.getStackItem(0);
ldcClassName = (String) stackItem.getUserValue();
}
} else if ("getMessage".equals(mthName)) {
String callingClsName = getClassConstantOperand();
JavaClass cls = Repository.lookupClass(callingClsName);
if (cls.instanceOf(THROWABLE_CLASS)) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item exItem = stack.getStackItem(0);
exMessageReg = exItem.getRegisterNumber();
}
}
} else if (LOGGER_METHODS.contains(mthName)) {
checkForProblemsWithLoggerMethods();
} else if ("toString".equals(mthName)) {
String callingClsName = getClassConstantOperand();
if (("java/lang/StringBuilder".equals(callingClsName) || "java/lang/StringBuffer".equals(callingClsName))) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item item = stack.getStackItem(0);
// if the stringbuilder was previously stored, don't
// report it
if (item.getRegisterNumber() < 0) {
seenMethodName = mthName;
}
}
}
}
} else if (seen == INVOKESPECIAL) {
checkForLoggerParam();
} else if (seen == ANEWARRAY) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item sizeItem = stack.getStackItem(0);
Object con = sizeItem.getConstant();
if (con instanceof Integer) {
arraySize = (Integer) con;
}
}
} else if (seen == AASTORE) {
if (stack.getStackDepth() >= 3) {
OpcodeStack.Item arrayItem = stack.getStackItem(2);
Integer size = (Integer) arrayItem.getUserValue();
if ((size != null) && (size > 0)) {
if (hasExceptionOnStack()) {
arrayItem.setUserValue(-size);
}
}
}
}
} catch (ClassNotFoundException cnfe) {
bugReporter.reportMissingClass(cnfe);
} finally {
TernaryPatcher.pre(stack, seen);
stack.sawOpcode(this, seen);
TernaryPatcher.post(stack, seen);
if (stack.getStackDepth() > 0) {
OpcodeStack.Item item = stack.getStackItem(0);
if (ldcClassName != null) {
item.setUserValue(ldcClassName);
} else if (seenMethodName != null) {
item.setUserValue(seenMethodName);
} else if (exMessageReg >= 0) {
item.setUserValue(Integer.valueOf(exMessageReg));
} else if (arraySize != null) {
item.setUserValue(arraySize);
}
}
}
}
private void checkForProblemsWithLoggerMethods() throws ClassNotFoundException {
String callingClsName = getClassConstantOperand();
if (callingClsName.endsWith("Log") || (callingClsName.endsWith("Logger"))) {
String sig = getSigConstantOperand();
if ("(Ljava/lang/String;Ljava/lang/Throwable;)V".equals(sig) || "(Ljava/lang/Object;Ljava/lang/Throwable;)V".equals(sig)) {
if (stack.getStackDepth() >= 2) {
OpcodeStack.Item exItem = stack.getStackItem(0);
OpcodeStack.Item msgItem = stack.getStackItem(1);
Object exReg = msgItem.getUserValue();
if (exReg instanceof Integer) {
if (((Integer) exReg).intValue() == exItem.getRegisterNumber()) {
bugReporter.reportBug(new BugInstance(this, BugType.LO_STUTTERED_MESSAGE.name(), NORMAL_PRIORITY).addClass(this).addMethod(this)
.addSourceLine(this));
}
}
}
} else if ("(Ljava/lang/Object;)V".equals(sig)) {
if (stack.getStackDepth() > 0) {
final JavaClass clazz = stack.getStackItem(0).getJavaClass();
if ((clazz != null) && clazz.instanceOf(THROWABLE_CLASS)) {
bugReporter.reportBug(new BugInstance(this, BugType.LO_LOGGER_LOST_EXCEPTION_STACK_TRACE.name(), NORMAL_PRIORITY).addClass(this)
.addMethod(this).addSourceLine(this));
}
}
} else if ("org/slf4j/Logger".equals(callingClsName)) {
String signature = getSigConstantOperand();
if ("(Ljava/lang/String;)V".equals(signature) || "(Ljava/lang/String;Ljava/lang/Object;)V".equals(signature)
|| "(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V".equals(signature)
|| "(Ljava/lang/String;[Ljava/lang/Object;)V".equals(signature)) {
int numParms = Type.getArgumentTypes(signature).length;
if (stack.getStackDepth() >= numParms) {
OpcodeStack.Item formatItem = stack.getStackItem(numParms - 1);
Object con = formatItem.getConstant();
if (con instanceof String) {
Matcher m = BAD_FORMATTING_ANCHOR.matcher((String) con);
if (m.find()) {
bugReporter.reportBug(new BugInstance(this, BugType.LO_INVALID_FORMATTING_ANCHOR.name(), NORMAL_PRIORITY).addClass(this)
.addMethod(this).addSourceLine(this));
} else {
int actualParms = getSLF4JParmCount(signature);
if (actualParms != -1) {
int expectedParms = countAnchors((String) con);
boolean hasEx = hasExceptionOnStack();
if ((!hasEx && (expectedParms != actualParms))
|| (hasEx && ((expectedParms != (actualParms - 1)) && (expectedParms != actualParms)))) {
bugReporter.reportBug(new BugInstance(this, BugType.LO_INCORRECT_NUMBER_OF_ANCHOR_PARAMETERS.name(), NORMAL_PRIORITY)
.addClass(this).addMethod(this).addSourceLine(this).addString("Expected: " + expectedParms)
.addString("Actual: " + actualParms));
}
}
}
} else if ("toString".equals(formatItem.getUserValue())) {
bugReporter.reportBug(new BugInstance(this, BugType.LO_APPENDED_STRING_IN_FORMAT_STRING.name(), NORMAL_PRIORITY).addClass(this)
.addMethod(this).addSourceLine(this));
}
}
}
}
}
}
private void checkForLoggerParam() {
if (Values.CONSTRUCTOR.equals(getNameConstantOperand())) {
String cls = getClassConstantOperand();
if ((cls.startsWith("java/") || cls.startsWith("javax/")) && cls.endsWith("Exception")) {
String sig = getSigConstantOperand();
Type[] types = Type.getArgumentTypes(sig);
if (types.length <= stack.getStackDepth()) {
for (int i = 0; i < types.length; i++) {
if ("Ljava/lang/String;".equals(types[i].getSignature())) {
OpcodeStack.Item item = stack.getStackItem(types.length - i - 1);
String cons = (String) item.getConstant();
if ((cons != null) && cons.contains("{}")) {
bugReporter.reportBug(new BugInstance(this, BugType.LO_EXCEPTION_WITH_LOGGER_PARMS.name(), NORMAL_PRIORITY).addClass(this)
.addMethod(this).addSourceLine(this));
break;
}
}
}
}
}
}
}
private void lookForSuspectClasses() {
String callingClsName = getClassConstantOperand();
String mthName = getNameConstantOperand();
String loggingClassName = null;
int loggingPriority = NORMAL_PRIORITY;
if ("org/slf4j/LoggerFactory".equals(callingClsName) && "getLogger".equals(mthName)) {
String signature = getSigConstantOperand();
if ("(Ljava/lang/Class;)Lorg/slf4j/Logger;".equals(signature)) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item item = stack.getStackItem(0);
loggingClassName = (String) item.getUserValue();
}
} else if ("(Ljava/lang/String;)Lorg/slf4j/Logger;".equals(signature)) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item item = stack.getStackItem(0);
loggingClassName = (String) item.getConstant();
if (loggingClassName != null) {
loggingClassName = loggingClassName.replace('.', '/');
}
loggingPriority = LOW_PRIORITY;
}
}
} else if ("org/apache/log4j/Logger".equals(callingClsName) && "getLogger".equals(mthName)) {
String signature = getSigConstantOperand();
if ("(Ljava/lang/Class;)Lorg/apache/log4j/Logger;".equals(signature)) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item item = stack.getStackItem(0);
loggingClassName = (String) item.getUserValue();
}
} else if ("(Ljava/lang/String;)Lorg/apache/log4j/Logger;".equals(signature)) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item item = stack.getStackItem(0);
loggingClassName = (String) item.getConstant();
Object userValue = item.getUserValue();
if (loggingClassName != null) {
// first look at the constant passed in
loggingClassName = loggingClassName.replace('.', '/');
loggingPriority = LOW_PRIORITY;
} else if (userValue instanceof String) {
// try the user value, which may have been set by a call
// to Foo.class.getName()
loggingClassName = (String) userValue;
loggingClassName = loggingClassName.replace('.', '/');
}
}
} else if ("(Ljava/lang/String;Lorg/apache/log4j/spi/LoggerFactory;)Lorg/apache/log4j/Logger;".equals(signature)) {
if (stack.getStackDepth() > 1) {
OpcodeStack.Item item = stack.getStackItem(1);
loggingClassName = (String) item.getConstant();
if (loggingClassName != null) {
loggingClassName = loggingClassName.replace('.', '/');
}
loggingPriority = LOW_PRIORITY;
}
}
} else if ("org/apache/commons/logging/LogFactory".equals(callingClsName) && "getLog".equals(mthName)) {
String signature = getSigConstantOperand();
if ("(Ljava/lang/Class;)Lorg/apache/commons/logging/Log;".equals(signature)) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item item = stack.getStackItem(0);
loggingClassName = (String) item.getUserValue();
}
} else if ("(Ljava/lang/String;)Lorg/apache/commons/logging/Log;".equals(signature)) {
if (stack.getStackDepth() > 0) {
OpcodeStack.Item item = stack.getStackItem(0);
loggingClassName = (String) item.getConstant();
if (loggingClassName != null) {
loggingClassName = loggingClassName.replace('.', '/');
}
loggingPriority = LOW_PRIORITY;
}
}
}
if (loggingClassName != null) {
if (stack.getStackDepth() > 0) {
if (!loggingClassName.equals(nameOfThisClass)) {
boolean isPrefix = nameOfThisClass.startsWith(loggingClassName);
boolean isAnonClassPrefix;
if (isPrefix) {
String anonClass = nameOfThisClass.substring(loggingClassName.length());
isAnonClassPrefix = anonClass.matches("(\\$\\d+)+");
} else {
isAnonClassPrefix = false;
}
if (!isAnonClassPrefix) {
bugReporter.reportBug(new BugInstance(this, BugType.LO_SUSPECT_LOG_CLASS.name(), loggingPriority).addClass(this).addMethod(this)
.addSourceLine(this).addString(loggingClassName).addString(nameOfThisClass));
}
}
}
}
}
/**
* returns the number of anchors {} in a string
*
* @param formatString
* the format string
* @return the number of anchors
*/
private static int countAnchors(String formatString) {
Matcher m = FORMATTER_ANCHOR.matcher(formatString);
int count = 0;
int start = 0;
while (m.find(start)) {
++count;
start = m.end();
}
return count;
}
/**
* returns the number of parameters slf4j is expecting to inject into the
* format string
*
* @param signature
* the method signature of the error, warn, info, debug statement
* @return the number of expected parameters
*/
private int getSLF4JParmCount(String signature) {
if ("(Ljava/lang/String;Ljava/lang/Object;)V".equals(signature))
return 1;
if ("(Ljava/lang/String;Ljava/lang/Object;Ljava/lang/Object;)V".equals(signature))
return 2;
OpcodeStack.Item item = stack.getStackItem(0);
Integer size = (Integer) item.getUserValue();
if (size != null) {
return Math.abs(size.intValue());
}
return -1;
}
/**
* returns whether an exception object is on the stack slf4j will find this,
* and not include it in the parm list so i we find one, just don't report
*
* @return whether or not an exception i present
*/
private boolean hasExceptionOnStack() {
try {
for (int i = 0; i < stack.getStackDepth() - 1; i++) {
OpcodeStack.Item item = stack.getStackItem(i);
String sig = item.getSignature();
if (sig.startsWith("L")) {
String name = SignatureUtils.stripSignature(sig);
JavaClass cls = Repository.lookupClass(name);
if (cls.instanceOf(THROWABLE_CLASS))
return true;
} else if (sig.startsWith("[")) {
Integer sz = (Integer) item.getUserValue();
if ((sz != null) && (sz.intValue() < 0))
return true;
}
}
return false;
} catch (ClassNotFoundException cnfe) {
bugReporter.reportMissingClass(cnfe);
return true;
}
}
}
|
package com.ryanddawkins.glowing_spice;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.lang.StringBuilder;
import com.ryanddawkins.glowing_spice.Request;
/**
* Class to deal with client connections and to execute their commands
*
* @author Ryan Dawkins
* @package com.ryanddawkins.glowing_spice
* @since 0.1
* @implements Runnable
*/
public class ClientConnection implements Runnable
{
private Socket socket;
/**
* Constructor to take and store the socket
*
* @param Socket socket
*/
public ClientConnection(Socket socket)
{
this.socket = socket;
}
/**
* Run method to execute when thread is called
*
* @return void
*/
public void run()
{
try
{
StringBuilder jsonBuilder = new StringBuilder();
String input = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while((input = reader.readLine()) != null)
{
jsonBuilder.append(input);
}
Request request = new Request(jsonBuilder.toString());
String command = request.getCommand();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
|
package com.untamedears.JukeAlert.manager;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import com.untamedears.JukeAlert.JukeAlert;
import com.untamedears.JukeAlert.model.Snitch;
import com.untamedears.JukeAlert.storage.JukeAlertLogger;
import com.untamedears.JukeAlert.util.QTBox;
import com.untamedears.JukeAlert.util.SparseQuadTree;
public class SnitchManager {
private JukeAlert plugin;
private JukeAlertLogger logger;
private Map<World, SparseQuadTree> snitches;
public SnitchManager() {
plugin = JukeAlert.getInstance();
logger = plugin.getJaLogger();
}
public void loadSnitches() {
Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
@Override
public void run() {
snitches = logger.getAllSnitches();
}
});
}
public void saveSnitches() {
logger.saveAllSnitches();
}
public Map<World, SparseQuadTree> getAllSnitches() {
return snitches;
}
public void setSnitches(Map<World, SparseQuadTree> snitches) {
this.snitches = snitches;
}
public Snitch getSnitch(World world, Location location) {
Set<? extends QTBox> potentials = snitches.get(world).find(location.getBlockX(), location.getBlockZ());
for (QTBox box : potentials) {
Snitch sn = (Snitch)box;
if (sn.at(location)) {
return sn;
}
}
return null;
}
public void addSnitch(Snitch snitch) {
World world = snitch.getLoc().getWorld();
if (snitches.get(world) == null) {
SparseQuadTree map = new SparseQuadTree();
map.add(snitch);
snitches.put(world, map);
} else {
snitches.get(world).add(snitch);
}
}
public void removeSnitch(Snitch snitch) {
snitches.get(snitch.getLoc().getWorld()).remove(snitch);
}
public Set<Snitch> findSnitches(World world, Location location) {
if (snitches.get(world) == null) {
return new TreeSet<Snitch>();
}
int y = location.getBlockY();
Set<Snitch> results = new TreeSet<Snitch>();
Set<QTBox> found = snitches.get(world).find(location.getBlockX(), location.getBlockZ());
for (QTBox box : found) {
Snitch sn = (Snitch)box;
if (sn.isWithinHeight(location.getBlockY())) {
results.add(sn);
}
}
return results;
}
}
|
package com.xtremelabs.droidsugar.fakes;
import android.app.PendingIntent;
import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.TextView;
import com.xtremelabs.droidsugar.util.Implementation;
import com.xtremelabs.droidsugar.util.Implements;
import java.util.ArrayList;
import java.util.List;
@SuppressWarnings({"UnusedDeclaration"})
@Implements(RemoteViews.class)
public class FakeRemoteViews {
private List<ViewUpdater> viewUpdaters = new ArrayList<ViewUpdater>();
@Implementation
public void setTextViewText(int viewId, final CharSequence text) {
viewUpdaters.add(new ViewUpdater(viewId) {
@Override public void doUpdate(View view) {
((TextView) view).setText(text);
}
});
}
@Implementation
public void setOnClickPendingIntent(int viewId, final PendingIntent pendingIntent) {
viewUpdaters.add(new ViewUpdater(viewId) {
@Override void doUpdate(final View view) {
view.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View v) {
try {
pendingIntent.send(view.getContext(), 0, null);
} catch (PendingIntent.CanceledException e) {
throw new RuntimeException(e);
}
}
});
}
});
}
@Implementation
public void setViewVisibility(int viewId, final int visibility) {
viewUpdaters.add(new ViewUpdater(viewId) {
@Override public void doUpdate(View view) {
view.setVisibility(visibility);
}
});
}
@Implementation
public void setImageViewBitmap(int viewId, final Bitmap bitmap) {
viewUpdaters.add(new ViewUpdater(viewId) {
@Override public void doUpdate(View view) {
((ImageView) view).setImageBitmap(bitmap);
}
});
}
@Implementation
public void reapply(Context context, View v) {
for (ViewUpdater viewUpdater : viewUpdaters) {
viewUpdater.update(v);
}
}
private abstract class ViewUpdater {
private int viewId;
public ViewUpdater(int viewId) {
this.viewId = viewId;
}
final void update(View parent) {
doUpdate(parent.findViewById(viewId));
}
abstract void doUpdate(View view);
}
}
|
package lab.dynafig;
import javax.annotation.Nonnull;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
/**
* {@code Default} is a simple implementation of {@link Tracking}.
* <p>
* <strong>NB</strong> — {@link #trackAs(String, Function) trackAs}
* requires an additional type token parameter. This seems
* redundant—the type should be captured by the converter function
* parameter—but is required as Java does not support generic type
* parameter reification, and there is not extant a hack which works with all
* possible ways to pass in a function (i.e., method reference). A solution
* would eliminate the type token parameter needed as a caching key in {@link
* Default}. Alternatively, give up on memoizing and recompute conversion
* from string each call.
*
* @author <a href="mailto:boxley@thoughtworks.com">Brian Oxley</a>
*/
public final class Default
implements Tracking, Updating {
private final Map<String, Value> values = new ConcurrentHashMap<>();
public Default() {
}
public Default(@Nonnull final Map<String, String> pairs) {
updateAll(pairs);
}
public Default(@Nonnull final Properties properties) {
properties.
forEach((k, v) -> update((String) k, (String) v));
}
@Nonnull
@Override
public Optional<AtomicReference<String>> track(@Nonnull final String key,
@Nonnull final BiConsumer<String, ? super String> onUpdate) {
return track(key, Value::track, onUpdate);
}
@Nonnull
@Override
public Optional<AtomicBoolean> trackBool(@Nonnull final String key,
@Nonnull final BiConsumer<String, ? super Boolean> onUpdate) {
return track(key, Value::trackBool, onUpdate);
}
@Nonnull
@Override
public Optional<AtomicInteger> trackInt(@Nonnull final String key,
@Nonnull final BiConsumer<String, ? super Integer> onUpdate) {
return track(key, Value::trackInt, onUpdate);
}
@Nonnull
@Override
public <T> Optional<AtomicReference<T>> trackAs(@Nonnull final String key,
@Nonnull final Function<String, T> convert,
@Nonnull final BiConsumer<String, ? super T> onUpdate) {
return track(key, (v, c) -> v.trackAs(convert, c), onUpdate);
}
@Override
public void update(@Nonnull final String key, final String value) {
values.merge(key, new Value(value), (a, b) -> a.update(value));
}
private <B, T> Optional<B> track(final String key,
final BiFunction<Value, Consumer<T>, B> fn,
final BiConsumer<String, ? super T> onUpdate) {
return Optional.ofNullable(values.get(key)).
map(v -> fn.apply(v, curry(key, onUpdate)));
}
private static <U> Consumer<U> curry(final String key,
final BiConsumer<String, ? super U> onUpdate) {
return u -> onUpdate.accept(key, u);
}
private static final class Value {
private final String value;
private final List<Atomic<?, ?>> atomics;
private Value(final String value) {
this(value, new CopyOnWriteArrayList<>());
}
private Value(final String value, final List<Atomic<?, ?>> atomics) {
this.value = value;
this.atomics = atomics;
atomics.stream().
forEach(a -> a.accept(value));
}
private Value update(final String value) {
return Objects.equals(this.value, value) ? this
: new Value(value, atomics);
}
private AtomicReference<String> track(
final Consumer<? super String> onUpdate) {
final Atomic<AtomicReference<String>, String> s = new Atomic<>(
value, new AtomicReference<>(), AtomicReference::get,
AtomicReference::set, onUpdate);
atomics.add(s);
return s.atomic;
}
private AtomicBoolean trackBool(
final Consumer<? super Boolean> onUpdate) {
final Atomic<AtomicBoolean, Boolean> b = new Atomic<>(value,
new AtomicBoolean(), AtomicBoolean::get,
(a, v) -> a.set(null == v ? false : Boolean.valueOf(v)),
onUpdate);
atomics.add(b);
return b.atomic;
}
private AtomicInteger trackInt(
final Consumer<? super Integer> onUpdate) {
final Atomic<AtomicInteger, Integer> i = new Atomic<>(value,
new AtomicInteger(), AtomicInteger::get,
(a, v) -> a.set(null == v ? 0 : Integer.valueOf(v)),
onUpdate);
atomics.add(i);
return i.atomic;
}
private <T> AtomicReference<T> trackAs(
final Function<? super String, T> convert,
final Consumer<? super T> onUpdate) {
final Atomic<AtomicReference<T>, T> t = new Atomic<>(value,
new AtomicReference<>(), AtomicReference::get,
(a, v) -> a.set(null == v ? null : convert.apply(v)),
onUpdate);
atomics.add(t);
return t.atomic;
}
}
private static class Atomic<T, U>
implements Consumer<String>, Supplier<U> {
protected final T atomic;
private final Function<T, U> get;
private final BiConsumer<T, String> set;
protected Atomic(final String value, final T atomic,
final Function<T, U> get, final BiConsumer<T, String> set,
final Consumer<? super U> onUpdate) {
this.atomic = atomic;
this.get = get;
this.set = set.
andThen((a, v) -> onUpdate.accept(get.apply(a)));
accept(value);
}
@Override
public final U get() {
return get.apply(atomic);
}
@Override
public final void accept(final String value) {
set.accept(atomic, value);
}
}
}
|
package com.restfb.types.send;
import com.restfb.Facebook;
import lombok.Setter;
public class WebButton extends AbstractButton {
@Setter
@Facebook("webview_height_ratio")
private WebviewHeightEnum webviewHeightRatio;
@Facebook
private String url;
@Facebook("messenger_extensions")
private Boolean messengerExtensions;
@Facebook("fallback_url")
private String fallbackUrl;
public WebButton(String title, String webUrl) {
super(title);
setType("web_url");
this.url = webUrl;
}
public void setMessengerExtensions(boolean withMessengerExtensions, String fallbackUrl) {
if (withMessengerExtensions) {
this.messengerExtensions = true;
this.fallbackUrl = fallbackUrl;
} else {
messengerExtensions = null;
this.fallbackUrl = null;
}
}
}
|
package net.katsuster.ememu.riscv.core;
import net.katsuster.ememu.generic.*;
public class InstructionRV32 extends Inst32 {
/**
* 32bit RISC-V
*
* @param inst 32bit RISC-V
*/
public InstructionRV32(int inst) {
super(inst, 4);
}
//opcode[6:2] (opcode[1:0] = 11)
public static final int OPCODE_LOAD = 0;
public static final int OPCODE_LOAD_FP = 1;
public static final int OPCODE_CUSTOM_0 = 2;
public static final int OPCODE_MISC_MEM = 3;
public static final int OPCODE_OP_IMM = 4;
public static final int OPCODE_AUIPC = 5;
public static final int OPCODE_OP_IMM_32 = 6;
public static final int OPCODE_48B_1 = 7;
public static final int OPCODE_STORE = 8;
public static final int OPCODE_STORE_FP = 9;
public static final int OPCODE_CUSTOM_1 = 10;
public static final int OPCODE_AMO = 11;
public static final int OPCODE_OP = 12;
public static final int OPCODE_LUI = 13;
public static final int OPCODE_OP_32 = 14;
public static final int OPCODE_64B = 15;
public static final int OPCODE_MADD = 16;
public static final int OPCODE_MSUB = 17;
public static final int OPCODE_NMSUB = 18;
public static final int OPCODE_NMADD = 19;
public static final int OPCODE_OP_FP = 20;
public static final int OPCODE_RESERVED_0 = 21;
public static final int OPCODE_CUSTOM_2 = 22;
public static final int OPCODE_48B_2 = 23;
public static final int OPCODE_BRANCH = 24;
public static final int OPCODE_JALR = 25;
public static final int OPCODE_RESERVED_1 = 26;
public static final int OPCODE_JAL = 27;
public static final int OPCODE_SYSTEM = 28;
public static final int OPCODE_RESERVED_2 = 29;
public static final int OPCODE_CUSTOM_3 = 30;
public static final int OPCODE_80B = 31;
/**
* 32bit opcode [6:2]
*
* @return opcode
*/
public int getOpcode() {
return getField(2, 5);
}
//funct3
public static final int FUNC_JALR_JALR = 0;
public static final int FUNC_BRANCH_BEQ = 0;
public static final int FUNC_BRANCH_BNE = 1;
public static final int FUNC_BRANCH_BLT = 4;
public static final int FUNC_BRANCH_BGE = 5;
public static final int FUNC_BRANCH_BLTU = 6;
public static final int FUNC_BRANCH_BGEU = 7;
public static final int FUNC_LOAD_LB = 0;
public static final int FUNC_LOAD_LH = 1;
public static final int FUNC_LOAD_LW = 2;
public static final int FUNC_LOAD_LD = 3;
public static final int FUNC_LOAD_LBU = 4;
public static final int FUNC_LOAD_LHU = 5;
public static final int FUNC_LOAD_LWU = 6;
public static final int FUNC_OP_IMM_ADDI = 0;
public static final int FUNC_OP_IMM_SLTI = 2;
public static final int FUNC_OP_IMM_SLTIU = 3;
public static final int FUNC_OP_IMM_XORI = 4;
public static final int FUNC_OP_IMM_ORI = 6;
public static final int FUNC_OP_IMM_ANDI = 7;
public static final int FUNC_OP_IMM_SLI = 1;
public static final int FUNC_OP_IMM_SRI = 5;
public static final int FUNC_OP_ADDSUB = 0;
public static final int FUNC_OP_SLL = 1;
public static final int FUNC_OP_SLT = 2;
public static final int FUNC_OP_SLTU = 3;
public static final int FUNC_OP_XOR = 4;
public static final int FUNC_OP_SR = 5;
public static final int FUNC_OP_OR = 6;
public static final int FUNC_OP_AND = 7;
public static final int FUNC_SYSTEM_EX = 0;
public static final int FUNC_SYSTEM_CSRRW = 1;
public static final int FUNC_SYSTEM_CSRRS = 2;
public static final int FUNC_SYSTEM_CSRRC = 3;
public static final int FUNC_SYSTEM_CSRRWI = 5;
public static final int FUNC_SYSTEM_CSRRSI = 6;
public static final int FUNC_SYSTEM_CSRRCI = 7;
/**
* 32bit funct3 [14:12]
*
* @return funct3
*/
public int getFunct3() {
return getField(12, 3);
}
/**
* 32bit rd [11:7]
*
* @return rd
*/
public int getRd() {
return getField(7, 5);
}
/**
* 32bit rs1 [19:15]
*
* @return rs1
*/
public int getRs1() {
return getField(15, 5);
}
/**
* 32bit rs2 [24:20]
*
* @return rs2
*/
public int getRs2() {
return getField(20, 5);
}
/**
* 32bit I-type imm [31:20]
*
* @return imm[11:0]
*/
public int getImm12I() {
return getField(20, 12);
}
/**
* 32bit I-type imm 7 [31:25]
*
* RV32I ADD, SLLI
*
* @return imm[11:0] 7
*/
public int getImm7I() {
return getField(25, 7);
}
/**
* RV64 I-type imm 6 [31:26]
*
* RV64I ADD, SLLI
*
* @return imm[11:0] 6
*/
public int getImm6I() {
return getField(26, 6);
}
/**
* 32bit U-type imm [31:12]
* 12bit
*
* @return imm
*/
public int getImm20U() {
return getField(12, 20) << 12;
}
/**
* 16
*
* @return 16
*/
@Override
public String toHex() {
return String.format("%08x", getInst());
}
}
|
package com.malhartech.stram.cli;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import jline.ArgumentCompletor;
import jline.Completor;
import jline.ConsoleReader;
import jline.FileNameCompletor;
import jline.History;
import jline.MultiCompletor;
import jline.SimpleCompletor;
import javax.ws.rs.core.MediaType;
import org.apache.commons.cli.*;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.api.protocolrecords.GetAllApplicationsRequest;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.api.records.ApplicationReport;
import org.apache.hadoop.yarn.api.records.FinalApplicationStatus;
import org.apache.hadoop.yarn.api.records.YarnApplicationState;
import org.apache.hadoop.yarn.exceptions.YarnRemoteException;
import org.apache.hadoop.yarn.util.Records;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.malhartech.stram.cli.StramAppLauncher.AppConfig;
import com.malhartech.stram.cli.StramClientUtils.ClientRMHelper;
import com.malhartech.stram.cli.StramClientUtils.YarnClientHelper;
import com.malhartech.stram.plan.logical.*;
import com.malhartech.stram.security.StramUserLogin;
import com.malhartech.stram.webapp.StramWebServices;
import com.malhartech.util.VersionInfo;
import com.malhartech.util.WebServicesClient;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
/**
*
* Provides command line interface for a streaming application on hadoop (yarn)<p>
*/
@SuppressWarnings("UseOfSystemOutOrSystemErr")
public class StramCli
{
private static final Logger LOG = LoggerFactory.getLogger(StramCli.class);
private final Configuration conf = new Configuration();
private ClientRMHelper rmClient;
private ApplicationReport currentApp = null;
private boolean consolePresent;
private String[] commandsToExecute;
private final Map<String, CommandSpec> globalCommands = new TreeMap<String, CommandSpec>();
private final Map<String, CommandSpec> connectedCommands = new TreeMap<String, CommandSpec>();
private final Map<String, CommandSpec> logicalPlanChangeCommands = new TreeMap<String, CommandSpec>();
private final Map<String, String> aliases = new HashMap<String, String>();
private final Map<String, List<String>> macros = new HashMap<String, List<String>>();
private boolean changingLogicalPlan = false;
List<LogicalPlanRequest> logicalPlanRequestQueue = new ArrayList<LogicalPlanRequest>();
private interface Command
{
void execute(String[] args, ConsoleReader reader) throws Exception;
}
private static class CommandSpec
{
Command command;
String[] requiredArgs;
String[] optionalArgs;
String description;
CommandSpec(Command command, String[] requiredArgs, String[] optionalArgs, String description)
{
this.command = command;
this.requiredArgs = requiredArgs;
this.optionalArgs = optionalArgs;
this.description = description;
}
}
StramCli()
{
globalCommands.put("help", new CommandSpec(new HelpCommand(), null, null, "Show help"));
globalCommands.put("connect", new CommandSpec(new ConnectCommand(), new String[] {"app-id"}, null, "Connect to an app"));
globalCommands.put("launch", new CommandSpec(new LaunchCommand(), new String[] {"jar-file"}, new String[] {"class-name"}, "Launch an app"));
globalCommands.put("launch-local", new CommandSpec(new LaunchCommand(), new String[] {"jar-file"}, new String[] {"class-name"}, "Launch an app in local mode"));
globalCommands.put("shutdown-app", new CommandSpec(new ShutdownAppCommand(), new String[] {"app-id"}, null, "Shutdown an app"));
globalCommands.put("list-apps", new CommandSpec(new ListAppsCommand(), null, new String[] {"app-id"}, "List applications"));
globalCommands.put("kill-app", new CommandSpec(new KillAppCommand(), new String[] {"app-id"}, null, "Kill an app"));
globalCommands.put("show-logical-plan", new CommandSpec(new ShowLogicalPlanCommand(), new String[] {"app-id"}, null, "Show logical plan of an app class"));
globalCommands.put("alias", new CommandSpec(new AliasCommand(), new String[] {"alias-name", "command"}, null, "Create a command alias"));
globalCommands.put("source", new CommandSpec(new SourceCommand(), new String[] {"file"}, null, "Execute the commands in a file"));
globalCommands.put("exit", new CommandSpec(new ExitCommand(), null, null, "Exit the CLI"));
globalCommands.put("begin-macro", new CommandSpec(new BeginMacroCommand(), new String[] {"name"}, null, "Begin Macro Definition"));
connectedCommands.put("list-containers", new CommandSpec(new ListContainersCommand(), null, null, "List containers"));
connectedCommands.put("list-operators", new CommandSpec(new ListOperatorsCommand(), null, new String[] {"pattern"}, "List operators"));
connectedCommands.put("kill-container", new CommandSpec(new KillContainerCommand(), new String[] {"container-id"}, null, "Kill a container"));
connectedCommands.put("shutdown-app", new CommandSpec(new ShutdownAppCommand(), null, null, "Shutdown an app"));
connectedCommands.put("kill-app", new CommandSpec(new KillAppCommand(), null, null, "Kill an app"));
connectedCommands.put("wait", new CommandSpec(new WaitCommand(), new String[] {"timeout"}, null, "Wait for completion of current application"));
connectedCommands.put("start-recording", new CommandSpec(new StartRecordingCommand(), new String[] {"operator-id"}, new String[] {"port-name"}, "Start recording"));
connectedCommands.put("stop-recording", new CommandSpec(new StopRecordingCommand(), new String[] {"operator-id"}, new String[] {"port-name"}, "Stop recording"));
connectedCommands.put("sync-recording", new CommandSpec(new SyncRecordingCommand(), new String[] {"operator-id"}, new String[] {"port-name"}, "Sync recording"));
connectedCommands.put("set-operator-property", new CommandSpec(new SetOperatorPropertyLiveCommand(), new String[] {"operator-name", "property-name", "property-value"}, null, "Set a property of an operator"));
connectedCommands.put("begin-logical-plan-change", new CommandSpec(new BeginLogicalPlanChangeCommand(), null, null, "Begin Logical Plan Change"));
logicalPlanChangeCommands.put("help", new CommandSpec(new HelpCommand(), null, null, "Show help"));
logicalPlanChangeCommands.put("create-operator", new CommandSpec(new CreateOperatorCommand(), new String[] {"operator-name", "class-name"}, null, "Create an operator"));
logicalPlanChangeCommands.put("create-stream", new CommandSpec(new CreateStreamCommand(), new String[] {"stream-name", "from-operator-name", "from-port-name", "to-operator-name", "to-port-name"}, null, "Create a stream"));
logicalPlanChangeCommands.put("remove-operator", new CommandSpec(new RemoveOperatorCommand(), new String[] {"operator-name"}, null, "Remove an operator"));
logicalPlanChangeCommands.put("remove-stream", new CommandSpec(new RemoveStreamCommand(), new String[] {"stream-name"}, null, "Remove a stream"));
logicalPlanChangeCommands.put("set-operator-property", new CommandSpec(new SetOperatorPropertyCommand(), new String[] {"operator-name", "property-name", "property-value"}, null, "Set a property of an operator"));
logicalPlanChangeCommands.put("set-operator-attribute", new CommandSpec(new SetOperatorAttributeCommand(), new String[] {"operator-name", "attr-name", "attr-value"}, null, "Set an attribute of an operator"));
logicalPlanChangeCommands.put("set-port-attribute", new CommandSpec(new SetPortAttributeCommand(), new String[] {"operator-name", "port-name", "attr-name", "attr-value"}, null, "Set an attribute of a port"));
logicalPlanChangeCommands.put("set-stream-attribute", new CommandSpec(new SetStreamAttributeCommand(), new String[] {"stream-name", "attr-name", "attr-value"}, null, "Set an attribute of a stream"));
logicalPlanChangeCommands.put("queue", new CommandSpec(new QueueCommand(), null, null, "Show the queue of the plan change"));
logicalPlanChangeCommands.put("submit", new CommandSpec(new SubmitCommand(), null, null, "Submit the plan change"));
logicalPlanChangeCommands.put("abort", new CommandSpec(new AbortCommand(), null, null, "Abort the plan change"));
StramClientUtils.addStramResources(conf);
}
protected ApplicationReport getApplication(int appSeq)
{
List<ApplicationReport> appList = getApplicationList();
for (ApplicationReport ar : appList) {
if (ar.getApplicationId().getId() == appSeq) {
return ar;
}
}
return null;
}
private class CliException extends RuntimeException
{
private static final long serialVersionUID = 1L;
CliException(String msg, Throwable cause)
{
super(msg, cause);
}
CliException(String msg)
{
super(msg);
}
}
public void init(String[] args) throws IOException
{
consolePresent = (System.console() != null);
Options options = new Options();
options.addOption("e", true, "Commands are read from the argument");
CommandLineParser parser = new BasicParser();
try {
CommandLine cmd = parser.parse(options, args);
if (cmd.hasOption("e")) {
commandsToExecute = cmd.getOptionValues("e");
consolePresent = false;
for (String command : commandsToExecute) {
LOG.debug("Command to be executed: {}", command);
}
}
}
catch (ParseException ex) {
System.err.println("Invalid argument: " + ex);
System.exit(1);
}
// Need to initialize security before starting RPC for the credentials to
// take effect
StramUserLogin.attemptAuthentication(conf);
YarnClientHelper yarnClient = new YarnClientHelper(conf);
rmClient = new ClientRMHelper(yarnClient);
}
/**
* Why reinvent the wheel?
* JLine 2.x supports search and more.. but it uses the same package as JLine 0.9.x
* Hadoop bundles and forces 0.9.x through zookeeper into our class path (when CLI is launched via hadoop command).
* And Jline 0.9.x hijacked Ctrl-R for REDISPLAY
*/
private class ConsoleReaderExt extends ConsoleReader
{
private final char REVERSE_SEARCH_KEY = (char)31;
ConsoleReaderExt() throws IOException
{
// CTRL-/ since CTRL-R already mapped to redisplay
addTriggeredAction(REVERSE_SEARCH_KEY, new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
try {
searchHistory();
}
catch (IOException ex) {
}
}
});
}
public int searchBackwards(CharSequence searchTerm, int startIndex)
{
@SuppressWarnings("unchecked")
List<String> history = getHistory().getHistoryList();
if (startIndex < 0) {
startIndex = history.size();
}
for (int i = startIndex; --i > 0;) {
String line = history.get(i);
if (line.contains(searchTerm)) {
return i;
}
}
return -1;
}
private void searchHistory() throws IOException
{
final String prompt = "reverse-search: ";
StringBuilder searchTerm = new StringBuilder();
String matchingCmd = null;
int historyIndex = -1;
while (true) {
while (backspace()) {
continue;
}
String line = prompt + searchTerm;
if (matchingCmd != null) {
line = line.concat(": ").concat(matchingCmd);
}
this.putString(line);
int c = this.readVirtualKey();
if (c == 8) {
if (searchTerm.length() > 0) {
searchTerm.deleteCharAt(searchTerm.length() - 1);
}
}
else if (c == REVERSE_SEARCH_KEY) {
int newIndex = searchBackwards(searchTerm, historyIndex);
if (newIndex >= 0) {
historyIndex = newIndex;
matchingCmd = (String)getHistory().getHistoryList().get(historyIndex);
}
}
else if (!Character.isISOControl(c)) {
searchTerm.append(Character.toChars(c));
int newIndex = searchBackwards(searchTerm, -1);
if (newIndex >= 0) {
historyIndex = newIndex;
matchingCmd = (String)getHistory().getHistoryList().get(historyIndex);
}
}
else {
while (backspace()) {
continue;
}
if (!StringUtils.isBlank(matchingCmd)) {
this.putString(matchingCmd);
this.flushConsole();
}
return;
}
}
}
}
private void processSourceFile(String fileName, ConsoleReader reader) throws FileNotFoundException, IOException
{
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line;
while ((line = br.readLine()) != null) {
processLine(line, reader);
}
br.close();
}
private void setupCompleter(ConsoleReader reader)
{
List<Completor> completors = new LinkedList<Completor>();
completors.add(new SimpleCompletor(connectedCommands.keySet().toArray(new String[] {})));
completors.add(new SimpleCompletor(globalCommands.keySet().toArray(new String[] {})));
completors.add(new SimpleCompletor(logicalPlanChangeCommands.keySet().toArray(new String[] {})));
List<Completor> launchCompletors = new LinkedList<Completor>();
launchCompletors.add(new SimpleCompletor(new String[] {"launch", "launch-local", "source"}));
launchCompletors.add(new FileNameCompletor()); // jarFile
launchCompletors.add(new FileNameCompletor()); // topology
completors.add(new ArgumentCompletor(launchCompletors));
reader.addCompletor(new MultiCompletor(completors));
}
private void setupHistory(ConsoleReader reader)
{
File historyFile = new File(StramClientUtils.getSettingsRootDir(), ".history");
historyFile.getParentFile().mkdirs();
try {
History history = new History(historyFile);
reader.setHistory(history);
}
catch (IOException ex) {
System.err.printf("Unable to open %s for writing.", historyFile);
}
}
public void run() throws IOException
{
ConsoleReader reader = new ConsoleReaderExt();
reader.setBellEnabled(false);
try {
processSourceFile(System.getProperty("user.home") + "/.stram/clirc", reader);
}
catch (Exception ex) {
// ignore
}
if (consolePresent) {
printWelcomeMessage();
setupCompleter(reader);
setupHistory(reader);
}
String line;
PrintWriter out = new PrintWriter(System.out);
int i = 0;
while (true) {
if (commandsToExecute != null) {
if (i >= commandsToExecute.length) {
break;
}
line = commandsToExecute[i++];
}
else {
line = readLine(reader, "");
if (line == null) {
break;
}
}
processLine(line, reader);
out.flush();
}
System.out.println("exit");
}
private List<String> expandMacro(List<String> lines, String[] args)
{
List<String> expandedLines = new ArrayList<String>();
for (String line : lines) {
int previousIndex = 0;
String expandedLine = "";
while (true) {
int currentIndex = line.indexOf('$', previousIndex);
if (currentIndex > 0 && line.length() > currentIndex + 1) {
int argIndex = line.charAt(currentIndex + 1) - '0';
if (args.length > argIndex && argIndex >= 0) {
expandedLine += line.substring(previousIndex, currentIndex);
expandedLine += args[argIndex];
} else {
expandedLine += line.substring(previousIndex, currentIndex + 2);
}
currentIndex += 2;
}
else {
expandedLine += line.substring(previousIndex);
expandedLines.add(expandedLine);
break;
}
previousIndex = currentIndex;
}
}
return expandedLines;
}
private void processLine(String line, ConsoleReader reader)
{
try {
String[] commands = line.split("\\s*;\\s*");
for (String command : commands) {
String[] args = command.split("\\s+");
if (StringUtils.isBlank(args[0])) {
continue;
}
if (macros.containsKey(args[0])) {
List<String> macroItems = expandMacro(macros.get(args[0]), args);
for (String macroItem : macroItems) {
System.out.println("expanded-macro> " + macroItem);
processLine(macroItem, reader);
}
continue;
}
if (aliases.containsKey(args[0])) {
args[0] = aliases.get(args[0]);
}
CommandSpec cs = null;
if (changingLogicalPlan) {
cs = logicalPlanChangeCommands.get(args[0]);
}
else {
if (currentApp != null) {
cs = connectedCommands.get(args[0]);
}
if (cs == null) {
cs = globalCommands.get(args[0]);
}
}
if (cs == null) {
System.err.println("Invalid command '" + args[0] + "'. Type \"help\" for list of commands");
}
else {
int minArgs = 0;
int maxArgs = 0;
if (cs.requiredArgs != null) {
minArgs = cs.requiredArgs.length;
maxArgs = cs.requiredArgs.length;
}
if (cs.optionalArgs != null) {
maxArgs += cs.optionalArgs.length;
}
if (args.length - 1 < minArgs || args.length - 1 > maxArgs) {
System.err.print("Usage: " + args[0]);
if (cs.requiredArgs != null) {
for (String arg : cs.requiredArgs) {
System.err.print(" <" + arg + ">");
}
}
if (cs.optionalArgs != null) {
for (String arg : cs.optionalArgs) {
System.err.print(" [<" + arg + ">]");
}
}
System.err.println();
}
else {
cs.command.execute(args, reader);
}
}
}
}
catch (CliException e) {
System.err.println(e.getMessage());
LOG.info("Error processing line: " + line, e);
}
catch (Exception e) {
System.err.println("Unexpected error: " + e);
}
}
private void printWelcomeMessage()
{
System.out.println("Stram CLI " + VersionInfo.getVersion() + " " + VersionInfo.getDate() + " " + VersionInfo.getRevision());
}
private void printHelp(Map<String, CommandSpec> commandSpecs)
{
for (Map.Entry<String, CommandSpec> entry : commandSpecs.entrySet()) {
CommandSpec cs = entry.getValue();
if (consolePresent) {
System.out.print("\033[0;93m");
System.out.print(entry.getKey());
System.out.print("\033[0m");
}
else {
System.out.print(entry.getKey());
}
if (cs.requiredArgs != null) {
for (String arg : cs.requiredArgs) {
if (consolePresent) {
System.out.print(" \033[3m" + arg + "\033[0m");
}
else {
System.out.print(" <" + arg + ">");
}
}
}
if (cs.optionalArgs != null) {
for (String arg : cs.optionalArgs) {
if (consolePresent) {
System.out.print(" [\033[3m" + arg + "\033[0m]");
}
else {
System.out.print(" [<" + arg + ">]");
}
}
}
System.out.println("\n\t" + cs.description);
//System.out.println();
}
}
private String readLine(ConsoleReader reader, String promptMessage)
throws IOException
{
String prompt = "";
if (consolePresent) {
prompt = promptMessage + "\n";
if (changingLogicalPlan) {
prompt += "logical-plan-change";
}
else {
prompt += "stramcli";
}
if (currentApp != null) {
prompt += " (";
prompt += currentApp.getApplicationId().toString();
prompt += ") ";
}
prompt += "> ";
}
String line = reader.readLine(prompt);
if (line == null) {
return null;
}
return line.trim();
}
private List<ApplicationReport> getApplicationList()
{
try {
GetAllApplicationsRequest appsReq = Records.newRecord(GetAllApplicationsRequest.class);
return rmClient.clientRM.getAllApplications(appsReq).getApplicationList();
}
catch (Exception e) {
throw new CliException("Error getting application list from resource manager: " + e.getMessage(), e);
}
}
private ApplicationReport assertRunningApp(ApplicationReport app)
{
ApplicationReport r;
try {
r = rmClient.getApplicationReport(app.getApplicationId());
if (r.getYarnApplicationState() != YarnApplicationState.RUNNING) {
String msg = String.format("Application %s not running (status %s)",
r.getApplicationId().getId(), r.getYarnApplicationState());
throw new CliException(msg);
}
}
catch (YarnRemoteException rmExc) {
throw new CliException("Unable to determine application status.", rmExc);
}
return r;
}
private ClientResponse getResource(String resourcePath)
{
if (currentApp == null) {
throw new CliException("No application selected");
}
if (StringUtils.isEmpty(currentApp.getTrackingUrl()) || currentApp.getFinalApplicationStatus() != FinalApplicationStatus.UNDEFINED) {
currentApp = null;
throw new CliException("Application terminated.");
}
WebServicesClient wsClient = new WebServicesClient();
Client client = wsClient.getClient();
client.setFollowRedirects(true);
WebResource r = client.resource("http://" + currentApp.getTrackingUrl()).path(StramWebServices.PATH).path(resourcePath);
try {
return wsClient.process(r, ClientResponse.class, new WebServicesClient.WebServicesHandler<ClientResponse>()
{
@Override
public ClientResponse process(WebResource webResource, Class<ClientResponse> clazz)
{
ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (!MediaType.APPLICATION_JSON_TYPE.equals(response.getType())) {
//throw new Exception("Unexpected response type " + response.getType());
}
return response;
}
});
}
catch (Exception e) {
// check the application status as above may have failed due application termination etc.
currentApp = assertRunningApp(currentApp);
throw new CliException("Failed to request " + r.getURI(), e);
}
}
private WebResource getPostResource(WebServicesClient webServicesClient)
{
if (currentApp == null) {
throw new CliException("No application selected");
}
// YARN-156 WebAppProxyServlet does not support POST - for now bypass it for this request
currentApp = assertRunningApp(currentApp); // or else "N/A" might be there..
String trackingUrl = currentApp.getOriginalTrackingUrl();
Client wsClient = webServicesClient.getClient();
wsClient.setFollowRedirects(true);
return wsClient.resource("http://" + trackingUrl).path(StramWebServices.PATH);
}
/*
* Below is the implementation of all commands
*/
private class HelpCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
System.out.println("GLOBAL COMMANDS EXCEPT WHEN CHANGING LOGICAL PLAN:\n");
printHelp(globalCommands);
System.out.println();
System.out.println("COMMANDS WHEN CONNECTED TO AN APP (via connect <appid>) EXCEPT WHEN CHANGING LOGICAL PLAN:\n");
printHelp(connectedCommands);
System.out.println();
System.out.println("COMMANDS WHEN CHANGING LOGICAL PLAN:\n");
printHelp(logicalPlanChangeCommands);
System.out.println();
}
}
private class ConnectCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (args.length != 2) {
System.err.println("Invalid arguments");
return;
}
currentApp = getApplication(Integer.parseInt(args[1]));
if (currentApp == null) {
throw new CliException("Invalid application id: " + args[1]);
}
boolean connected = false;
try {
LOG.info("Selected {} with tracking url: ", currentApp.getApplicationId(), currentApp.getTrackingUrl());
ClientResponse rsp = getResource(StramWebServices.PATH_INFO);
JSONObject json = rsp.getEntity(JSONObject.class);
System.out.println(json.toString(2));
connected = true; // set as current only upon successful connection
}
catch (CliException e) {
throw e; // pass on
}
catch (JSONException e) {
throw new CliException("Error connecting to app " + args[1], e);
}
finally {
if (!connected) {
//currentApp = null;
//currentDir = "/";
}
}
}
}
private class LaunchCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
boolean localMode = "launch-local".equals(args[0]);
AppConfig appConfig = null;
if (args.length == 3) {
File file = new File(args[2]);
appConfig = new StramAppLauncher.PropertyFileAppConfig(file);
}
try {
StramAppLauncher submitApp = new StramAppLauncher(new File(args[1]));
if (appConfig == null) {
List<AppConfig> cfgList = submitApp.getBundledTopologies();
if (cfgList.isEmpty()) {
throw new CliException("No applications bundled in jar, please specify one");
}
else if (cfgList.size() == 1) {
appConfig = cfgList.get(0);
}
else {
for (int i = 0; i < cfgList.size(); i++) {
System.out.printf("%3d. %s\n", i + 1, cfgList.get(i).getName());
}
boolean useHistory = reader.getUseHistory();
reader.setUseHistory(false);
@SuppressWarnings("unchecked")
List<Completor> completors = new ArrayList<Completor>(reader.getCompletors());
for (Completor c : completors) {
reader.removeCompletor(c);
}
String optionLine = reader.readLine("Pick application? ");
reader.setUseHistory(useHistory);
for (Completor c : completors) {
reader.addCompletor(c);
}
try {
int option = Integer.parseInt(optionLine);
if (0 < option && option <= cfgList.size()) {
appConfig = cfgList.get(option - 1);
}
}
catch (Exception e) {
// ignore
}
}
}
if (appConfig != null) {
if (!localMode) {
ApplicationId appId = submitApp.launchApp(appConfig);
currentApp = rmClient.getApplicationReport(appId);
System.out.println(appId);
}
else {
submitApp.runLocal(appConfig);
}
}
else {
System.err.println("No application specified.");
}
}
catch (Exception e) {
throw new CliException("Failed to launch " + args[1] + ": " + e.getMessage(), e);
}
}
}
private class ShutdownAppCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
WebServicesClient webServicesClient = new WebServicesClient();
WebResource r = getPostResource(webServicesClient).path(StramWebServices.PATH_SHUTDOWN);
try {
JSONObject response = webServicesClient.process(r, JSONObject.class, new WebServicesClient.WebServicesHandler<JSONObject>()
{
@Override
public JSONObject process(WebResource webResource, Class<JSONObject> clazz)
{
return webResource.accept(MediaType.APPLICATION_JSON).post(clazz);
}
});
System.out.println("shutdown requested: " + response);
currentApp = null;
}
catch (Exception e) {
throw new CliException("Failed to request " + r.getURI(), e);
}
}
}
private class ListAppsCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
try {
List<ApplicationReport> appList = getApplicationList();
Collections.sort(appList, new Comparator<ApplicationReport>()
{
@Override
public int compare(ApplicationReport o1, ApplicationReport o2)
{
return o1.getApplicationId().getId() - o2.getApplicationId().getId();
}
});
System.out.println("Applications:");
int totalCnt = 0;
int runningCnt = 0;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
for (ApplicationReport ar : appList) {
boolean show;
/*
* This is inefficient, but what the heck, if this can be passed through the command line, can anyone notice slowness.
*/
if (args.length == 1 || args.length == 2 && (args[1].equals("/") || args[1].equals(".."))) {
show = true;
}
else {
show = false;
String appid = String.valueOf(ar.getApplicationId().getId());
for (int i = args.length; i
if (appid.equals(args[i])) {
show = true;
break;
}
}
}
if (show) {
StringBuilder sb = new StringBuilder();
sb.append("startTime: ").append(sdf.format(new java.util.Date(ar.getStartTime()))).
append(", id: ").append(ar.getApplicationId().getId()).
append(", name: ").append(ar.getName()).
append(", state: ").append(ar.getYarnApplicationState().name()).
append(", trackingUrl: ").append(ar.getTrackingUrl()).
append(", finalStatus: ").append(ar.getFinalApplicationStatus());
System.out.println(sb);
totalCnt++;
if (ar.getYarnApplicationState() == YarnApplicationState.RUNNING) {
runningCnt++;
}
}
}
System.out.println(runningCnt + " active, total " + totalCnt + " applications.");
}
catch (Exception ex) {
throw new CliException("Failed to retrieve application list", ex);
}
}
}
private class KillAppCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (args.length == 1) {
if (currentApp == null) {
throw new CliException("No application selected");
}
else {
try {
rmClient.killApplication(currentApp.getApplicationId());
currentApp = null;
}
catch (YarnRemoteException e) {
throw new CliException("Failed to kill " + currentApp.getApplicationId(), e);
}
}
return;
}
ApplicationReport app = null;
int i = 0;
try {
while (++i < args.length) {
app = getApplication(Integer.parseInt(args[i]));
rmClient.killApplication(app.getApplicationId());
if (app == currentApp) {
currentApp = null;
}
}
}
catch (YarnRemoteException e) {
throw new CliException("Failed to kill " + ((app == null || app.getApplicationId() == null) ? "unknown application" : app.getApplicationId()) + ". Aborting killing of any additional applications.", e);
}
catch (NumberFormatException nfe) {
throw new CliException("Invalid application Id " + args[i], nfe);
}
catch (NullPointerException npe) {
throw new CliException("Application with Id " + args[i] + " does not seem to be alive!", npe);
}
}
}
private class AliasCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
aliases.put(args[1], args[2]);
}
}
private class SourceCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
processSourceFile(args[1], reader);
}
}
private class ExitCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
System.exit(0);
}
}
private class ListContainersCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
ClientResponse rsp = getResource(StramWebServices.PATH_CONTAINERS);
JSONObject json = rsp.getEntity(JSONObject.class);
if (args.length == 1) {
System.out.println(json.toString(2));
}
else {
JSONArray containers = json.getJSONArray("containers");
if (containers == null) {
System.out.println("No containers found!");
}
else {
for (int o = containers.length(); o
JSONObject container = containers.getJSONObject(o);
String id = container.getString("id");
if (id != null && !id.isEmpty()) {
for (int argc = args.length; argc
String s1 = "0" + args[argc];
String s2 = "_" + args[argc];
if (id.endsWith(s1) || id.endsWith(s2)) {
System.out.println(container.toString(2));
}
}
}
}
}
}
}
}
private class ListOperatorsCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
ClientResponse rsp = getResource(StramWebServices.PATH_OPERATORS);
JSONObject json = rsp.getEntity(JSONObject.class);
if (args.length > 1) {
String singleKey = "" + json.keys().next();
JSONArray matches = new JSONArray();
// filter operators
JSONArray arr = json.getJSONArray(singleKey);
for (int i = 0; i < arr.length(); i++) {
Object val = arr.get(i);
if (val.toString().matches(args[1])) {
matches.put(val);
}
}
json.put(singleKey, matches);
}
System.out.println(json.toString(2));
}
}
private class KillContainerCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
WebServicesClient webServicesClient = new WebServicesClient();
WebResource r = getPostResource(webServicesClient).path(StramWebServices.PATH_CONTAINERS).path(args[1]).path("kill");
try {
JSONObject response = webServicesClient.process(r, JSONObject.class, new WebServicesClient.WebServicesHandler<JSONObject>()
{
@Override
public JSONObject process(WebResource webResource, Class<JSONObject> clazz)
{
return webResource.accept(MediaType.APPLICATION_JSON).post(clazz, new JSONObject());
}
});
System.out.println("container stop requested: " + response);
}
catch (Exception e) {
throw new CliException("Failed to request " + r.getURI(), e);
}
}
}
private class WaitCommand implements Command
{
@Override
public void execute(String[] args, final ConsoleReader reader) throws Exception
{
if (currentApp == null) {
throw new CliException("No application selected");
}
int timeout = Integer.valueOf(args[1]);
ClientRMHelper.AppStatusCallback cb = new ClientRMHelper.AppStatusCallback()
{
@Override
public boolean exitLoop(ApplicationReport report)
{
System.out.println("current status is: " + report.getYarnApplicationState());
try {
if (reader.getInput().available() > 0) {
return true;
}
}
catch (IOException e) {
LOG.error("Error checking for input.", e);
}
return false;
}
};
try {
boolean result = rmClient.waitForCompletion(currentApp.getApplicationId(), cb, timeout * 1000);
if (!result) {
System.err.println("Application terminated unsucessful.");
}
}
catch (YarnRemoteException e) {
throw new CliException("Failed to kill " + currentApp.getApplicationId(), e);
}
}
}
private class StartRecordingCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (args.length != 2 && args.length != 3) {
System.err.println("Invalid arguments");
return;
}
WebServicesClient webServicesClient = new WebServicesClient();
WebResource r = getPostResource(webServicesClient).path(StramWebServices.PATH_STARTRECORDING);
final JSONObject request = new JSONObject();
try {
request.put("operId", args[1]);
if (args.length == 3) {
request.put("portName", args[2]);
}
JSONObject response = webServicesClient.process(r, JSONObject.class, new WebServicesClient.WebServicesHandler<JSONObject>()
{
@Override
public JSONObject process(WebResource webResource, Class<JSONObject> clazz)
{
return webResource.accept(MediaType.APPLICATION_JSON).post(clazz, request);
}
});
System.out.println("start recording requested: " + response);
}
catch (Exception e) {
throw new CliException("Failed to request " + r.getURI(), e);
}
}
}
private class StopRecordingCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (args.length != 2 && args.length != 3) {
System.err.println("Invalid arguments");
return;
}
WebServicesClient webServicesClient = new WebServicesClient();
WebResource r = getPostResource(webServicesClient).path(StramWebServices.PATH_STOPRECORDING);
final JSONObject request = new JSONObject();
try {
request.put("operId", args[1]);
if (args.length == 3) {
request.put("portName", args[2]);
}
JSONObject response = webServicesClient.process(r, JSONObject.class, new WebServicesClient.WebServicesHandler<JSONObject>()
{
@Override
public JSONObject process(WebResource webResource, Class<JSONObject> clazz)
{
return webResource.accept(MediaType.APPLICATION_JSON).post(clazz, request);
}
});
System.out.println("stop recording requested: " + response);
}
catch (Exception e) {
throw new CliException("Failed to request " + r.getURI(), e);
}
}
}
private class SyncRecordingCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (args.length != 2 && args.length != 3) {
System.err.println("Invalid arguments");
return;
}
WebServicesClient webServicesClient = new WebServicesClient();
WebResource r = getPostResource(webServicesClient).path(StramWebServices.PATH_SYNCRECORDING);
final JSONObject request = new JSONObject();
try {
request.put("operId", args[1]);
if (args.length == 3) {
request.put("portName", args[2]);
}
JSONObject response = webServicesClient.process(r, JSONObject.class, new WebServicesClient.WebServicesHandler<JSONObject>()
{
@Override
public JSONObject process(WebResource webResource, Class<JSONObject> clazz)
{
return webResource.accept(MediaType.APPLICATION_JSON).post(clazz, request);
}
});
System.out.println("sync recording requested: " + response);
}
catch (Exception e) {
throw new CliException("Failed to request " + r.getURI(), e);
}
}
}
private class SetOperatorPropertyLiveCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (currentApp == null) {
throw new CliException("No application selected");
}
WebServicesClient webServicesClient = new WebServicesClient();
WebResource r = getPostResource(webServicesClient).path(StramWebServices.PATH_LOGICAL_PLAN_OPERATORS).path(args[1]).path("setProperty");
try {
final JSONObject request = new JSONObject();
request.put("propertyName", args[2]);
request.put("propertyValue", args[3]);
JSONObject response = webServicesClient.process(r, JSONObject.class, new WebServicesClient.WebServicesHandler<JSONObject>()
{
@Override
public JSONObject process(WebResource webResource, Class<JSONObject> clazz)
{
return webResource.accept(MediaType.APPLICATION_JSON).post(JSONObject.class, request);
}
});
System.out.println("request submitted: " + response);
}
catch (Exception e) {
throw new CliException("Failed to request " + r.getURI(), e);
}
}
}
private class SetOperatorPropertyCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String operatorName = args[1];
String propertyName = args[2];
String propertyValue = args[3];
SetOperatorPropertyRequest request = new SetOperatorPropertyRequest();
request.setOperatorName(operatorName);
request.setPropertyName(propertyName);
request.setPropertyValue(propertyValue);
logicalPlanRequestQueue.add(request);
}
}
private class BeginLogicalPlanChangeCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
changingLogicalPlan = true;
}
}
private class ShowLogicalPlanCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
private class CreateOperatorCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String operatorName = args[1];
String className = args[2];
CreateOperatorRequest request = new CreateOperatorRequest();
request.setOperatorName(operatorName);
request.setOperatorFQCN(className);
logicalPlanRequestQueue.add(request);
}
}
private class RemoveOperatorCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String operatorName = args[1];
RemoveOperatorRequest request = new RemoveOperatorRequest();
request.setOperatorName(operatorName);
logicalPlanRequestQueue.add(request);
}
}
private class CreateStreamCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String streamName = args[1];
String sourceOperatorName = args[2];
String sourcePortName = args[3];
String sinkOperatorName = args[4];
String sinkPortName = args[5];
CreateStreamRequest request = new CreateStreamRequest();
request.setStreamName(streamName);
request.setSourceOperatorName(sourceOperatorName);
request.setSinkOperatorName(sinkOperatorName);
request.setSourceOperatorPortName(sourcePortName);
request.setSinkOperatorPortName(sinkPortName);
logicalPlanRequestQueue.add(request);
}
}
private class RemoveStreamCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String streamName = args[1];
RemoveStreamRequest request = new RemoveStreamRequest();
request.setStreamName(streamName);
logicalPlanRequestQueue.add(request);
}
}
private class SetOperatorAttributeCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String operatorName = args[1];
String attributeName = args[2];
String attributeValue = args[3];
SetOperatorAttributeRequest request = new SetOperatorAttributeRequest();
request.setOperatorName(operatorName);
request.setAttributeName(attributeName);
request.setAttributeValue(attributeValue);
logicalPlanRequestQueue.add(request);
}
}
private class SetStreamAttributeCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String streamName = args[1];
String attributeName = args[2];
String attributeValue = args[3];
SetStreamAttributeRequest request = new SetStreamAttributeRequest();
request.setStreamName(streamName);
request.setAttributeName(attributeName);
request.setAttributeValue(attributeValue);
logicalPlanRequestQueue.add(request);
}
}
private class SetPortAttributeCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String operatorName = args[1];
String attributeName = args[2];
String attributeValue = args[3];
SetPortAttributeRequest request = new SetPortAttributeRequest();
request.setOperatorName(operatorName);
request.setAttributeName(attributeName);
request.setAttributeValue(attributeValue);
logicalPlanRequestQueue.add(request);
}
}
private class AbortCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
logicalPlanRequestQueue.clear();
changingLogicalPlan = false;
}
}
private class SubmitCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
if (logicalPlanRequestQueue.isEmpty()) {
throw new CliException("Nothing to submit. Type \"abort\" to abort change");
}
WebServicesClient webServicesClient = new WebServicesClient();
WebResource r = getPostResource(webServicesClient).path(StramWebServices.PATH_LOGICAL_PLAN_MODIFICATION);
try {
final Map<String, Object> m = new HashMap<String, Object>();
ObjectMapper mapper = new ObjectMapper();
m.put("requests", logicalPlanRequestQueue);
final JSONObject jsonRequest = new JSONObject(mapper.writeValueAsString(m));
JSONObject response = webServicesClient.process(r, JSONObject.class, new WebServicesClient.WebServicesHandler<JSONObject>()
{
@Override
public JSONObject process(WebResource webResource, Class<JSONObject> clazz)
{
return webResource.accept(MediaType.APPLICATION_JSON).post(JSONObject.class, jsonRequest);
}
});
System.out.println("request submitted: " + response);
}
catch (Exception e) {
throw new CliException("Failed to request " + r.getURI(), e);
}
logicalPlanRequestQueue.clear();
changingLogicalPlan = false;
}
}
private class QueueCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
ObjectMapper mapper = new ObjectMapper();
System.out.println(mapper.defaultPrettyPrintingWriter().writeValueAsString(logicalPlanRequestQueue));
System.out.println("Total operations in queue: " + logicalPlanRequestQueue.size());
}
}
private class BeginMacroCommand implements Command
{
@Override
public void execute(String[] args, ConsoleReader reader) throws Exception
{
String name = args[1];
if (macros.containsKey(name) || aliases.containsKey(name)) {
System.err.println("Name '" + name + "' already exists.");
return;
}
try {
List<String> commands = new ArrayList<String>();
while (true) {
String line = reader.readLine("macro def (" + name + ") > ");
if (line.equals("end")) {
macros.put(name, commands);
System.out.println("Macro '" + name + "' created.");
return;
}
else if (line.equals("abort")) {
System.err.println("Aborted");
return;
}
else {
commands.add(line);
}
}
}
catch (IOException ex) {
System.err.println("Aborted");
}
}
}
public static void main(String[] args) throws Exception
{
StramCli shell = new StramCli();
shell.init(args);
shell.run();
}
}
|
package com.jme3.scene.plugins.ogre;
import com.jme3.animation.Animation;
import com.jme3.scene.plugins.ogre.matext.OgreMaterialKey;
import com.jme3.animation.AnimControl;
import com.jme3.animation.BoneAnimation;
import com.jme3.animation.SkeletonControl;
import com.jme3.asset.AssetInfo;
import com.jme3.asset.AssetKey;
import com.jme3.asset.AssetLoader;
import com.jme3.asset.AssetManager;
import com.jme3.asset.AssetNotFoundException;
import com.jme3.material.Material;
import com.jme3.material.MaterialList;
import com.jme3.math.ColorRGBA;
import com.jme3.renderer.queue.RenderQueue.Bucket;
import com.jme3.scene.Geometry;
import com.jme3.scene.Mesh;
import com.jme3.scene.Node;
import com.jme3.scene.UserData;
import com.jme3.scene.VertexBuffer;
import com.jme3.scene.VertexBuffer.Format;
import com.jme3.scene.VertexBuffer.Type;
import com.jme3.scene.VertexBuffer.Usage;
import com.jme3.system.JmeSystem;
import com.jme3.util.BufferUtils;
import com.jme3.util.IntMap;
import com.jme3.util.IntMap.Entry;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
import static com.jme3.util.xml.SAXUtil.*;
/**
* Loads Ogre3D mesh.xml files.
*/
public class MeshLoader extends DefaultHandler implements AssetLoader {
private static final Logger logger = Logger.getLogger(MeshLoader.class.getName());
public static boolean AUTO_INTERLEAVE = true;
public static boolean HARDWARE_SKINNING = false;
private static final Type[] TEXCOORD_TYPES =
new Type[]{
Type.TexCoord,
Type.TexCoord2,
Type.TexCoord3,
Type.TexCoord4,
Type.TexCoord5,
Type.TexCoord6,
Type.TexCoord7,
Type.TexCoord8,};
private String meshName;
private String folderName;
private AssetManager assetManager;
private MaterialList materialList;
// Data per submesh/sharedgeom
private ShortBuffer sb;
private IntBuffer ib;
private FloatBuffer fb;
private VertexBuffer vb;
private Mesh mesh;
private Geometry geom;
private ByteBuffer indicesData;
private FloatBuffer weightsFloatData;
private int vertCount;
private boolean usesSharedVerts;
private boolean usesBigIndices;
// Global data
private Mesh sharedMesh;
private int meshIndex = 0;
private int texCoordIndex = 0;
private String ignoreUntilEnd = null;
private List<Geometry> geoms = new ArrayList<Geometry>();
private IntMap<List<VertexBuffer>> lodLevels = new IntMap<List<VertexBuffer>>();
private AnimData animData;
public MeshLoader() {
super();
}
@Override
public void startDocument() {
geoms.clear();
lodLevels.clear();
sb = null;
ib = null;
fb = null;
vb = null;
mesh = null;
geom = null;
sharedMesh = null;
usesSharedVerts = false;
vertCount = 0;
meshIndex = 0;
texCoordIndex = 0;
ignoreUntilEnd = null;
animData = null;
indicesData = null;
weightsFloatData = null;
}
@Override
public void endDocument() {
}
private void pushFace(String v1, String v2, String v3) throws SAXException {
int i1 = parseInt(v1);
// TODO: fan/strip support
int i2 = parseInt(v2);
int i3 = parseInt(v3);
if (ib != null) {
ib.put(i1).put(i2).put(i3);
} else {
sb.put((short) i1).put((short) i2).put((short) i3);
}
}
private boolean isUsingSharedVerts(Geometry geom) {
return geom.getUserData(UserData.JME_SHAREDMESH) != null;
}
private void startFaces(String count) throws SAXException {
int numFaces = parseInt(count);
int numIndices;
if (mesh.getMode() == Mesh.Mode.Triangles) {
numIndices = numFaces * 3;
} else {
throw new SAXException("Triangle strip or fan not supported!");
}
vb = new VertexBuffer(VertexBuffer.Type.Index);
if (!usesBigIndices) {
sb = BufferUtils.createShortBuffer(numIndices);
ib = null;
vb.setupData(Usage.Static, 3, Format.UnsignedShort, sb);
} else {
ib = BufferUtils.createIntBuffer(numIndices);
sb = null;
vb.setupData(Usage.Static, 3, Format.UnsignedInt, ib);
}
mesh.setBuffer(vb);
}
private void applyMaterial(Geometry geom, String matName) {
Material mat = null;
if (matName.endsWith(".j3m")) {
// load as native jme3 material instance
mat = assetManager.loadMaterial(matName);
} else {
if (materialList != null) {
mat = materialList.get(matName);
}
if (mat == null) {
logger.log(Level.WARNING, "Material {0} not found. Applying default material", matName);
mat = (Material) assetManager.loadMaterial("Common/Materials/RedColor.j3m");
}
}
if (mat == null) {
throw new RuntimeException("Cannot locate material named " + matName);
}
if (mat.isTransparent()) {
geom.setQueueBucket(Bucket.Transparent);
}
geom.setMaterial(mat);
}
private void startSubMesh(String matName, String usesharedvertices, String use32bitIndices, String opType) throws SAXException {
mesh = new Mesh();
if (opType == null || opType.equals("triangle_list")) {
mesh.setMode(Mesh.Mode.Triangles);
} else if (opType.equals("triangle_strip")) {
mesh.setMode(Mesh.Mode.TriangleStrip);
} else if (opType.equals("triangle_fan")) {
mesh.setMode(Mesh.Mode.TriangleFan);
}
usesBigIndices = parseBool(use32bitIndices, false);
usesSharedVerts = parseBool(usesharedvertices, false);
if (usesSharedVerts) {
// import vertexbuffers from shared geom
IntMap<VertexBuffer> sharedBufs = sharedMesh.getBuffers();
for (Entry<VertexBuffer> entry : sharedBufs) {
mesh.setBuffer(entry.getValue());
}
}
if (meshName == null) {
geom = new Geometry("OgreSubmesh-" + (++meshIndex), mesh);
} else {
geom = new Geometry(meshName + "-geom-" + (++meshIndex), mesh);
}
if (usesSharedVerts) {
// this mesh is shared!
geom.setUserData(UserData.JME_SHAREDMESH, sharedMesh);
}
applyMaterial(geom, matName);
geoms.add(geom);
}
private void startSharedGeom(String vertexcount) throws SAXException {
sharedMesh = new Mesh();
vertCount = parseInt(vertexcount);
usesSharedVerts = false;
geom = null;
mesh = sharedMesh;
}
private void startGeometry(String vertexcount) throws SAXException {
vertCount = parseInt(vertexcount);
}
/**
* Normalizes weights if needed and finds largest amount of weights used
* for all vertices in the buffer.
*/
private void endBoneAssigns() {
if (mesh != sharedMesh && isUsingSharedVerts(geom)) {
return;
}
//int vertCount = mesh.getVertexCount();
int maxWeightsPerVert = 0;
weightsFloatData.rewind();
for (int v = 0; v < vertCount; v++) {
float w0 = weightsFloatData.get(),
w1 = weightsFloatData.get(),
w2 = weightsFloatData.get(),
w3 = weightsFloatData.get();
if (w3 != 0) {
maxWeightsPerVert = Math.max(maxWeightsPerVert, 4);
} else if (w2 != 0) {
maxWeightsPerVert = Math.max(maxWeightsPerVert, 3);
} else if (w1 != 0) {
maxWeightsPerVert = Math.max(maxWeightsPerVert, 2);
} else if (w0 != 0) {
maxWeightsPerVert = Math.max(maxWeightsPerVert, 1);
}
float sum = w0 + w1 + w2 + w3;
if (sum != 1f) {
weightsFloatData.position(weightsFloatData.position() - 4);
// compute new vals based on sum
float sumToB = 1f / sum;
weightsFloatData.put(w0 * sumToB);
weightsFloatData.put(w1 * sumToB);
weightsFloatData.put(w2 * sumToB);
weightsFloatData.put(w3 * sumToB);
}
}
weightsFloatData.rewind();
weightsFloatData = null;
indicesData = null;
mesh.setMaxNumWeights(maxWeightsPerVert);
}
private void startBoneAssigns() {
if (mesh != sharedMesh && usesSharedVerts) {
// will use bone assignments from shared mesh (?)
return;
}
// current mesh will have bone assigns
//int vertCount = mesh.getVertexCount();
// each vertex has
// - 4 bone weights
// - 4 bone indices
if (HARDWARE_SKINNING) {
weightsFloatData = BufferUtils.createFloatBuffer(vertCount * 4);
indicesData = BufferUtils.createByteBuffer(vertCount * 4);
} else {
// create array-backed buffers if software skinning for access speed
weightsFloatData = FloatBuffer.allocate(vertCount * 4);
indicesData = ByteBuffer.allocate(vertCount * 4);
}
VertexBuffer weights = new VertexBuffer(Type.BoneWeight);
VertexBuffer indices = new VertexBuffer(Type.BoneIndex);
Usage usage = HARDWARE_SKINNING ? Usage.Static : Usage.CpuOnly;
weights.setupData(usage, 4, Format.Float, weightsFloatData);
indices.setupData(usage, 4, Format.UnsignedByte, indicesData);
mesh.setBuffer(weights);
mesh.setBuffer(indices);
}
private void startVertexBuffer(Attributes attribs) throws SAXException {
if (parseBool(attribs.getValue("positions"), false)) {
vb = new VertexBuffer(Type.Position);
fb = BufferUtils.createFloatBuffer(vertCount * 3);
vb.setupData(Usage.Static, 3, Format.Float, fb);
mesh.setBuffer(vb);
}
if (parseBool(attribs.getValue("normals"), false)) {
vb = new VertexBuffer(Type.Normal);
fb = BufferUtils.createFloatBuffer(vertCount * 3);
vb.setupData(Usage.Static, 3, Format.Float, fb);
mesh.setBuffer(vb);
}
if (parseBool(attribs.getValue("colours_diffuse"), false)) {
vb = new VertexBuffer(Type.Color);
fb = BufferUtils.createFloatBuffer(vertCount * 4);
vb.setupData(Usage.Static, 4, Format.Float, fb);
mesh.setBuffer(vb);
}
if (parseBool(attribs.getValue("tangents"), false)) {
int dimensions = parseInt(attribs.getValue("tangent_dimensions"), 3);
vb = new VertexBuffer(Type.Tangent);
fb = BufferUtils.createFloatBuffer(vertCount * dimensions);
vb.setupData(Usage.Static, dimensions, Format.Float, fb);
mesh.setBuffer(vb);
}
if (parseBool(attribs.getValue("binormals"), false)) {
vb = new VertexBuffer(Type.Binormal);
fb = BufferUtils.createFloatBuffer(vertCount * 3);
vb.setupData(Usage.Static, 3, Format.Float, fb);
mesh.setBuffer(vb);
}
int texCoords = parseInt(attribs.getValue("texture_coords"), 0);
for (int i = 0; i < texCoords; i++) {
int dims = parseInt(attribs.getValue("texture_coord_dimensions_" + i), 2);
if (dims < 1 || dims > 4) {
throw new SAXException("Texture coord dimensions must be 1 <= dims <= 4");
}
if (i <= 7) {
vb = new VertexBuffer(TEXCOORD_TYPES[i]);
} else {
// more than 8 texture coordinates are not supported by ogre.
throw new SAXException("More than 8 texture coordinates not supported");
}
fb = BufferUtils.createFloatBuffer(vertCount * dims);
vb.setupData(Usage.Static, dims, Format.Float, fb);
mesh.setBuffer(vb);
}
}
private void startVertex() {
texCoordIndex = 0;
}
private void pushAttrib(Type type, Attributes attribs) throws SAXException {
try {
FloatBuffer buf = (FloatBuffer) mesh.getBuffer(type).getData();
buf.put(parseFloat(attribs.getValue("x"))).put(parseFloat(attribs.getValue("y"))).put(parseFloat(attribs.getValue("z")));
} catch (Exception ex) {
throw new SAXException("Failed to push attrib", ex);
}
}
private void pushTangent(Attributes attribs) throws SAXException {
try {
VertexBuffer tangentBuf = mesh.getBuffer(Type.Tangent);
FloatBuffer buf = (FloatBuffer) tangentBuf.getData();
buf.put(parseFloat(attribs.getValue("x"))).put(parseFloat(attribs.getValue("y"))).put(parseFloat(attribs.getValue("z")));
if (tangentBuf.getNumComponents() == 4) {
buf.put(parseFloat(attribs.getValue("w")));
}
} catch (Exception ex) {
throw new SAXException("Failed to push attrib", ex);
}
}
private void pushTexCoord(Attributes attribs) throws SAXException {
if (texCoordIndex >= 8) {
return; // More than 8 not supported by ogre.
}
Type type = TEXCOORD_TYPES[texCoordIndex];
VertexBuffer tcvb = mesh.getBuffer(type);
FloatBuffer buf = (FloatBuffer) tcvb.getData();
buf.put(parseFloat(attribs.getValue("u")));
if (tcvb.getNumComponents() >= 2) {
buf.put(parseFloat(attribs.getValue("v")));
if (tcvb.getNumComponents() >= 3) {
buf.put(parseFloat(attribs.getValue("w")));
if (tcvb.getNumComponents() == 4) {
buf.put(parseFloat(attribs.getValue("x")));
}
}
}
texCoordIndex++;
}
private void pushColor(Attributes attribs) throws SAXException {
FloatBuffer buf = (FloatBuffer) mesh.getBuffer(Type.Color).getData();
String value = parseString(attribs.getValue("value"));
String[] vals = value.split(" ");
if (vals.length != 3 && vals.length != 4) {
throw new SAXException("Color value must contain 3 or 4 components");
}
ColorRGBA color = new ColorRGBA();
color.r = parseFloat(vals[0]);
color.g = parseFloat(vals[1]);
color.b = parseFloat(vals[2]);
if (vals.length == 3) {
color.a = 1f;
} else {
color.a = parseFloat(vals[3]);
}
buf.put(color.r).put(color.g).put(color.b).put(color.a);
}
private void startLodFaceList(String submeshindex, String numfaces) {
int index = Integer.parseInt(submeshindex);
int faceCount = Integer.parseInt(numfaces);
vb = new VertexBuffer(VertexBuffer.Type.Index);
sb = BufferUtils.createShortBuffer(faceCount * 3);
ib = null;
vb.setupData(Usage.Static, 3, Format.UnsignedShort, sb);
List<VertexBuffer> levels = lodLevels.get(index);
if (levels == null) {
levels = new ArrayList<VertexBuffer>();
Mesh submesh = geoms.get(index).getMesh();
levels.add(submesh.getBuffer(Type.Index));
lodLevels.put(index, levels);
}
levels.add(vb);
}
private void startLevelOfDetail(String numlevels) {
// numLevels = Integer.parseInt(numlevels);
}
private void endLevelOfDetail() {
// set the lod data for each mesh
for (Entry<List<VertexBuffer>> entry : lodLevels) {
Mesh m = geoms.get(entry.getKey()).getMesh();
List<VertexBuffer> levels = entry.getValue();
VertexBuffer[] levelArray = new VertexBuffer[levels.size()];
levels.toArray(levelArray);
m.setLodLevels(levelArray);
}
}
private void startLodGenerated(String depthsqr) {
}
private void pushBoneAssign(String vertIndex, String boneIndex, String weight) throws SAXException {
int vert = parseInt(vertIndex);
float w = parseFloat(weight);
byte bone = (byte) parseInt(boneIndex);
assert bone >= 0;
assert vert >= 0 && vert < mesh.getVertexCount();
int i;
float v = 0;
// see which weights are unused for a given bone
for (i = vert * 4; i < vert * 4 + 4; i++) {
v = weightsFloatData.get(i);
if (v == 0) {
break;
}
}
if (v != 0) {
logger.log(Level.WARNING, "Vertex {0} has more than 4 weights per vertex! Ignoring..", vert);
return;
}
weightsFloatData.put(i, w);
indicesData.put(i, bone);
}
private void startSkeleton(String name) {
animData = (AnimData) assetManager.loadAsset(folderName + name + ".xml");
}
private void startSubmeshName(String indexStr, String nameStr) {
int index = Integer.parseInt(indexStr);
geoms.get(index).setName(nameStr);
}
@Override
public void startElement(String uri, String localName, String qName, Attributes attribs) throws SAXException {
if (ignoreUntilEnd != null) {
return;
}
if (qName.equals("texcoord")) {
pushTexCoord(attribs);
} else if (qName.equals("vertexboneassignment")) {
pushBoneAssign(attribs.getValue("vertexindex"),
attribs.getValue("boneindex"),
attribs.getValue("weight"));
} else if (qName.equals("face")) {
pushFace(attribs.getValue("v1"),
attribs.getValue("v2"),
attribs.getValue("v3"));
} else if (qName.equals("position")) {
pushAttrib(Type.Position, attribs);
} else if (qName.equals("normal")) {
pushAttrib(Type.Normal, attribs);
} else if (qName.equals("tangent")) {
pushTangent(attribs);
} else if (qName.equals("binormal")) {
pushAttrib(Type.Binormal, attribs);
} else if (qName.equals("colour_diffuse")) {
pushColor(attribs);
} else if (qName.equals("vertex")) {
startVertex();
} else if (qName.equals("faces")) {
startFaces(attribs.getValue("count"));
} else if (qName.equals("geometry")) {
String count = attribs.getValue("vertexcount");
if (count == null) {
count = attribs.getValue("count");
}
startGeometry(count);
} else if (qName.equals("vertexbuffer")) {
startVertexBuffer(attribs);
} else if (qName.equals("lodfacelist")) {
startLodFaceList(attribs.getValue("submeshindex"),
attribs.getValue("numfaces"));
} else if (qName.equals("lodgenerated")) {
startLodGenerated(attribs.getValue("fromdepthsquared"));
} else if (qName.equals("levelofdetail")) {
startLevelOfDetail(attribs.getValue("numlevels"));
} else if (qName.equals("boneassignments")) {
startBoneAssigns();
} else if (qName.equals("submesh")) {
startSubMesh(attribs.getValue("material"),
attribs.getValue("usesharedvertices"),
attribs.getValue("use32bitindexes"),
attribs.getValue("operationtype"));
} else if (qName.equals("sharedgeometry")) {
String count = attribs.getValue("vertexcount");
if (count == null) {
count = attribs.getValue("count");
}
if (count != null && !count.equals("0")) {
startSharedGeom(count);
}
} else if (qName.equals("submeshes")) {
} else if (qName.equals("skeletonlink")) {
startSkeleton(attribs.getValue("name"));
} else if (qName.equals("submeshnames")) {
} else if (qName.equals("submeshname")) {
startSubmeshName(attribs.getValue("index"), attribs.getValue("name"));
} else if (qName.equals("mesh")) {
} else {
logger.log(Level.WARNING, "Unknown tag: {0}. Ignoring.", qName);
ignoreUntilEnd = qName;
}
}
@Override
public void endElement(String uri, String name, String qName) {
if (ignoreUntilEnd != null) {
if (ignoreUntilEnd.equals(qName)) {
ignoreUntilEnd = null;
}
return;
}
if (qName.equals("submesh")) {
usesBigIndices = false;
geom = null;
mesh = null;
} else if (qName.equals("submeshes")) {
// IMPORTANT: restore sharedmesh, for use with shared boneweights
geom = null;
mesh = sharedMesh;
usesSharedVerts = false;
} else if (qName.equals("faces")) {
if (ib != null) {
ib.flip();
} else {
sb.flip();
}
vb = null;
ib = null;
sb = null;
} else if (qName.equals("vertexbuffer")) {
fb = null;
vb = null;
} else if (qName.equals("geometry")
|| qName.equals("sharedgeometry")) {
// finish writing to buffers
IntMap<VertexBuffer> bufs = mesh.getBuffers();
for (Entry<VertexBuffer> entry : bufs) {
Buffer data = entry.getValue().getData();
if (data.position() != 0) {
data.flip();
}
}
mesh.updateBound();
mesh.setStatic();
if (qName.equals("sharedgeometry")) {
geom = null;
mesh = null;
}
} else if (qName.equals("lodfacelist")) {
sb.flip();
vb = null;
sb = null;
} else if (qName.equals("levelofdetail")) {
endLevelOfDetail();
} else if (qName.equals("boneassignments")) {
endBoneAssigns();
}
}
@Override
public void characters(char ch[], int start, int length) {
}
private Node compileModel() {
Node model = new Node(meshName + "-ogremesh");
for (int i = 0; i < geoms.size(); i++) {
Geometry g = geoms.get(i);
Mesh m = g.getMesh();
if (sharedMesh != null && isUsingSharedVerts(g)) {
m.setBound(sharedMesh.getBound().clone());
}
model.attachChild(geoms.get(i));
}
// Do not attach shared geometry to the node!
if (animData != null) {
// This model uses animation
// generate bind pose for mesh
// ONLY if not using shared geometry
// This includes the shared geoemtry itself actually
if (sharedMesh != null) {
sharedMesh.generateBindPose(!HARDWARE_SKINNING);
}
for (int i = 0; i < geoms.size(); i++) {
Geometry g = geoms.get(i);
Mesh m = geoms.get(i).getMesh();
boolean useShared = isUsingSharedVerts(g);
if (!useShared) {
// create bind pose
m.generateBindPose(!HARDWARE_SKINNING);
// } else {
// Inherit animation data from shared mesh
// VertexBuffer bindPos = sharedMesh.getBuffer(Type.BindPosePosition);
// VertexBuffer bindNorm = sharedMesh.getBuffer(Type.BindPoseNormal);
// VertexBuffer boneIndex = sharedMesh.getBuffer(Type.BoneIndex);
// VertexBuffer boneWeight = sharedMesh.getBuffer(Type.BoneWeight);
// if (bindPos != null) {
// m.setBuffer(bindPos);
// if (bindNorm != null) {
// m.setBuffer(bindNorm);
// if (boneIndex != null) {
// m.setBuffer(boneIndex);
// if (boneWeight != null) {
// m.setBuffer(boneWeight);
}
}
// Put the animations in the AnimControl
HashMap<String, Animation> anims = new HashMap<String, Animation>();
ArrayList<Animation> animList = animData.anims;
for (int i = 0; i < animList.size(); i++) {
Animation anim = animList.get(i);
anims.put(anim.getName(), anim);
}
AnimControl ctrl = new AnimControl(animData.skeleton);
ctrl.setAnimations(anims);
model.addControl(ctrl);
// Put the skeleton in the skeleton control
SkeletonControl skeletonControl = new SkeletonControl(animData.skeleton);
// This will acquire the targets from the node
model.addControl(skeletonControl);
}
return model;
}
public Object load(AssetInfo info) throws IOException {
try {
AssetKey key = info.getKey();
meshName = key.getName();
folderName = key.getFolder();
String ext = key.getExtension();
meshName = meshName.substring(0, meshName.length() - ext.length() - 1);
if (folderName != null && folderName.length() > 0) {
meshName = meshName.substring(folderName.length());
}
assetManager = info.getManager();
OgreMeshKey meshKey = null;
if (key instanceof OgreMeshKey) {
meshKey = (OgreMeshKey) key;
materialList = meshKey.getMaterialList();
String materialName = meshKey.getMaterialName();
if (materialList == null && materialName != null) {
materialList = (MaterialList) assetManager.loadAsset(new OgreMaterialKey(folderName + materialName + ".material"));
}
else{
materialList = (MaterialList) assetManager.loadAsset(new OgreMaterialKey(folderName + meshName + ".material"));
}
} else {
try {
materialList = (MaterialList) assetManager.loadAsset(new OgreMaterialKey(folderName + meshName + ".material"));
} catch (AssetNotFoundException e) {
logger.log(Level.WARNING, "Cannot locate {0}{1}.material for model {2}{3}.{4}", new Object[]{folderName, meshName, folderName, meshName, ext});
}
}
// Added by larynx 25.06.2011
// Android needs the namespace aware flag set to true
// Kirill 30.06.2011
// Now, hack is applied for both desktop and android to avoid
// checking with JmeSystem.
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
XMLReader xr = factory.newSAXParser().getXMLReader();
xr.setContentHandler(this);
xr.setErrorHandler(this);
InputStreamReader r = new InputStreamReader(info.openStream());
xr.parse(new InputSource(r));
r.close();
return compileModel();
} catch (SAXException ex) {
IOException ioEx = new IOException("Error while parsing Ogre3D mesh.xml");
ioEx.initCause(ex);
throw ioEx;
} catch (ParserConfigurationException ex) {
IOException ioEx = new IOException("Error while parsing Ogre3D mesh.xml");
ioEx.initCause(ex);
throw ioEx;
}
}
}
|
package test.dataprovider;
import org.testng.Assert;
public class StaticDataProviderSampleTest {
/**
* @testng.test dataProvider="static" dataProviderClass="test.dataprovider.StaticProvider"
*/
public void verifyStatic(String s) {
Assert.assertEquals(s, "Cedric");
}
}
|
package org.deidentifier.arx.examples;
import org.deidentifier.arx.DataType;
import org.deidentifier.arx.DataType.Entry;
/**
* This class implements an example of how to list the available data types
*
* @author Prasser, Kohlmayer
*/
public class Example17 extends Example {
/**
* Entry point.
*
* @param args The arguments
*/
@SuppressWarnings("unused")
public static void main(final String[] args) {
// List all data types
for (Entry<?> type : DataType.LIST){
// Print basic information
System.out.println(" - Label : " + type.getLabel());
System.out.println(" * Format: " + type.hasFormat());
if (type.hasFormat()){
System.out.println(" * Formats: " + type.getExampleFormats());
}
// Create an instance without a format string
DataType<?> instance = type.newInstance();
// Create an instance with format string
if (type.hasFormat() && !type.getExampleFormats().isEmpty()) {
instance = type.newInstance(type.getExampleFormats().get(0));
}
}
}
}
|
package to.etc.domui.dom.html;
import org.eclipse.jdt.annotation.NonNullByDefault;
import to.etc.domui.state.IPageParameters;
@NonNullByDefault
final public class ClickInfo {
private boolean m_shift;
private boolean m_alt;
private final boolean m_doubleClick;
private boolean m_control;
private int m_pageX, m_pageY;
public ClickInfo(IPageParameters pi, boolean doubleClick) {
m_shift = "true".equals(pi.getString("_shiftKey", null));
m_control = "true".equals(pi.getString("_controlKey", null));
m_alt = "true".equals(pi.getString("_altKey", null));
m_doubleClick = doubleClick;
m_pageX = decode(pi, "_pageX");
m_pageY = decode(pi, "_pageY");
}
static private int decode(IPageParameters pp, String name) {
String s = pp.getString(name, "0");
int pos = s.indexOf('.');
if(pos > 0) {
s = s.substring(0, pos);
}
try {
return Integer.parseInt(s);
} catch(Exception x) {
return 0;
}
}
public boolean isShift() {
return m_shift;
}
public boolean isAlt() {
return m_alt;
}
public boolean isControl() {
return m_control;
}
public boolean isDoubleClick() {
return m_doubleClick;
}
public int getPageX() {
return m_pageX;
}
public int getPageY() {
return m_pageY;
}
}
|
package com.litle.sdk;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Properties;
import javax.xml.bind.JAXBException;
import com.litle.sdk.generate.*;
import com.sun.org.apache.xerces.internal.jaxp.datatype.XMLGregorianCalendarImpl;
import org.junit.Test;
public class TestBatchFile {
@Test
public void testSendToLitle_WithFileConfig() throws Exception {
String requestFileName = "litleSdk-testBatchFile-fileConfig.xml";
LitleBatchFileRequest request = new LitleBatchFileRequest(
requestFileName);
// request file is being set in the constructor
assertNotNull(request.getFile());
Properties configFromFile = request.getConfig();
// pre-assert the config file has required param values
assertEquals("prelive.litle.com",
configFromFile.getProperty("batchHost"));
assertEquals("15000", configFromFile.getProperty("batchPort"));
String workingDirRequests = configFromFile
.getProperty("batchRequestFolder");
prepDir(workingDirRequests);
String workingDirResponses = configFromFile
.getProperty("batchResponseFolder");
prepDir(workingDirResponses);
prepareTestRequest(request);
/* call method under test */
LitleBatchFileResponse response = request.sendToLitle();
// assert response can be processed through Java API
assertJavaApi(request, response);
// assert request and response files were created properly
assertGeneratedFiles(workingDirRequests, workingDirResponses,
requestFileName, request, response);
}
@Test
public void testSendToLitle_WithConfigOverrides() throws Exception {
String workingDir = System.getProperty("java.io.tmpdir");
String workingDirRequests = workingDir + File.separator
+ "litleSdkTestBatchRequests";
prepDir(workingDirRequests);
String workingDirResponses = workingDir + File.separator
+ "litleSdkTestBatchResponses";
prepDir(workingDirResponses);
Properties configOverrides = new Properties();
configOverrides.setProperty("batchHost", "prelive.litle.com");
configOverrides.setProperty("batchPort", "15000");
configOverrides.setProperty("batchRequestFolder", workingDirRequests);
configOverrides.setProperty("batchResponseFolder", workingDirResponses);
String requestFileName = "litleSdk-testBatchFile-configOverrides.xml";
LitleBatchFileRequest request = new LitleBatchFileRequest(
requestFileName, configOverrides);
// request file is being set in the constructor
assertNotNull(request.getFile());
prepareTestRequest(request);
// actually add a transaction
/* call method under test */
LitleBatchFileResponse response = request.sendToLitle();
// assert response can be processed through Java API
assertJavaApi(request, response);
// assert request and response files were created properly
assertGeneratedFiles(workingDirRequests, workingDirResponses,
requestFileName, request, response);
}
@Test
public void testSendToLitleSFTP_WithPreviouslyCreatedFile()
throws Exception {
String requestFileName = "litleSdk-testBatchFile-fileConfigSFTP.xml";
LitleBatchFileRequest request = new LitleBatchFileRequest(
requestFileName);
// request file is being set in the constructor
assertNotNull(request.getFile());
Properties configFromFile = request.getConfig();
// pre-assert the config file has required param values
assertEquals("prelive.litle.com",
configFromFile.getProperty("batchHost"));
assertEquals("15000", configFromFile.getProperty("batchPort"));
String workingDirRequests = configFromFile
.getProperty("batchRequestFolder");
prepDir(workingDirRequests);
String workingDirResponses = configFromFile
.getProperty("batchResponseFolder");
prepDir(workingDirResponses);
prepareTestRequest(request);
// This should have generated the file
request.prepareForDelivery();
// Make sure the file exists
File requestFile = request.getFile();
assertTrue(requestFile.exists());
assertTrue(requestFile.length() > 0);
LitleBatchFileRequest request2 = new LitleBatchFileRequest(
requestFileName);
LitleBatchFileResponse response = request2.sendToLitleSFTP(true);
// Assert response matches what was requested
assertJavaApi(request2, response);
// Make sure files were created correctly
assertGeneratedFiles(workingDirRequests, workingDirResponses,
requestFileName, request2, response);
}
@Test
public void testSendOnlyToLitleSFTP_WithPreviouslyCreatedFile()
throws Exception {
String requestFileName = "litleSdk-testBatchFile-fileConfigSFTP.xml";
LitleBatchFileRequest request1 = new LitleBatchFileRequest(
requestFileName);
// request file is being set in the constructor
assertNotNull(request1.getFile());
Properties configFromFile = request1.getConfig();
// pre-assert the config file has required param values
assertEquals("prelive.litle.com",
configFromFile.getProperty("batchHost"));
assertEquals("15000", configFromFile.getProperty("batchPort"));
String workingDirRequests = configFromFile
.getProperty("batchRequestFolder");
prepDir(workingDirRequests);
String workingDirResponses = configFromFile
.getProperty("batchResponseFolder");
prepDir(workingDirResponses);
prepareTestRequest(request1);
// This should have generated the file
request1.prepareForDelivery();
// Make sure the file exists
File requestFile1 = request1.getFile();
assertTrue(requestFile1.exists());
assertTrue(requestFile1.length() > 0);
// Move request file to temporary location
File requestFile2 = File.createTempFile("litle", "xml");
copyFile(requestFile1, requestFile2);
Properties configForRequest2 = (Properties) configFromFile.clone();
configForRequest2.setProperty("batchRequestFolder", requestFile2
.getParentFile().getCanonicalPath());
LitleBatchFileRequest request2 = new LitleBatchFileRequest(
requestFile2.getName(), configForRequest2);
request2.sendOnlyToLitleSFTP(true);
LitleBatchFileRequest request3 = new LitleBatchFileRequest(
requestFile2.getName(), configForRequest2);
LitleBatchFileResponse response = request3.retrieveOnlyFromLitleSFTP();
// Assert response matches what was requested
assertJavaApi(request3, response);
// Make sure files were created correctly
assertGeneratedFiles(requestFile2.getParentFile().getCanonicalPath(),
workingDirResponses, requestFile2.getName(), request3, response);
}
@Test
public void testSendToLitleSFTP_WithFileConfig() throws Exception {
String requestFileName = "litleSdk-testBatchFile-fileConfigSFTP.xml";
LitleBatchFileRequest request = new LitleBatchFileRequest(
requestFileName);
// request file is being set in the constructor
assertNotNull(request.getFile());
Properties configFromFile = request.getConfig();
// pre-assert the config file has required param values
assertEquals("prelive.litle.com",
configFromFile.getProperty("batchHost"));
assertEquals("15000", configFromFile.getProperty("batchPort"));
String workingDirRequests = configFromFile
.getProperty("batchRequestFolder");
prepDir(workingDirRequests);
String workingDirResponses = configFromFile
.getProperty("batchResponseFolder");
prepDir(workingDirResponses);
prepareTestRequest(request);
/* call method under test */
LitleBatchFileResponse response = request.sendToLitleSFTP();
// assert response can be processed through Java API
assertJavaApi(request, response);
// assert request and response files were created properly
assertGeneratedFiles(workingDirRequests, workingDirResponses,
requestFileName, request, response);
}
@Test
public void testSendToLitleSFTP_WithConfigOverrides() throws Exception {
String workingDir = System.getProperty("java.io.tmpdir");
String workingDirRequests = workingDir + File.separator
+ "litleSdkTestBatchRequests";
prepDir(workingDirRequests);
String workingDirResponses = workingDir + File.separator
+ "litleSdkTestBatchResponses";
prepDir(workingDirResponses);
Properties configOverrides = new Properties();
configOverrides.setProperty("batchHost", "prelive.litle.com");
configOverrides.setProperty("sftpTimeout", "720000");
configOverrides.setProperty("batchRequestFolder", workingDirRequests);
configOverrides.setProperty("batchResponseFolder", workingDirResponses);
String requestFileName = "litleSdk-testBatchFile-configOverridesSFTP.xml";
LitleBatchFileRequest request = new LitleBatchFileRequest(
requestFileName, configOverrides);
// request file is being set in the constructor
assertNotNull(request.getFile());
prepareTestRequest(request);
/* call method under test */
LitleBatchFileResponse response = request.sendToLitleSFTP();
// assert response can be processed through Java API
assertJavaApi(request, response);
// assert request and response files were created properly
}
private void prepareTestRequest(LitleBatchFileRequest request)
throws FileNotFoundException, JAXBException {
Properties configFromFile = request.getConfig();
LitleBatchRequest batchRequest1 = request.createBatch(configFromFile.getProperty("merchantId"));
Sale sale11 = new Sale();
sale11.setReportGroup("reportGroup11");
sale11.setOrderId("orderId11");
sale11.setAmount(1099L);
sale11.setOrderSource(OrderSourceType.ECOMMERCE);
sale11.setId("id");
CardType card = new CardType();
card.setType(MethodOfPaymentTypeEnum.VI);
card.setNumber("4457010000000009");
card.setExpDate("0114");
card.setPin("1234");
sale11.setCard(card);
batchRequest1.addTransaction(sale11);
}
@Test
public void testMechaBatchAndProcess() {
String requestFileName = "litleSdk-testBatchFile-MECHA.xml";
LitleBatchFileRequest request = new LitleBatchFileRequest(
requestFileName);
Properties configFromFile = request.getConfig();
// pre-assert the config file has required param values
assertEquals("prelive.litle.com",
configFromFile.getProperty("batchHost"));
assertEquals("15000", configFromFile.getProperty("batchPort"));
LitleBatchRequest batch = request.createBatch(configFromFile.getProperty("merchantId"));
// card
CardType card = new CardType();
card.setNumber("4100000000000001");
card.setExpDate("1210");
card.setType(MethodOfPaymentTypeEnum.VI);
// echeck
EcheckType echeck = new EcheckType();
echeck.setAccNum("1234567890");
echeck.setAccType(EcheckAccountTypeEnum.CHECKING);
echeck.setRoutingNum("123456789");
echeck.setCheckNum("123455");
// billto address
Contact contact = new Contact();
contact.setName("Bob");
contact.setCity("Lowell");
contact.setState("MA");
contact.setEmail("Bob@litle.com");
Authorization auth = new Authorization();
auth.setReportGroup("Planets");
auth.setOrderId("12344");
auth.setAmount(106L);
auth.setOrderSource(OrderSourceType.ECOMMERCE);
auth.setCard(card);
auth.setId("id");
batch.addTransaction(auth);
Sale sale = new Sale();
sale.setReportGroup("Planets");
sale.setOrderId("12344");
sale.setAmount(6000L);
sale.setOrderSource(OrderSourceType.ECOMMERCE);
sale.setCard(card);
sale.setId("id");
batch.addTransaction(sale);
Credit credit = new Credit();
credit.setReportGroup("Planets");
credit.setOrderId("12344");
credit.setAmount(106L);
credit.setOrderSource(OrderSourceType.ECOMMERCE);
credit.setCard(card);
credit.setId("id");
batch.addTransaction(credit);
AuthReversal authReversal = new AuthReversal();
authReversal.setReportGroup("Planets");
authReversal.setLitleTxnId(12345678000L);
authReversal.setAmount(106L);
authReversal.setPayPalNotes("Notes");
authReversal.setId("id");
batch.addTransaction(authReversal);
RegisterTokenRequestType registerTokenRequestType = new RegisterTokenRequestType();
registerTokenRequestType.setReportGroup("Planets");
registerTokenRequestType.setOrderId("12344");
registerTokenRequestType.setAccountNumber("1233456789103801");
registerTokenRequestType.setId("id");
batch.addTransaction(registerTokenRequestType);
UpdateCardValidationNumOnToken cardValidationNumOnToken = new UpdateCardValidationNumOnToken();
cardValidationNumOnToken.setReportGroup("Planets");
cardValidationNumOnToken.setId("12345");
cardValidationNumOnToken.setCustomerId("0987");
cardValidationNumOnToken.setOrderId("12344");
cardValidationNumOnToken.setLitleToken("1233456789103801");
cardValidationNumOnToken.setCardValidationNum("123");
cardValidationNumOnToken.setId("id");
batch.addTransaction(cardValidationNumOnToken);
ForceCapture forceCapture = new ForceCapture();
forceCapture.setReportGroup("Planets");
forceCapture.setId("123456");
forceCapture.setOrderId("12344");
forceCapture.setAmount(106L);
forceCapture.setOrderSource(OrderSourceType.ECOMMERCE);
forceCapture.setCard(card);
forceCapture.setId("id");
batch.addTransaction(forceCapture);
Capture capture = new Capture();
capture.setReportGroup("Planets");
capture.setLitleTxnId(123456000L);
capture.setAmount(106L);
capture.setId("id");
batch.addTransaction(capture);
CaptureGivenAuth captureGivenAuth = new CaptureGivenAuth();
captureGivenAuth.setReportGroup("Planets");
captureGivenAuth.setOrderId("12344");
captureGivenAuth.setAmount(106L);
AuthInformation authInformation = new AuthInformation();
authInformation.setAuthDate(Calendar.getInstance());
authInformation.setAuthAmount(12345L);
authInformation.setAuthCode("543216");
captureGivenAuth.setAuthInformation(authInformation);
captureGivenAuth.setOrderSource(OrderSourceType.ECOMMERCE);
captureGivenAuth.setCard(card);
captureGivenAuth.setId("id");
batch.addTransaction(captureGivenAuth);
EcheckVerification echeckVerification = new EcheckVerification();
echeckVerification.setReportGroup("Planets");
echeckVerification.setAmount(123456L);
echeckVerification.setOrderId("12345");
echeckVerification.setOrderSource(OrderSourceType.ECOMMERCE);
echeckVerification.setBillToAddress(contact);
echeckVerification.setEcheck(echeck);
echeckVerification.setId("id");
batch.addTransaction(echeckVerification);
EcheckCredit echeckCredit = new EcheckCredit();
echeckCredit.setReportGroup("Planets");
echeckCredit.setLitleTxnId(1234567890L);
echeckCredit.setAmount(12L);
echeckCredit.setId("id");
batch.addTransaction(echeckCredit);
EcheckRedeposit echeckRedeposit = new EcheckRedeposit();
echeckRedeposit.setReportGroup("Planets");
echeckRedeposit.setLitleTxnId(124321341412L);
echeckRedeposit.setId("id");
batch.addTransaction(echeckRedeposit);
EcheckSale echeckSale = new EcheckSale();
echeckSale.setReportGroup("Planets");
echeckSale.setAmount(123456L);
echeckSale.setOrderId("12345");
echeckSale.setOrderSource(OrderSourceType.ECOMMERCE);
echeckSale.setBillToAddress(contact);
echeckSale.setEcheck(echeck);
echeckSale.setVerify(true);
echeckSale.setId("id");
batch.addTransaction(echeckSale);
int transactionCount = batch.getNumberOfTransactions();
LitleBatchFileResponse fileResponse = request.sendToLitle();
LitleBatchResponse batchResponse = fileResponse
.getNextLitleBatchResponse();
int txns = 0;
ResponseValidatorProcessor processor = new ResponseValidatorProcessor();
while (batchResponse.processNextTransaction(processor)) {
txns++;
}
assertEquals(transactionCount, txns);
assertEquals(transactionCount, processor.responseCount);
}
@Test
public void testEcheckPreNoteAll() {
String requestFileName = "litleSdk-testBatchFile-EcheckPreNoteAll.xml";
LitleBatchFileRequest request = new LitleBatchFileRequest(
requestFileName);
Properties configFromFile = request.getConfig();
// pre-assert the config file has required param values
assertEquals("prelive.litle.com",
configFromFile.getProperty("batchHost"));
assertEquals("15000", configFromFile.getProperty("batchPort"));
LitleBatchRequest batch = request.createBatch(configFromFile.getProperty("merchantId"));
// echeck success
EcheckType echeckSuccess = new EcheckType();
echeckSuccess.setAccNum("1092969901");
echeckSuccess.setAccType(EcheckAccountTypeEnum.CORPORATE);
echeckSuccess.setRoutingNum("011075150");
echeckSuccess.setCheckNum("123455");
EcheckType echeckAccErr = new EcheckType();
echeckAccErr.setAccNum("10@2969901");
echeckAccErr.setAccType(EcheckAccountTypeEnum.CORPORATE);
echeckAccErr.setRoutingNum("011100012");
echeckAccErr.setCheckNum("123455");
EcheckType echeckRoutErr = new EcheckType();
echeckRoutErr.setAccNum("6099999992");
echeckRoutErr.setAccType(EcheckAccountTypeEnum.CHECKING);
echeckRoutErr.setRoutingNum("053133052");
echeckRoutErr.setCheckNum("123455");
// billto address
Contact contact = new Contact();
contact.setName("Bob");
contact.setCity("Lowell");
contact.setState("MA");
contact.setEmail("Bob@litle.com");
EcheckPreNoteSale echeckPreNoteSaleSuccess = new EcheckPreNoteSale();
echeckPreNoteSaleSuccess.setReportGroup("Planets");
echeckPreNoteSaleSuccess.setOrderId("000");
echeckPreNoteSaleSuccess.setBillToAddress(contact);
echeckPreNoteSaleSuccess.setEcheck(echeckSuccess);
echeckPreNoteSaleSuccess.setOrderSource(OrderSourceType.ECOMMERCE);
echeckPreNoteSaleSuccess.setId("Id");
batch.addTransaction(echeckPreNoteSaleSuccess);
EcheckPreNoteSale echeckPreNoteSaleAccErr = new EcheckPreNoteSale();
echeckPreNoteSaleAccErr.setReportGroup("Planets");
echeckPreNoteSaleAccErr.setOrderId("301");
echeckPreNoteSaleAccErr.setBillToAddress(contact);
echeckPreNoteSaleAccErr.setEcheck(echeckAccErr);
echeckPreNoteSaleAccErr.setOrderSource(OrderSourceType.ECOMMERCE);
echeckPreNoteSaleAccErr.setId("Id");
batch.addTransaction(echeckPreNoteSaleAccErr);
EcheckPreNoteSale echeckPreNoteSaleRoutErr = new EcheckPreNoteSale();
echeckPreNoteSaleRoutErr.setReportGroup("Planets");
echeckPreNoteSaleRoutErr.setOrderId("900");
echeckPreNoteSaleRoutErr.setBillToAddress(contact);
echeckPreNoteSaleRoutErr.setEcheck(echeckRoutErr);
echeckPreNoteSaleRoutErr.setOrderSource(OrderSourceType.ECOMMERCE);
echeckPreNoteSaleRoutErr.setId("Id");
batch.addTransaction(echeckPreNoteSaleRoutErr);
EcheckPreNoteCredit echeckPreNoteCreditSuccess = new EcheckPreNoteCredit();
echeckPreNoteCreditSuccess.setReportGroup("Planets");
echeckPreNoteCreditSuccess.setOrderId("000");
echeckPreNoteCreditSuccess.setBillToAddress(contact);
echeckPreNoteCreditSuccess.setEcheck(echeckSuccess);
echeckPreNoteCreditSuccess.setOrderSource(OrderSourceType.ECOMMERCE);
echeckPreNoteCreditSuccess.setId("Id");
batch.addTransaction(echeckPreNoteCreditSuccess);
EcheckPreNoteCredit echeckPreNoteCreditAccErr = new EcheckPreNoteCredit();
echeckPreNoteCreditAccErr.setReportGroup("Planets");
echeckPreNoteCreditAccErr.setOrderId("301");
echeckPreNoteCreditAccErr.setBillToAddress(contact);
echeckPreNoteCreditAccErr.setEcheck(echeckAccErr);
echeckPreNoteCreditAccErr.setOrderSource(OrderSourceType.ECOMMERCE);
echeckPreNoteCreditAccErr.setId("Id");
batch.addTransaction(echeckPreNoteCreditAccErr);
EcheckPreNoteCredit echeckPreNoteCreditRoutErr = new EcheckPreNoteCredit();
echeckPreNoteCreditRoutErr.setReportGroup("Planets");
echeckPreNoteCreditRoutErr.setOrderId("900");
echeckPreNoteCreditRoutErr.setBillToAddress(contact);
echeckPreNoteCreditRoutErr.setEcheck(echeckRoutErr);
echeckPreNoteCreditRoutErr.setOrderSource(OrderSourceType.ECOMMERCE);
echeckPreNoteCreditRoutErr.setId("Id");
batch.addTransaction(echeckPreNoteCreditRoutErr);
int transactionCount = batch.getNumberOfTransactions();
LitleBatchFileResponse fileResponse = request.sendToLitle();
LitleBatchResponse batchResponse = fileResponse
.getNextLitleBatchResponse();
int txns = 0;
// ResponseValidatorProcessor processor = new ResponseValidatorProcessor();
while (batchResponse
.processNextTransaction(new LitleResponseProcessor() {
public void processVendorDebitResponse(
VendorDebitResponse vendorDebitResponse) {
}
public void processVendorCreditRespsonse(
VendorCreditResponse vendorCreditResponse) {
}
public void processUpdateSubscriptionResponse(
UpdateSubscriptionResponse updateSubscriptionResponse) {
}
public void processUpdatePlanResponse(
UpdatePlanResponse updatePlanResponse) {
}
public void processUpdateCardValidationNumOnTokenResponse(
UpdateCardValidationNumOnTokenResponse updateCardValidationNumOnTokenResponse) {
}
public void processUnloadResponse(
UnloadResponse unloadResponse) {
}
public void processSubmerchantDebitResponse(
SubmerchantDebitResponse submerchantDebitResponse) {
}
public void processSubmerchantCreditResponse(
SubmerchantCreditResponse submerchantCreditResponse) {
}
public void processSaleResponse(SaleResponse saleResponse) {
}
public void processReserveDebitResponse(
ReserveDebitResponse reserveDebitResponse) {
}
public void processReserveCreditResponse(
ReserveCreditResponse reserveCreditResponse) {
}
public void processRegisterTokenResponse(
RegisterTokenResponse registerTokenResponse) {
}
public void processPhysicalCheckDebitResponse(
PhysicalCheckDebitResponse checkDebitResponse) {
}
public void processPhysicalCheckCreditResponse(
PhysicalCheckCreditResponse checkCreditResponse) {
}
public void processPayFacDebitResponse(
PayFacDebitResponse payFacDebitResponse) {
}
public void processPayFacCreditResponse(
PayFacCreditResponse payFacCreditResponse) {
}
public void processLoadResponse(LoadResponse loadResponse) {
}
public void processForceCaptureResponse(
ForceCaptureResponse forceCaptureResponse) {
}
public void processEcheckVerificationResponse(
EcheckVerificationResponse echeckVerificationResponse) {
}
public void processEcheckSalesResponse(
EcheckSalesResponse echeckSalesResponse) {
}
public void processEcheckRedepositResponse(
EcheckRedepositResponse echeckRedepositResponse) {
}
public void processEcheckPreNoteSaleResponse(
EcheckPreNoteSaleResponse echeckPreNoteSaleResponse) {
}
public void processEcheckPreNoteCreditResponse(
EcheckPreNoteCreditResponse echeckPreNoteCreditResponse) {
}
public void processEcheckCreditResponse(
EcheckCreditResponse echeckCreditResponse) {
}
public void processDeactivateResponse(
DeactivateResponse deactivateResponse) {
}
public void processCreditResponse(
CreditResponse creditResponse) {
}
public void processCreatePlanResponse(
CreatePlanResponse createPlanResponse) {
}
public void processCaptureResponse(
CaptureResponse captureResponse) {
}
public void processCaptureGivenAuthResponse(
CaptureGivenAuthResponse captureGivenAuthResponse) {
}
public void processCancelSubscriptionResponse(
CancelSubscriptionResponse cancelSubscriptionResponse) {
}
public void processBalanceInquiryResponse(
BalanceInquiryResponse balanceInquiryResponse) {
}
public void processAuthorizationResponse(
AuthorizationResponse authorizationResponse) {
}
public void processAuthReversalResponse(
AuthReversalResponse authReversalResponse) {
}
public void processActivateResponse(
ActivateResponse activateResponse) {
}
public void processAccountUpdate(
AccountUpdateResponse accountUpdateResponse) {
}
public void processFundingInstructionVoidResponse(
FundingInstructionVoidResponse fundingInstructionVoidResponse) {
}
public void processGiftCardAuthReversalResponse(
GiftCardAuthReversalResponse giftCardAuthReversalResponse) {
}
public void processGiftCardCaptureResponse(GiftCardCaptureResponse giftCardCaptureResponse) {
}
public void processGiftCardCreditResponse(GiftCardCreditResponse giftCardCreditResponse) {
}
})) {
txns++;
}
assertEquals(transactionCount, txns);
}
// @Test
// public void testPFIFInstructionTxn() {
// String requestFileName = "litleSdk-testBatchFile-PFIF.xml";
// LitleBatchFileRequest request = new LitleBatchFileRequest(
// requestFileName);
// Properties configFromFile = request.getConfig();
// // pre-assert the config file has required param values
// assertEquals("prelive.litle.com",
// configFromFile.getProperty("batchHost"));
// assertEquals("15000", configFromFile.getProperty("batchPort"));
// LitleBatchRequest batch = request.createBatch(configFromFile.getProperty("merchantId"));
// // echeck
// EcheckType echeck = new EcheckType();
// echeck.setAccNum("1092969901");
// echeck.setAccType(EcheckAccountTypeEnum.CORPORATE);
// echeck.setRoutingNum("011075150");
// echeck.setCheckNum("123455");
// // billto address
// Contact contact = new Contact();
// contact.setName("Bob");
// contact.setCity("Lowell");
// contact.setState("MA");
// contact.setEmail("Bob@litle.com");
// SubmerchantCredit submerchantCredit = new SubmerchantCredit();
// submerchantCredit.setReportGroup("Planets");
// submerchantCredit.setFundingSubmerchantId("12345");
// submerchantCredit.setSubmerchantName("submerchant co.");
// submerchantCredit.setFundsTransferId("000");
// submerchantCredit.setAmount(1000L);
// submerchantCredit.setAccountInfo(echeck);
// submerchantCredit.setId("ID");
// submerchantCredit.setCustomIdentifier("custom field");
// batch.addTransaction(submerchantCredit);
// PayFacCredit payFacCredit = new PayFacCredit();
// payFacCredit.setReportGroup("Planets");
// payFacCredit.setFundingSubmerchantId("12346");
// payFacCredit.setFundsTransferId("000");
// payFacCredit.setAmount(1000L);
// payFacCredit.setId("ID");
// batch.addTransaction(payFacCredit);
// VendorCredit vendorCredit = new VendorCredit();
// vendorCredit.setReportGroup("Planets");
// vendorCredit.setFundingSubmerchantId("12347");
// vendorCredit.setVendorName("vendor co.");
// vendorCredit.setFundsTransferId("000");
// vendorCredit.setAmount(1000L);
// vendorCredit.setAccountInfo(echeck);
// vendorCredit.setId("ID");
// batch.addTransaction(vendorCredit);
// ReserveCredit reserveCredit = new ReserveCredit();
// reserveCredit.setReportGroup("Planets");
// reserveCredit.setFundingSubmerchantId("12348");
// reserveCredit.setFundsTransferId("000");
// reserveCredit.setAmount(1000L);
// reserveCredit.setId("ID");
// batch.addTransaction(reserveCredit);
// PhysicalCheckCredit physicalCheckCredit = new PhysicalCheckCredit();
// physicalCheckCredit.setReportGroup("Planets");
// physicalCheckCredit.setFundingSubmerchantId("12349");
// physicalCheckCredit.setFundsTransferId("000");
// physicalCheckCredit.setAmount(1000L);
// physicalCheckCredit.setId("ID");
// batch.addTransaction(physicalCheckCredit);
// SubmerchantDebit submerchantDebit = new SubmerchantDebit();
// submerchantDebit.setReportGroup("Planets");
// submerchantDebit.setFundingSubmerchantId("12345");
// submerchantDebit.setSubmerchantName("submerchant co.");
// submerchantDebit.setFundsTransferId("000");
// submerchantDebit.setAmount(1000L);
// submerchantDebit.setAccountInfo(echeck);
// submerchantDebit.setId("ID");
// submerchantDebit.setCustomIdentifier("custom field");
// batch.addTransaction(submerchantDebit);
// PayFacDebit payFacDebit = new PayFacDebit();
// payFacDebit.setReportGroup("Planets");
// payFacDebit.setFundingSubmerchantId("12346");
// payFacDebit.setFundsTransferId("000");
// payFacDebit.setAmount(1000L);
// payFacDebit.setId("ID");
// batch.addTransaction(payFacDebit);
// VendorDebit vendorDebit = new VendorDebit();
// vendorDebit.setReportGroup("Planets");
// vendorDebit.setFundingSubmerchantId("12347");
// vendorDebit.setVendorName("vendor co.");
// vendorDebit.setFundsTransferId("000");
// vendorDebit.setAmount(1000L);
// vendorDebit.setAccountInfo(echeck);
// vendorDebit.setId("ID");
// batch.addTransaction(vendorDebit);
// ReserveDebit reserveDebit = new ReserveDebit();
// reserveDebit.setReportGroup("Planets");
// reserveDebit.setFundingSubmerchantId("12348");
// reserveDebit.setFundsTransferId("000");
// reserveDebit.setAmount(1000L);
// reserveDebit.setId("ID");
// batch.addTransaction(reserveDebit);
// PhysicalCheckDebit physicalCheckDebit = new PhysicalCheckDebit();
// physicalCheckDebit.setReportGroup("Planets");
// physicalCheckDebit.setFundingSubmerchantId("12349");
// physicalCheckDebit.setFundsTransferId("000");
// physicalCheckDebit.setAmount(1000L);
// physicalCheckDebit.setId("ID");
// batch.addTransaction(physicalCheckDebit);
// int transactionCount = batch.getNumberOfTransactions();
// LitleBatchFileResponse fileResponse = request.sendToLitle();
// LitleBatchResponse batchResponse = fileResponse
// .getNextLitleBatchResponse();
// int txns = 0;
// ResponseValidatorProcessor processor = new ResponseValidatorProcessor();
// while (batchResponse.processNextTransaction(processor)) {
// txns++;
// assertEquals(transactionCount, txns);
// assertEquals(transactionCount, processor.responseCount);
@Test
public void testGiftCardTransactions() {
String requestFileName = "litleSdk-testBatchFile-GiftCardTransactions.xml";
LitleBatchFileRequest request = new LitleBatchFileRequest(
requestFileName);
Properties configFromFile = request.getConfig();
// pre-assert the config file has required param values
assertEquals("prelive.litle.com",
configFromFile.getProperty("batchHost"));
assertEquals("15000", configFromFile.getProperty("batchPort"));
LitleBatchRequest batch = request.createBatch(configFromFile.getProperty("merchantId"));
CardType card = new CardType();
card.setType(MethodOfPaymentTypeEnum.GC);
card.setExpDate("1218");
card.setNumber("4100000000000001");
VirtualGiftCardType virtualGiftCard = new VirtualGiftCardType();
virtualGiftCard.setGiftCardBin("abcd1234");
GiftCardCardType giftCard = new GiftCardCardType();
giftCard.setType(MethodOfPaymentTypeEnum.GC);
giftCard.setNumber("4100000000000001");
giftCard.setExpDate("0850");
giftCard.setCardValidationNum("111");
giftCard.setPin("4111");
Activate activate = new Activate();
activate.setReportGroup("Planets");
activate.setOrderSource(OrderSourceType.ECOMMERCE);
activate.setAmount(100L);
activate.setOrderId("abc");
activate.setCard(giftCard);
activate.setId("id");
batch.addTransaction(activate);
Deactivate deactivate = new Deactivate();
deactivate.setReportGroup("Planets");
deactivate.setOrderId("def");
deactivate.setOrderSource(OrderSourceType.ECOMMERCE);
deactivate.setCard(giftCard);
deactivate.setId("id");
batch.addTransaction(deactivate);
Load load = new Load();
load.setReportGroup("Planets");
load.setOrderId("ghi");
load.setAmount(100L);
load.setOrderSource(OrderSourceType.ECOMMERCE);
load.setCard(giftCard);
load.setId("id");
batch.addTransaction(load);
Unload unload = new Unload();
unload.setReportGroup("Planets");
unload.setOrderId("jkl");
unload.setAmount(100L);
unload.setOrderSource(OrderSourceType.ECOMMERCE);
unload.setCard(giftCard);
unload.setId("id");
batch.addTransaction(unload);
BalanceInquiry balanceInquiry = new BalanceInquiry();
balanceInquiry.setReportGroup("Planets");
balanceInquiry.setOrderId("mno");
balanceInquiry.setOrderSource(OrderSourceType.ECOMMERCE);
balanceInquiry.setCard(giftCard);
balanceInquiry.setId("id");
batch.addTransaction(balanceInquiry);
GiftCardAuthReversal gcAuthReversal = new GiftCardAuthReversal();
gcAuthReversal.setId("979797");
gcAuthReversal.setCustomerId("customer_23");
gcAuthReversal.setLitleTxnId(8521478963210145l);
gcAuthReversal.setReportGroup("rptGrp2");
gcAuthReversal.setOriginalAmount(45l);
gcAuthReversal.setOriginalSequenceNumber("333333");
gcAuthReversal.setOriginalTxnTime(new XMLGregorianCalendarImpl(new GregorianCalendar()));
gcAuthReversal.setOriginalSystemTraceId(0);
gcAuthReversal.setOriginalRefCode("ref");
gcAuthReversal.setCard(giftCard);
batch.addTransaction(gcAuthReversal);
GiftCardCapture gcCapture = new GiftCardCapture();
gcCapture.setLitleTxnId(123L);
gcCapture.setId("id");
gcCapture.setReportGroup("rptGrp");
gcCapture.setCaptureAmount(2434l);
gcCapture.setCard(giftCard);
gcCapture.setOriginalRefCode("ref");
gcCapture.setOriginalAmount(44455l);
gcCapture.setOriginalTxnTime(new XMLGregorianCalendarImpl(new GregorianCalendar()));
batch.addTransaction(gcCapture);
GiftCardCredit gcCredit = new GiftCardCredit();
gcCredit.setLitleTxnId(369852147l);
gcCredit.setId("id");
gcCredit.setReportGroup("rptGrp1");
gcCredit.setCustomerId("customer_22");
gcCredit.setCreditAmount(1942l);
gcCredit.setCard(giftCard);
batch.addTransaction(gcCredit);
int transactionCount = batch.getNumberOfTransactions();
LitleBatchFileResponse fileResponse = request.sendToLitle();
LitleBatchResponse batchResponse = fileResponse.getNextLitleBatchResponse();
int txns = 0;
// iterate over all transactions in the file with a custom response
// processor
while (batchResponse
.processNextTransaction(new LitleResponseProcessor() {
public void processAuthorizationResponse(
AuthorizationResponse authorizationResponse) {
assertNotNull(authorizationResponse.getLitleTxnId());
}
public void processCaptureResponse(
CaptureResponse captureResponse) {
assertNotNull(captureResponse.getLitleTxnId());
}
public void processForceCaptureResponse(
ForceCaptureResponse forceCaptureResponse) {
assertNotNull(forceCaptureResponse.getLitleTxnId());
}
public void processCaptureGivenAuthResponse(
CaptureGivenAuthResponse captureGivenAuthResponse) {
assertNotNull(captureGivenAuthResponse.getLitleTxnId());
}
public void processSaleResponse(SaleResponse saleResponse) {
assertNotNull(saleResponse.getLitleTxnId());
}
public void processCreditResponse(
CreditResponse creditResponse) {
assertNotNull(creditResponse.getLitleTxnId());
}
public void processEcheckSalesResponse(
EcheckSalesResponse echeckSalesResponse) {
assertNotNull(echeckSalesResponse.getLitleTxnId());
}
public void processEcheckCreditResponse(
EcheckCreditResponse echeckCreditResponse) {
assertNotNull(echeckCreditResponse.getLitleTxnId());
}
public void processEcheckVerificationResponse(
EcheckVerificationResponse echeckVerificationResponse) {
assertNotNull(echeckVerificationResponse
.getLitleTxnId());
}
public void processEcheckRedepositResponse(
EcheckRedepositResponse echeckRedepositResponse) {
assertNotNull(echeckRedepositResponse.getLitleTxnId());
}
public void processAuthReversalResponse(
AuthReversalResponse authReversalResponse) {
assertNotNull(authReversalResponse.getLitleTxnId());
}
public void processRegisterTokenResponse(
RegisterTokenResponse registerTokenResponse) {
assertNotNull(registerTokenResponse.getLitleTxnId());
}
public void processUpdateSubscriptionResponse(
UpdateSubscriptionResponse updateSubscriptionResponse) {
assertNotNull(updateSubscriptionResponse
.getLitleTxnId());
}
public void processCancelSubscriptionResponse(
CancelSubscriptionResponse cancelSubscriptionResponse) {
assertNotNull(cancelSubscriptionResponse
.getLitleTxnId());
}
public void processUpdateCardValidationNumOnTokenResponse(
UpdateCardValidationNumOnTokenResponse updateCardValidationNumOnTokenResponse) {
assertNotNull(updateCardValidationNumOnTokenResponse
.getLitleTxnId());
}
public void processAccountUpdate(
AccountUpdateResponse accountUpdateResponse) {
assertNotNull(accountUpdateResponse.getLitleTxnId());
}
public void processCreatePlanResponse(
CreatePlanResponse createPlanResponse) {
assertNotNull(createPlanResponse.getLitleTxnId());
}
public void processUpdatePlanResponse(
UpdatePlanResponse updatePlanResponse) {
assertNotNull(updatePlanResponse.getLitleTxnId());
}
public void processActivateResponse(
ActivateResponse activateResponse) {
assertNotNull(activateResponse.getLitleTxnId());
}
public void processDeactivateResponse(
DeactivateResponse deactivateResponse) {
assertNotNull(deactivateResponse.getLitleTxnId());
}
public void processLoadResponse(LoadResponse loadResponse) {
assertNotNull(loadResponse.getLitleTxnId());
}
public void processUnloadResponse(
UnloadResponse unloadResponse) {
assertNotNull(unloadResponse.getLitleTxnId());
}
public void processBalanceInquiryResponse(
BalanceInquiryResponse balanceInquiryResponse) {
assertNotNull(balanceInquiryResponse.getLitleTxnId());
}
public void processEcheckPreNoteSaleResponse(
EcheckPreNoteSaleResponse echeckPreNoteSaleResponse) {
}
public void processEcheckPreNoteCreditResponse(
EcheckPreNoteCreditResponse echeckPreNoteCreditResponse) {
}
public void processSubmerchantCreditResponse(
SubmerchantCreditResponse submerchantCreditResponse) {
}
public void processPayFacCreditResponse(
PayFacCreditResponse payFacCreditResponse) {
}
public void processVendorCreditRespsonse(
VendorCreditResponse vendorCreditResponse) {
}
public void processReserveCreditResponse(
ReserveCreditResponse reserveCreditResponse) {
}
public void processPhysicalCheckCreditResponse(
PhysicalCheckCreditResponse checkCreditResponse) {
}
public void processSubmerchantDebitResponse(
SubmerchantDebitResponse submerchantDebitResponse) {
}
public void processPayFacDebitResponse(
PayFacDebitResponse payFacDebitResponse) {
}
public void processVendorDebitResponse(
VendorDebitResponse vendorDebitResponse) {
}
public void processReserveDebitResponse(
ReserveDebitResponse reserveDebitResponse) {
}
public void processPhysicalCheckDebitResponse(
PhysicalCheckDebitResponse checkDebitResponse) {
}
public void processFundingInstructionVoidResponse(
FundingInstructionVoidResponse fundingInstructionVoidResponse) {
}
public void processGiftCardAuthReversalResponse(GiftCardAuthReversalResponse giftCardAuthReversalResponse) {
assertNotNull(giftCardAuthReversalResponse.getLitleTxnId());
}
public void processGiftCardCaptureResponse(GiftCardCaptureResponse giftCardCaptureResponse) {
assertNotNull(giftCardCaptureResponse.getLitleTxnId());
}
public void processGiftCardCreditResponse(GiftCardCreditResponse giftCardCreditResponse) {
assertNotNull(giftCardCreditResponse.getLitleTxnId());
}
})) {
txns++;
}
assertEquals(5, txns);
}
@Test
public void testMechaBatchAndProcess_RecurringDemonstratesUseOfProcessorAdapter() {
String requestFileName = "litleSdk-testBatchFile-RECURRING.xml";
LitleBatchFileRequest request = new LitleBatchFileRequest(
requestFileName);
Properties configFromFile = request.getConfig();
// pre-assert the config file has required param values
assertEquals("prelive.litle.com",
configFromFile.getProperty("batchHost"));
assertEquals("15000", configFromFile.getProperty("batchPort"));
LitleBatchRequest batch = request.createBatch(configFromFile.getProperty("merchantId"));
CancelSubscription cancelSubscription = new CancelSubscription();
cancelSubscription.setSubscriptionId(12345L);
batch.addTransaction(cancelSubscription);
UpdateSubscription updateSubscription = new UpdateSubscription();
updateSubscription.setSubscriptionId(12345L);
batch.addTransaction(updateSubscription);
CreatePlan createPlan = new CreatePlan();
createPlan.setPlanCode("abc");
createPlan.setName("name");
createPlan.setIntervalType(IntervalTypeEnum.ANNUAL);
createPlan.setAmount(100L);
batch.addTransaction(createPlan);
UpdatePlan updatePlan = new UpdatePlan();
updatePlan.setPlanCode("def");
updatePlan.setActive(true);
batch.addTransaction(updatePlan);
LitleBatchFileResponse fileResponse = request.sendToLitle();
LitleBatchResponse batchResponse = fileResponse
.getNextLitleBatchResponse();
int txns = 0;
// iterate over all transactions in the file with a custom response
// processor
while (batchResponse
.processNextTransaction(new LitleResponseProcessorAdapter() {
@Override
public void processUpdateSubscriptionResponse(
UpdateSubscriptionResponse updateSubscriptionResponse) {
assertEquals(12345L,
updateSubscriptionResponse.getSubscriptionId());
}
@Override
public void processCancelSubscriptionResponse(
CancelSubscriptionResponse cancelSubscriptionResponse) {
assertEquals(12345L,
cancelSubscriptionResponse.getSubscriptionId());
}
@Override
public void processCreatePlanResponse(
CreatePlanResponse createPlanResponse) {
assertEquals("abc", createPlanResponse.getPlanCode());
}
@Override
public void processUpdatePlanResponse(
UpdatePlanResponse updatePlanResponse) {
assertEquals("def", updatePlanResponse.getPlanCode());
}
})) {
txns++;
}
assertEquals(4, txns);
}
@Test
public void testBatch_AU() {
String requestFileName = "litleSdk-testBatchFile_AU.xml";
LitleBatchFileRequest request = new LitleBatchFileRequest(
requestFileName);
Properties configFromFile = request.getConfig();
// pre-assert the config file has required param values
assertEquals("prelive.litle.com",
configFromFile.getProperty("batchHost"));
assertEquals("15000", configFromFile.getProperty("batchPort"));
LitleBatchRequest batch = request.createBatch(configFromFile.getProperty("merchantId"));
// card
CardType card = new CardType();
card.setNumber("4100000000000001");
card.setExpDate("1210");
card.setType(MethodOfPaymentTypeEnum.VI);
ObjectFactory objectFactory = new ObjectFactory();
AccountUpdate accountUpdate = new AccountUpdate();
accountUpdate.setReportGroup("Planets");
accountUpdate.setId("12345");
accountUpdate.setCustomerId("0987");
accountUpdate.setOrderId("1234");
accountUpdate.setCardOrToken(objectFactory.createCard(card));
batch.addTransaction(accountUpdate);
LitleBatchFileResponse fileResponse = request.sendToLitle();
LitleBatchResponse batchResponse = fileResponse
.getNextLitleBatchResponse();
int txns = 0;
// iterate over all transactions in the file with a custom response
// processor
while (batchResponse
.processNextTransaction(new LitleResponseProcessor() {
public void processAuthorizationResponse(
AuthorizationResponse authorizationResponse) {
}
public void processCaptureResponse(
CaptureResponse captureResponse) {
}
public void processForceCaptureResponse(
ForceCaptureResponse forceCaptureResponse) {
}
public void processCaptureGivenAuthResponse(
CaptureGivenAuthResponse captureGivenAuthResponse) {
}
public void processSaleResponse(SaleResponse saleResponse) {
}
public void processCreditResponse(
CreditResponse creditResponse) {
}
public void processEcheckSalesResponse(
EcheckSalesResponse echeckSalesResponse) {
}
public void processEcheckCreditResponse(
EcheckCreditResponse echeckCreditResponse) {
}
public void processEcheckVerificationResponse(
EcheckVerificationResponse echeckVerificationResponse) {
}
public void processEcheckRedepositResponse(
EcheckRedepositResponse echeckRedepositResponse) {
}
public void processAuthReversalResponse(
AuthReversalResponse authReversalResponse) {
}
public void processRegisterTokenResponse(
RegisterTokenResponse registerTokenResponse) {
}
public void processAccountUpdate(
AccountUpdateResponse accountUpdateResponse) {
assertEquals("Planets",
accountUpdateResponse.getReportGroup());
assertEquals("12345", accountUpdateResponse.getId());
assertEquals("0987",
accountUpdateResponse.getCustomerId());
}
public void processUpdateSubscriptionResponse(
UpdateSubscriptionResponse updateSubscriptionResponse) {
}
public void processCancelSubscriptionResponse(
CancelSubscriptionResponse cancelSubscriptionResponse) {
}
public void processUpdateCardValidationNumOnTokenResponse(
UpdateCardValidationNumOnTokenResponse updateCardValidationNumOnTokenResponse) {
}
public void processCreatePlanResponse(
CreatePlanResponse createPlanResponse) {
}
public void processUpdatePlanResponse(
UpdatePlanResponse updatePlanResponse) {
}
public void processActivateResponse(
ActivateResponse activateResponse) {
}
public void processDeactivateResponse(
DeactivateResponse deactivateResponse) {
}
public void processLoadResponse(LoadResponse loadResponse) {
}
public void processUnloadResponse(
UnloadResponse unloadResponse) {
}
public void processBalanceInquiryResponse(
BalanceInquiryResponse balanceInquiryResponse) {
}
public void processEcheckPreNoteSaleResponse(
EcheckPreNoteSaleResponse echeckPreNoteSaleResponse) {
}
public void processEcheckPreNoteCreditResponse(
EcheckPreNoteCreditResponse echeckPreNoteCreditResponse) {
}
public void processSubmerchantCreditResponse(
SubmerchantCreditResponse submerchantCreditResponse) {
}
public void processPayFacCreditResponse(
PayFacCreditResponse payFacCreditResponse) {
}
public void processVendorCreditRespsonse(
VendorCreditResponse vendorCreditResponse) {
}
public void processReserveCreditResponse(
ReserveCreditResponse reserveCreditResponse) {
}
public void processPhysicalCheckCreditResponse(
PhysicalCheckCreditResponse checkCreditResponse) {
}
public void processSubmerchantDebitResponse(
SubmerchantDebitResponse submerchantDebitResponse) {
}
public void processPayFacDebitResponse(
PayFacDebitResponse payFacDebitResponse) {
}
public void processVendorDebitResponse(
VendorDebitResponse vendorDebitResponse) {
}
public void processReserveDebitResponse(
ReserveDebitResponse reserveDebitResponse) {
}
public void processPhysicalCheckDebitResponse(
PhysicalCheckDebitResponse checkDebitResponse) {
}
public void processFundingInstructionVoidResponse(
FundingInstructionVoidResponse fundingInstructionVoidResponse) {
}
public void processGiftCardAuthReversalResponse(GiftCardAuthReversalResponse giftCardAuthReversalResponse) {
}
public void processGiftCardCaptureResponse(GiftCardCaptureResponse giftCardCaptureResponse) {
}
public void processGiftCardCreditResponse(GiftCardCreditResponse giftCardCreditResponse) {
}
})) {
txns++;
}
assertEquals(1, txns);
}
private void assertJavaApi(LitleBatchFileRequest request,
LitleBatchFileResponse response) {
assertNotNull(response);
assertNotNull(response.getLitleSessionId());
assertEquals("0", response.getResponse());
assertEquals("Valid Format", response.getMessage());
//TODO: uncomment this assertion when prelive responds with XML v11.0
// assertEquals(Versions.XML_VERSION, response.getVersion());
LitleBatchResponse batchResponse1 = response
.getNextLitleBatchResponse();
assertNotNull(batchResponse1);
assertNotNull(batchResponse1.getLitleBatchId());
Properties configFromFile = request.getConfig();
assertEquals(configFromFile.getProperty("merchantId"), batchResponse1.getMerchantId());
LitleTransactionInterface txnResponse = batchResponse1
.getNextTransaction();
SaleResponse saleResponse11 = (SaleResponse) txnResponse;
assertEquals("000", saleResponse11.getResponse());
assertEquals("Approved", saleResponse11.getMessage());
assertNotNull(saleResponse11.getLitleTxnId());
assertEquals("orderId11", saleResponse11.getOrderId());
assertEquals("reportGroup11", saleResponse11.getReportGroup());
// assertNull("expected no more than one transaction in batchResponse1",
// batchResponse1.getNextTransaction());
// assertNull("expected no more than one batch in file",
// response.getNextLitleBatchResponse());
}
private void assertGeneratedFiles(String workingDirRequests,
String workingDirResponses, String requestFileName,
LitleBatchFileRequest request, LitleBatchFileResponse response)
throws Exception {
File fRequest = request.getFile();
assertEquals(workingDirRequests + File.separator + requestFileName,
fRequest.getAbsolutePath());
assertTrue(fRequest.exists());
assertTrue(fRequest.length() > 0);
File fResponse = response.getFile();
assertEquals(workingDirResponses + File.separator + requestFileName,
fResponse.getAbsolutePath());
assertTrue(fResponse.exists());
assertTrue(fResponse.length() > 0);
// assert contents of the response file by reading it through the Java
// API again
LitleBatchFileResponse responseFromFile = new LitleBatchFileResponse(
fResponse);
assertJavaApi(request, responseFromFile);
}
private void prepDir(String dirName) {
File fRequestDir = new File(dirName);
fRequestDir.mkdirs();
}
private void copyFile(File source, File destination) throws IOException {
FileInputStream sourceIn = null;
FileOutputStream destOut = null;
try {
sourceIn = new FileInputStream(source);
destOut = new FileOutputStream(destination);
byte[] buffer = new byte[2048];
int bytesRead = -1;
while ((bytesRead = sourceIn.read(buffer)) != -1) {
destOut.write(buffer, 0, bytesRead);
}
} finally {
if (sourceIn != null) {
sourceIn.close();
}
if (destOut != null) {
destOut.close();
}
}
}
class ResponseValidatorProcessor implements LitleResponseProcessor {
int responseCount = 0;
public void processAuthorizationResponse(
AuthorizationResponse authorizationResponse) {
assertNotNull(authorizationResponse.getLitleTxnId());
responseCount++;
}
public void processCaptureResponse(CaptureResponse captureResponse) {
assertNotNull(captureResponse.getLitleTxnId());
responseCount++;
}
public void processForceCaptureResponse(
ForceCaptureResponse forceCaptureResponse) {
assertNotNull(forceCaptureResponse.getLitleTxnId());
responseCount++;
}
public void processCaptureGivenAuthResponse(
CaptureGivenAuthResponse captureGivenAuthResponse) {
assertNotNull(captureGivenAuthResponse.getLitleTxnId());
responseCount++;
}
public void processSaleResponse(SaleResponse saleResponse) {
assertNotNull(saleResponse.getLitleTxnId());
responseCount++;
}
public void processCreditResponse(CreditResponse creditResponse) {
assertNotNull(creditResponse.getLitleTxnId());
responseCount++;
}
public void processEcheckSalesResponse(
EcheckSalesResponse echeckSalesResponse) {
assertNotNull(echeckSalesResponse.getLitleTxnId());
responseCount++;
}
public void processEcheckCreditResponse(
EcheckCreditResponse echeckCreditResponse) {
assertNotNull(echeckCreditResponse.getLitleTxnId());
responseCount++;
}
public void processEcheckVerificationResponse(
EcheckVerificationResponse echeckVerificationResponse) {
assertNotNull(echeckVerificationResponse.getLitleTxnId());
responseCount++;
}
public void processEcheckRedepositResponse(
EcheckRedepositResponse echeckRedepositResponse) {
assertNotNull(echeckRedepositResponse.getLitleTxnId());
responseCount++;
}
public void processAuthReversalResponse(
AuthReversalResponse authReversalResponse) {
assertNotNull(authReversalResponse.getLitleTxnId());
responseCount++;
}
public void processRegisterTokenResponse(
RegisterTokenResponse registerTokenResponse) {
assertNotNull(registerTokenResponse.getLitleTxnId());
responseCount++;
}
public void processUpdateSubscriptionResponse(
UpdateSubscriptionResponse updateSubscriptionResponse) {
assertNotNull(updateSubscriptionResponse.getLitleTxnId());
responseCount++;
}
public void processCancelSubscriptionResponse(
CancelSubscriptionResponse cancelSubscriptionResponse) {
assertNotNull(cancelSubscriptionResponse.getLitleTxnId());
responseCount++;
}
public void processUpdateCardValidationNumOnTokenResponse(
UpdateCardValidationNumOnTokenResponse updateCardValidationNumOnTokenResponse) {
assertNotNull(updateCardValidationNumOnTokenResponse
.getLitleTxnId());
responseCount++;
}
public void processEcheckPreNoteSaleResponse(
EcheckPreNoteSaleResponse echeckPreNoteSaleResponse) {
assertNotNull(echeckPreNoteSaleResponse.getLitleTxnId());
responseCount++;
}
public void processEcheckPreNoteCreditResponse(
EcheckPreNoteCreditResponse echeckPreNoteCreditResponse) {
assertNotNull(echeckPreNoteCreditResponse.getLitleTxnId());
responseCount++;
}
public void processAccountUpdate(
AccountUpdateResponse accountUpdateResponse) {
assertNotNull(accountUpdateResponse.getLitleTxnId());
responseCount++;
}
public void processCreatePlanResponse(
CreatePlanResponse createPlanResponse) {
assertNotNull(createPlanResponse.getLitleTxnId());
responseCount++;
}
public void processUpdatePlanResponse(
UpdatePlanResponse updatePlanResponse) {
assertNotNull(updatePlanResponse.getLitleTxnId());
responseCount++;
}
public void processActivateResponse(ActivateResponse activateResponse) {
assertNotNull(activateResponse.getLitleTxnId());
responseCount++;
}
public void processDeactivateResponse(
DeactivateResponse deactivateResponse) {
assertNotNull(deactivateResponse.getLitleTxnId());
responseCount++;
}
public void processLoadResponse(LoadResponse loadResponse) {
assertNotNull(loadResponse.getLitleTxnId());
responseCount++;
}
public void processUnloadResponse(UnloadResponse unloadResponse) {
assertNotNull(unloadResponse.getLitleTxnId());
responseCount++;
}
public void processBalanceInquiryResponse(
BalanceInquiryResponse balanceInquiryResponse) {
assertNotNull(balanceInquiryResponse.getLitleTxnId());
responseCount++;
}
public void processSubmerchantCreditResponse(
SubmerchantCreditResponse submerchantCreditResponse) {
assertNotNull(submerchantCreditResponse.getLitleTxnId());
responseCount++;
}
public void processPayFacCreditResponse(
PayFacCreditResponse payFacCreditResponse) {
assertNotNull(payFacCreditResponse.getLitleTxnId());
responseCount++;
}
public void processVendorCreditRespsonse(
VendorCreditResponse vendorCreditResponse) {
assertNotNull(vendorCreditResponse.getLitleTxnId());
responseCount++;
}
public void processReserveCreditResponse(
ReserveCreditResponse reserveCreditResponse) {
assertNotNull(reserveCreditResponse.getLitleTxnId());
responseCount++;
}
public void processPhysicalCheckCreditResponse(
PhysicalCheckCreditResponse physicalCheckCreditResponse) {
assertNotNull(physicalCheckCreditResponse.getLitleTxnId());
responseCount++;
}
public void processSubmerchantDebitResponse(
SubmerchantDebitResponse submerchantDebitResponse) {
assertNotNull(submerchantDebitResponse.getLitleTxnId());
responseCount++;
}
public void processPayFacDebitResponse(
PayFacDebitResponse payFacDebitResponse) {
assertNotNull(payFacDebitResponse.getLitleTxnId());
responseCount++;
}
public void processVendorDebitResponse(
VendorDebitResponse vendorDebitResponse) {
assertNotNull(vendorDebitResponse.getLitleTxnId());
responseCount++;
}
public void processReserveDebitResponse(
ReserveDebitResponse reserveDebitResponse) {
assertNotNull(reserveDebitResponse.getLitleTxnId());
responseCount++;
}
public void processPhysicalCheckDebitResponse(
PhysicalCheckDebitResponse physicalCheckDebitResponse) {
assertNotNull(physicalCheckDebitResponse.getLitleTxnId());
responseCount++;
}
public void processFundingInstructionVoidResponse(
FundingInstructionVoidResponse fundingInstructionVoidResponse) {
assertNotNull(fundingInstructionVoidResponse.getLitleTxnId());
responseCount++;
}
public void processGiftCardAuthReversalResponse(GiftCardAuthReversalResponse giftCardAuthReversalResponse) {
assertNotNull(giftCardAuthReversalResponse.getLitleTxnId());
responseCount++;
}
public void processGiftCardCaptureResponse(GiftCardCaptureResponse giftCardCaptureResponse) {
assertNotNull(giftCardCaptureResponse.getLitleTxnId());
responseCount++;
}
public void processGiftCardCreditResponse(GiftCardCreditResponse giftCardCreditResponse) {
assertNotNull(giftCardCreditResponse.getLitleTxnId());
responseCount++;
}
}
public static void main(String[] args) throws Exception {
TestBatchFile t = new TestBatchFile();
t.testSendToLitle_WithFileConfig();
t.testSendToLitle_WithConfigOverrides();
}
}
|
package gov.nih.nci.calab.dto.administration;
/**
* This class represents all properties of a sample that need to be viewed and
* saved.
*
* @author pansu
*
*/
/* CVS $Id: SampleBean.java,v 1.2 2006-03-28 22:59:36 pansu Exp $ */
public class SampleBean {
private String sampleId;
private String sampleType;
private String sampleSOP;
private String sampleDescription;
private String sampleSource;
private String sourceSampleId;
private String dateReceived;
private String lotId;
private String lotDescription;
private String solubility;
private String numberOfContainers;
private String generalComments;
private String sampleSubmitter;
private String accessionDate;
private ContainerBean[] containers;
public SampleBean(String sampleId, String sampleType, String sampleSOP,
String sampleDescription, String sampleSource,
String sourceSampleId, String dateReceived, String solubility,
String lotId, String lotDescription, String numberOfContainers,
String generalComments, String sampleSubmitter,
String accessionDate, ContainerBean[] containers) {
super();
// TODO Auto-generated constructor stub
this.sampleId = sampleId;
this.sampleType = sampleType;
this.sampleSOP = sampleSOP;
this.sampleDescription = sampleDescription;
this.sampleSource = sampleSource;
this.sourceSampleId = sourceSampleId;
this.dateReceived = dateReceived;
this.lotId = lotId;
this.lotDescription = lotDescription;
this.solubility = solubility;
this.numberOfContainers = numberOfContainers;
this.generalComments = generalComments;
this.sampleSubmitter = sampleSubmitter;
this.accessionDate=accessionDate;
this.containers = containers;
}
public String getDateReceived() {
return dateReceived;
}
public String getAccessionDate() {
return accessionDate;
}
public void setAccessionDate(String accessionDate) {
this.accessionDate = accessionDate;
}
public void setDateReceived(String dateReceived) {
this.dateReceived = dateReceived;
}
public String getGeneralComments() {
return generalComments;
}
public void setGeneralComments(String generalComments) {
this.generalComments = generalComments;
}
public String getLotDescription() {
return lotDescription;
}
public void setLotDescription(String lotDescription) {
this.lotDescription = lotDescription;
}
public String getLotId() {
return lotId;
}
public void setLotId(String lotId) {
this.lotId = lotId;
}
public String getNumberOfContainers() {
return numberOfContainers;
}
public void setNumberOfContainers(String numberOfContainers) {
this.numberOfContainers = numberOfContainers;
}
public String getSampleDescription() {
return sampleDescription;
}
public void setSampleDescription(String sampleDescription) {
this.sampleDescription = sampleDescription;
}
public String getSampleId() {
return sampleId;
}
public void setSampleId(String sampleId) {
this.sampleId = sampleId;
}
public String getSampleSOP() {
return sampleSOP;
}
public void setSampleSOP(String sampleSOP) {
this.sampleSOP = sampleSOP;
}
public String getSampleType() {
return sampleType;
}
public void setSampleType(String sampleType) {
this.sampleType = sampleType;
}
public String getSolubility() {
return solubility;
}
public void setSolubility(String solubility) {
this.solubility = solubility;
}
public String getSampleSource() {
return sampleSource;
}
public void setSampleSource(String sampleSource) {
this.sampleSource = sampleSource;
}
public String getSourceSampleId() {
return sourceSampleId;
}
public void setSourceSampleId(String sourceSampleId) {
this.sourceSampleId = sourceSampleId;
}
public String getSampleSubmitter() {
return sampleSubmitter;
}
public void setSampleSubmitter(String sampleSubmitter) {
this.sampleSubmitter = sampleSubmitter;
}
public ContainerBean[] getContainers() {
return containers;
}
public void setContainers(ContainerBean[] containers) {
this.containers = containers;
}
}
|
package xal.extension.service;
import xal.tools.coding.*;
import java.io.*;
import java.lang.reflect.*;
import java.net.*;
import java.util.*;
import java.util.logging.*;
/**
* RpcServer implements a server which handles remote requests against registered handlers.
* @author tap
*/
//public class RpcServer extends WebServer {
public class RpcServer {
/** terminator for remote messages */
final static char REMOTE_MESSAGE_TERMINATOR = SocketMessageIO.REMOTE_MESSAGE_TERMINATOR;
/** delimeter for encoding remote messages */
final static private String REMOTE_MESSAGE_DELIMITER = "
/** socket which listens for and dispatches remote requests */
final private ServerSocket SERVER_SOCKET;
/** set of active sockets serving remote requests */
final private Set<Socket> REMOTE_SOCKETS;
/** remote request handlers keyed by service name */
final private Map<String,RemoteRequestHandler<?>> REMOTE_REQUEST_HANDLERS;
/** coder for encoding and decoding messages for remote transport */
final private Coder MESSAGE_CODER;
/** Constructor */
public RpcServer( final Coder messageCoder ) throws java.io.IOException {
MESSAGE_CODER = messageCoder;
REMOTE_REQUEST_HANDLERS = new Hashtable<String,RemoteRequestHandler<?>>();
SERVER_SOCKET = new ServerSocket( 0 );
REMOTE_SOCKETS = new HashSet<Socket>();
System.out.println( "Listening on: " + getHost() + ":" + getPort() );
}
/**
* Get the port used by the web server.
* @return The port used by the web server.
*/
public int getPort() {
return SERVER_SOCKET.getLocalPort();
}
/**
* Get the host address used for the web server.
* @return The host address used for the web server.
*/
public String getHost() {
try {
return InetAddress.getLocalHost().getHostName();
}
catch(UnknownHostException exception) {
final String message = "Error getting the host name of the RPC Server.";
Logger.getLogger("global").log( Level.SEVERE, message, exception );
System.err.println(exception);
return null;
}
}
/** start the server, listen for remote requests and dispatch them to the appropriate handlers */
public void start() {
new Thread( new Runnable() {
public void run() {
try {
while ( !SERVER_SOCKET.isClosed() ) {
final Socket remoteSocket = SERVER_SOCKET.accept();
remoteSocket.setKeepAlive( true );
synchronized( REMOTE_SOCKETS ) {
REMOTE_SOCKETS.add( remoteSocket );
}
processRemoteEvents( remoteSocket );
}
}
catch ( SocketException exception ) {
// server being shutdown
}
catch ( IOException exception ) {
exception.printStackTrace();
}
}
}).start();
}
/** shutdown the server */
public void shutdown() throws IOException {
// stop establishing new remote sockets
SERVER_SOCKET.close();
// close the existing remote sockets
final Set<Socket> sockets = new HashSet<Socket>();
synchronized( REMOTE_SOCKETS ) {
sockets.addAll( REMOTE_SOCKETS );
}
for ( final Socket socket : sockets ) {
try {
socket.close();
}
catch( Exception exception ) {
exception.printStackTrace();
}
}
// clear the remote sockets
synchronized( REMOTE_SOCKETS ) {
REMOTE_SOCKETS.clear();
}
}
/** cleanup the remote socket which has been closed */
private void cleanupClosedRemoteSocket( final Socket remoteSocket ) {
synchronized( REMOTE_SOCKETS ) {
REMOTE_SOCKETS.remove( remoteSocket );
}
}
public <ProtocolType> void addHandler( final String serviceName, final Class<ProtocolType> protocol, final ProtocolType provider ) {
final RemoteRequestHandler<ProtocolType> handler = new RemoteRequestHandler<ProtocolType>( serviceName, protocol, provider );
REMOTE_REQUEST_HANDLERS.put( serviceName, handler );
System.out.println( "Added request handler with service name: " + serviceName );
}
public void removeHandler( final String serviceName ) {
}
/** process remote socket events */
@SuppressWarnings( "unchecked" ) // need to cast generic request object to Map
private void processRemoteEvents( final Socket remoteSocket ) {
new Thread( new Runnable() {
public void run() {
if ( !remoteSocket.isClosed() ) {
// process the initial handshake
try {
WebSocketIO.processHandshake( remoteSocket );
}
catch ( Exception exception ) {
throw new RuntimeException( "Exception handling handshake", exception );
}
}
// process the messages as they arrive
while( !remoteSocket.isClosed() ) {
try {
String jsonRequest = null;
try {
jsonRequest = WebSocketIO.readMessage( remoteSocket );
}
catch( Exception exception ) {
throw new RemoteClientDroppedException( "Session has been closed during read..." );
}
final Object requestObject = MESSAGE_CODER.decode( jsonRequest );
System.out.println( "JSON Request: " + jsonRequest );
System.out.println( "Request Object: " + requestObject );
System.out.println( "Request Object Class: " + requestObject.getClass() );
if ( requestObject instanceof Map ) {
System.out.println( "Writing output..." );
final Writer output = new OutputStreamWriter( remoteSocket.getOutputStream() );
final Map<String,Object> request = (Map<String,Object>)requestObject;
final String message = (String)request.get( "message" );
System.out.println( "Request Message: " + message );
final String[] messageParts = decodeRemoteMessage( message );
final String serviceName = messageParts[0];
final String methodName = messageParts[1];
System.out.println( "Request Service: " + serviceName );
System.out.println( "Request Method: " + methodName );
final Number requestID = (Number)request.get( "id" );
System.out.println( "request ID: " + requestID );
final List<Object> params = (List<Object>)request.get( "params" );
System.out.println( "Params: " + params );
final RemoteRequestHandler<?> handler = REMOTE_REQUEST_HANDLERS.get( serviceName );
System.out.println( "Request handler: " + handler );
final EvaluationResult result = handler.evaluateRequest( methodName, params );
// methods marked with the OneWay annotation return immediately and do not provide any response
final boolean provideResponse = !result.isOneWay();
if ( provideResponse ) {
final Map<String,Object> response = new HashMap<String,Object>();
response.put( "result", result.getValue() );
response.put( "id", requestID );
response.put( "error", result.getRuntimeExceptionWrapper() );
final String jsonResponse = MESSAGE_CODER.encode( response );
System.out.println( "Response: " + jsonResponse );
output.write( jsonResponse );
output.flush();
}
}
}
catch ( Exception exception ) {
if ( !remoteSocket.isClosed() ) {
try {
remoteSocket.close();
}
catch( Exception closeException ) {
closeException.printStackTrace();
}
}
cleanupClosedRemoteSocket( remoteSocket );
return;
}
}
}
}).start();
}
/** encode the service name and method name into the remote message */
static String encodeRemoteMessage( final String serviceName, final String methodName ) {
return serviceName + REMOTE_MESSAGE_DELIMITER + methodName;
}
/** decode the service name and method name from the remote message */
static String[] decodeRemoteMessage( final String message ) {
return message.split( REMOTE_MESSAGE_DELIMITER, 2 );
}
}
/** Handles remote requests */
class RemoteRequestHandler<ProtocolType> {
/** primitive type wrappers keyed by type */
final static private Map<Class<?>,Class<?>> PRIMITIVE_TYPE_WRAPPERS;
/** identifier of the service */
final private String SERVICE_NAME;
/** protocol of available methods */
final private Class<ProtocolType> PROTOCOL;
/** object to message */
final private ProtocolType PROVIDER;
/** cache of methods keyed by their signature */
final private Map<String,Method> METHOD_CACHE;
// static initializer
static {
PRIMITIVE_TYPE_WRAPPERS = populatePrimitiveTypeWrappers();
}
/** Constructor */
public RemoteRequestHandler( final String serviceName, final Class<ProtocolType> protocol, final ProtocolType provider ) {
SERVICE_NAME = serviceName;
PROTOCOL = protocol;
PROVIDER = provider;
METHOD_CACHE = new Hashtable<String,Method>();
}
/** populate the table of primitive type wrappers */
private static Map<Class<?>,Class<?>> populatePrimitiveTypeWrappers() {
final Map<Class<?>,Class<?>> table = new Hashtable<Class<?>,Class<?>>();
table.put( Integer.TYPE, Integer.class );
table.put( Long.TYPE, Long.class );
table.put( Short.TYPE, Short.class );
table.put( Byte.TYPE, Byte.class );
table.put( Character.TYPE, Character.class );
table.put( Float.TYPE, Float.class );
table.put( Double.TYPE, Double.class );
table.put( Boolean.TYPE, Boolean.class );
return table;
}
/** Evaluate the request */
public EvaluationResult evaluateRequest( final String methodName, final List<Object> params ) {
final Object[] methodParams = new Object[ params.size() ];
final Class<?>[] methodParamTypes = new Class<?>[ methodParams.length ];
for ( int index = 0 ; index < methodParams.length ; index++ ) {
final Object param = params.get( index );
methodParams[index] = param;
methodParamTypes[index] = param != null ? param.getClass() : null;
}
final Method method = getMethod( methodName, methodParamTypes );
final boolean isOneWay = method.isAnnotationPresent( OneWay.class );
try {
final Object value = method.invoke( PROVIDER, methodParams );
return new EvaluationResult( value, isOneWay );
}
catch ( Exception exception ) {
exception.printStackTrace();
return new EvaluationResult( null, isOneWay, exception.getCause() );
}
}
/** Get the method either from the cache or find and cache it if necessary */
private Method getMethod( final String methodName, final Class<?>[] parameterTypes ) {
final String methodSignature = getMethodSignature( methodName, parameterTypes );
Method method = METHOD_CACHE.get( methodSignature );
if ( method == null ) {
method = findMethod( methodName, parameterTypes );
METHOD_CACHE.put( methodSignature, method );
}
return method;
}
/** Get the method signature for the specified method name and parameter types */
static private String getMethodSignature( final String methodName, final Class<?>[] parameterTypes ) {
final StringBuilder buffer = new StringBuilder();
buffer.append( methodName );
for ( final Class<?> parameterType : parameterTypes ) {
final String parameterTypeID = parameterType != null ? parameterType.getName() : "";
buffer.append( ":" );
buffer.append( parameterTypeID );
}
return buffer.toString();
}
/** Find the best method in the protocol that matches the method name and parameters */
private Method findMethod( final String methodName, final Class<?>[] parameterTypes ) {
try {
return PROTOCOL.getMethod( methodName, parameterTypes );
}
catch ( NoSuchMethodException exception ) {
try {
final Method[] methods = PROTOCOL.getMethods();
final List<Method> methodCandidates = new ArrayList<Method>();
int bestScore = 0;
Method bestMethod = null;
for ( final Method method : methods ) {
final int score = matchScore( method, methodName, parameterTypes );
if ( score > bestScore ) {
bestScore = score;
bestMethod = method;
}
}
if ( bestMethod != null ) {
return bestMethod;
}
else {
throw new RuntimeException( "No matching method found for <" + methodName + "" + parameterTypes + ">", exception );
}
}
catch ( Exception searchException ) {
throw new RuntimeException( "Exception evaluating the remote request with the request handler.", searchException );
}
}
}
/** Score the match between the method and the specified method name and parameter types. Higher scores are better and zero means no match. */
static private int matchScore( final Method method, final String methodName, final Class<?>[] parameterTypes ) {
int score = 0;
final Class<?>[] methodParamTypes = method.getParameterTypes();
if ( method.getName().equals( methodName ) && methodParamTypes.length == parameterTypes.length ) {
score += 1; // credit for matching the name and parameters length
}
else {
return 0; // no match
}
// test each parameter type for consistency
for ( int index = 0 ; index < methodParamTypes.length ; index++ ) {
final Class<?> methodParamType = methodParamTypes[index];
final Class<?> parameterType = parameterTypes[index];
if ( methodParamType.isPrimitive() ) {
if ( parameterType == null ) {
return 0; // no match since a primitive cannot be null
}
else if ( PRIMITIVE_TYPE_WRAPPERS.get( methodParamType ).equals( parameterType ) ) {
score += 1; // primitive type's corresponding wrapper matches parameter type
}
else {
return 0; // no match since the primitive must be mapped to its corresponding wrapper class
}
}
else if ( methodParamType.equals( parameterType ) ) {
score += 2; // bonus for exact match
}
else if ( parameterType.isAssignableFrom( methodParamType ) ) {
score += 1; // types are consistent
}
else if ( parameterType == null ) {
// null matches an object type so compatible, but no credit
}
else {
return 0; // no match for this parameter
}
}
return score;
}
}
/** result of evaluating the requested method */
class EvaluationResult {
/** result of the method evaluation */
final private Object VALUE;
/** indicates whether the method is one way (no response to remote caller) */
final private boolean IS_ONE_WAY;
/** exception */
final private Throwable EXCEPTION;
/** Constructor */
public EvaluationResult( final Object value, final boolean isOneWay ) {
this( value, isOneWay, null );
}
/** Constructor */
public EvaluationResult( final Object value, final boolean isOneWay, final Throwable exception ) {
VALUE = value;
IS_ONE_WAY = isOneWay;
EXCEPTION = exception;
}
/** determine whether the call is one way */
public boolean isOneWay() {
return IS_ONE_WAY;
}
/** get the value */
public Object getValue() {
return VALUE;
}
/** get the exception */
public Throwable getException() {
return EXCEPTION;
}
/** wrap the raw exception as runtime exception */
public RuntimeException getRuntimeExceptionWrapper() {
if ( EXCEPTION != null ) {
final RuntimeException wrapper = new RuntimeException( EXCEPTION );
wrapper.setStackTrace( EXCEPTION.getStackTrace() );
return wrapper;
}
else {
return null;
}
}
}
/** indicates that a remote client connection has been dropped */
class RemoteClientDroppedException extends RuntimeException {
/** serialization ID */
private static final long serialVersionUID = 1L;
public RemoteClientDroppedException( final String message ) {
super( message );
}
}
|
package org.xins.server;
import java.io.IOException;
public interface Responder
extends ResponderStates {
/**
* Creates a new session and associates it with this call. After calling
* this method, {@link #getSession()} will return the session returned from
* this call.
*
* <p>Calling this method will trigger the return of the
* <code>_session</code> output parameter from the call.
*
* @return
* the created session, not <code>null</code>.
*/
public Session createSession();
void startResponse(ResultCode resultCode)
throws IllegalStateException, InvalidResponseException, IOException;
void startResponse(boolean success)
throws IllegalStateException, InvalidResponseException, IOException;
void startResponse(boolean success, String returnCode)
throws IllegalStateException, InvalidResponseException, IOException;
void param(String name, String value)
throws IllegalStateException, IllegalArgumentException, InvalidResponseException, IOException;
void startTag(String type)
throws IllegalStateException, IllegalArgumentException, InvalidResponseException, IOException;
void attribute(String name, String value)
throws IllegalStateException, IllegalArgumentException, InvalidResponseException, IOException;
void pcdata(String text)
throws IllegalStateException, IllegalArgumentException, InvalidResponseException, IOException;
void endTag()
throws IllegalStateException, InvalidResponseException, IOException;
void fail(ResultCode resultCode)
throws IllegalArgumentException, IllegalStateException, InvalidResponseException, IOException;
/**
* Ends the response output. This is done by writing a <code>result</code>
* end tag. If necessary a <code>result</code> start tag is written as
* well.
*
* @throws InvalidResponseException
* if the response is considered invalid.
*
* @throws IOException
* if an I/O error occurred.
*/
void endResponse() throws InvalidResponseException, IOException;
}
|
package afc.ant.modular;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.IdentityHashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;
public class ParallelDependencyResolver implements DependencyResolver
{
private LinkedBlockingQueue<Node> shortlist;
private IdentityHashMap<Module, Node> modulesAcquired;
private int remainingModuleCount;
public void init(final Collection<Module> rootModules) throws CyclicDependenciesDetectedException
{
if (rootModules == null) {
throw new NullPointerException("rootModules");
}
for (final Module module : rootModules) {
if (module == null) {
throw new NullPointerException("rootModules contains null element.");
}
}
synchronized (this) {
final LinkedBlockingQueue<Node> newShortlist = new LinkedBlockingQueue<Node>();
/* If buildNodeGraph() throws an exception then the state is not changed
so that this ParallelDependencyResolver instance could be used as if
this init() were not invoked. */
remainingModuleCount = buildNodeGraph(rootModules, newShortlist);
shortlist = newShortlist;
modulesAcquired = new IdentityHashMap<Module, Node>();
}
}
// returns a module that does not have dependencies
public synchronized Module getFreeModule()
{
ensureInitialised();
if (remainingModuleCount == 0) {
return null;
}
try {
final Node node = shortlist.take();
final Module module = node.module;
modulesAcquired.put(module, node);
--remainingModuleCount;
return module;
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
throw new IllegalStateException();
}
}
public synchronized void moduleProcessed(final Module module)
{
ensureInitialised();
if (module == null) {
throw new NullPointerException("module");
}
try {
final Node node = modulesAcquired.remove(module);
if (node == null) {
throw new IllegalArgumentException(MessageFormat.format(
"The module ''{0}'' is not being processed.", module.getPath()));
}
for (int j = 0, n = node.dependencyOf.size(); j < n; ++j) {
final Node depOf = node.dependencyOf.get(j);
if (--depOf.dependencyCount == 0) {
// all modules with no dependencies go to the shortlist
shortlist.put(depOf);
}
}
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
throw new IllegalStateException();
}
}
private void ensureInitialised()
{
if (shortlist == null) {
throw new IllegalStateException("Resolver is not initialised.");
}
}
private static class Node
{
private Node(final Module module)
{
this.module = module;
dependencyCount = module.getDependencies().size();
dependencyOf = new ArrayList<Node>();
}
private final Module module;
/* Knowing just dependency count is enough to detect the moment
when this node has no dependencies remaining. */
private int dependencyCount;
private final ArrayList<Node> dependencyOf;
}
/*
* Builds a DAG which nodes hold modules and arcs that represent inverted module dependencies.
* The list of nodes returned via shortlist contains the starting vertices of the graph.
* The modules that are bound to these vertices do not have dependencies on other modules
* and are used as modules to start unwinding dependencies from.
*
* @returns the total number of modules.
*/
private static int buildNodeGraph(final Collection<Module> rootModules, LinkedBlockingQueue<Node> shortlist)
throws CyclicDependenciesDetectedException
{
/* TODO it is known that there are no loops in the dependency graph.
Use it knowledge to eliminate unnecessary checks OR merge buildNodeGraph() with
ensureNoLoops() so that loops are checked for while the node graph is being built. */
final IdentityHashMap<Module, Node> registry = new IdentityHashMap<Module, Node>();
final LinkedHashSet<Module> path = new LinkedHashSet<Module>();
for (final Module module : rootModules) {
addNodeDeep(module, shortlist, registry, path);
}
// the number
return registry.size();
}
private static Node addNodeDeep(final Module module, final LinkedBlockingQueue<Node> shortlist,
final IdentityHashMap<Module, Node> registry, final LinkedHashSet<Module> path)
throws CyclicDependenciesDetectedException
{
Node node = registry.get(module);
if (node != null) {
return node; // the module is already processed
}
if (path.add(module)) {
node = new Node(module);
final Set<Module> deps = module.getDependencies();
if (deps.isEmpty()) {
shortlist.add(node);
} else {
// inverted dependencies are assigned
for (final Module dep : module.getDependencies()) {
final Node depNode = addNodeDeep(dep, shortlist, registry, path);
assert depNode != null;
depNode.dependencyOf.add(node);
}
}
registry.put(module, node);
path.remove(module);
return node;
}
/* A loop is detected. It does not necessarily end with the starting node,
some leading nodes could be truncated. */
int loopSize = path.size();
final Iterator<Module> it = path.iterator();
while (it.next() != module) {
// skipping all leading nodes that are outside the loop
--loopSize;
}
final ArrayList<Module> loop = new ArrayList<Module>(loopSize);
loop.add(module);
while (it.hasNext()) {
loop.add(it.next());
}
assert loopSize == loop.size();
throw new CyclicDependenciesDetectedException(loop);
}
}
|
package com.sun.facelets.compiler;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import com.sun.facelets.tag.AbstractTagLibrary;
import com.sun.facelets.tag.TagHandler;
import com.sun.facelets.tag.TagLibrary;
import com.sun.facelets.util.ParameterCheck;
import com.sun.facelets.util.Classpath;
/**
* Handles creating a {@link com.sun.facelets.tag.TagLibrary TagLibrary} from a
* {@link java.net.URL URL} source.
*
* @author Jacob Hookom
* @version $Id: TagLibraryConfig.java,v 1.9 2006-05-03 05:18:10 jhook Exp $
*/
public final class TagLibraryConfig {
private final static String SUFFIX = ".taglib.xml";
protected final static Logger log = Logger.getLogger("facelets.compiler");
private static class TagLibraryImpl extends AbstractTagLibrary {
public TagLibraryImpl(String namespace) {
super(namespace);
}
public void putConverter(String name, String id) {
ParameterCheck.notNull("name", name);
ParameterCheck.notNull("id", id);
this.addConverter(name, id);
}
public void putConverter(String name, String id, Class handlerClass) {
ParameterCheck.notNull("name", name);
ParameterCheck.notNull("id", id);
ParameterCheck.notNull("handlerClass", handlerClass);
this.addConverter(name, id, handlerClass);
}
public void putValidator(String name, String id) {
ParameterCheck.notNull("name", name);
ParameterCheck.notNull("id", id);
this.addValidator(name, id);
}
public void putValidator(String name, String id, Class handlerClass) {
ParameterCheck.notNull("name", name);
ParameterCheck.notNull("id", id);
ParameterCheck.notNull("handlerClass", handlerClass);
this.addValidator(name, id, handlerClass);
}
public void putTagHandler(String name, Class type) {
ParameterCheck.notNull("name", name);
ParameterCheck.notNull("type", type);
this.addTagHandler(name, type);
}
public void putComponent(String name, String componentType,
String rendererType) {
ParameterCheck.notNull("name", name);
ParameterCheck.notNull("componentType", componentType);
this.addComponent(name, componentType, rendererType);
}
public void putComponent(String name, String componentType,
String rendererType, Class handlerClass) {
ParameterCheck.notNull("name", name);
ParameterCheck.notNull("componentType", componentType);
ParameterCheck.notNull("handlerClass", handlerClass);
this.addComponent(name, componentType, rendererType, handlerClass);
}
public void putUserTag(String name, URL source) {
ParameterCheck.notNull("name", name);
ParameterCheck.notNull("source", source);
this.addUserTag(name, source);
}
public void putFunction(String name, Method method) {
ParameterCheck.notNull("name", name);
ParameterCheck.notNull("method", method);
this.addFunction(name, method);
}
}
private static class LibraryHandler extends DefaultHandler {
private final String file;
private final URL source;
private TagLibrary library;
private final StringBuffer buffer;
private Locator locator;
private String tagName;
private String componentClassName;
private String componentType;
private String rendererType;
private String functionName;
private Class handlerClass;
private Class functionClass;
private String functionSignature;
public LibraryHandler(URL source) {
this.file = source.getFile();
this.source = source;
this.buffer = new StringBuffer(64);
}
public TagLibrary getLibrary() {
return this.library;
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
try {
if ("facelet-taglib".equals(qName)) {
; // Nothing to do
}
else if ("library-class".equals(qName)) {
this.processLibraryClass();
}
else if ("namespace".equals(qName)) {
this.library = new TagLibraryImpl(this.captureBuffer());
}
else if ("component-type".equals(qName)) {
this.componentType = this.captureBuffer();
}
else if ("renderer-type".equals(qName)) {
this.rendererType = this.captureBuffer();
}
else if ("tag-name".equals(qName)) {
this.tagName = this.captureBuffer();
}
else if ("function-name".equals(qName)) {
this.functionName = this.captureBuffer();
}
else if ("function-class".equals(qName)) {
String className = this.captureBuffer();
this.functionClass = this.createClass(Object.class, className);
}
else
{
// Make sure there we've seen a namespace element
// before trying any of the following elements to avoid
// obscure NPEs
if (this.library == null) {
throw new IllegalStateException("No <namespace> element");
}
TagLibraryImpl impl = (TagLibraryImpl) this.library;
if ("tag".equals(qName)) {
if (this.handlerClass != null) {
impl.putTagHandler(this.tagName, this.handlerClass);
}
}
else if ("handler-class".equals(qName)) {
String cName = this.captureBuffer();
this.handlerClass = this.createClass(
TagHandler.class, cName);
}
else if ("component".equals(qName)) {
if (this.handlerClass != null) {
impl.putComponent(this.tagName,
this.componentType,
this.rendererType,
this.handlerClass);
this.handlerClass = null;
}
else {
impl.putComponent(this.tagName,
this.componentType,
this.rendererType);
}
}
else if ("converter-id".equals(qName)) {
if (this.handlerClass != null) {
impl.putConverter(this.tagName,
this.captureBuffer(),
handlerClass);
this.handlerClass = null;
}
else {
impl.putConverter(this.tagName,
this.captureBuffer());
}
}
else if ("validator-id".equals(qName)) {
if (this.handlerClass != null) {
impl.putValidator(this.tagName,
this.captureBuffer(),
handlerClass);
this.handlerClass = null;
}
else {
impl.putValidator(this.tagName,
this.captureBuffer());
}
}
else if ("source".equals(qName)) {
String path = this.captureBuffer();
URL url = new URL(this.source, path);
impl.putUserTag(this.tagName, url);
}
else if ("function-signature".equals(qName)) {
this.functionSignature = this.captureBuffer();
Method m = this.createMethod(this.functionClass, this.functionSignature);
impl.putFunction(this.functionName, m);
}
}
} catch (Exception e) {
SAXException saxe =
new SAXException("Error Handling [" + this.source + "@"
+ this.locator.getLineNumber() + ","
+ this.locator.getColumnNumber() + "] <" + qName
+ ">");
saxe.initCause(e);
throw saxe;
}
}
private String captureBuffer() throws Exception {
String s = this.buffer.toString().trim();
if (s.length() == 0) {
throw new Exception("Value Cannot be Empty");
}
this.buffer.setLength(0);
return s;
}
private static Class createClass(Class type, String name) throws Exception {
Class factory = ReflectionUtil.forName(name);
if (!type.isAssignableFrom(factory)) {
throw new Exception(name + " must be an instance of "
+ type.getName());
}
return factory;
}
private static Method createMethod(Class type, String s) throws Exception {
Method m = null;
int pos = s.indexOf(' ');
if (pos == -1) {
throw new Exception("Must Provide Return Type: "+s);
} else {
String rt = s.substring(0, pos).trim();
int pos2 = s.indexOf('(', pos+1);
if (pos2 == -1) {
throw new Exception("Must provide a method name, followed by '(': "+s);
} else {
String mn = s.substring(pos+1, pos2).trim();
pos = s.indexOf(')', pos2 + 1);
if (pos == -1) {
throw new Exception("Must close parentheses, ')' missing: "+s);
} else {
String[] ps = s.substring(pos2 + 1, pos).trim().split(",");
Class[] pc;
if (ps.length == 1 && "".equals(ps[0])) {
pc = new Class[0];
} else {
pc = new Class[ps.length];
for (int i = 0; i < pc.length; i ++) {
pc[i] = ReflectionUtil.forName(ps[i].trim());
}
}
try {
return type.getMethod(mn, pc);
} catch (NoSuchMethodException e) {
throw new Exception("No Function Found on type: "+type.getName()+" with signature: "+s);
}
}
}
}
}
private void processLibraryClass() throws Exception {
String name = this.captureBuffer();
Class type = this.createClass(TagLibrary.class, name);
this.library = (TagLibrary) type.newInstance();
}
public InputSource resolveEntity(String publicId, String systemId)
throws SAXException {
if ("-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN"
.equals(publicId)) {
URL url = Thread.currentThread().getContextClassLoader()
.getResource("facelet-taglib_1_0.dtd");
return new InputSource(url.toExternalForm());
}
return null;
}
public void characters(char[] ch, int start, int length)
throws SAXException {
this.buffer.append(ch, start, length);
}
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
this.buffer.setLength(0);
if ("tag".equals(qName)) {
this.componentClassName = null;
this.handlerClass = null;
this.componentType = null;
this.rendererType = null;
this.tagName = null;
} else if ("function".equals(qName)) {
this.functionName = null;
this.functionClass = null;
this.functionSignature = null;
}
}
public void error(SAXParseException e) throws SAXException {
SAXException saxe =
new SAXException("Error Handling [" + this.source + "@"
+ e.getLineNumber() + "," + e.getColumnNumber() + "]");
saxe.initCause(e);
throw saxe;
}
public void setDocumentLocator(Locator locator) {
this.locator = locator;
}
public void fatalError(SAXParseException e) throws SAXException {
throw e;
}
public void warning(SAXParseException e) throws SAXException {
throw e;
}
}
public TagLibraryConfig() {
super();
}
public static TagLibrary create(URL url) throws IOException {
InputStream is = null;
TagLibrary t = null;
try {
is = url.openStream();
LibraryHandler handler = new LibraryHandler(url);
SAXParser parser = createSAXParser(handler);
parser.parse(is, handler);
t = handler.getLibrary();
} catch (SAXException e) {
IOException ioe =
new IOException("Error parsing [" + url + "]: ");
ioe.initCause(e);
throw ioe;
} catch (ParserConfigurationException e) {
IOException ioe =
new IOException("Error parsing [" + url + "]: ");
ioe.initCause(e);
throw ioe;
} finally {
if (is != null)
is.close();
}
return t;
}
public void loadImplicit(Compiler compiler) throws IOException {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
URL[] urls = Classpath.search(cl, "META-INF/", SUFFIX);
for (int i = 0; i < urls.length; i++) {
try {
compiler.addTagLibrary(create(urls[i]));
log.info("Added Library from: " + urls[i]);
} catch (Exception e) {
log.log(Level.SEVERE, "Error Loading Library: " + urls[i], e);
}
}
}
private static final SAXParser createSAXParser(LibraryHandler handler)
throws SAXException, ParserConfigurationException {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(false);
factory.setFeature("http://xml.org/sax/features/validation", true);
factory.setValidating(true);
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setErrorHandler(handler);
reader.setEntityResolver(handler);
return parser;
}
}
|
package org.apache.commons.betwixt;
import java.beans.BeanDescriptor;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;
import org.apache.commons.betwixt.expression.EmptyExpression;
import org.apache.commons.betwixt.expression.IteratorExpression;
import org.apache.commons.betwixt.expression.MethodExpression;
import org.apache.commons.betwixt.expression.MethodUpdater;
import org.apache.commons.betwixt.expression.StringExpression;
import org.apache.commons.betwixt.digester.XMLBeanInfoDigester;
import org.apache.commons.betwixt.digester.XMLIntrospectorHelper;
import org.apache.commons.betwixt.strategy.DefaultNameMapper;
import org.apache.commons.betwixt.strategy.DefaultPluralStemmer;
import org.apache.commons.betwixt.strategy.NameMapper;
import org.apache.commons.betwixt.strategy.PluralStemmer;
/**
* <p><code>XMLIntrospector</code> an introspector of beans to create a
* XMLBeanInfo instance.</p>
*
* <p>By default, <code>XMLBeanInfo</code> caching is switched on.
* This means that the first time that a request is made for a <code>XMLBeanInfo</code>
* for a particular class, the <code>XMLBeanInfo</code> is cached.
* Later requests for the same class will return the cached value.</p>
*
* <p>Note :</p>
* <p>This class makes use of the <code>java.bean.Introspector</code>
* class, which contains a BeanInfoSearchPath. To make sure betwixt can
* do his work correctly, this searchpath is completely ignored during
* processing. The original values will be restored after processing finished
* </p>
*
* @author <a href="mailto:jstrachan@apache.org">James Strachan</a>
* @author <a href="mailto:martin@mvdb.net">Martin van den Bemt</a>
* @version $Id: XMLIntrospector.java,v 1.8 2002/07/02 20:31:45 mvdb Exp $
*/
public class XMLIntrospector {
/** Log used for logging (Doh!) */
protected Log log = LogFactory.getLog( XMLIntrospector.class );
/** should attributes or elements be used for primitive types */
private boolean attributesForPrimitives = false;
/** should we wrap collections in an extra element? */
private boolean wrapCollectionsInElement = true;
/** Is <code>XMLBeanInfo</code> caching enabled? */
boolean cachingEnabled = true;
/** Maps classes to <code>XMLBeanInfo</code>'s */
protected Map cacheXMLBeanInfos = new HashMap();
/** Digester used to parse the XML descriptor files */
private XMLBeanInfoDigester digester;
// pluggable strategies
/** The strategy used to detect matching singular and plural properties */
private PluralStemmer pluralStemmer;
/** The strategy used to convert bean type names into element names */
private NameMapper elementNameMapper;
/**
* The strategy used to convert bean type names into attribute names
* It will default to the normal nameMapper.
*/
private NameMapper attributeNameMapper;
/** Base constructor */
public XMLIntrospector() {
}
/**
* <p> Get the current logging implementation. </p>
*/
public Log getLog() {
return log;
}
/**
* <p> Set the current logging implementation. </p>
*/
public void setLog(Log log) {
this.log = log;
}
/**
* Is <code>XMLBeanInfo</code> caching enabled?
*/
public boolean isCachingEnabled() {
return cachingEnabled;
}
/**
* Set whether <code>XMLBeanInfo</code> caching should be enabled.
*/
public void setCachingEnabled(boolean cachingEnabled) {
this.cachingEnabled = cachingEnabled;
}
/**
* Flush existing cached <code>XMLBeanInfo</code>'s.
*/
public void flushCache() {
cacheXMLBeanInfos.clear();
}
/** Create a standard <code>XMLBeanInfo</code> by introspection
The actual introspection depends only on the <code>BeanInfo</code>
associated with the bean.
*/
public XMLBeanInfo introspect(Object bean) throws IntrospectionException {
if (log.isDebugEnabled()) {
log.debug( "Introspecting..." );
log.debug(bean);
}
return introspect( bean.getClass() );
}
/** Create a standard <code>XMLBeanInfo</code> by introspection.
The actual introspection depends only on the <code>BeanInfo</code>
associated with the bean.
*/
public XMLBeanInfo introspect(Class aClass) throws IntrospectionException {
// we first reset the beaninfo searchpath.
String[] searchPath = Introspector.getBeanInfoSearchPath();
Introspector.setBeanInfoSearchPath(new String[] { });
XMLBeanInfo xmlInfo = null;
if ( cachingEnabled ) {
// if caching is enabled, try in caching first
xmlInfo = (XMLBeanInfo) cacheXMLBeanInfos.get( aClass );
}
if (xmlInfo == null) {
// lets see if we can find an XML descriptor first
if ( log.isDebugEnabled() ) {
log.debug( "Attempting to lookup an XML descriptor for class: " + aClass );
}
xmlInfo = findByXMLDescriptor( aClass );
if ( xmlInfo == null ) {
BeanInfo info = Introspector.getBeanInfo( aClass );
xmlInfo = introspect( info );
}
if (xmlInfo != null) {
cacheXMLBeanInfos.put( aClass, xmlInfo );
}
} else {
log.trace("Used cached XMLBeanInfo.");
}
if (log.isTraceEnabled()) {
log.trace(xmlInfo);
}
// we restore the beaninfo searchpath.
Introspector.setBeanInfoSearchPath(searchPath);
return xmlInfo;
}
/** Create a standard <code>XMLBeanInfo</code> by introspection.
The actual introspection depends only on the <code>BeanInfo</code>
associated with the bean.
*/
public XMLBeanInfo introspect(BeanInfo beanInfo) throws IntrospectionException {
XMLBeanInfo answer = createXMLBeanInfo( beanInfo );
BeanDescriptor beanDescriptor = beanInfo.getBeanDescriptor();
Class beanClass = beanDescriptor.getBeanClass();
ElementDescriptor elementDescriptor = new ElementDescriptor();
elementDescriptor.setLocalName( getElementNameMapper().mapTypeToElementName( beanDescriptor.getName() ) );
elementDescriptor.setPropertyType( beanInfo.getBeanDescriptor().getBeanClass() );
if (log.isTraceEnabled()) {
log.trace(elementDescriptor);
}
// add default string value for primitive types
if ( isPrimitiveType( beanClass ) ) {
elementDescriptor.setTextExpression( StringExpression.getInstance() );
elementDescriptor.setPrimitiveType(true);
}
else if ( isLoopType( beanClass ) ) {
ElementDescriptor loopDescriptor = new ElementDescriptor();
loopDescriptor.setContextExpression(
new IteratorExpression( EmptyExpression.getInstance() )
);
if ( Map.class.isAssignableFrom( beanClass ) ) {
loopDescriptor.setQualifiedName( "entry" );
}
elementDescriptor.setElementDescriptors( new ElementDescriptor[] { loopDescriptor } );
/*
elementDescriptor.setContextExpression(
new IteratorExpression( EmptyExpression.getInstance() )
);
*/
}
else {
List elements = new ArrayList();
List attributes = new ArrayList();
addProperties( beanInfo, elements, attributes );
BeanInfo[] additionals = beanInfo.getAdditionalBeanInfo();
if ( additionals != null ) {
for ( int i = 0, size = additionals.length; i < size; i++ ) {
BeanInfo otherInfo = additionals[i];
addProperties( otherInfo, elements, attributes );
}
}
int size = elements.size();
if ( size > 0 ) {
ElementDescriptor[] descriptors = new ElementDescriptor[size];
elements.toArray( descriptors );
elementDescriptor.setElementDescriptors( descriptors );
}
size = attributes.size();
if ( size > 0 ) {
AttributeDescriptor[] descriptors = new AttributeDescriptor[size];
attributes.toArray( descriptors );
elementDescriptor.setAttributeDescriptors( descriptors );
}
}
answer.setElementDescriptor( elementDescriptor );
// default any addProperty() methods
XMLIntrospectorHelper.defaultAddMethods( this, elementDescriptor, beanClass );
return answer;
}
// Properties
/** Should attributes (or elements) be used for primitive types.
*/
public boolean isAttributesForPrimitives() {
return attributesForPrimitives;
}
/** Set whether attributes (or elements) should be used for primitive types. */
public void setAttributesForPrimitives(boolean attributesForPrimitives) {
this.attributesForPrimitives = attributesForPrimitives;
}
/** @return whether we should we wrap collections in an extra element? */
public boolean isWrapCollectionsInElement() {
return wrapCollectionsInElement;
}
/** Sets whether we should we wrap collections in an extra element? */
public void setWrapCollectionsInElement(boolean wrapCollectionsInElement) {
this.wrapCollectionsInElement = wrapCollectionsInElement;
}
/**
* @return the strategy used to detect matching singular and plural properties
*/
public PluralStemmer getPluralStemmer() {
if ( pluralStemmer == null ) {
pluralStemmer = createPluralStemmer();
}
return pluralStemmer;
}
/**
* Sets the strategy used to detect matching singular and plural properties
*/
public void setPluralStemmer(PluralStemmer pluralStemmer) {
this.pluralStemmer = pluralStemmer;
}
/**
* @return the strategy used to convert bean type names into element names
* @deprecated getNameMapper is split up in {@link #getElementNameMapper()} and {@link #getAttributeNameMapper()}
*/
public NameMapper getNameMapper() {
return getElementNameMapper();
}
/**
* Sets the strategy used to convert bean type names into element names
* @param nameMapper
* @deprecated setNameMapper is split up in {@link #setElementNameMapper(NameMapper)} and {@link #setAttributeNameMapper(NameMapper)}
*/
public void setNameMapper(NameMapper nameMapper) {
setElementNameMapper(nameMapper);
}
/**
* @return the strategy used to convert bean type names into element
* names. If no element mapper is currently defined then a default one is created.
*/
public NameMapper getElementNameMapper() {
if ( elementNameMapper == null ) {
elementNameMapper = createNameMapper();
}
return elementNameMapper;
}
/**
* Sets the strategy used to convert bean type names into element names
* @param nameMapper
*/
public void setElementNameMapper(NameMapper nameMapper) {
this.elementNameMapper = nameMapper;
}
/**
* @return the strategy used to convert bean type names into attribute
* names. If no attributeNamemapper is known, it will default to the ElementNameMapper
*/
public NameMapper getAttributeNameMapper() {
if (attributeNameMapper == null) {
attributeNameMapper = createNameMapper();
}
return attributeNameMapper;
}
/**
* Sets the strategy used to convert bean type names into attribute names
* @param nameMapper
*/
public void setAttributeNameMapper(NameMapper nameMapper) {
this.attributeNameMapper = nameMapper;
}
// Implementation methods
/**
* A Factory method to lazily create a new strategy to detect matching singular and plural properties
*/
protected PluralStemmer createPluralStemmer() {
return new DefaultPluralStemmer();
}
/**
* A Factory method to lazily create a strategy used to convert bean type names into element names
*/
protected NameMapper createNameMapper() {
return new DefaultNameMapper();
}
/**
* Attempt to lookup the XML descriptor for the given class using the
* classname + ".betwixt" using the same ClassLoader used to load the class
* or return null if it could not be loaded
*/
protected synchronized XMLBeanInfo findByXMLDescriptor( Class aClass ) {
// trim the package name
String name = aClass.getName();
int idx = name.lastIndexOf( '.' );
if ( idx >= 0 ) {
name = name.substring( idx + 1 );
}
name += ".betwixt";
URL url = aClass.getResource( name );
if ( url != null ) {
try {
String urlText = url.toString();
if ( log.isDebugEnabled( )) {
log.debug( "Parsing Betwixt XML descriptor: " + urlText );
}
// synchronized method so this digester is only used by
// one thread at once
if ( digester == null ) {
digester = new XMLBeanInfoDigester();
digester.setXMLIntrospector( this );
}
digester.setBeanClass( aClass );
return (XMLBeanInfo) digester.parse( urlText );
}
catch (Exception e) {
log.warn( "Caught exception trying to parse: " + name, e );
}
}
return null;
}
/** Loop through properties and process each one */
protected void addProperties(
BeanInfo beanInfo,
List elements,
List attributes)
throws
IntrospectionException {
PropertyDescriptor[] descriptors = beanInfo.getPropertyDescriptors();
if ( descriptors != null ) {
for ( int i = 0, size = descriptors.length; i < size; i++ ) {
addProperty(beanInfo, descriptors[i], elements, attributes);
}
}
if (log.isTraceEnabled()) {
log.trace(elements);
log.trace(attributes);
}
}
/**
* Process a property.
* Go through and work out whether it's a loop property, a primitive or a standard.
* The class property is ignored.
*/
protected void addProperty(
BeanInfo beanInfo,
PropertyDescriptor propertyDescriptor,
List elements,
List attributes)
throws
IntrospectionException {
Class type = propertyDescriptor.getPropertyType();
NodeDescriptor nodeDescriptor = null;
Method readMethod = propertyDescriptor.getReadMethod();
Method writeMethod = propertyDescriptor.getWriteMethod();
if ( readMethod == null ) {
if (log.isTraceEnabled()) {
log.trace( "No read method" );
}
return;
}
if ( log.isTraceEnabled() ) {
log.trace( "Read method=" + readMethod.getName() );
}
// choose response from property type
// XXX: ignore class property ??
if ( Class.class.equals( type ) && "class".equals( propertyDescriptor.getName() ) ) {
if (log.isTraceEnabled()) {
log.trace( "Ignoring class property" );
}
return;
}
if ( isPrimitiveType( type ) ) {
if (log.isTraceEnabled()) {
log.trace( "Primitive type" );
}
if ( isAttributesForPrimitives() ) {
if (log.isTraceEnabled()) {
log.trace( "Added attribute" );
}
nodeDescriptor = new AttributeDescriptor();
attributes.add( nodeDescriptor );
}
else {
if (log.isTraceEnabled()) {
log.trace( "Added element" );
}
nodeDescriptor = new ElementDescriptor(true);
elements.add( nodeDescriptor );
}
nodeDescriptor.setTextExpression( new MethodExpression( readMethod ) );
if ( writeMethod != null ) {
nodeDescriptor.setUpdater( new MethodUpdater( writeMethod ) );
}
}
else if ( isLoopType( type ) ) {
if (log.isTraceEnabled()) {
log.trace("Loop type");
}
ElementDescriptor loopDescriptor = new ElementDescriptor();
loopDescriptor.setContextExpression(
new IteratorExpression( new MethodExpression( readMethod ) )
);
// XXX: need to support some kind of 'add' or handle arrays, s or indexed properties
//loopDescriptor.setUpdater( new MethodUpdater( writeMethod ) );
if ( Map.class.isAssignableFrom( type ) ) {
loopDescriptor.setQualifiedName( "entry" );
}
ElementDescriptor elementDescriptor = new ElementDescriptor();
elementDescriptor.setElementDescriptors( new ElementDescriptor[] { loopDescriptor } );
elementDescriptor.setWrapCollectionsInElement(isWrapCollectionsInElement());
nodeDescriptor = elementDescriptor;
elements.add( nodeDescriptor );
}
else {
if (log.isTraceEnabled()) {
log.trace( "Standard property" );
}
ElementDescriptor elementDescriptor = new ElementDescriptor();
elementDescriptor.setContextExpression( new MethodExpression( readMethod ) );
if ( writeMethod != null ) {
elementDescriptor.setUpdater( new MethodUpdater( writeMethod ) );
}
nodeDescriptor = elementDescriptor;
elements.add( nodeDescriptor );
}
nodeDescriptor.setLocalName( getNameMapper().mapTypeToElementName( propertyDescriptor.getName() ) );
if (nodeDescriptor instanceof AttributeDescriptor) {
// we want to use the attributemapper only when it is an attribute..
nodeDescriptor.setLocalName( getAttributeNameMapper().mapTypeToElementName( propertyDescriptor.getName() ) );
}
else{
nodeDescriptor.setLocalName( getElementNameMapper().mapTypeToElementName( propertyDescriptor.getName() ) );
}
nodeDescriptor.setPropertyName( propertyDescriptor.getName() );
nodeDescriptor.setPropertyType( type );
// XXX: associate more bean information with the descriptor?
//nodeDescriptor.setDisplayName( propertyDescriptor.getDisplayName() );
//nodeDescriptor.setShortDescription( propertyDescriptor.getShortDescription() );
}
/** Factory method to create XMLBeanInfo instances */
protected XMLBeanInfo createXMLBeanInfo( BeanInfo beanInfo ) {
XMLBeanInfo answer = new XMLBeanInfo( beanInfo.getBeanDescriptor().getBeanClass() );
return answer;
}
/** Returns true if the type is a loop type */
public boolean isLoopType(Class type) {
return XMLIntrospectorHelper.isLoopType(type);
}
/** Returns true for primitive types */
public boolean isPrimitiveType(Class type) {
return XMLIntrospectorHelper.isPrimitiveType(type);
}
}
|
package org.archive.wayback.cdx.indexer;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.Iterator;
import java.util.logging.Logger;
import org.archive.io.arc.ARCReader;
import org.archive.io.arc.ARCReaderFactory;
import org.archive.io.arc.ARCRecord;
import org.archive.io.arc.ARCRecordMetaData;
import org.archive.net.UURI;
import org.archive.net.UURIFactory;
import org.archive.wayback.WaybackConstants;
import org.archive.wayback.cdx.CDXRecord;
import org.archive.wayback.core.SearchResult;
import org.archive.wayback.core.SearchResults;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.URIException;
/**
* Transforms an ARC file into ResourceResults, or a serialized ResourceResults
* file(CDX).
*
* @author Brad Tofel
* @version $Date$, $Revision$
*/
public class ArcIndexer {
/**
* Logger for this class
*/
private static final Logger LOGGER =
Logger.getLogger(ArcIndexer.class.getName());
/**
* HTTP Header for redirection URL
*/
private final static String LOCATION_HTTP_HEADER = "Location";
/**
* Constructor
*/
public ArcIndexer() {
super();
}
/**
* Create a ResourceResults representing the records in ARC file at arcPath.
*
* @param arc
* @return ResourceResults in arcPath.
* @throws IOException
*/
public SearchResults indexArc(File arc) throws IOException {
SearchResults results = new SearchResults();
ARCReader arcReader = ARCReaderFactory.get(arc);
try {
arcReader.setParseHttpHeaders(true);
// doh. this does not generate quite the columns we need:
// arcReader.createCDXIndexFile(arcPath);
Iterator itr = arcReader.iterator();
while (itr.hasNext()) {
ARCRecord rec = (ARCRecord) itr.next();
SearchResult result;
try {
result = arcRecordToSearchResult(rec, arc);
} catch (NullPointerException e) {
e.printStackTrace();
continue;
} catch (ParseException e) {
e.printStackTrace();
continue;
}
if(result != null) {
results.addSearchResult(result);
}
}
} finally {
arcReader.close();
}
return results;
}
/** transform an ARCRecord into a SearchResult
* @param rec
* @param arc
* @return SearchResult for this document
* @throws NullPointerException
* @throws IOException
* @throws ParseException
*/
private SearchResult arcRecordToSearchResult(final ARCRecord rec,
File arc) throws NullPointerException, IOException, ParseException {
rec.close();
ARCRecordMetaData meta = rec.getMetaData();
SearchResult result = new SearchResult();
result.put(WaybackConstants.RESULT_ARC_FILE,arc.getName());
result.put(WaybackConstants.RESULT_OFFSET,""+meta.getOffset());
// initialize with default HTTP code...
result.put(WaybackConstants.RESULT_HTTP_CODE,"-");
result.put(WaybackConstants.RESULT_MD5_DIGEST,meta.getDigest());
result.put(WaybackConstants.RESULT_MIME_TYPE,meta.getMimetype());
result.put(WaybackConstants.RESULT_CAPTURE_DATE,meta.getDate());
String uriStr = meta.getUrl();
if(uriStr.startsWith(ARCRecord.ARC_MAGIC_NUMBER)) {
// skip filedesc record altogether...
return null;
}
if(uriStr.startsWith(WaybackConstants.DNS_URL_PREFIX)) {
// skip URL + HTTP header processing for dns records...
} else {
UURI uri = UURIFactory.getInstance(uriStr);
String uriHost = uri.getHost();
if(uriHost == null) {
LOGGER.info("No host in " + uriStr + " in " +
arc.getAbsolutePath());
} else {
result.put(WaybackConstants.RESULT_ORIG_HOST,uriHost);
String statusCode = (meta.getStatusCode() == null) ? "-" : meta
.getStatusCode();
result.put(WaybackConstants.RESULT_HTTP_CODE,statusCode);
String redirectUrl = "-";
Header[] headers = rec.getHttpHeaders();
if (headers != null) {
for (int i = 0; i < headers.length; i++) {
if (headers[i].getName().equals(LOCATION_HTTP_HEADER)) {
String locationStr = headers[i].getValue();
// TODO: "Location" is supposed to be absolute:
// (section 14.30) but Content-Location can be relative.
// is it correct to resolve a relative Location, as we are?
// it's also possible to have both in the HTTP headers...
// should we prefer one over the other?
// right now, we're ignoring "Content-Location"
try {
UURI uriRedirect = UURIFactory.getInstance(uri,
locationStr);
redirectUrl = uriRedirect.getEscapedURI();
} catch (URIException e) {
LOGGER.info("Bad Location: " + locationStr +
" for " + uriStr + " in " +
arc.getAbsolutePath() + " Skipped");
}
break;
}
}
}
result.put(WaybackConstants.RESULT_REDIRECT_URL,redirectUrl);
String indexUrl = CDXRecord.urlStringToKey(meta.getUrl());
result.put(WaybackConstants.RESULT_URL,indexUrl);
}
}
return result;
}
/**
* Write out ResourceResults into CDX file at cdxPath
*
* @param results
* @param target
* @throws IOException
*/
public void serializeResults(final SearchResults results,
File target) throws IOException {
FileOutputStream os = new FileOutputStream(target);
BufferedOutputStream bos = new BufferedOutputStream(os);
PrintWriter pw = new PrintWriter(bos);
try {
pw.println(CDXRecord.CDX_HEADER_MAGIC);
CDXRecord cdxRecord = new CDXRecord();
Iterator itr = results.iterator();
while (itr.hasNext()) {
SearchResult result = (SearchResult) itr.next();
cdxRecord.fromSearchResult(result);
pw.println(cdxRecord.toValue());
}
} finally {
pw.close();
}
}
/**
* @param args
*/
public static void main(String[] args) {
ArcIndexer indexer = new ArcIndexer();
File arc = new File(args[0]);
File cdx = new File(args[1]);
try {
SearchResults results = indexer.indexArc(arc);
indexer.serializeResults(results, cdx);
} catch (Exception e) {
e.printStackTrace();
}
}
}
|
package org.granite.grails.web;
import grails.util.GrailsUtil;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.commons.GrailsResourceUtils;
import org.codehaus.groovy.grails.web.pages.GroovyPageResourceLoader;
import org.codehaus.groovy.grails.web.servlet.DefaultGrailsApplicationAttributes;
import org.codehaus.groovy.grails.web.servlet.GrailsApplicationAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.web.context.support.ServletContextResourceLoader;
import org.springframework.web.context.support.WebApplicationContextUtils;
public class GrailsWebSWFServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected ResourceLoader resourceLoader = null;
protected ResourceLoader servletContextLoader = null;
protected GrailsApplicationAttributes grailsAttributes;
@Override
public void init(ServletConfig servletConfig) throws ServletException {
this.servletContextLoader = new ServletContextResourceLoader(servletConfig.getServletContext());
ApplicationContext springContext = WebApplicationContextUtils.getRequiredWebApplicationContext(servletConfig.getServletContext());
if (springContext.containsBean(GroovyPageResourceLoader.BEAN_ID))
this.resourceLoader = (ResourceLoader)springContext.getBean(GroovyPageResourceLoader.BEAN_ID);
this.grailsAttributes = new DefaultGrailsApplicationAttributes(servletConfig.getServletContext());
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute(GrailsApplicationAttributes.REQUEST_SCOPE_ID, grailsAttributes);
// Get the name of the Groovy script (intern the name so that we can
// lock on it)
String pageName = "/swf"+request.getServletPath();
Resource requestedFile = getResourceForUri(pageName);
File swfFile = requestedFile.getFile();
if (requestedFile == null || swfFile==null || !swfFile.exists()) {
response.sendError(404, "\"" + pageName + "\" not found.");
return;
}
response.setContentType("application/x-shockwave-flash");
response.setContentLength((int)swfFile.length());
response.setBufferSize((int)swfFile.length());
response.setDateHeader("Expires", 0);
FileInputStream is = null;
FileChannel inChan = null;
try {
is = new FileInputStream(swfFile);
OutputStream os = response.getOutputStream();
inChan = is.getChannel();
long fSize = inChan.size();
MappedByteBuffer mBuf = inChan.map(FileChannel.MapMode.READ_ONLY, 0,fSize);
byte[] buf = new byte[(int)fSize];
mBuf.get(buf);
os.write(buf);
} finally {
if (is != null) {
is.close();
}
if (inChan != null) {
inChan.close();
}
}
}
/**
* Attempts to retrieve a reference to a GSP as a Spring Resource instance for the given URI.
*
* @param uri The URI to check
* @return A Resource instance
*/
public Resource getResourceForUri(String uri) {
Resource r = getResourceWithinContext(uri);
if (r != null && r.exists())
return r;
// try plugin
String pluginUri = GrailsResourceUtils.WEB_INF + uri;
r = getResourceWithinContext(pluginUri);
if (r != null && r.exists())
return r;
uri = getUriWithinGrailsViews(uri);
return getResourceWithinContext(uri);
}
private Resource getResourceWithinContext(String uri) {
Resource r = servletContextLoader.getResource(uri);
if (r.exists())
return r;
return resourceLoader != null ? resourceLoader.getResource(uri) : null;
}
/**
* Returns the path to the view of the relative URI within the Grails views directory
*
* @param relativeUri The relative URI
* @return The path of the URI within the Grails view directory
*/
@SuppressWarnings("deprecation")
protected String getUriWithinGrailsViews(String relativeUri) {
StringBuilder buf = new StringBuilder();
String[] tokens;
if (relativeUri.startsWith("/"))
relativeUri = relativeUri.substring(1);
if (relativeUri.indexOf('/') >= 0)
tokens = relativeUri.split("/");
else
tokens = new String[] { relativeUri };
String pathToViews = GrailsApplicationAttributes.PATH_TO_VIEWS;
int idx = GrailsUtil.getGrailsVersion().indexOf(".");
int majorGrailsVersion = Integer.parseInt(GrailsUtil.getGrailsVersion().substring(0, idx));
if (GrailsUtil.getEnvironment().equals(GrailsApplication.ENV_DEVELOPMENT)
&& majorGrailsVersion >= 2 && pathToViews.startsWith("/WEB-INF"))
pathToViews = pathToViews.substring("/WEB-INF".length());
buf.append(pathToViews);
for (int i = 0; i < tokens.length; i++) {
String token = tokens[i];
buf.append('/').append(token);
}
return buf.toString();
}
@Override
public void destroy() {
}
}
|
package org.havi.ui;
public class HScreenDimension {
public HScreenDimension(float width, float height) {
setSize(width, height);
}
public void setSize(float width, float height) {
if (width < 0.0f)
width = 0.0f;
if (height < 0.0f)
height = 0.0f;
this.width = width;
this.height = height;
}
public float width;
public float height;
}
|
package edu.umd.cs.findbugs;
import edu.umd.cs.findbugs.visitclass.BetterVisitor;
import edu.umd.cs.findbugs.visitclass.DismantleBytecode;
import edu.umd.cs.findbugs.ba.SignatureConverter;
import org.dom4j.Element;
import org.dom4j.Branch;
import org.dom4j.DocumentException;
/**
* A BugAnnotation specifying a particular method in a particular class.
* A MethodAnnotation may (optionally) have a SourceLineAnnotation directly
* embedded inside it to indicate the range of source lines where the
* method is defined.
*
* @see BugAnnotation
* @author David Hovemeyer
*/
public class MethodAnnotation extends PackageMemberAnnotation {
private static final boolean UGLY_METHODS = Boolean.getBoolean("ma.ugly");
private static final String DEFAULT_ROLE = "METHOD_DEFAULT";
private String methodName;
private String methodSig;
private String fullMethod;
private SourceLineAnnotation sourceLines;
/**
* Constructor.
* @param className the name of the class containing the method
* @param methodName the name of the method
* @param methodSig the Java type signature of the method
*/
public MethodAnnotation(String className, String methodName, String methodSig) {
super(className, DEFAULT_ROLE);
this.methodName = methodName;
this.methodSig = methodSig;
fullMethod = null;
sourceLines = null;
}
/**
* Factory method to create a MethodAnnotation from the method the
* given visitor is currently visiting.
* @param visitor the BetterVisitor currently visiting the method
*/
public static MethodAnnotation fromVisitedMethod(BetterVisitor visitor) {
MethodAnnotation result = new MethodAnnotation(visitor.getBetterClassName(), visitor.getMethodName(), visitor.getMethodSig());
// Try to find the source lines for the method
SourceLineAnnotation srcLines = SourceLineAnnotation.fromVisitedMethod(visitor);
result.setSourceLines(srcLines);
return result;
}
/** Get the method name. */
public String getMethodName() { return methodName; }
/** Get the method type signature. */
public String getMethodSignature() { return methodSig; }
/**
* Set a SourceLineAnnotation describing the source lines
* where the method is defined.
*/
public void setSourceLines(SourceLineAnnotation sourceLines) {
this.sourceLines = sourceLines;
}
/**
* Get the SourceLineAnnotation describing the source lines
* where the method is defined.
* @return the SourceLineAnnotation, or null if there is no source information
* for this method
*/
public SourceLineAnnotation getSourceLines() {
return sourceLines;
}
public void accept(BugAnnotationVisitor visitor) {
visitor.visitMethodAnnotation(this);
}
protected String formatPackageMember(String key) {
if (key.equals(""))
return UGLY_METHODS ? getUglyMethod() : getFullMethod();
else if (key.equals("shortMethod"))
return className + "." + methodName + "()";
else
throw new IllegalArgumentException("unknown key " + key);
}
/**
* Get the "full" method name.
* This is a format which looks sort of like a method signature
* that would appear in Java source code.
*/
public String getFullMethod() {
if (fullMethod == null) {
// Convert to "nice" representation
SignatureConverter converter = new SignatureConverter(methodSig);
String pkgName = getPackageName();
StringBuffer args = new StringBuffer();
if (converter.getFirst() != '(')
throw new IllegalStateException("bad method signature " + methodSig);
converter.skip();
while (converter.getFirst() != ')') {
if (args.length() > 0)
args.append(',');
args.append(shorten(pkgName, converter.parseNext()));
}
converter.skip();
// NOTE: we omit the return type.
// It is not needed to disambiguate the method,
// and would just clutter the output.
// Actually, GJ implements covariant return types at the source level,
// so perhaps it really is necessary.
StringBuffer result = new StringBuffer();
result.append(className);
result.append('.');
result.append(methodName);
result.append('(');
result.append(args);
result.append(')');
fullMethod = result.toString();
}
return fullMethod;
}
private String getUglyMethod() {
return className + "." + methodName + " : " + methodSig.replace('/', '.');
}
public int hashCode() {
return className.hashCode() + methodName.hashCode() + methodSig.hashCode();
}
public boolean equals(Object o) {
if (!(o instanceof MethodAnnotation))
return false;
MethodAnnotation other = (MethodAnnotation) o;
return className.equals(other.className)
&& methodName.equals(other.methodName)
&& methodSig.equals(other.methodSig);
}
public int compareTo(BugAnnotation o) {
if (!(o instanceof MethodAnnotation)) // BugAnnotations must be Comparable with any type of BugAnnotation
return this.getClass().getName().compareTo(o.getClass().getName());
MethodAnnotation other = (MethodAnnotation) o;
int cmp;
cmp = className.compareTo(other.className);
if (cmp != 0)
return cmp;
cmp = methodName.compareTo(other.methodName);
if (cmp != 0)
return cmp;
return methodSig.compareTo(other.methodSig);
}
private static final String ELEMENT_NAME = "Method";
private static class MethodAnnotationXMLTranslator implements XMLTranslator {
public String getElementName() {
return ELEMENT_NAME;
}
public XMLConvertible fromElement(Element element) throws DocumentException {
String className = element.attributeValue("classname");
String methodName = element.attributeValue("name");
String methodSig = element.attributeValue("signature");
MethodAnnotation annotation = new MethodAnnotation(className, methodName, methodSig);
String role = element.attributeValue("role");
if (role != null)
annotation.setDescription(role);
// SourceLines may be present as a nested element
java.util.Iterator i = element.elements().iterator();
while (i.hasNext()) {
Element child = (Element) i.next();
String childName = child.getName();
XMLTranslator translator = XMLTranslatorRegistry.instance().getTranslator(childName);
if (translator == null)
throw new DocumentException("Bad element type: " + childName);
annotation.setSourceLines((SourceLineAnnotation) translator.fromElement(child));
}
return annotation;
}
}
static int dummy; // XXX: needed to allow BugCollection to force static init in JDK 1.5
static {
XMLTranslatorRegistry.instance().registerTranslator(new MethodAnnotationXMLTranslator());
}
public Element toElement(Branch parent) {
Element element = parent.addElement(ELEMENT_NAME)
.addAttribute("classname", getClassName())
.addAttribute("name", getMethodName())
.addAttribute("signature", getMethodSignature());
String role = getDescription();
if (!role.equals(DEFAULT_ROLE))
element.addAttribute("role", role);
if (sourceLines != null)
sourceLines.toElement(element);
return element;
}
}
// vim:ts=4
|
package ar.fiuba.tecnicas.giledrose;
public class Inventory {
private static final String NAME_BRIE = "Aged Brie";
private static final String NAME_SULFURAS = "Sulfuras, Hand of Ragnaros";
private static final String NAME_BACKSTAGE =
"Backstage passes to a TAFKAL80ETC concert";
private Item[] items;
public Inventory(Item[] items) {
super();
this.items = items;
}
public Inventory() {
super();
items =
new Item[] {
new Item("+5 Dexterity Vest", 10, 20),
new Item("Aged Brie", 2, 0),
new Item("Elixir of the Mongoose", 5, 7),
new Item("Sulfuras, Hand of Ragnaros", 0, 80),
new Item("Backstage passes to a TAFKAL80ETC concert",
15, 20), new Item("Conjured Mana Cake", 3, 6) };
}
public void updateQuality() {
for (int i = 0; i < items.length; i++) {
Item itemToUpdate = items[i];
if (!isItemAgedBrie(itemToUpdate)
&& !isItemConcertPasses(itemToUpdate)) {
if (isItemQualityGreaterThanZero(itemToUpdate)) {
if (!isItemSulfuras(itemToUpdate)) {
decrementItemQualityByOne(itemToUpdate);
}
}
}
else {
if (isItemQualityLessThanFifty(itemToUpdate)) {
incrementItemQualityByOne(itemToUpdate);
if (isItemConcertPasses(itemToUpdate)) {
if (isItemSellInLessThanEleven(itemToUpdate)) {
if (isItemQualityLessThanFifty(itemToUpdate)) {
incrementItemQualityByOne(itemToUpdate);
}
}
if (isItemSellInLessThanSix(itemToUpdate)) {
if (isItemQualityLessThanFifty(itemToUpdate)) {
incrementItemQualityByOne(itemToUpdate);
}
}
}
}
}
if (!isItemSulfuras(itemToUpdate)) {
decrementItemSellInByOne(itemToUpdate);
}
if (isItemSellInLessThanZero(itemToUpdate)) {
if (!isItemAgedBrie(itemToUpdate)) {
if (!isItemConcertPasses(itemToUpdate)) {
if (isItemQualityGreaterThanZero(itemToUpdate)) {
if (!isItemSulfuras(itemToUpdate)) {
decrementItemQualityByOne(itemToUpdate);
}
}
}
else {
setItemQualityToZero(itemToUpdate);
}
}
else {
if (isItemQualityLessThanFifty(itemToUpdate)) {
incrementItemQualityByOne(itemToUpdate);
}
}
}
}
}
private boolean isItemAgedBrie(Item item) {
return item.getName() == NAME_BRIE;
}
private boolean isItemSulfuras(Item item) {
return item.getName() == NAME_SULFURAS;
}
private boolean isItemConcertPasses(Item item) {
return item.getName() == NAME_BACKSTAGE;
}
private boolean isItemQualityGreaterThanZero(Item item) {
return item.getQuality() > 0;
}
private boolean isItemQualityLessThanFifty(Item item) {
return item.getQuality() < 50;
}
private boolean isItemSellInLessThanZero(Item item) {
return item.getSellIn() < 0;
}
private boolean isItemSellInLessThanSix(Item item) {
return item.getSellIn() < 6;
}
private boolean isItemSellInLessThanEleven(Item item) {
return item.getSellIn() < 11;
}
private void incrementItemQualityByOne(Item item) {
item.setQuality(item.getQuality() + 1);
}
private void decrementItemQualityByOne(Item item) {
item.setQuality(item.getQuality() - 1);
}
private void setItemQualityToZero(Item item) {
item.setQuality(0);
}
private void decrementItemSellInByOne(Item item) {
item.setSellIn(item.getSellIn() - 1);
}
}
|
package bio.terra.cli.service.utils;
import bio.terra.cli.command.exception.SystemException;
import com.google.api.client.http.HttpStatusCodes;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.time.Duration;
import java.util.Map;
import java.util.function.Predicate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Utility methods for making raw HTTP requests (e.g. in place of using a client library). */
public class HttpUtils {
private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);
// default value for the maximum number of times to retry HTTP requests
public static final int DEFAULT_MAXIMUM_RETRIES = 30;
// default value for the time to sleep between retries
public static final Duration DEFAULT_DURATION_SLEEP_FOR_RETRY = Duration.ofSeconds(1);
private HttpUtils() {}
/** This is a POJO class to hold the HTTP status code and the raw JSON response body. */
public static class HttpResponse {
public String responseBody;
public int statusCode;
HttpResponse(String responseBody, int statusCode) {
this.responseBody = responseBody;
this.statusCode = statusCode;
}
}
/**
* Sends an HTTP request using Java's HTTPURLConnection class.
*
* @param urlStr where to direct the request
* @param requestType the type of request, GET/PUT/POST/DELETE
* @param accessToken the bearer token to include in the request, null if not required
* @param params map of request parameters
* @return a POJO that includes the HTTP status code and the raw JSON response body
* @throws IOException
*/
public static HttpResponse sendHttpRequest(
String urlStr, String requestType, String accessToken, Map<String, String> params)
throws IOException {
// build parameter string
boolean hasParams = params != null && params.size() > 0;
String paramsStr = "";
if (hasParams) {
StringBuilder paramsStrBuilder = new StringBuilder();
for (Map.Entry<String, String> mapEntry : params.entrySet()) {
paramsStrBuilder.append(URLEncoder.encode(mapEntry.getKey(), "UTF-8"));
paramsStrBuilder.append("=");
paramsStrBuilder.append(URLEncoder.encode(mapEntry.getValue(), "UTF-8"));
paramsStrBuilder.append("&");
}
paramsStr = paramsStrBuilder.toString();
}
// for GET requests, append the parameters to the URL
if (requestType.equals("GET") && hasParams) {
urlStr += "?" + paramsStr;
}
// open HTTP connection
URL url = new URL(urlStr);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
// set header properties
// con.setRequestProperty("Content-Type", "*/*");
con.setRequestMethod(requestType);
con.setRequestProperty("accept", "*/*");
if (accessToken != null) {
con.setRequestProperty("Authorization", "Bearer " + accessToken);
}
// for other request types, write the parameters to the request body
if (!requestType.equals("GET")) {
con.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(con.getOutputStream());
outputStream.writeBytes(paramsStr);
outputStream.flush();
outputStream.close();
}
// send the request and read the returned status code
int statusCode = con.getResponseCode();
// select the appropriate input stream depending on the status code
InputStream inputStream;
if (HttpStatusCodes.isSuccess(statusCode)) {
inputStream = con.getInputStream();
} else {
inputStream = con.getErrorStream();
}
// read the response body
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(inputStream, Charset.defaultCharset()));
String inputLine;
StringBuffer responseBody = new StringBuffer();
while ((inputLine = bufferedReader.readLine()) != null) {
responseBody.append(inputLine);
}
bufferedReader.close();
// close HTTP connection
con.disconnect();
// return a POJO that includes both the response body and status code
return new HttpResponse(responseBody.toString(), statusCode);
}
/**
* Helper method to call a function with retries. Uses {@link #DEFAULT_MAXIMUM_RETRIES} for
* maximum number of retries and {@link #DEFAULT_DURATION_SLEEP_FOR_RETRY} for the time to sleep
* between retries.
*
* @param makeRequest function to perform the request
* @param isRetryable function to test whether the exception is retryable or not
* @param <T> type of the response object (i.e. return type of the makeRequest function)
* @return the response object
* @throws E if makeRequest throws an exception that is not retryable
* @throws SystemException if the maximum number of retries is exhausted, and the last attempt
* threw a retryable exception
*/
public static <T, E extends Exception> T callWithRetries(
SupplierWithCheckedException<T, E> makeRequest, Predicate<Exception> isRetryable)
throws E, InterruptedException {
return callWithRetries(
makeRequest, isRetryable, DEFAULT_MAXIMUM_RETRIES, DEFAULT_DURATION_SLEEP_FOR_RETRY);
}
/**
* Helper method to call a function with retries.
*
* @param <T> type of the response object (i.e. return type of the makeRequest function)
* @param makeRequest function to perform the request
* @param isRetryable function to test whether the exception is retryable or not
* @param maxCalls maximum number of times to retry
* @param sleepDuration time to sleep between tries
* @return the response object
* @throws E if makeRequest throws an exception that is not retryable
* @throws SystemException if the maximum number of retries is exhausted, and the last attempt
* threw a retryable exception
*/
public static <T, E extends Exception> T callWithRetries(
SupplierWithCheckedException<T, E> makeRequest,
Predicate<Exception> isRetryable,
int maxCalls,
Duration sleepDuration)
throws E, InterruptedException {
// isDone always return true
return pollWithRetries(makeRequest, (result) -> true, isRetryable, maxCalls, sleepDuration);
}
/**
* Helper method to poll with retries. Uses {@link #DEFAULT_MAXIMUM_RETRIES} for maximum number of
* retries and {@link #DEFAULT_DURATION_SLEEP_FOR_RETRY} for the time to sleep between retries.
*
* @param makeRequest function to perform the request
* @param isRetryable function to test whether the exception is retryable or not
* @param <T> type of the response object (i.e. return type of the makeRequest function)
* @return the response object
* @throws E if makeRequest throws an exception that is not retryable
* @throws SystemException if the maximum number of retries is exhausted, and the last attempt
* threw a retryable exception
*/
public static <T, E extends Exception> T pollWithRetries(
SupplierWithCheckedException<T, E> makeRequest,
Predicate<T> isDone,
Predicate<Exception> isRetryable)
throws E, InterruptedException {
return pollWithRetries(
makeRequest,
isDone,
isRetryable,
DEFAULT_MAXIMUM_RETRIES,
DEFAULT_DURATION_SLEEP_FOR_RETRY);
}
/**
* Helper method to poll with retries.
*
* <p>If there is no timeout, the method returns the last result.
*
* <p>If there is a timeout, the behavior depends on the last attempt.
*
* <p>- If the last attempt produced a result that is not done (i.e. isDone returns false), then
* the result is returned.
*
* <p>- If the last attempt threw a retryable exception, then this method re-throws that last
* exception wrapped in a {@link SystemException} with a timeout message.
*
* @param <T> type of the response object (i.e. return type of the makeRequest function)
* @param makeRequest function to perform the request
* @param isDone function to decide whether to keep polling or not, based on the result
* @param isRetryable function to test whether the exception is retryable or not
* @param maxCalls maximum number of times to poll or retry
* @param sleepDuration time to sleep between tries
* @return the response object
* @throws E if makeRequest throws an exception that is not retryable
* @throws SystemException if the maximum number of retries is exhausted, and the last attempt
* threw a retryable exception
*/
public static <T, E extends Exception> T pollWithRetries(
SupplierWithCheckedException<T, E> makeRequest,
Predicate<T> isDone,
Predicate<Exception> isRetryable,
int maxCalls,
Duration sleepDuration)
throws E, InterruptedException {
int numTries = 0;
Exception lastRetryableException = null;
do {
numTries++;
try {
logger.debug("Request attempt #{}", numTries);
T result = makeRequest.makeRequest();
logger.debug("Result: {}", result);
boolean jobCompleted = isDone.test(result);
boolean timedOut = numTries > maxCalls;
if (jobCompleted || timedOut) {
// polling is either done (i.e. job completed) or timed out: return the last result
logger.debug(
"polling with retries completed. jobCompleted = {}, timedOut = {}",
jobCompleted,
timedOut);
return result;
}
} catch (Exception ex) {
if (!isRetryable.test(ex)) {
// the exception is not retryable: re-throw
throw ex;
} else {
// keep track of the last retryable exception so we can re-throw it in case of a timeout
lastRetryableException = ex;
}
logger.info("Caught retryable exception: {}", ex);
}
// sleep before retrying, unless this is the last try
if (numTries < maxCalls) {
Thread.sleep(sleepDuration.toMillis());
}
} while (numTries <= maxCalls);
// request with retries timed out: re-throw the last exception
throw new SystemException(
"Request with retries timed out after " + numTries + " tries.", lastRetryableException);
}
/**
* Helper method to make a request, handle a possible one-time error, and then retry the request.
*
* <p>Example: - Make a request to add a user to a workspace.
*
* <p>- Catch a user not found error. Handle it by making a request to invite the user.
*
* <p>- Retry the request to add a user to a workspace.
*
* @param makeRequest function to perform the request
* @param isOneTimeError function to test whether the exception is the expected one-time error
* @param handleOneTimeError function to handle the one-time error before retrying the request
* @param <T> type of the response object (i.e. return type of the makeRequest function)
* @return the response object
* @throws E1 if makeRequest throws an exception that is not the expected one-time error
* @throws E2 if handleOneTimeError throws an exception
*/
public static <T, E1 extends Exception, E2 extends Exception> T callAndHandleOneTimeError(
SupplierWithCheckedException<T, E1> makeRequest,
Predicate<Exception> isOneTimeError,
SupplierWithCheckedException<Void, E2> handleOneTimeError)
throws E1, E2, InterruptedException {
try {
// make the initial request
return makeRequest.makeRequest();
} catch (Exception ex) {
// if the exception is not the expected one-time error, then quit here
if (!isOneTimeError.test(ex)) {
throw ex;
}
logger.info("Caught possible one-time error: {}", ex);
// handle the one-time error
handleOneTimeError.makeRequest();
// retry the request. include some retries for the one-time error, to allow time for
// information to propagate (this delay seems to happen on inviting a new user -- sometimes it
// takes several seconds for WSM to recognize a newly invited user in SAM. not sure why)
return callWithRetries(makeRequest, isOneTimeError);
}
}
/**
* Function interface for making a retryable Http request. This interface is explicitly defined so
* that it can throw an exception (i.e. Supplier does not have this method annotation).
*
* @param <T> type of the Http response (i.e. return type of the makeRequest method)
*/
@FunctionalInterface
public interface SupplierWithCheckedException<T, E extends Exception> {
T makeRequest() throws E;
}
}
|
package com.Acrobot.ChestShop.Economy;
import com.Acrobot.Breeze.Utils.NumberUtil;
import com.Acrobot.ChestShop.Configuration.Properties;
import com.Acrobot.ChestShop.Signs.ChestShopSign;
import com.Acrobot.ChestShop.Utils.uName;
import org.bukkit.inventory.Inventory;
import static com.Acrobot.Breeze.Utils.NumberUtil.roundUp;
/**
* @author Acrobot
* Economy management
*/
public class Economy {
private static EconomyManager manager = new EconomyManager();
public static boolean transactionCanFail() {
return manager.transactionCanFail();
}
public static boolean isOwnerEconomicallyActive(Inventory inventory) {
return !ChestShopSign.isAdminShop(inventory) || !getServerAccountName().isEmpty();
}
public static boolean hasAccount(String player) {
return !player.isEmpty() && manager.hasAccount(uName.getName(player));
}
public static String getServerAccountName() {
return Properties.SERVER_ECONOMY_ACCOUNT;
}
public static boolean isServerAccount(String acc) {
return ChestShopSign.isAdminShop(acc);
}
public static boolean isBank(String name) {
return name.startsWith(uName.BANK_PREFIX);
}
public static boolean hasBankSupport() {
return manager.hasBankSupport();
}
public static boolean bankExists(String name) {
if (hasBankSupport()) {
return manager.bankExists(name);
} else {
return false;
}
}
public static boolean add(String name, double amount) {
if (isServerAccount(name)) {
if (!getServerAccountName().isEmpty()) {
name = getServerAccountName();
} else {
return true;
}
}
float taxAmount = isServerAccount(name) ? Properties.SERVER_TAX_AMOUNT : isBank(name) ? Properties.BANK_TAX_AMOUNT : Properties.TAX_AMOUNT;
double tax = getTax(taxAmount, amount);
if (tax != 0) {
if (!getServerAccountName().isEmpty()) {
manager.add(getServerAccountName(), tax);
}
amount -= tax;
}
name = uName.getName(name);
amount = roundUp(amount);
if (isBank(name)) {
if (hasBankSupport()) {
return manager.bankAdd(uName.stripBankPrefix(name), amount);
} else {
return false;
}
} else {
return manager.add(name, amount);
}
}
public static double getTax(float tax, double price) {
return NumberUtil.roundDown((tax / 100F) * price);
}
public static boolean subtract(String name, double amount) {
if (isServerAccount(name)) {
if (!getServerAccountName().isEmpty()) {
name = getServerAccountName();
} else {
return true;
}
}
name = uName.getName(name);
amount = roundUp(amount);
if (isBank(name)) {
if (hasBankSupport()) {
return manager.bankSubtract(uName.stripBankPrefix(name), amount);
} else {
return false;
}
} else {
return manager.subtract(name, amount);
}
}
public static boolean canHold(String name, double amount) {
if (!transactionCanFail()) {
return true;
}
if (isServerAccount(name)) {
if (!getServerAccountName().isEmpty()) {
name = getServerAccountName();
} else {
return true;
}
}
name = uName.getName(name);
amount = roundUp(amount);
if (isBank(name)) {
if (hasBankSupport()) {
if (!manager.bankAdd(name, amount)) {
return false;
} else {
manager.bankSubtract(name, amount);
}
} else {
return false;
}
} else {
if (!manager.add(name, amount)) {
return false;
} else {
manager.subtract(name, amount);
}
}
return true;
}
public static boolean hasEnough(String name, double amount) {
if (amount <= 0) {
return true;
}
if (isServerAccount(name)) {
if (!getServerAccountName().isEmpty()) {
name = getServerAccountName();
} else {
return true;
}
}
name = uName.getName(name);
amount = roundUp(amount);
if (isBank(name)) {
if (hasBankSupport()) {
return manager.bankHasEnough(uName.stripBankPrefix(name), amount);
} else {
return false;
}
} else {
return manager.hasEnough(name, amount);
}
}
public static double getBalance(String name) {
if (isServerAccount(name)) {
if (!getServerAccountName().isEmpty()) {
name = getServerAccountName();
} else {
return Double.MAX_VALUE;
}
}
name = uName.getName(name);
if (isBank(name)) {
if (hasBankSupport()) {
return manager.bankBalance(uName.stripBankPrefix(name));
} else {
return 0;
}
} else {
return manager.balance(name);
}
}
public static String formatBalance(double amount) {
return manager.format(roundUp(amount));
}
public static boolean isBankOwner(String player, String bank) {
if (hasBankSupport()) {
return manager.isBankOwner(player, bank);
} else {
return false;
}
}
public static boolean isBankMember(String player, String bank) {
if (hasBankSupport()) {
return manager.isBankMember(player, bank);
} else {
return false;
}
}
public static void setPlugin(EconomyManager plugin) {
manager = plugin;
}
public static EconomyManager getManager() {
return manager;
}
public static boolean isLoaded() {
return manager.getClass() != EconomyManager.class;
}
}
|
package com.almasb.fxgl.physics;
import com.almasb.ents.Entity;
import com.almasb.fxgl.entity.component.TypeComponent;
import com.almasb.gameutils.pool.Poolable;
final class CollisionPair extends Pair<Entity> implements Poolable {
private CollisionHandler handler;
CollisionPair() {
super(null, null);
}
void init(Entity a, Entity b, CollisionHandler handler) {
this.handler = handler;
// we check the order here so that we won't have to do that every time
// when triggering collision between A and B
// this ensures that client gets back entities in the same order
// he registered the handler with
if (a.getComponentUnsafe(TypeComponent.class).getValue().equals(handler.getA())) {
setA(a);
setB(b);
} else {
setA(b);
setB(a);
}
}
/**
* @return collision handler for this pair
*/
CollisionHandler getHandler() {
return handler;
}
void collisionBegin() {
handler.onCollisionBegin(getA(), getB());
}
void collision() {
handler.onCollision(getA(), getB());
}
void collisionEnd() {
handler.onCollisionEnd(getA(), getB());
}
@Override
public void reset() {
handler = null;
setA(null);
setB(null);
}
}
|
package com.codelot.controller;
import com.codelot.Beans.Building;
import com.codelot.Beans.CodelotUser;
import com.codelot.Beans.Floor;
import com.codelot.services.CodelotUserService;
import com.codelot.services.CompilerService;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.googlecode.objectify.ObjectifyService;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
@Controller
public class HomeController {
@RequestMapping(value = "/")
public ModelAndView home(){
ModelAndView model = new ModelAndView("WEB-INF/pages/home");
return model;
}
@RequestMapping("/updateProfile")
public ModelAndView updateProfile(@RequestParam("fullname") String fullname,
@RequestParam("age") int age,
@RequestParam("username") String username,
@RequestParam("avatar") String avatar) {
CodelotUser profile = CodelotUserService.getCurrentUserProfile();
if(profile == null){
//create new user and redirect to language select
CodelotUserService.createUser(fullname, age, username, avatar);
}
else{
//update the existing profile
CodelotUserService.updateUser(fullname, age, username, avatar);
}
return languageSelection();
}
@RequestMapping(value = "/signin")
public ModelAndView signin() {
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
//if there is no logged in user, redirect to login page.
if (user == null){
ModelAndView model = new ModelAndView("redirect:" + userService.createLoginURL("/signin"));
return model;
}
//if account does not have a profile, redirect to profile creation page.
if (CodelotUserService.getCurrentUserProfile() == null){
ModelAndView model = new ModelAndView("WEB-INF/pages/profilePage");
return model;
}
//redirect to map select otherwise
else{
return languageSelection();
}
}
@RequestMapping("/signout")
public ModelAndView signout () {
UserService userService = UserServiceFactory.getUserService();
ModelAndView model = new ModelAndView("redirect:" + userService.createLogoutURL("/"));
return model;
}
@RequestMapping("/languageSelection")
public ModelAndView languageSelection() {
CodelotUser profile = CodelotUserService.getCurrentUserProfile();
//direct to map select page
ModelAndView model = new ModelAndView("WEB-INF/pages/mapSelect");
if(profile != null){
model.addObject("fullName", profile.getFullname());
model.addObject("username", profile.getUsername());
model.addObject("avatar", profile.avatarImage);
model.addObject("email", profile.getUser_email());
model.addObject("age", profile.getAge());
}
return model;
}
@RequestMapping("/map")
public ModelAndView map() {
ModelAndView model = new ModelAndView("WEB-INF/pages/map");
CodelotUser c_user = CodelotUserService.getCurrentUserProfile();
if(c_user != null){
ArrayList<Building> buildings = c_user.getJavaCodelot().getBuildings();
int progress = (int)((((double) c_user.getJavaCodelot().getNumCompleted())/buildings.size()) * 100);
model.addObject("fullName", c_user.getFullname());
model.addObject("username", c_user.getUsername());
model.addObject("avatar", c_user.avatarImage);
model.addObject("email", c_user.getUser_email());
model.addObject("age", c_user.getAge());
model.addObject("progress", progress);
}
return model;
}
@RequestMapping("/profilePage")
public ModelAndView profilePage() {
//Load values for user
CodelotUser profile = CodelotUserService.getCurrentUserProfile();
ModelAndView model = new ModelAndView("WEB-INF/pages/profilePage");
//populate fields if not null
if(profile != null){
model.addObject("fullName", profile.getFullname());
model.addObject("username", profile.getUsername());
model.addObject("avatar", profile.avatarImage);
model.addObject("email", profile.getUser_email());
model.addObject("age", profile.getAge());
}
return model;
}
@RequestMapping("/TaskPage")
public String taskPage(){
return "WEB-INF/pages/TaskPage";
}
@RequestMapping(value = "/execute", method = RequestMethod.POST, produces="application/json")
public @ResponseBody String execute(@RequestBody String source) throws IOException {
//parse parameter to get source
JSONObject obj = new JSONObject(source);
//source code for attempt
String sourceText = obj.getString("source");
//current task floor index
int currentFloor = Integer.parseInt(obj.getString("currentFloor"));
//get floors for current building
CodelotUser profile = CodelotUserService.getCurrentUserProfile();
Building currentBuilding = profile.getJavaCodelot().getBuildings().get(0);
List<Floor> floors = currentBuilding.getFloors();
//get the expected outputs for the current floor
ArrayList<String> expectedOutputs = floors.get(currentFloor).getExpectedOutputs();
//save attempt
floors.get(currentFloor).addAttempt(sourceText);
//compile the code and return a response object
CompilerService service = new CompilerService();
JSONObject response = CompilerService.createResponse(service.execute(sourceText), expectedOutputs);
//if successful, add to task set for the building
if(response.get("outcome").equals("true")){
currentBuilding.getCompletedTaskSet().add(currentFloor);
//unlock next floor if current floor is not last floor.
if(currentFloor < floors.size()-1){
floors.get(currentFloor + 1).setLocked(false);
}
}
//add progress to response
int progress = (int)((((double) currentBuilding.getCompletedTaskSet().size())/floors.size()) * 100);
response.put("progress", progress);
//save changes
ObjectifyService.ofy().save().entity(profile).now();
return response.toString();
}
@RequestMapping("/getJavaTasksPage")
public ModelAndView javaTasks() {
//Load values for user
CodelotUser c_user = CodelotUserService.getCurrentUserProfile();
Building currbldg = c_user.getJavaCodelot().getBuildings().get(0);
List<Floor> floors = currbldg.getFloors();
String warning = "";
Floor currentFloor = floors.get(currbldg.getCurrentFloor());
//get the latest 5 attempts for the user
List<String> attempts = new ArrayList<>();
for (int i = 0; i < currentFloor.getAttempts().size(); i++){
if(attempts.size() < 5 && !currentFloor.getAttempts().get(i).isEmpty()){
attempts.add(currentFloor.getAttempts().get(i));
}
}
//progress = number of completed tasks / total tasks * 100
int prog = (int)((((double) currbldg.getCompletedTaskSet().size())/floors.size()) * 100);
ModelAndView model = new ModelAndView("WEB-INF/pages/TaskPage");
model.addObject("floors", floors);
model.addObject("taskDesc", currentFloor.getTaskDescription());
model.addObject("warning", warning);
model.addObject("hints", currentFloor.getHints());
model.addObject("attempts", attempts);
model.addObject("lesson", currentFloor.getLesson());
model.addObject("progress", prog);
model.addObject("baseCode", currentFloor.getBaseCode());
model.addObject("currentFloor", currbldg.getCurrentFloor());
return model;
}
@RequestMapping("/getJavaTask")
public ModelAndView javaTasks(@RequestParam("floorNum") int floorNum) {
//Load values for user
CodelotUser c_user = CodelotUserService.getCurrentUserProfile();
Building currbldg = c_user.getJavaCodelot().getBuildings().get(0);
List<Floor> floors = currbldg.getFloors();
String warning = "";
int currentFloorNumber = currbldg.getCurrentFloor();
// if coming from map page, load current floor/task of user
if (floorNum == -1){ // means it is redirected from map page
floorNum = currentFloorNumber;
}
//if the floor is locked, create a warning and navigate to current task
else if (floors.get(floorNum).isLocked()) {
warning = "NOTE: Floor " + (floorNum + 1) + " is locked. Please pass through all lower floors to access this one.";
floorNum = currentFloorNumber;
}
Floor currentFloor = floors.get(floorNum);
//get the latest 5 attempts for the user
List<String> attempts = new ArrayList<>();
for (int i = 0; i < currentFloor.getAttempts().size(); i++){
if(attempts.size() < 5 && !currentFloor.getAttempts().get(i).isEmpty()){
attempts.add(currentFloor.getAttempts().get(i));
}
}
//progress = number of completed tasks / total tasks * 100
int prog = (int)((((double) currbldg.getCompletedTaskSet().size())/floors.size()) * 100);
currbldg.setCurrentFloor(floorNum); // update current floor
ObjectifyService.ofy().save().entity(c_user).now(); // save user
ModelAndView model = new ModelAndView("WEB-INF/pages/TaskPage");
model.addObject("floors", floors);
model.addObject("taskDesc", currentFloor.getTaskDescription());
model.addObject("warning", warning);
model.addObject("hints", currentFloor.getHints());
model.addObject("attempts", attempts);
model.addObject("lesson", currentFloor.getLesson());
model.addObject("progress", prog);
model.addObject("baseCode", floors.get(floorNum).getBaseCode());
model.addObject("currentFloor", floorNum);
return model;
}
}
|
package com.conveyal.taui.analysis.broker;
import com.conveyal.r5.analyst.Grid;
import com.conveyal.r5.analyst.WorkerCategory;
import com.conveyal.r5.analyst.cluster.RegionalTask;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
public class Job {
private static final Logger LOG = LoggerFactory.getLogger(Job.class);
// TODO Reimplement re-delivery - jobs can get stuck with a few undelivered tasks if something happens to a worker.
public static final int REDELIVERY_WAIT_SEC = 2 * 60;
public static final int MAX_DELIVERY_PASSES = 5;
// In order to provide realistic estimates of job processing time, we don't want to deliver the tasks to
// workers in row-by-row geographic order, because spatial patterns exist in the world that make some areas
// much faster than others. Ideally rather than storing the entire sequence (which is O(n) in the number of
// tasks) you'd want to store a permutation seed that would allow instant lookup of the task in position N.
// Essentially what we want to do is random selection (sampling) without replacement.
// As far as I know there's no way to do this without storing the full sequence, or taking longer and longer
// to find random tasks as the set of completed tasks gets larger.
// On the other hand, working on tasks from the same geographic area might be more efficient because
// they probably use all the same transit lines and roads, which will already be in cache.
// So let's just keep track of where we're at in the sequence.
private int nextTaskToDeliver;
/* A unique identifier for this job, we use random UUIDs. */
public final String jobId;
// This can be derived from other fields but is provided as a convenience.
public final int nTasksTotal;
// Each task will be checked off when it a result is returned by the worker.
// Once the worker has returned a result, the task will never be redelivered.
private final BitSet completedTasks;
// The number of remaining tasks can be derived from the deliveredTasks BitSet,
// but as an optimization we keep a separate counter to avoid constantly scanning over that whole bitset.
protected int nTasksCompleted;
// The total number of task deliveries that have occurred. A task may be counted more than once if it is redelivered.
protected int nTasksDelivered;
// Every task in this job will be based on this template task, but have its origin coordinates changed.
private final RegionalTask templateTask;
// This will serve as as a source of coordinates for each numbered task in the job - one per pointSet point.
// We will eventually want to expand this to work with any PointSet of origins, not just a grid.
// private final WebMercatorGridPointSet originGrid;
/**
* The only thing that changes from one task to the next is the origin coordinates.
* @param taskNumber the task number within the job, equal to the point number within the origin point set.
*/
private RegionalTask makeOneTask (int taskNumber) {
RegionalTask task = templateTask.clone();
// We want to support any Pointset but for now we only have grids tied to the task itself.
// In the future we'll set origin coords from a PointSet object.
task.x = taskNumber % templateTask.width;
task.y = taskNumber / templateTask.width;
task.taskId = taskNumber;
task.fromLat = Grid.pixelToCenterLat(task.north + task.y, task.zoom);
task.fromLon = Grid.pixelToCenterLon(task.west + task.x, task.zoom);
return task;
}
/**
* The graph and r5 commit on which tasks are to be run.
* All tasks contained in a job must run on the same graph and r5 commit.
* TODO this field is kind of redundant - it's implied by the template request.
*/
public final WorkerCategory workerCategory;
// The last time a non-empty set of tasks was delivered to a worker, in milliseconds since the epoch.
// Enables a quiet period after all tasks have been delivered, before we attempt any re-delivery.
long lastDeliveryTime = 0;
// How many times we have started over delivering tasks, working through those that were not marked complete.
public int deliveryPass = 0;
public Job (RegionalTask templateTask) {
this.jobId = templateTask.jobId;
this.templateTask = templateTask;
this.nTasksTotal = templateTask.width * templateTask.height;
this.completedTasks = new BitSet(nTasksTotal);
this.workerCategory = new WorkerCategory(templateTask.graphId, templateTask.workerVersion);
this.nTasksCompleted = 0;
this.nextTaskToDeliver = 0;
}
public boolean markTaskCompleted(int taskId) {
// Don't allow negative or huge task numbers to avoid exceptions or expanding the bitset to a huge size.
if (taskId < 0 || taskId > nTasksTotal) {
return false;
}
if (completedTasks.get(taskId)) {
return false;
} else {
completedTasks.set(taskId);
nTasksCompleted += 1;
return true;
}
}
public boolean isComplete() {
return nTasksCompleted == nTasksTotal;
}
/**
* @param maxTasks the maximum number of tasks to return.
* @return some tasks that are not yet marked as completed and have not yet been delivered in this delivery pass.
*/
public List<RegionalTask> generateSomeTasksToDeliver (int maxTasks) {
List<RegionalTask> tasks = new ArrayList<>(maxTasks);
// TODO use special bitset iteration syntax.
while (nextTaskToDeliver < nTasksTotal && tasks.size() < maxTasks) {
if (!completedTasks.get(nextTaskToDeliver)) {
tasks.add(makeOneTask(nextTaskToDeliver));
}
nextTaskToDeliver += 1;
}
if (!tasks.isEmpty()) {
this.lastDeliveryTime = System.currentTimeMillis();
}
nTasksDelivered += tasks.size();
return tasks;
}
public boolean hasTasksToDeliver() {
if (this.isComplete()) {
return false;
}
if (nextTaskToDeliver < nTasksTotal) {
return true;
}
// Check whether we should start redelivering tasks - this will be triggered by workers polling.
// The method that generates more tasks to deliver knows to skip already completed tasks.
if (System.currentTimeMillis() >= lastDeliveryTime + (REDELIVERY_WAIT_SEC * 1000)) {
if (deliveryPass >= MAX_DELIVERY_PASSES) {
LOG.error("Job {} has been delivered {} times and it's still not finished. Not redelivering.", jobId, deliveryPass);
return false;
}
nextTaskToDeliver = 0;
deliveryPass += 1;
LOG.warn("Delivered all tasks for job {}, but {} seconds later {} results have not been received. Starting redelivery pass {}.",
jobId, REDELIVERY_WAIT_SEC, nTasksTotal - nTasksCompleted, deliveryPass);
return true;
}
return false;
}
/**
* Just as a failsafe, when our counter indicates that the job is complete, actually check how many bits are set.
*/
public void verifyComplete() {
if (this.isComplete() && completedTasks.cardinality() != nTasksTotal) {
LOG.error("Something is amiss in completed task tracking.");
}
}
@Override
public String toString() {
return "Job{" +
"jobId='" + jobId + '\'' +
", nTasksTotal=" + nTasksTotal +
", nTasksCompleted=" + nTasksCompleted +
", deliveryPass=" + deliveryPass +
'}';
}
}
|
package com.gameminers.farrago.pane;
import gminers.glasspane.GlassPane;
import gminers.glasspane.component.PaneImage;
import gminers.kitchensink.Rendering;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.GuiIngameForge;
import org.lwjgl.opengl.GL11;
import com.gameminers.farrago.FarragoMod;
import com.gameminers.farrago.enums.RifleMode;
public class PaneRifle extends GlassPane {
private static final ResourceLocation[] crosshairs = new ResourceLocation[26];
static {
for (int i = 0; i < crosshairs.length; i++) {
crosshairs[i] = new ResourceLocation("farrago", "textures/crosshairs/rifle_crosshair_"+i+".png");
}
}
@Override
protected void doRender(int mouseX, int mouseY, float partialTicks) {
Minecraft mc = Minecraft.getMinecraft();
if (mc.thePlayer != null) {
if (mc.thePlayer.getHeldItem() != null) {
ItemStack held = mc.thePlayer.getHeldItem();
if (held.getItem() == FarragoMod.RIFLE) {
GuiIngameForge.renderCrosshairs = false;
int idx = 0;
boolean overloadImminent = false;
boolean ready = false;
RifleMode mode = FarragoMod.RIFLE.getMode(held);
if (mc.thePlayer.isUsingItem()) {
float useTime = mc.thePlayer.getItemInUseDuration()+partialTicks;
idx = (int)(((float)useTime)/((float)held.getItem().getMaxItemUseDuration(held))*25f)+1;
overloadImminent = (useTime >= ((FarragoMod.RIFLE.getChargeTicks(mode) + 15)/mode.getChargeSpeed()));
ready = (useTime >= FarragoMod.RIFLE.getTicksToFire(held));
}
if (!(overloadImminent || ready)) {
GL11.glEnable(GL11.GL_BLEND);
OpenGlHelper.glBlendFunc(GL11.GL_ONE_MINUS_DST_COLOR, GL11.GL_ONE_MINUS_SRC_COLOR, 1, 0);
}
int color = overloadImminent ? 0xFFFF0000 : ready ? 0xFF00FF00 : -1;
PaneImage.render(crosshairs[Math.min(25, idx)], (getWidth()/2)-8, (getHeight()/2)-8, 0, 0, 16, 16, 256, 256, color, 1.0f, true);
GL11.glPushMatrix();
GL11.glScalef(0.5f, 0.5f, 1.0f);
if (overloadImminent) {
Rendering.drawCenteredString(mc.fontRenderer, "\u00A7lOVERLOAD IMMINENT", getWidth()-2, getHeight()-28, color);
} else if (ready) {
Rendering.drawCenteredString(mc.fontRenderer, "\u00A7lREADY", getWidth()-2, getHeight()-28, color);
}
Rendering.drawCenteredString(mc.fontRenderer, mode.getDisplayName(), getWidth()-2, getHeight()+20, color);
GL11.glPopMatrix();
if (!(overloadImminent || ready)) {
OpenGlHelper.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, 1, 0);
GL11.glDisable(GL11.GL_BLEND);
}
return;
}
}
}
GuiIngameForge.renderCrosshairs = true;
}
}
|
package com.google.sps.data;
import java.util.List;
import java.util.LinkedList;
import java.util.Arrays;
import java.io.Serializable;
import java.net.URL;
import java.util.logging.Logger;
import com.google.maps.GeoApiContext;
import com.google.maps.PlacesApi;
import com.google.maps.NearbySearchRequest;
import com.google.maps.model.LatLng;
import com.google.maps.model.LocationType;
import com.google.maps.model.Photo;
import com.google.maps.model.PlaceType;
import com.google.maps.model.RankBy;
import com.google.maps.model.Geometry;
import com.google.maps.model.PlacesSearchResponse;
import com.google.maps.model.PlacesSearchResult;
import java.util.logging.Logger;
import java.util.Iterator;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.maps.TextSearchRequest;
import com.google.api.services.customsearch.model.Search;
import com.google.api.services.customsearch.model.Result;
import com.google.api.services.customsearch.Customsearch;
import com.google.api.services.customsearch.CustomsearchRequestInitializer;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import java.security.GeneralSecurityException;
import java.io.IOException;
import java.util.Map;
import java.lang.Integer;
import com.google.maps.errors.ApiException;
import com.google.maps.model.PlacesSearchResult;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.EntityNotFoundException;
/** BusinessesService object representing all businesses
* components of the webapp.
**/
public class BusinessesService {
private final String KEY = "REDACTED";
private final static Logger LOGGER =
Logger.getLogger(BusinessesService.class.getName());
private final int ALLOWED_SEARCH_REQUESTS = 3;
private final int MINFOLLOWERS = 50000;
private final String START_SUBSTRING = "| ";
private final String END_SUBSTRING = "followers";
private Listing currentBusiness;
private Iterator<Listing> businesses;
private LatLng latLng;
private List<Listing> allBusinesses;
/** Create a new Businesses instance
* @param allBusinesses businesses from SmallCityService
**/
public BusinessesService(List<Listing> allBusinesses) {
this.allBusinesses = allBusinesses;
}
public List<Listing> removeBigBusinessesFromResults(){
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Iterator<Listing> businesses = allBusinesses.iterator();
String businessName;
while (businesses.hasNext()) {
Listing currentBusiness = businesses.next();
try {
businessName =
(String) datastore.get(KeyFactory.createKey(
"BigBusinesses",
currentBusiness.getName()))
.getProperty("Business");
if(businessName.equals(currentBusiness.getName())){
businesses.remove();
}
} catch(EntityNotFoundException e){
LOGGER.warning(e.getMessage());
}
}
return allBusinesses;
}
public List<Listing> getBusinessesFromPlacesApi(MapLocation mapLocation) {
latLng =
new LatLng(mapLocation.lat, mapLocation.lng);
final GeoApiContext context = new GeoApiContext.Builder()
.apiKey(KEY)
.build();
NearbySearchRequest request = PlacesApi.nearbySearchQuery(context, latLng);
try {
PlacesSearchResponse response = request.type(PlaceType.STORE)
.rankby(RankBy.DISTANCE)
.await();
for (int i=0; i<ALLOWED_SEARCH_REQUESTS; i++) {
for(PlacesSearchResult place : response.results) {
addListingToBusinesses(place);
}
//Maximum of 2 next token requests allowed
if (i < 2) {
Thread.sleep(2000); // Required delay before next API request
response = PlacesApi
.nearbySearchNextPage(context, response.nextPageToken).await();
}
}
} catch(Exception e) {
LOGGER.warning(e.getMessage());
}
return allBusinesses;
}
private void addListingToBusinesses(PlacesSearchResult place) {
String name = place.name;
String formattedAddress = place.vicinity;
Geometry geometry = place.geometry;
MapLocation placeLocation =
new MapLocation(geometry.location.lat, geometry.location.lng);
double rating = place.rating;
Photo photos[] = place.photos;
String types[] = place.types;
allBusinesses.add(new Listing(name, formattedAddress,
placeLocation, rating, photos, types));
}
public void checkNumberOfLocationsOfBusiness() {
GeoApiContext context = new GeoApiContext.Builder()
.apiKey(KEY)
.build();
businesses = allBusinesses.iterator();
while (businesses.hasNext()) {
currentBusiness = businesses.next();
TextSearchRequest request = new TextSearchRequest(context)
.query(currentBusiness.getName())
.location(latLng)
.radius(50000);
try {
PlacesSearchResult[] similarBusinessesInTheArea = request
.await()
.results;
if (similarBusinessesInTheArea.length > 1){
checkBusinessThroughLinkedin(currentBusiness.getName(), similarBusinessesInTheArea);
}
} catch(GeneralSecurityException | IOException | InterruptedException | ApiException e ) {
LOGGER.warning(e.getMessage());
}
}
}
private void checkBusinessThroughLinkedin(String currentBusinessName,
PlacesSearchResult[] similarBusinessesInTheArea)
throws GeneralSecurityException, IOException {
String cx = "REDACTED";
Customsearch cs = new Customsearch.Builder(
GoogleNetHttpTransport.newTrustedTransport(),
JacksonFactory.getDefaultInstance(), null)
.setApplicationName("linkedinSearch")
.setGoogleClientRequestInitializer(new CustomsearchRequestInitializer(KEY))
.build();
Customsearch.Cse.List list = cs.cse().list(currentBusinessName).setCx(cx);
List<Result> searchJsonResults = list.execute().getItems();
String[] numberOfFollowers;
int companyFollowers = 0;
if (searchJsonResults!=null && searchJsonResults.size() != 0) {
Result linkedinBusiness = searchJsonResults.get(0);
String businessDescription =
(String) linkedinBusiness.getPagemap().get("metatags").get(0).get("og:description");
if(businessDescription.indexOf(START_SUBSTRING) != -1
&& businessDescription.indexOf(END_SUBSTRING) != -1){
String followers = businessDescription.substring(
businessDescription.indexOf(START_SUBSTRING) + 2,
businessDescription.indexOf(END_SUBSTRING) - 1);
try{
companyFollowers =
Integer.parseInt(followers.replaceAll(",", ""));
} catch (NumberFormatException e){
LOGGER.warning(e.getMessage());
}
}
if (companyFollowers > MINFOLLOWERS) {
addBigBusinessToDatabase();
} else {
checkNumberOfSimilarBusinessesInTheArea(currentBusiness.getName(),
similarBusinessesInTheArea);
}
}
}
private void checkNumberOfSimilarBusinessesInTheArea(String businessName,
PlacesSearchResult[] similarBusinessesInTheArea) {
int countNumberOfMatchingBusiness = 0;
int i = 0;
while (i < similarBusinessesInTheArea.length
&& countNumberOfMatchingBusiness < 10) {
if(similarBusinessesInTheArea[i].vicinity != null){
if (similarBusinessesInTheArea[i].name.contains(businessName)
&& !(similarBusinessesInTheArea[i].vicinity.equals(currentBusiness.getFormattedAddress()))) {
countNumberOfMatchingBusiness++;
}
}
i++;
}
if (countNumberOfMatchingBusiness >= 10) {
addBigBusinessToDatabase();
}
}
private void addBigBusinessToDatabase(){
businesses.remove();
String title = "Business";
String businessTypes = "BusinessTypes";
String address = "Address";
String rating = "Rating";
String photos = "Photos";
Entity businessEntity = new Entity("BigBusinesses", currentBusiness.getName());
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
businessEntity.setProperty(title, currentBusiness.getName());
businessEntity.setProperty(address, currentBusiness.getFormattedAddress());
businessEntity.setProperty(rating, currentBusiness.getRating());
businessEntity.setProperty(businessTypes,
Arrays.asList(currentBusiness.getBusinessTypes()));
datastore.put(businessEntity);
}
}
|
package com.jaamsim.controllers;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.Image;
import java.awt.dnd.DragSourceDragEvent;
import java.awt.dnd.DragSourceDropEvent;
import java.awt.dnd.DragSourceEvent;
import java.awt.dnd.DragSourceListener;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import com.jaamsim.DisplayModels.DisplayModel;
import com.jaamsim.DisplayModels.ImageModel;
import com.jaamsim.DisplayModels.TextModel;
import com.jaamsim.font.TessFont;
import com.jaamsim.input.InputAgent;
import com.jaamsim.math.AABB;
import com.jaamsim.math.Mat4d;
import com.jaamsim.math.MathUtils;
import com.jaamsim.math.Plane;
import com.jaamsim.math.Quaternion;
import com.jaamsim.math.Ray;
import com.jaamsim.math.Transform;
import com.jaamsim.math.Vec3d;
import com.jaamsim.math.Vec4d;
import com.jaamsim.render.Action;
import com.jaamsim.render.CameraInfo;
import com.jaamsim.render.DisplayModelBinding;
import com.jaamsim.render.Future;
import com.jaamsim.render.HasScreenPoints;
import com.jaamsim.render.MeshDataCache;
import com.jaamsim.render.MeshProtoKey;
import com.jaamsim.render.OffscreenTarget;
import com.jaamsim.render.PreviewCache;
import com.jaamsim.render.RenderProxy;
import com.jaamsim.render.RenderUtils;
import com.jaamsim.render.Renderer;
import com.jaamsim.render.TessFontKey;
import com.jaamsim.render.WindowInteractionListener;
import com.jaamsim.render.util.ExceptionLogger;
import com.jaamsim.ui.FrameBox;
import com.jaamsim.ui.View;
import com.sandwell.JavaSimulation.Entity;
import com.sandwell.JavaSimulation.Input;
import com.sandwell.JavaSimulation.InputErrorException;
import com.sandwell.JavaSimulation.IntegerVector;
import com.sandwell.JavaSimulation.ObjectType;
import com.sandwell.JavaSimulation.StringVector;
import com.sandwell.JavaSimulation3D.DisplayEntity;
import com.sandwell.JavaSimulation3D.DisplayModelCompat;
import com.sandwell.JavaSimulation3D.GUIFrame;
import com.sandwell.JavaSimulation3D.Graph;
import com.sandwell.JavaSimulation3D.ObjectSelector;
import com.sandwell.JavaSimulation3D.Region;
/**
* Top level owner of the JaamSim renderer. This class both owns and drives the Renderer object, but is also
* responsible for gathering rendering data every frame.
* @author Matt Chudleigh
*
*/
public class RenderManager implements DragSourceListener {
private final static int EXCEPTION_STACK_THRESHOLD = 10; // The number of recoverable exceptions until a stack trace is output
private final static int EXCEPTION_PRINT_RATE = 30; // The number of total exceptions until the overall log is printed
private int numberOfExceptions = 0;
private static RenderManager s_instance = null;
/**
* Basic singleton pattern
*/
public static void initialize(boolean safeGraphics) {
s_instance = new RenderManager(safeGraphics);
}
public static RenderManager inst() { return s_instance; }
private final Thread _managerThread;
private final Renderer _renderer;
private final AtomicBoolean _finished = new AtomicBoolean(false);
private final AtomicBoolean _fatalError = new AtomicBoolean(false);
private final AtomicBoolean _redraw = new AtomicBoolean(false);
private final AtomicBoolean _screenshot = new AtomicBoolean(false);
// These values are used to limit redraw rate, the stored values are time in milliseconds
// returned by System.currentTimeMillis()
private final AtomicLong _lastDraw = new AtomicLong(0);
private final AtomicLong _scheduledDraw = new AtomicLong(0);
private final ExceptionLogger _exceptionLogger;
private final static double FPS = 60;
private final Timer _timer;
private final HashMap<Integer, CameraControl> _windowControls = new HashMap<Integer, CameraControl>();
private final HashMap<Integer, View> _windowToViewMap= new HashMap<Integer, View>();
private int _activeWindowID = -1;
private final Object _popupLock;
private JPopupMenu _lastPopup;
/**
* The last scene rendered
*/
private ArrayList<RenderProxy> _cachedScene;
private DisplayEntity _selectedEntity = null;
private double _simTime = 0.0d;
private long _dragHandleID = 0;
private Vec3d _dragCollisionPoint;
// The object type for drag-and-drop operation, if this is null, the user is not dragging
private ObjectType _dndObjectType;
private long _dndDropTime = 0;
// The video recorder to sample
private VideoRecorder _recorder;
private PreviewCache _previewCache = new PreviewCache();
// Below are special PickingIDs for resizing and dragging handles
public static final long MOVE_PICK_ID = -1;
// For now this order is implicitly the same as the handle order in RenderObserver, don't re arrange it without touching
// the handle list
public static final long RESIZE_POSX_PICK_ID = -2;
public static final long RESIZE_NEGX_PICK_ID = -3;
public static final long RESIZE_POSY_PICK_ID = -4;
public static final long RESIZE_NEGY_PICK_ID = -5;
public static final long RESIZE_PXPY_PICK_ID = -6;
public static final long RESIZE_PXNY_PICK_ID = -7;
public static final long RESIZE_NXPY_PICK_ID = -8;
public static final long RESIZE_NXNY_PICK_ID = -9;
public static final long ROTATE_PICK_ID = -10;
public static final long LINEDRAG_PICK_ID = -11;
// Line nodes start at this constant and proceed into the negative range, therefore this should be the lowest defined constant
public static final long LINENODE_PICK_ID = -12;
private RenderManager(boolean safeGraphics) {
_renderer = new Renderer(safeGraphics);
_exceptionLogger = new ExceptionLogger(EXCEPTION_STACK_THRESHOLD);
_managerThread = new Thread(new Runnable() {
@Override
public void run() {
renderManagerLoop();
}
}, "RenderManagerThread");
_managerThread.start();
// Start the display timer
_timer = new Timer("RedrawThread");
TimerTask displayTask = new TimerTask() {
@Override
public void run() {
// Is a redraw scheduled
long lastRedraw = _lastDraw.get();
long scheduledTime = _scheduledDraw.get();
long currentTime = System.currentTimeMillis();
// Only draw if the scheduled time is before now and after the last redraw
// but never skip a draw if a screen shot is requested
if (!_screenshot.get() && (scheduledTime < lastRedraw || currentTime < scheduledTime)) {
return;
}
synchronized(_redraw) {
if (_renderer.getNumOpenWindows() == 0 && !_screenshot.get()) {
return; // Do not queue a redraw if there are no open windows
}
_redraw.set(true);
_redraw.notifyAll();
}
_lastDraw.set(currentTime);
}
};
_timer.scheduleAtFixedRate(displayTask, 0, (long) (1000 / (FPS*2)));
_popupLock = new Object();
}
public static final void updateTime(double simTime) {
if (!RenderManager.isGood())
return;
RenderManager.inst()._simTime = simTime;
RenderManager.inst().queueRedraw();
}
public static final void redraw() {
if (!isGood()) return;
inst().queueRedraw();
}
private void queueRedraw() {
long scheduledTime = _scheduledDraw.get();
long lastRedraw = _lastDraw.get();
long currentTime = System.currentTimeMillis();
if (scheduledTime > lastRedraw) {
// A draw is scheduled
return;
}
long newDraw = currentTime;
long frameTime = (long)(1000.0/FPS);
if (newDraw < lastRedraw + frameTime) {
// This would be scheduled too soon
newDraw = lastRedraw + frameTime;
}
_scheduledDraw.set(newDraw);
}
public void createWindow(View view) {
// First see if this window has already been opened
for (Map.Entry<Integer, CameraControl> entry : _windowControls.entrySet()) {
if (entry.getValue().getView() == view) {
// This view has a window, just reshow that one
focusWindow(entry.getKey());
return;
}
}
IntegerVector windSize = view.getWindowSize();
IntegerVector windPos = view.getWindowPos();
Image icon = GUIFrame.getWindowIcon();
CameraControl control = new CameraControl(_renderer, view);
int windowID = _renderer.createWindow(windPos.get(0), windPos.get(1),
windSize.get(0), windSize.get(1),
view.getID(),
view.getTitle(), view.getInputName(),
icon, control);
control.setWindowID(windowID);
_windowControls.put(windowID, control);
_windowToViewMap.put(windowID, view);
queueRedraw();
}
public static final void clear() {
if (!isGood()) return;
RenderManager.inst().closeAllWindows();
}
private void closeAllWindows() {
ArrayList<Integer> windIDs = _renderer.getOpenWindowIDs();
for (int id : windIDs) {
_renderer.closeWindow(id);
}
}
public void windowClosed(int windowID) {
_windowControls.remove(windowID);
_windowToViewMap.remove(windowID);
}
public void setActiveWindow(int windowID) {
_activeWindowID = windowID;
}
public static boolean isGood() {
return (s_instance != null && !s_instance._finished.get() && !s_instance._fatalError.get());
}
/**
* Ideally, this states that it is safe to call initialize() (assuming isGood() returned false)
* @return
*/
public static boolean canInitialize() {
return s_instance == null;
}
private void renderManagerLoop() {
while (!_finished.get() && !_fatalError.get()) {
try {
if (_renderer.hasFatalError()) {
// Well, something went horribly wrong
_fatalError.set(true);
System.out.printf("Renderer failed with error: %s\n", _renderer.getErrorString());
// Do some basic cleanup
_windowControls.clear();
_previewCache.clear();
_timer.cancel();
break;
}
if (!_renderer.isInitialized()) {
// Give the renderer a chance to initialize
try {
Thread.sleep(100);
} catch(InterruptedException e) {}
continue;
}
for (CameraControl cc : _windowControls.values()) {
cc.checkForUpdate();
}
_cachedScene = new ArrayList<RenderProxy>();
DisplayModelBinding.clearCacheCounters();
DisplayModelBinding.clearCacheMissData();
boolean screenShotThisFrame = _screenshot.get();
double renderTime = _simTime;
long startNanos = System.nanoTime();
for (int i = 0; i < View.getAll().size(); i++) {
View v = View.getAll().get(i);
v.update(renderTime);
}
ArrayList<DisplayModelBinding> selectedBindings = new ArrayList<DisplayModelBinding>();
// Update all graphical entities in the simulation
for (int i = 0; i < DisplayEntity.getAll().size(); i++) {
DisplayEntity de;
try {
de = DisplayEntity.getAll().get(i);
}
catch (IndexOutOfBoundsException e) {
break;
}
try {
de.updateGraphics(renderTime);
}
// Catch everything so we don't screw up the behavior handling
catch (Throwable e) {
logException(e);
}
}
long updateNanos = System.nanoTime();
int totalBindings = 0;
for (int i = 0; i < DisplayEntity.getAll().size(); i++) {
DisplayEntity de;
try {
de = DisplayEntity.getAll().get(i);
} catch (IndexOutOfBoundsException ex) {
// This is probably the end of the list, so just move on
break;
}
for (DisplayModelBinding binding : de.getDisplayBindings()) {
try {
totalBindings++;
binding.collectProxies(renderTime, _cachedScene);
if (binding.isBoundTo(_selectedEntity)) {
selectedBindings.add(binding);
}
} catch (Throwable t) {
// Log the exception in the exception list
logException(t);
}
}
}
// Collect selection proxies second so they always appear on top
for (DisplayModelBinding binding : selectedBindings) {
try {
binding.collectSelectionProxies(renderTime, _cachedScene);
} catch (Throwable t) {
// Log the exception in the exception list
logException(t);
}
}
long endNanos = System.nanoTime();
_renderer.setScene(_cachedScene);
String cacheString = " Hits: " + DisplayModelBinding.getCacheHits() + " Misses: " + DisplayModelBinding.getCacheMisses() +
" Total: " + totalBindings;
double gatherMS = (endNanos - updateNanos) / 1000000.0;
double updateMS = (updateNanos - startNanos) / 1000000.0;
String timeString = "Gather time (ms): " + gatherMS + " Update time (ms): " + updateMS;
// Do some picking debug
ArrayList<Integer> windowIDs = _renderer.getOpenWindowIDs();
for (int id : windowIDs) {
Renderer.WindowMouseInfo mouseInfo = _renderer.getMouseInfo(id);
if (mouseInfo == null || !mouseInfo.mouseInWindow) {
// Not currently picking for this window
_renderer.setWindowDebugInfo(id, cacheString + " Not picking. " + timeString, new ArrayList<Long>());
continue;
}
List<PickData> picks = pickForMouse(id, false);
ArrayList<Long> debugIDs = new ArrayList<Long>(picks.size());
StringBuilder dbgMsg = new StringBuilder(cacheString);
dbgMsg.append(" Picked ").append(picks.size());
dbgMsg.append(" entities at (").append(mouseInfo.x);
dbgMsg.append(", ").append(mouseInfo.y).append("): ");
for (PickData pd : picks) {
Entity ent = Entity.idToEntity(pd.id);
if (ent != null)
dbgMsg.append(ent.getInputName());
dbgMsg.append(", ");
debugIDs.add(pd.id);
}
dbgMsg.append(timeString);
_renderer.setWindowDebugInfo(id, dbgMsg.toString(), debugIDs);
}
if (GUIFrame.getShuttingDownFlag()) {
shutdown();
}
_renderer.queueRedraw();
_redraw.set(false);
if (screenShotThisFrame) {
takeScreenShot();
}
} catch (Throwable t) {
// Make a note of it, but try to keep going
logException(t);
}
// Wait for a redraw request
synchronized(_redraw) {
while (!_redraw.get()) {
try {
_redraw.wait();
} catch (InterruptedException e) {}
}
}
}
_exceptionLogger.printExceptionLog();
}
public void popupMenu(final int windowID) {
try {
// Transfer control from the NEWT-EDT to the AWT-EDT
EventQueue.invokeAndWait(new Runnable() {
@Override
public void run() {
popupMenuImp(windowID);
}
});
} catch (InvocationTargetException ex) {
assert(false);
} catch (InterruptedException ex) {
assert(false);
}
}
// Temporary dumping ground until I find a better place for this
// Note: this is intentionally package private to be called by an inner class
void popupMenuImp(int windowID) {
synchronized (_popupLock) {
Renderer.WindowMouseInfo mouseInfo = _renderer.getMouseInfo(windowID);
if (mouseInfo == null) {
// Somehow this window was closed along the way, just ignore this click
return;
}
final Frame awtFrame = _renderer.getAWTFrame(windowID);
if (awtFrame == null) {
return;
}
List<PickData> picks = pickForMouse(windowID, false);
ArrayList<DisplayEntity> ents = new ArrayList<DisplayEntity>();
for (PickData pd : picks) {
if (!pd.isEntity) { continue; }
Entity ent = Entity.idToEntity(pd.id);
if (ent == null) { continue; }
if (!(ent instanceof DisplayEntity)) { continue; }
DisplayEntity de = (DisplayEntity)ent;
if (!de.isMovable()) { continue; } // only a movable DisplayEntity responds to a right-click
ents.add(de);
}
if (!mouseInfo.mouseInWindow) {
// Somehow this window does not currently have the mouse over it.... ignore?
return;
}
final JPopupMenu menu = new JPopupMenu();
_lastPopup = menu;
menu.setLightWeightPopupEnabled(false);
final int menuX = mouseInfo.x + awtFrame.getInsets().left;
final int menuY = mouseInfo.y + awtFrame.getInsets().top;
if (ents.size() == 0) { return; } // Nothing to show
if (ents.size() == 1) {
ObjectSelector.populateMenu(menu, ents.get(0), menuX, menuY);
}
else {
// Several entities, let the user pick the interesting entity first
for (final DisplayEntity de : ents) {
JMenuItem thisItem = new JMenuItem(de.getInputName());
thisItem.addActionListener( new ActionListener() {
@Override
public void actionPerformed( ActionEvent event ) {
menu.removeAll();
ObjectSelector.populateMenu(menu, de, menuX, menuY);
menu.show(awtFrame, menuX, menuY);
}
} );
menu.add( thisItem );
}
}
menu.show(awtFrame, menuX, menuY);
menu.repaint();
} // synchronized (_popupLock)
}
public void handleSelection(int windowID) {
List<PickData> picks = pickForMouse(windowID, false);
Collections.sort(picks, new SelectionSorter());
for (PickData pd : picks) {
// Select the first entity after sorting
if (pd.isEntity) {
DisplayEntity ent = (DisplayEntity)Entity.idToEntity(pd.id);
if (!ent.isMovable()) {
continue;
}
FrameBox.setSelectedEntity(ent);
queueRedraw();
return;
}
}
FrameBox.setSelectedEntity(null);
queueRedraw();
}
/**
* Utility, convert a window and mouse coordinate into a list of picking IDs for that pixel
* @param windowID
* @param mouseX
* @param mouseY
* @return
*/
private List<PickData> pickForMouse(int windowID, boolean precise) {
Renderer.WindowMouseInfo mouseInfo = _renderer.getMouseInfo(windowID);
View view = _windowToViewMap.get(windowID);
if (mouseInfo == null || view == null || !mouseInfo.mouseInWindow) {
// The mouse is not actually in the window, or the window was closed along the way
return new ArrayList<PickData>(); // empty set
}
Ray pickRay = RenderUtils.getPickRay(mouseInfo);
return pickForRay(pickRay, view.getID(), precise);
}
/**
* PickData represents enough information to sort a list of picks based on a picking preference
* metric. For now it holds the object size and distance from pick point to object center
*
*/
private static class PickData {
public long id;
public double size;
public double dist;
boolean isEntity;
/**
* This pick does not correspond to an entity, and is a handle or other UI element
* @param id
*/
public PickData(long id, double d) {
this.id = id;
size = 0;
dist = d;
isEntity = false;
}
/**
* This pick was an entity
* @param id - the id
* @param ent - the entity
*/
public PickData(long id, double d, DisplayEntity ent) {
this.id = id;
size = ent.getSize().mag3();
dist = d;
isEntity = true;
}
}
/**
* This Comparator sorts based on entity selection preference
*/
private static class SelectionSorter implements Comparator<PickData> {
@Override
public int compare(PickData p0, PickData p1) {
if (p0.isEntity && !p1.isEntity) {
return -1;
}
if (!p0.isEntity && p1.isEntity) {
return 1;
}
if (p0.size == p1.size) {
return 0;
}
return (p0.size < p1.size) ? -1 : 1;
}
}
/**
* This Comparator sorts based on interaction handle priority
*/
private static class HandleSorter implements Comparator<PickData> {
@Override
public int compare(PickData p0, PickData p1) {
int p0priority = getHandlePriority(p0.id);
int p1priority = getHandlePriority(p1.id);
if (p0priority == p1priority)
return 0;
return (p0priority < p1priority) ? 1 : -1;
}
}
/**
* This determines the priority for interaction handles if several are selectable at drag time
* @param handleID
* @return
*/
private static int getHandlePriority(long handleID) {
if (handleID == MOVE_PICK_ID) return 1;
if (handleID == LINEDRAG_PICK_ID) return 1;
if (handleID <= LINENODE_PICK_ID) return 2;
if (handleID == ROTATE_PICK_ID) return 3;
if (handleID == RESIZE_POSX_PICK_ID) return 4;
if (handleID == RESIZE_NEGX_PICK_ID) return 4;
if (handleID == RESIZE_POSY_PICK_ID) return 4;
if (handleID == RESIZE_NEGY_PICK_ID) return 4;
if (handleID == RESIZE_PXPY_PICK_ID) return 5;
if (handleID == RESIZE_PXNY_PICK_ID) return 5;
if (handleID == RESIZE_NXPY_PICK_ID) return 5;
if (handleID == RESIZE_NXNY_PICK_ID) return 5;
return 0;
}
public Vec3d getNearestPick(int windowID) {
Renderer.WindowMouseInfo mouseInfo = _renderer.getMouseInfo(windowID);
View view = _windowToViewMap.get(windowID);
if (mouseInfo == null || view == null || !mouseInfo.mouseInWindow) {
// The mouse is not actually in the window, or the window was closed along the way
return null;
}
Ray pickRay = RenderUtils.getPickRay(mouseInfo);
List<Renderer.PickResult> picks = _renderer.pick(pickRay, view.getID(), true);
if (picks.size() == 0) {
return null;
}
double pickDist = Double.POSITIVE_INFINITY;
for (Renderer.PickResult pick : picks) {
if (pick.dist < pickDist && pick.pickingID >= 0) {
// Negative pickingIDs are reserved for interaction handles and are therefore not
// part of the content
pickDist = pick.dist;
}
}
if (pickDist == Double.POSITIVE_INFINITY) {
return null;
}
return pickRay.getPointAtDist(pickDist);
}
/**
* Perform a pick from this world space ray
* @param pickRay - the ray
* @return
*/
private List<PickData> pickForRay(Ray pickRay, int viewID, boolean precise) {
List<Renderer.PickResult> picks = _renderer.pick(pickRay, viewID, precise);
List<PickData> uniquePicks = new ArrayList<PickData>();
// IDs that have already been added
Set<Long> knownIDs = new HashSet<Long>();
for (Renderer.PickResult pick : picks) {
if (knownIDs.contains(pick.pickingID)) {
continue;
}
knownIDs.add(pick.pickingID);
DisplayEntity ent = (DisplayEntity)Entity.idToEntity(pick.pickingID);
if (ent == null) {
// This object is not an entity, but may be a picking handle
uniquePicks.add(new PickData(pick.pickingID, pick.dist));
} else {
uniquePicks.add(new PickData(pick.pickingID, pick.dist, ent));
}
}
return uniquePicks;
}
/**
* Pick on a window at a position other than the current mouse position
* @param windowID
* @param x
* @param y
* @return
*/
private Ray getRayForMouse(int windowID, int x, int y) {
Renderer.WindowMouseInfo mouseInfo = _renderer.getMouseInfo(windowID);
if (mouseInfo == null) {
return new Ray();
}
return RenderUtils.getPickRayForPosition(mouseInfo.cameraInfo, x, y, mouseInfo.width, mouseInfo.height);
}
public Vec3d getRenderedStringSize(TessFontKey fontKey, double textHeight, String string) {
TessFont font = _renderer.getTessFont(fontKey);
return font.getStringSize(textHeight, string);
}
private void logException(Throwable t) {
_exceptionLogger.logException(t);
numberOfExceptions++;
// Only print the exception log periodically (this can get a bit spammy)
if (numberOfExceptions % EXCEPTION_PRINT_RATE == 0) {
System.out.println("Recoverable Exceptions from RenderManager: ");
_exceptionLogger.printExceptionLog();
System.out.println("");
}
}
public static void setSelection(Entity ent) {
if (!RenderManager.isGood())
return;
RenderManager.inst().setSelectEntity(ent);
}
private void setSelectEntity(Entity ent) {
if (ent instanceof DisplayEntity)
_selectedEntity = (DisplayEntity)ent;
else
_selectedEntity = null;
queueRedraw();
}
/**
* This method gives the RenderManager a chance to handle mouse drags before the CameraControl
* gets to handle it (note: this may need to be refactored into a proper event handling heirarchy)
* @param dragInfo
* @return
*/
public boolean handleDrag(WindowInteractionListener.DragInfo dragInfo) {
// Any quick outs go here
if (!dragInfo.controlDown()) {
return false;
}
if (_dragHandleID == 0) {
return true;
}
if (_selectedEntity == null || !_selectedEntity.isMovable()) {
return true;
}
// Find the start and current world space positions
Ray currentRay = getRayForMouse(dragInfo.windowID, dragInfo.x, dragInfo.y);
Ray lastRay = getRayForMouse(dragInfo.windowID,
dragInfo.x - dragInfo.dx,
dragInfo.y - dragInfo.dy);
Transform trans = _selectedEntity.getGlobalTrans(_simTime);
Vec3d size = _selectedEntity.getSize();
Mat4d transMat = _selectedEntity.getTransMatrix(_simTime);
Mat4d invTransMat = _selectedEntity.getInvTransMatrix(_simTime);
Plane entityPlane = new Plane(); // Defaults to XY
entityPlane.transform(trans, entityPlane, new Vec3d()); // Transform the plane to world space
double currentDist = entityPlane.collisionDist(currentRay);
double lastDist = entityPlane.collisionDist(lastRay);
if (_dragHandleID != MOVE_PICK_ID &&
(currentDist < 0 || currentDist == Double.POSITIVE_INFINITY ||
lastDist < 0 || lastDist == Double.POSITIVE_INFINITY))
{
// The plane is parallel or behind one of the rays...
// Moving uses a different plane, so we'll test that below
return true; // Just ignore it for now...
}
// The points where the previous pick ended and current position. Collision is with the entity's XY plane
Vec3d currentPoint = currentRay.getPointAtDist(currentDist);
Vec3d lastPoint = lastRay.getPointAtDist(lastDist);
Vec3d entSpaceCurrent = new Vec3d(); // entSpacePoint is the current point in model space
entSpaceCurrent.multAndTrans3(invTransMat, currentPoint);
Vec3d entSpaceLast = new Vec3d(); // entSpaceLast is the last point in model space
entSpaceLast.multAndTrans3(invTransMat, lastPoint);
Vec3d delta = new Vec3d();
delta.sub3(currentPoint, lastPoint);
Vec3d entSpaceDelta = new Vec3d();
entSpaceDelta.sub3(entSpaceCurrent, entSpaceLast);
// Handle each handle by type...
if (_dragHandleID == MOVE_PICK_ID) {
// We are dragging
// Dragging may not happen in the entity's XY plane, so we need to re-do some of the work above
Plane dragPlane = new Plane(new Vec3d(0, 0, 1), _dragCollisionPoint.z); // XY plane at collistion point
if (dragInfo.shiftDown()) {
Vec3d entPos = _selectedEntity.getGlobalPosition();
double zDiff = RenderUtils.getZDiff(_dragCollisionPoint, currentRay, lastRay);
entPos.z += zDiff;
_selectedEntity.setGlobalPosition(entPos);
return true;
}
double cDist = dragPlane.collisionDist(currentRay);
double lDist = dragPlane.collisionDist(lastRay);
if (cDist < 0 || cDist == Double.POSITIVE_INFINITY ||
lDist < 0 || lDist == Double.POSITIVE_INFINITY)
return true;
Vec3d cPoint = currentRay.getPointAtDist(cDist);
Vec3d lPoint = lastRay.getPointAtDist(lDist);
Vec3d del = new Vec3d();
del.sub3(cPoint, lPoint);
Vec3d pos = _selectedEntity.getGlobalPosition();
pos.add3(del);
_selectedEntity.setGlobalPosition(pos);
return true;
}
// Handle resize
if (_dragHandleID <= RESIZE_POSX_PICK_ID &&
_dragHandleID >= RESIZE_NXNY_PICK_ID) {
Vec3d pos = _selectedEntity.getGlobalPosition();
Vec3d scale = _selectedEntity.getSize();
Vec4d fixedPoint = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
if (_dragHandleID == RESIZE_POSX_PICK_ID) {
//scale.x = 2*entSpaceCurrent.x() * size.x();
scale.x += entSpaceDelta.x * size.x;
fixedPoint = new Vec4d(-0.5, 0.0, 0.0, 1.0d);
}
if (_dragHandleID == RESIZE_POSY_PICK_ID) {
scale.y += entSpaceDelta.y * size.y;
fixedPoint = new Vec4d( 0.0, -0.5, 0.0, 1.0d);
}
if (_dragHandleID == RESIZE_NEGX_PICK_ID) {
scale.x -= entSpaceDelta.x * size.x;
fixedPoint = new Vec4d( 0.5, 0.0, 0.0, 1.0d);
}
if (_dragHandleID == RESIZE_NEGY_PICK_ID) {
scale.y -= entSpaceDelta.y * size.y;
fixedPoint = new Vec4d( 0.0, 0.5, 0.0, 1.0d);
}
if (_dragHandleID == RESIZE_PXPY_PICK_ID) {
scale.x += entSpaceDelta.x * size.x;
scale.y += entSpaceDelta.y * size.y;
fixedPoint = new Vec4d(-0.5, -0.5, 0.0, 1.0d);
}
if (_dragHandleID == RESIZE_PXNY_PICK_ID) {
scale.x += entSpaceDelta.x * size.x;
scale.y -= entSpaceDelta.y * size.y;
fixedPoint = new Vec4d(-0.5, 0.5, 0.0, 1.0d);
}
if (_dragHandleID == RESIZE_NXPY_PICK_ID) {
scale.x -= entSpaceDelta.x * size.x;
scale.y += entSpaceDelta.y * size.y;
fixedPoint = new Vec4d( 0.5, -0.5, 0.0, 1.0d);
}
if (_dragHandleID == RESIZE_NXNY_PICK_ID) {
scale.x -= entSpaceDelta.x * size.x;
scale.y -= entSpaceDelta.y * size.y;
fixedPoint = new Vec4d( 0.5, 0.5, 0.0, 1.0d);
}
// Handle the case where the scale is pulled through itself. Fix the scale,
// and swap the currently selected handle
if (scale.x <= 0.00005) {
scale.x = 0.0001;
if (_dragHandleID == RESIZE_POSX_PICK_ID) { _dragHandleID = RESIZE_NEGX_PICK_ID; }
else if (_dragHandleID == RESIZE_NEGX_PICK_ID) { _dragHandleID = RESIZE_POSX_PICK_ID; }
else if (_dragHandleID == RESIZE_PXPY_PICK_ID) { _dragHandleID = RESIZE_NXPY_PICK_ID; }
else if (_dragHandleID == RESIZE_PXNY_PICK_ID) { _dragHandleID = RESIZE_NXNY_PICK_ID; }
else if (_dragHandleID == RESIZE_NXPY_PICK_ID) { _dragHandleID = RESIZE_PXPY_PICK_ID; }
else if (_dragHandleID == RESIZE_NXNY_PICK_ID) { _dragHandleID = RESIZE_PXNY_PICK_ID; }
}
if (scale.y <= 0.00005) {
scale.y = 0.0001;
if (_dragHandleID == RESIZE_POSY_PICK_ID) { _dragHandleID = RESIZE_NEGY_PICK_ID; }
else if (_dragHandleID == RESIZE_NEGY_PICK_ID) { _dragHandleID = RESIZE_POSY_PICK_ID; }
else if (_dragHandleID == RESIZE_PXPY_PICK_ID) { _dragHandleID = RESIZE_PXNY_PICK_ID; }
else if (_dragHandleID == RESIZE_PXNY_PICK_ID) { _dragHandleID = RESIZE_PXPY_PICK_ID; }
else if (_dragHandleID == RESIZE_NXPY_PICK_ID) { _dragHandleID = RESIZE_NXNY_PICK_ID; }
else if (_dragHandleID == RESIZE_NXNY_PICK_ID) { _dragHandleID = RESIZE_NXPY_PICK_ID; }
}
Vec4d oldFixed = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
oldFixed.mult4(transMat, fixedPoint);
_selectedEntity.setSize(scale);
transMat = _selectedEntity.getTransMatrix(_simTime); // Get the new matrix
Vec4d newFixed = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
newFixed.mult4(transMat, fixedPoint);
Vec4d posAdjust = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
posAdjust.sub3(oldFixed, newFixed);
pos.add3(posAdjust);
_selectedEntity.setGlobalPosition(pos);
Vec3d vec = _selectedEntity.getSize();
InputAgent.processEntity_Keyword_Value(_selectedEntity, "Size", String.format( "%.6f %.6f %.6f %s", vec.x, vec.y, vec.z, "m" ));
FrameBox.valueUpdate();
return true;
}
if (_dragHandleID == ROTATE_PICK_ID) {
Vec3d align = _selectedEntity.getAlignment();
Vec4d rotateCenter = new Vec4d(align.x, align.y, align.z, 1.0d);
rotateCenter.mult4(transMat, rotateCenter);
Vec4d a = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
a.sub3(lastPoint, rotateCenter);
Vec4d b = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
b.sub3(currentPoint, rotateCenter);
Vec4d aCrossB = new Vec4d(0.0d, 0.0d, 0.0d, 1.0d);
aCrossB.cross3(a, b);
double sinTheta = aCrossB.z / a.mag3() / b.mag3();
double theta = Math.asin(sinTheta);
Vec3d orient = _selectedEntity.getOrientation();
orient.z += theta;
InputAgent.processEntity_Keyword_Value(_selectedEntity, "Orientation", String.format("%f %f %f rad", orient.x, orient.y, orient.z));
FrameBox.valueUpdate();
return true;
}
if (_dragHandleID == LINEDRAG_PICK_ID) {
// Dragging a line object
if (dragInfo.shiftDown()) {
ArrayList<Vec3d> screenPoints = null;
if (_selectedEntity instanceof HasScreenPoints)
screenPoints = ((HasScreenPoints)_selectedEntity).getScreenPoints()[0].points;
if (screenPoints == null || screenPoints.size() == 0) return true; // just ignore this
// Find the geometric median of the points
Vec4d medPoint = RenderUtils.getGeometricMedian(screenPoints);
double zDiff = RenderUtils.getZDiff(medPoint, currentRay, lastRay);
_selectedEntity.dragged(new Vec3d(0, 0, zDiff));
return true;
}
Region reg = _selectedEntity.getCurrentRegion();
Transform regionInvTrans = new Transform();
if (reg != null) {
regionInvTrans = reg.getRegionTrans(0.0d);
regionInvTrans.inverse(regionInvTrans);
}
Vec3d localDelta = new Vec3d();
regionInvTrans.multAndTrans(delta, localDelta);
_selectedEntity.dragged(localDelta);
return true;
}
if (_dragHandleID <= LINENODE_PICK_ID) {
int nodeIndex = (int)(-1*(_dragHandleID - LINENODE_PICK_ID));
ArrayList<Vec3d> screenPoints = null;
if (_selectedEntity instanceof HasScreenPoints)
screenPoints = ((HasScreenPoints)_selectedEntity).getScreenPoints()[0].points;
// Note: screenPoints is not a defensive copy, but we'll put it back into itself
// in a second so everything should be safe
if (screenPoints == null || nodeIndex >= screenPoints.size()) {
// huh?
return false;
}
Vec3d point = screenPoints.get(nodeIndex);
if (dragInfo.shiftDown()) {
double zDiff = RenderUtils.getZDiff(point, currentRay, lastRay);
point.z += zDiff;
} else {
Plane pointPlane = new Plane(null, point.z);
Vec3d diff = RenderUtils.getPlaneCollisionDiff(pointPlane, currentRay, lastRay);
point.x += diff.x;
point.y += diff.y;
point.z += 0;
}
Input<?> pointsInput = _selectedEntity.getInput("Points");
assert(pointsInput != null);
if (pointsInput == null) {
return true;
}
StringBuilder sb = new StringBuilder();
String pointFormatter = " { %.3f %.3f %.3f m }";
for(Vec3d pt : screenPoints) {
sb.append(String.format(pointFormatter, pt.x, pt.y, pt.z));
}
InputAgent.processEntity_Keyword_Value(_selectedEntity, pointsInput, sb.toString());
FrameBox.valueUpdate();
return true;
}
return false;
}
private void splitLineEntity(int windowID, int x, int y) {
Ray currentRay = getRayForMouse(windowID, x, y);
Mat4d rayMatrix = MathUtils.RaySpace(currentRay);
HasScreenPoints hsp = (HasScreenPoints)_selectedEntity;
assert(hsp != null);
ArrayList<Vec3d> points = hsp.getScreenPoints()[0].points;
int splitInd = 0;
Vec4d nearPoint = null;
// Find a line segment we are near
for (;splitInd < points.size() - 1; ++splitInd) {
Vec4d a = new Vec4d(points.get(splitInd ).x, points.get(splitInd ).y, points.get(splitInd ).z, 1.0d);
Vec4d b = new Vec4d(points.get(splitInd+1).x, points.get(splitInd+1).y, points.get(splitInd+1).z, 1.0d);
nearPoint = RenderUtils.rayClosePoint(rayMatrix, a, b);
double rayAngle = RenderUtils.angleToRay(rayMatrix, nearPoint);
if (rayAngle > 0 && rayAngle < 0.01309) { // 0.75 degrees in radians
break;
}
}
if (splitInd == points.size() - 1) {
// No appropriate point was found
return;
}
// If we are here, we have a segment to split, at index i
StringBuilder sb = new StringBuilder();
String pointFormatter = " { %.3f %.3f %.3f m }";
for(int i = 0; i <= splitInd; ++i) {
Vec3d pt = points.get(i);
sb.append(String.format(pointFormatter, pt.x, pt.y, pt.z));
}
sb.append(String.format(pointFormatter, nearPoint.x, nearPoint.y, nearPoint.z));
for (int i = splitInd+1; i < points.size(); ++i) {
Vec3d pt = points.get(i);
sb.append(String.format(pointFormatter, pt.x, pt.y, pt.z));
}
Input<?> pointsInput = _selectedEntity.getInput("Points");
InputAgent.processEntity_Keyword_Value(_selectedEntity, pointsInput, sb.toString());
FrameBox.valueUpdate();
}
private void removeLineNode(int windowID, int x, int y) {
Ray currentRay = getRayForMouse(windowID, x, y);
Mat4d rayMatrix = MathUtils.RaySpace(currentRay);
HasScreenPoints hsp = (HasScreenPoints)_selectedEntity;
assert(hsp != null);
ArrayList<Vec3d> points = hsp.getScreenPoints()[0].points;
// Find a point that is within the threshold
if (points.size() <= 2) {
return;
}
int removeInd = 0;
// Find a line segment we are near
for ( ;removeInd < points.size(); ++removeInd) {
Vec4d p = new Vec4d(points.get(removeInd).x, points.get(removeInd).y, points.get(removeInd).z, 1.0d);
double rayAngle = RenderUtils.angleToRay(rayMatrix, p);
if (rayAngle > 0 && rayAngle < 0.01309) { // 0.75 degrees in radians
break;
}
if (removeInd == points.size()) {
// No appropriate point was found
return;
}
}
StringBuilder sb = new StringBuilder();
String pointFormatter = " { %.3f %.3f %.3f m }";
for(int i = 0; i < points.size(); ++i) {
if (i == removeInd) {
continue;
}
Vec3d pt = points.get(i);
sb.append(String.format(pointFormatter, pt.x, pt.y, pt.z));
}
Input<?> pointsInput = _selectedEntity.getInput("Points");
InputAgent.processEntity_Keyword_Value(_selectedEntity, pointsInput, sb.toString());
FrameBox.valueUpdate();
}
private boolean isMouseHandleID(long id) {
return (id < 0); // For now all negative IDs are mouse handles, this may change
}
public boolean handleMouseButton(int windowID, int x, int y, int button, boolean isDown, int modifiers) {
if (button != 1) { return false; }
if (!isDown) {
// Click released
_dragHandleID = 0;
return true; // handled
}
boolean controlDown = (modifiers & WindowInteractionListener.MOD_CTRL) != 0;
boolean altDown = (modifiers & WindowInteractionListener.MOD_ALT) != 0;
if (controlDown && altDown) {
// Check if we can split a line segment
if (_selectedEntity != null && _selectedEntity instanceof HasScreenPoints) {
if ((modifiers & WindowInteractionListener.MOD_SHIFT) != 0) {
removeLineNode(windowID, x, y);
} else {
splitLineEntity(windowID, x, y);
}
return true;
}
}
if (!controlDown) {
return false;
}
Ray pickRay = getRayForMouse(windowID, x, y);
View view = _windowToViewMap.get(windowID);
if (view == null) {
return false;
}
List<PickData> picks = pickForRay(pickRay, view.getID(), true);
Collections.sort(picks, new HandleSorter());
if (picks.size() == 0) {
return false;
}
double mouseHandleDist = Double.POSITIVE_INFINITY;
double entityDist = Double.POSITIVE_INFINITY;
// See if we are hovering over any interaction handles
for (PickData pd : picks) {
if (isMouseHandleID(pd.id) && mouseHandleDist == Double.POSITIVE_INFINITY) {
// this is a mouse handle, remember the handle for future drag events
_dragHandleID = pd.id;
mouseHandleDist = pd.dist;
}
if (_selectedEntity != null && pd.id == _selectedEntity.getEntityNumber()) {
// We clicked on the selected entity
entityDist = pd.dist;
}
}
// The following logical condition effectively checks if we hit the entity first, and did not select
// any mouse handle other than the move handle
if (entityDist != Double.POSITIVE_INFINITY &&
entityDist < mouseHandleDist &&
(_dragHandleID == 0 || _dragHandleID == MOVE_PICK_ID)) {
// Use the entity collision point for dragging instead of the handle collision point
_dragCollisionPoint = pickRay.getPointAtDist(entityDist);
_dragHandleID = MOVE_PICK_ID;
return true;
}
if (mouseHandleDist != Double.POSITIVE_INFINITY) {
// We hit a mouse handle
_dragCollisionPoint = pickRay.getPointAtDist(mouseHandleDist);
return true;
}
return false;
}
public void clearSelection() {
_selectedEntity = null;
}
public void hideExistingPopups() {
synchronized (_popupLock) {
if (_lastPopup == null) {
return;
}
_lastPopup.setVisible(false);
_lastPopup = null;
}
}
public boolean isDragAndDropping() {
// This is such a brutal hack to work around newt's lack of drag and drop support
// Claim we are still dragging for up to 10ms after the last drop failed...
long currTime = System.nanoTime();
return _dndObjectType != null &&
((currTime - _dndDropTime) < 100000000); // Did the last 'drop' happen less than 100 ms ago?
}
public void startDragAndDrop(ObjectType ot) {
_dndObjectType = ot;
}
public void mouseMoved(int windowID, int x, int y) {
Ray currentRay = getRayForMouse(windowID, x, y);
double dist = Plane.XY_PLANE.collisionDist(currentRay);
if (dist == Double.POSITIVE_INFINITY) {
// I dunno...
return;
}
Vec3d xyPlanePoint = currentRay.getPointAtDist(dist);
GUIFrame.instance().showLocatorPosition(xyPlanePoint);
queueRedraw();
}
public void createDNDObject(int windowID, int x, int y) {
Ray currentRay = getRayForMouse(windowID, x, y);
double dist = Plane.XY_PLANE.collisionDist(currentRay);
if (dist == Double.POSITIVE_INFINITY) {
// Unfortunate...
return;
}
Vec3d creationPoint = currentRay.getPointAtDist(dist);
// Create a new instance
Class<? extends Entity> proto = _dndObjectType.getJavaClass();
String name = proto.getSimpleName();
Entity ent = InputAgent.defineEntityWithUniqueName(proto, name, true);
// We are no longer drag-and-dropping
_dndObjectType = null;
FrameBox.setSelectedEntity(ent);
if (!(ent instanceof DisplayEntity)) {
// This object is not a display entity, so the rest of this method does not apply
return;
}
DisplayEntity dEntity = (DisplayEntity) ent;
try {
dEntity.dragged(creationPoint);
}
catch (InputErrorException e) {}
boolean isFlat = false;
// Shudder....
ArrayList<DisplayModel> displayModels = dEntity.getDisplayModelList();
if (displayModels != null && displayModels.size() > 0) {
DisplayModel dm0 = displayModels.get(0);
if (dm0 instanceof DisplayModelCompat || dm0 instanceof ImageModel || dm0 instanceof TextModel )
isFlat = true;
}
if (dEntity instanceof HasScreenPoints) {
isFlat = true;
}
if (dEntity instanceof Graph) {
isFlat = true;
}
if (isFlat) {
Vec3d size = dEntity.getSize();
Input<?> in = dEntity.getInput("Size");
StringVector args = new StringVector(4);
args.add(String.format("%.3f", size.x));
args.add(String.format("%.3f", size.y));
args.add("0.0");
args.add("m");
InputAgent.apply(dEntity, in, args);
InputAgent.updateInput(dEntity, in, args);
} else {
Input<?> in = dEntity.getInput("Alignment");
StringVector args = new StringVector(3);
args.add("0.0");
args.add("0.0");
args.add("-0.5");
InputAgent.apply(dEntity, in, args);
InputAgent.updateInput(dEntity, in, args);
}
FrameBox.valueUpdate();
}
@Override
public void dragDropEnd(DragSourceDropEvent arg0) {
// Clear the dragging flag
_dndDropTime = System.nanoTime();
}
@Override
public void dragEnter(DragSourceDragEvent arg0) {}
@Override
public void dragExit(DragSourceEvent arg0) {}
@Override
public void dragOver(DragSourceDragEvent arg0) {}
@Override
public void dropActionChanged(DragSourceDragEvent arg0) {}
public AABB getMeshBounds(MeshProtoKey key, boolean block) {
if (block || MeshDataCache.isMeshLoaded(key)) {
return MeshDataCache.getMeshData(key).getDefaultBounds();
}
// The mesh is not loaded and we are non-blocking, so trigger a mesh load and return
MeshDataCache.loadMesh(key, new AtomicBoolean());
return null;
}
public ArrayList<Action.Description> getMeshActions(MeshProtoKey key, boolean block) {
if (block || MeshDataCache.isMeshLoaded(key)) {
return MeshDataCache.getMeshData(key).getActionDescriptions();
}
// The mesh is not loaded and we are non-blocking, so trigger a mesh load and return
MeshDataCache.loadMesh(key, new AtomicBoolean());
return null;
}
/**
* Set the current windows camera to an isometric view
*/
public void setIsometricView() {
CameraControl control = _windowControls.get(_activeWindowID);
if (control == null) return;
// The constant is acos(1/sqrt(3))
control.setRotationAngles(0.955316, Math.PI/4);
}
/**
* Set the current windows camera to an XY plane view
*/
public void setXYPlaneView() {
CameraControl control = _windowControls.get(_activeWindowID);
if (control == null) return;
// Do not look straight down the Z axis as that is actually a degenerate state
control.setRotationAngles(0.0000001, 0.0);
}
public View getActiveView() {
return _windowToViewMap.get(_activeWindowID);
}
public ArrayList<Integer> getOpenWindowIDs() {
return _renderer.getOpenWindowIDs();
}
public String getWindowName(int windowID) {
return _renderer.getWindowName(windowID);
}
public void focusWindow(int windowID) {
_renderer.focusWindow(windowID);
}
/**
* Queue up an off screen rendering, this simply passes the call directly to the renderer
* @param scene
* @param camInfo
* @param width
* @param height
* @return
*/
public Future<BufferedImage> renderOffscreen(ArrayList<RenderProxy> scene, CameraInfo camInfo, int viewID,
int width, int height, Runnable runWhenDone) {
return _renderer.renderOffscreen(scene, viewID, camInfo, width, height, runWhenDone, null);
}
/**
* Return a FutureImage of the equivalent screen renderer from the given position looking at the given center
* @param cameraPos
* @param viewCenter
* @param width - width of returned image
* @param height - height of returned image
* @param target - optional target to prevent re-allocating GPU resources
* @return
*/
public Future<BufferedImage> renderScreenShot(Vec3d cameraPos, Vec3d viewCenter, int viewID,
int width, int height, OffscreenTarget target) {
Vec3d viewDiff = new Vec3d();
viewDiff.sub3(cameraPos, viewCenter);
double rotZ = Math.atan2(viewDiff.x, -viewDiff.y);
double xyDist = Math.hypot(viewDiff.x, viewDiff.y);
double rotX = Math.atan2(xyDist, viewDiff.z);
if (Math.abs(rotX) < 0.005) {
rotZ = 0; // Don't rotate if we are looking straight up or down
}
double viewDist = viewDiff.mag3();
Quaternion rot = new Quaternion();
rot.setRotZAxis(rotZ);
Quaternion tmp = new Quaternion();
tmp.setRotXAxis(rotX);
rot.mult(rot, tmp);
Transform trans = new Transform(cameraPos, rot, 1);
CameraInfo camInfo = new CameraInfo(Math.PI/3, viewDist*0.1, viewDist*10, trans, null);
return _renderer.renderOffscreen(null, viewID, camInfo, width, height, null, target);
}
public Future<BufferedImage> getPreviewForDisplayModel(DisplayModel dm, Runnable notifier) {
return _previewCache.getPreview(dm, notifier);
}
public OffscreenTarget createOffscreenTarget(int width, int height) {
return _renderer.createOffscreenTarget(width, height);
}
public void freeOffscreenTarget(OffscreenTarget target) {
_renderer.freeOffscreenTarget(target);
}
private void takeScreenShot() {
if (_recorder != null)
_recorder.sample();
synchronized(_screenshot) {
_screenshot.set(false);
_recorder = null;
_screenshot.notifyAll();
}
}
public void blockOnScreenShot(VideoRecorder recorder) {
assert(!_screenshot.get());
synchronized (_screenshot) {
_screenshot.set(true);
_recorder = recorder;
queueRedraw();
while (_screenshot.get()) {
try {
_screenshot.wait();
} catch (InterruptedException ex) {}
}
}
}
public void shutdown() {
_timer.cancel();
_finished.set(true);
if (_renderer != null) {
_renderer.shutdown();
}
}
}
|
package com.krux.kafka.consumer;
import com.krux.kafka.helpers.PropertiesUtils;
import com.krux.stdlib.KruxStdLib;
import com.krux.stdlib.shutdown.ShutdownTask;
import joptsimple.OptionParser;
import joptsimple.OptionSet;
import joptsimple.OptionSpec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class KafkaConsumer {
private static final Logger LOG = LoggerFactory.getLogger( KafkaConsumer.class );
private Map<String, Integer> _topicMap;
private Map<String, List<org.apache.kafka.clients.consumer.KafkaConsumer<byte[], byte[]>>> _topicConsumers;
private MessageHandler<?> _handler;
Map<String, ExecutorService> _executors;
Long _consumerPollTimeout;
public KafkaConsumer( OptionSet options, MessageHandler<?> handler ) {
// parse out topic->thread count mappings
List<String> topicThreadMappings = (List<String>) options.valuesOf( "topic-threads" );
Map<String, Integer> topicMap = new HashMap<String, Integer>();
for ( String topicThreadCount : topicThreadMappings ) {
if ( topicThreadCount.contains( "," ) ) {
String[] parts = topicThreadCount.split( "," );
topicMap.put( parts[0], Integer.parseInt( parts[1] ) );
} else {
topicMap.put( topicThreadCount, 1 );
}
}
Properties consumerProps = (Properties) PropertiesUtils.createPropertiesFromOptionSpec( options ).clone();
setUpConsumer( topicMap, handler, consumerProps );
}
public KafkaConsumer( Properties props, Map<String, Integer> topicMap, MessageHandler<?> handler ) {
Properties consumerProps = (Properties) props.clone();
setUpConsumer( topicMap, handler, consumerProps );
}
private void setUpConsumer( Map<String, Integer> topicMap, MessageHandler<?> handler, Properties consumerProps ) {
_executors = new HashMap<String, ExecutorService>();
_topicConsumers = new HashMap<String, List<org.apache.kafka.clients.consumer.KafkaConsumer<byte[], byte[]>>>();
// Get consumer poll inteval from CLI options
_consumerPollTimeout = (Long) consumerProps.get("consumer.poll.timeout");
// Remove the consumer poll interval so all properties can be passed to KafkaConsumer() clas
consumerProps.remove("consumer.poll.timeout");
for ( String topic : topicMap.keySet() ) {
String normalizedTopic = topic.replace( ".", "_" );
String normalizedConsumerGroupId = getGroupId( consumerProps.getProperty( "group.id" ), normalizedTopic );
consumerProps.setProperty( "group.id", normalizedConsumerGroupId );
LOG.warn( "Consuming topic '" + topic + "' with group.id '" + normalizedConsumerGroupId + "'" );
LOG.warn( consumerProps.toString() );
List<org.apache.kafka.clients.consumer.KafkaConsumer<byte[], byte[]>> consumers = new ArrayList<>();
// Read thread count for topic and create that many consumers
for (int i = 0; i < topicMap.get(topic); i++) {
consumers.add(new org.apache.kafka.clients.consumer.KafkaConsumer<byte[], byte[]>( consumerProps ));
}
_topicConsumers.put( topic, consumers);
}
_topicMap = topicMap;
_handler = handler;
}
private String getGroupId( String groupProperty, String normalizedTopic ) {
LOG.warn( "*****groupProperty: " + groupProperty );
if ( groupProperty == null || groupProperty.trim().equals( "" ) || groupProperty.equals( "null" ) ) {
try {
LOG.warn( "*****host: " + InetAddress.getLocalHost().getHostName() );
groupProperty = InetAddress.getLocalHost().getHostName().split( "\\." )[0].trim();
} catch ( UnknownHostException e ) {
LOG.error( "can't resolve hostname", e );
}
}
return groupProperty + "_" + normalizedTopic;
}
public void start() {
LOG.info( "Creating consumers: " );
for ( String topic : _topicMap.keySet() ) {
LOG.info( "Creating consumers for topic {}", topic);
List<org.apache.kafka.clients.consumer.KafkaConsumer<byte[], byte[]>> consumers =_topicConsumers.get( topic );
LOG.info( "consumers.size() : " + consumers.size() );
// now create an object to consume the messages
ExecutorService executor = Executors.newFixedThreadPool( _topicMap.get( topic ) );
_executors.put( topic, executor );
LOG.info( "Creating executor for topic : " + topic );
for ( org.apache.kafka.clients.consumer.KafkaConsumer<byte[], byte[]> consumer : consumers ) {
LOG.info( "Subscribing consumer for topic : " + topic );
executor.submit( new ConsumerThread( consumer, _consumerPollTimeout, topic, _handler ) );
}
}
KruxStdLib.registerShutdownHook( new ShutdownTask( 50 ) {
@Override
public void run() {
LOG.warn( "Shutting down kafka consumer threads" );
stop();
}
} );
}
public void stop() {
for ( String key : _topicMap.keySet() ) {
ExecutorService executor = _executors.get( key );
executor.shutdownNow();
try {
executor.awaitTermination( 3, TimeUnit.SECONDS );
} catch ( InterruptedException e ) {
LOG.error( "Error waiting for consumer thread executors to terminate", e );
}
}
}
public static void addStandardOptionsToParser( OptionParser parser ) {
OptionSpec<String> consumerGroupName = parser.accepts( "group.id", "Consumer group name." ).withRequiredArg()
.ofType( String.class );
OptionSpec<String> kafkaBrokers = parser
.accepts(
"bootstrap.servers",
"This is for bootstrapping and the producer will only use it for getting metadata (topics, partitions and replicas). The socket connections for sending the actual data will be established based on the broker information returned in the metadata. The format is host1:port1,host2:port2, and the list can be a subset of brokers or a VIP pointing to a subset of brokers." )
.withOptionalArg().ofType( String.class ).defaultsTo( "localhost:9092" );
OptionSpec<Long> consumerPollTimeout = parser
.accepts(
"consumer.poll.timeout",
"The amount of time in milliseconds before timeout for each poll to the kafka servers" )
.withOptionalArg().ofType( Long.class ).defaultsTo( 100L );
OptionSpec<String> keyDeserializer = parser
.accepts("key.deserializer",
"Deserializer class for key that implements the org.apache.kafka.common.serialization.Deserializer interface.")
.withOptionalArg().ofType( String.class ).defaultsTo( "org.apache.kafka.common.serialization.ByteArrayDeserializer" );
OptionSpec<String> valueDeserializer = parser
.accepts("value.deserializer",
"Deserializer class for value that implements the org.apache.kafka.common.serialization.Deserializer interface.")
.withOptionalArg().ofType( String.class ).defaultsTo( "org.apache.kafka.common.serialization.ByteArrayDeserializer" );
OptionSpec<Integer> receiveBufferSize = parser
.accepts( "receive.buffer.bytes", "The socket receive buffer for network requests" )
.withRequiredArg().ofType( Integer.class ).defaultsTo( 1000 * 1024 );
OptionSpec<Boolean> commitOffsets = parser
.accepts(
"enable.auto.commit",
"If true, periodically commit to ZooKeeper the offset of messages already fetched by the consumer. This committed offset will be used when the process fails as the position from which the new consumer will begin." )
.withRequiredArg().ofType( Boolean.class ).defaultsTo( Boolean.TRUE );
OptionSpec<Integer> autoCommitInterval = parser
.accepts( "auto.commit.interval.ms",
"The frequency in ms that the consumer offsets are committed to zookeeper." ).withRequiredArg()
.ofType( Integer.class ).defaultsTo( 15 * 1000 );
OptionSpec<Integer> fetchMinBytes = parser
.accepts(
"fetch.min.bytes",
"The minimum amount of data the server should return for a fetch request. If insufficient data is available the request will wait for that much data to accumulate before answering the request." )
.withRequiredArg().ofType( Integer.class ).defaultsTo( 1 );
OptionSpec<Integer> fetchWaitMaxMs = parser
.accepts(
"fetch.max.wait.ms",
"The maximum amount of time the server will block before answering the fetch request if there isn't sufficient data to immediately satisfy fetch.min.bytes" )
.withRequiredArg().ofType( Integer.class ).defaultsTo( 100 );
OptionSpec<String> autoOffsetReset = parser
.accepts(
"auto.offset.reset",
"What to do when there is no initial offset in ZooKeeper or if an offset is out of range: * smallest : automatically reset the offset to the smallest offset * largest : automatically reset the offset to the largest offset * anything else: throw exception to the consumer" )
.withRequiredArg().ofType( String.class ).defaultsTo( "earliest" );
OptionSpec<String> clientId = parser
.accepts(
"client.id",
"The client id is a user-specified string sent in each request to help trace calls. It should logically identify the application making the request." )
.withRequiredArg().ofType( String.class ).defaultsTo( "group" );
OptionSpec<Integer> requestTimeoutMs = parser
.accepts(
"request.timeout.ms",
"The configuration controls the maximum amount of time the client will wait for the response of a request. If the response is not received before the timeout elapses the client will resend the request if necessary or fail the request if retries are exhausted." )
.withRequiredArg().ofType( Integer.class ).defaultsTo( 10000 );
OptionSpec<Integer> sessionTimeoutMs = parser
.accepts(
"session.timeout.ms",
"ZooKeeper session timeout. If the consumer fails to heartbeat to ZooKeeper for this period of time it is considered dead and a rebalance will occur." )
.withRequiredArg().ofType( Integer.class ).defaultsTo( 6000 );
OptionSpec<String> topicThreadMapping = parser
.accepts(
"topic-threads",
"Topic and number of threads to listen to that topic. Example: '--topic.threads topic1,4' "
+ "would configure 4 threads to consumer messages from the 'topic1' topic. Multiple topics can be configured "
+ "by passing multiple cl options, e.g.: '--topic.threads topic1,4 --topic.threads topic2,8'. At least"
+ "one --topic.thread must be specified. The thread pool sizes can be omitted, like so: '--topic.threads topic1 "
+ "--topic.threads topic2' If so, each topic will be assigned a single thread for consumption." )
.withRequiredArg().ofType( String.class );
}
public static OptionParser getStandardOptionParser() {
OptionParser parser = new OptionParser();
addStandardOptionsToParser( parser );
return parser;
}
}
|
package com.lookout.jenkins;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.Launcher;
import hudson.Util;
import hudson.matrix.MatrixAggregatable;
import hudson.matrix.MatrixAggregator;
import hudson.matrix.MatrixRun;
import hudson.matrix.MatrixBuild;
import hudson.matrix.MatrixProject;
import hudson.model.BuildListener;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.tasks.BuildWrapper;
import hudson.tasks.BuildWrapperDescriptor;
import hudson.tasks.Shell;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import jenkins.model.Jenkins;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
public class EnvironmentScript extends BuildWrapper implements MatrixAggregatable {
private final String script;
private final boolean onlyRunOnParent;
@DataBoundConstructor
public EnvironmentScript(String script, boolean onlyRunOnParent) {
this.script = script;
this.onlyRunOnParent = onlyRunOnParent;
}
/**
* We'll use this from the <tt>config.jelly</tt>.
*/
public String getScript() {
return script;
}
/**
* @return Whether or not we only run this on the {@link MatrixBuild} parent, or on the individual {@link MatrixRun}s.
*/
public boolean shouldOnlyRunOnParent () {
return onlyRunOnParent;
}
@SuppressWarnings("rawtypes")
@Override
public Environment setUp(AbstractBuild build,
final Launcher launcher,
final BuildListener listener) throws IOException, InterruptedException {
if ((build instanceof MatrixRun) && shouldOnlyRunOnParent()) {
// If this is a matrix run and we have the onlyRunOnParent option
// enabled, we just retrieve the persisted environment from the
// PersistedEnvironment Action.
MatrixBuild parent = ((MatrixRun)build).getParentBuild();
if (parent != null) {
PersistedEnvironment persisted = parent.getAction(PersistedEnvironment.class);
if (persisted != null) {
return persisted.getEnvironment();
} else {
listener.error("[environment-script] Unable to load persisted environment from matrix parent job, not injecting any variables");
return new Environment() {};
}
} else {
// If there's no parent, then the module build was triggered
// manually, so we generate a new environment.
return generateEnvironment (build, launcher, listener);
}
} else {
// Otherwise we generate a new one.
return generateEnvironment (build, launcher, listener);
}
}
private Environment generateEnvironment(AbstractBuild<?, ?> build,
final Launcher launcher,
final BuildListener listener) throws IOException, InterruptedException {
// First we create the script in a temporary directory.
FilePath ws = build.getWorkspace(), scriptFile;
try {
// Create a file in the system temporary directory with our script in it.
scriptFile = ws.createTextTempFile(build.getProject().getName(), ".sh", script, false);
} catch (IOException e) {
Util.displayIOException(e,listener);
e.printStackTrace(listener.fatalError(Messages.EnvironmentScriptWrapper_UnableToProduceScript()));
return null;
}
// Then we execute the script, putting STDOUT in commandOutput.
ByteArrayOutputStream commandOutput = new ByteArrayOutputStream();
int returnCode =
launcher.launch().cmds(buildCommandLine(scriptFile))
.envs(build.getEnvironment(listener))
.stderr(listener.getLogger())
.stdout(commandOutput)
.pwd(ws).join();
if (returnCode != 0) {
listener.fatalError(Messages.EnvironmentScriptWrapper_UnableToExecuteScript(returnCode));
return null;
}
// Pass the output of the command to the Properties loader.
ByteArrayInputStream propertiesInput = new ByteArrayInputStream(commandOutput.toByteArray());
Properties properties = new Properties();
try {
properties.load(propertiesInput);
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError(Messages.EnvironmentScriptWrapper_UnableToParseScriptOutput()));
return null;
}
// We sort overrides and additions into two different buckets, because they have to be processed in sequence.
// See hudson.EnvVars.override for how this logic works.
final Map<String, String> envAdditions = new HashMap<String, String>(), envOverrides = new HashMap<String, String>();
for (String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
listener.getLogger().println("[environment-script] Adding variable '" + key + "' with value '" + value + "'");
if (key.indexOf('+') > 0)
envOverrides.put(key, value);
else
envAdditions.put(key, value);
}
return new Environment() {
@Override
public void buildEnvVars(Map<String, String> env) {
// A little roundabout, but allows us to do overrides per
// how EnvVars#override works (PATH+unique=/foo/bar)
EnvVars envVars = new EnvVars(env);
envVars.putAll(envAdditions);
envVars.overrideAll(envOverrides);
env.putAll(envVars);
}
};
}
// Mostly stolen from hudson.tasks.Shell.buildCommandLine.
public String[] buildCommandLine(FilePath scriptFile) {
// Respect shebangs
if (script.startsWith("#!")) {
// Find first line, or just entire script if it's one line.
int end = script.indexOf('\n');
if (end < 0)
end = script.length();
String shell = script.substring(0, end).trim();
shell = shell.substring(2);
List<String> args = new ArrayList<String>(Arrays.asList(Util.tokenize(shell)));
args.add(scriptFile.getRemote());
return args.toArray(new String[args.size()]);
} else {
Shell.DescriptorImpl shellDescriptor = Jenkins.getInstance().getDescriptorByType(Shell.DescriptorImpl.class);
String shell = shellDescriptor.getShellOrDefault(scriptFile.getChannel());
return new String[] { shell, "-xe", scriptFile.getRemote() };
}
}
/**
* Create an aggregator that will calculate the environment once iff
* onlyRunOnParent is true.
*
* The aggregator we return is called on the parent job for matrix jobs. In
* it we generate the environment once and persist it in an Action (of type
* {@link PersistedEnvironment}) if the job has onlyRunOnParent enabled. The
* subjobs ("configuration runs") will retrieve this and apply it to their
* environment, without performing the calculation.
*/
public MatrixAggregator createAggregator(MatrixBuild build, Launcher launcher, BuildListener listener) {
if (!shouldOnlyRunOnParent()) {
return null;
}
return new MatrixAggregator(build, launcher, listener) {
@Override
public boolean startBuild() throws InterruptedException, IOException {
Environment env = generateEnvironment(build, launcher, listener);
if (env == null) {
return false;
}
build.addAction(new PersistedEnvironment(env));
build.getEnvironments().add(env);
return true;
}
};
}
/**
* Descriptor for {@link EnvironmentScript}. Used as a singleton.
* The class is marked as public so that it can be accessed from views.
*
*/
@Extension
public static final class DescriptorImpl extends BuildWrapperDescriptor {
/**
* This human readable name is used in the configuration screen.
*/
public String getDisplayName() {
return "Generate environment variables from script";
}
@Override
public boolean isApplicable(AbstractProject<?, ?> project) {
return true;
}
public boolean isMatrix(StaplerRequest request) {
return (request.findAncestorObject(AbstractProject.class) instanceof MatrixProject);
}
}
}
|
package com.microsoft.sqlserver.jdbc;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.security.KeyStore;
import java.security.Provider;
import java.security.Security;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.sql.Timestamp;
import java.text.MessageFormat;
import java.time.OffsetDateTime;
import java.time.OffsetTime;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SimpleTimeZone;
import java.util.TimeZone;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import javax.xml.bind.DatatypeConverter;
final class TDS {
// TDS protocol versions
static final int VER_DENALI = 0x74000004; // TDS 7.4
static final int VER_KATMAI = 0x730B0003; // TDS 7.3B(includes null bit compression)
static final int VER_YUKON = 0x72090002; // TDS 7.2
static final int VER_UNKNOWN = 0x00000000; // Unknown/uninitialized
static final int TDS_RET_STAT = 0x79;
static final int TDS_COLMETADATA = 0x81;
static final int TDS_TABNAME = 0xA4;
static final int TDS_COLINFO = 0xA5;
static final int TDS_ORDER = 0xA9;
static final int TDS_ERR = 0xAA;
static final int TDS_MSG = 0xAB;
static final int TDS_RETURN_VALUE = 0xAC;
static final int TDS_LOGIN_ACK = 0xAD;
static final int TDS_FEATURE_EXTENSION_ACK = 0xAE;
static final int TDS_ROW = 0xD1;
static final int TDS_NBCROW = 0xD2;
static final int TDS_ENV_CHG = 0xE3;
static final int TDS_SSPI = 0xED;
static final int TDS_DONE = 0xFD;
static final int TDS_DONEPROC = 0xFE;
static final int TDS_DONEINPROC = 0xFF;
static final int TDS_FEDAUTHINFO = 0xEE;
// FedAuth
static final int TDS_FEATURE_EXT_FEDAUTH = 0x02;
static final int TDS_FEDAUTH_LIBRARY_SECURITYTOKEN = 0x01;
static final int TDS_FEDAUTH_LIBRARY_ADAL = 0x02;
static final int TDS_FEDAUTH_LIBRARY_RESERVED = 0x7F;
static final byte ADALWORKFLOW_ACTIVEDIRECTORYPASSWORD = 0x01;
static final byte ADALWORKFLOW_ACTIVEDIRECTORYINTEGRATED = 0x02;
static final byte FEDAUTH_INFO_ID_STSURL = 0x01; // FedAuthInfoData is token endpoint URL from which to acquire fed auth token
static final byte FEDAUTH_INFO_ID_SPN = 0x02; // FedAuthInfoData is the SPN to use for acquiring fed auth token
// AE constants
static final int TDS_FEATURE_EXT_AE = 0x04;
static final int MAX_SUPPORTED_TCE_VERSION = 0x01; // max version
static final int CUSTOM_CIPHER_ALGORITHM_ID = 0; // max version
static final int AES_256_CBC = 1;
static final int AEAD_AES_256_CBC_HMAC_SHA256 = 2;
static final int AE_METADATA = 0x08;
static final int TDS_TVP = 0xF3;
static final int TVP_ROW = 0x01;
static final int TVP_NULL_TOKEN = 0xFFFF;
static final int TVP_STATUS_DEFAULT = 0x02;
static final int TVP_ORDER_UNIQUE_TOKEN = 0x10;
// TVP_ORDER_UNIQUE_TOKEN flags
static final byte TVP_ORDERASC_FLAG = 0x1;
static final byte TVP_ORDERDESC_FLAG = 0x2;
static final byte TVP_UNIQUE_FLAG = 0x4;
// TVP flags, may be used in other places
static final int FLAG_NULLABLE = 0x01;
static final int FLAG_TVP_DEFAULT_COLUMN = 0x200;
static final int FEATURE_EXT_TERMINATOR = -1;
static final String getTokenName(int tdsTokenType) {
switch (tdsTokenType) {
case TDS_RET_STAT:
return "TDS_RET_STAT (0x79)";
case TDS_COLMETADATA:
return "TDS_COLMETADATA (0x81)";
case TDS_TABNAME:
return "TDS_TABNAME (0xA4)";
case TDS_COLINFO:
return "TDS_COLINFO (0xA5)";
case TDS_ORDER:
return "TDS_ORDER (0xA9)";
case TDS_ERR:
return "TDS_ERR (0xAA)";
case TDS_MSG:
return "TDS_MSG (0xAB)";
case TDS_RETURN_VALUE:
return "TDS_RETURN_VALUE (0xAC)";
case TDS_LOGIN_ACK:
return "TDS_LOGIN_ACK (0xAD)";
case TDS_FEATURE_EXTENSION_ACK:
return "TDS_FEATURE_EXTENSION_ACK (0xAE)";
case TDS_ROW:
return "TDS_ROW (0xD1)";
case TDS_NBCROW:
return "TDS_NBCROW (0xD2)";
case TDS_ENV_CHG:
return "TDS_ENV_CHG (0xE3)";
case TDS_SSPI:
return "TDS_SSPI (0xED)";
case TDS_DONE:
return "TDS_DONE (0xFD)";
case TDS_DONEPROC:
return "TDS_DONEPROC (0xFE)";
case TDS_DONEINPROC:
return "TDS_DONEINPROC (0xFF)";
case TDS_FEDAUTHINFO:
return "TDS_FEDAUTHINFO (0xEE)";
default:
return "unknown token (0x" + Integer.toHexString(tdsTokenType).toUpperCase() + ")";
}
}
// RPC ProcIDs for use with RPCRequest (PKT_RPC) calls
static final short PROCID_SP_CURSOR = 1;
static final short PROCID_SP_CURSOROPEN = 2;
static final short PROCID_SP_CURSORPREPARE = 3;
static final short PROCID_SP_CURSOREXECUTE = 4;
static final short PROCID_SP_CURSORPREPEXEC = 5;
static final short PROCID_SP_CURSORUNPREPARE = 6;
static final short PROCID_SP_CURSORFETCH = 7;
static final short PROCID_SP_CURSOROPTION = 8;
static final short PROCID_SP_CURSORCLOSE = 9;
static final short PROCID_SP_EXECUTESQL = 10;
static final short PROCID_SP_PREPARE = 11;
static final short PROCID_SP_EXECUTE = 12;
static final short PROCID_SP_PREPEXEC = 13;
static final short PROCID_SP_PREPEXECRPC = 14;
static final short PROCID_SP_UNPREPARE = 15;
// Constants for use with cursor RPCs
static final short SP_CURSOR_OP_UPDATE = 1;
static final short SP_CURSOR_OP_DELETE = 2;
static final short SP_CURSOR_OP_INSERT = 4;
static final short SP_CURSOR_OP_REFRESH = 8;
static final short SP_CURSOR_OP_LOCK = 16;
static final short SP_CURSOR_OP_SETPOSITION = 32;
static final short SP_CURSOR_OP_ABSOLUTE = 64;
// Constants for server-cursored result sets.
// See the Engine Cursors Functional Specification for details.
static final int FETCH_FIRST = 1;
static final int FETCH_NEXT = 2;
static final int FETCH_PREV = 4;
static final int FETCH_LAST = 8;
static final int FETCH_ABSOLUTE = 16;
static final int FETCH_RELATIVE = 32;
static final int FETCH_REFRESH = 128;
static final int FETCH_INFO = 256;
static final int FETCH_PREV_NOADJUST = 512;
static final byte RPC_OPTION_NO_METADATA = (byte) 0x02;
// Transaction manager request types
static final short TM_GET_DTC_ADDRESS = 0;
static final short TM_PROPAGATE_XACT = 1;
static final short TM_BEGIN_XACT = 5;
static final short TM_PROMOTE_PROMOTABLE_XACT = 6;
static final short TM_COMMIT_XACT = 7;
static final short TM_ROLLBACK_XACT = 8;
static final short TM_SAVE_XACT = 9;
static final byte PKT_QUERY = 1;
static final byte PKT_RPC = 3;
static final byte PKT_REPLY = 4;
static final byte PKT_CANCEL_REQ = 6;
static final byte PKT_BULK = 7;
static final byte PKT_DTC = 14;
static final byte PKT_LOGON70 = 16; // 0x10
static final byte PKT_SSPI = 17;
static final byte PKT_PRELOGIN = 18; // 0x12
static final byte PKT_FEDAUTH_TOKEN_MESSAGE = 8; // Authentication token for federated authentication
static final byte STATUS_NORMAL = 0x00;
static final byte STATUS_BIT_EOM = 0x01;
static final byte STATUS_BIT_ATTENTION = 0x02;// this is called ignore bit in TDS spec
static final byte STATUS_BIT_RESET_CONN = 0x08;
// Various TDS packet size constants
static final int INVALID_PACKET_SIZE = -1;
static final int INITIAL_PACKET_SIZE = 4096;
static final int MIN_PACKET_SIZE = 512;
static final int MAX_PACKET_SIZE = 32767;
static final int DEFAULT_PACKET_SIZE = 8000;
static final int SERVER_PACKET_SIZE = 0; // Accept server's configured packet size
// TDS packet header size and offsets
static final int PACKET_HEADER_SIZE = 8;
static final int PACKET_HEADER_MESSAGE_TYPE = 0;
static final int PACKET_HEADER_MESSAGE_STATUS = 1;
static final int PACKET_HEADER_MESSAGE_LENGTH = 2;
static final int PACKET_HEADER_SPID = 4;
static final int PACKET_HEADER_SEQUENCE_NUM = 6;
static final int PACKET_HEADER_WINDOW = 7; // Reserved/Not used
// MARS header length:
// 2 byte header type
// 8 byte transaction descriptor
// 4 byte outstanding request count
static final int MARS_HEADER_LENGTH = 18; // 2 byte header type, 8 byte transaction descriptor,
static final int TRACE_HEADER_LENGTH = 26; // header length (4) + header type (2) + guid (16) + Sequence number size (4)
static final short HEADERTYPE_TRACE = 3; // trace header type
// Message header length
static final int MESSAGE_HEADER_LENGTH = MARS_HEADER_LENGTH + 4; // length includes message header itself
static final byte B_PRELOGIN_OPTION_VERSION = 0x00;
static final byte B_PRELOGIN_OPTION_ENCRYPTION = 0x01;
static final byte B_PRELOGIN_OPTION_INSTOPT = 0x02;
static final byte B_PRELOGIN_OPTION_THREADID = 0x03;
static final byte B_PRELOGIN_OPTION_MARS = 0x04;
static final byte B_PRELOGIN_OPTION_TRACEID = 0x05;
static final byte B_PRELOGIN_OPTION_FEDAUTHREQUIRED = 0x06;
static final byte B_PRELOGIN_OPTION_TERMINATOR = (byte) 0xFF;
// Login option byte 1
static final byte LOGIN_OPTION1_ORDER_X86 = 0x00;
static final byte LOGIN_OPTION1_ORDER_6800 = 0x01;
static final byte LOGIN_OPTION1_CHARSET_ASCII = 0x00;
static final byte LOGIN_OPTION1_CHARSET_EBCDIC = 0x02;
static final byte LOGIN_OPTION1_FLOAT_IEEE_754 = 0x00;
static final byte LOGIN_OPTION1_FLOAT_VAX = 0x04;
static final byte LOGIN_OPTION1_FLOAT_ND5000 = 0x08;
static final byte LOGIN_OPTION1_DUMPLOAD_ON = 0x00;
static final byte LOGIN_OPTION1_DUMPLOAD_OFF = 0x10;
static final byte LOGIN_OPTION1_USE_DB_ON = 0x00;
static final byte LOGIN_OPTION1_USE_DB_OFF = 0x20;
static final byte LOGIN_OPTION1_INIT_DB_WARN = 0x00;
static final byte LOGIN_OPTION1_INIT_DB_FATAL = 0x40;
static final byte LOGIN_OPTION1_SET_LANG_OFF = 0x00;
static final byte LOGIN_OPTION1_SET_LANG_ON = (byte) 0x80;
// Login option byte 2
static final byte LOGIN_OPTION2_INIT_LANG_WARN = 0x00;
static final byte LOGIN_OPTION2_INIT_LANG_FATAL = 0x01;
static final byte LOGIN_OPTION2_ODBC_OFF = 0x00;
static final byte LOGIN_OPTION2_ODBC_ON = 0x02;
static final byte LOGIN_OPTION2_TRAN_BOUNDARY_OFF = 0x00;
static final byte LOGIN_OPTION2_TRAN_BOUNDARY_ON = 0x04;
static final byte LOGIN_OPTION2_CACHE_CONNECTION_OFF = 0x00;
static final byte LOGIN_OPTION2_CACHE_CONNECTION_ON = 0x08;
static final byte LOGIN_OPTION2_USER_NORMAL = 0x00;
static final byte LOGIN_OPTION2_USER_SERVER = 0x10;
static final byte LOGIN_OPTION2_USER_REMUSER = 0x20;
static final byte LOGIN_OPTION2_USER_SQLREPL = 0x30;
static final byte LOGIN_OPTION2_INTEGRATED_SECURITY_OFF = 0x00;
static final byte LOGIN_OPTION2_INTEGRATED_SECURITY_ON = (byte) 0x80;
// Login option byte 3
static final byte LOGIN_OPTION3_DEFAULT = 0x00;
static final byte LOGIN_OPTION3_CHANGE_PASSWORD = 0x01;
static final byte LOGIN_OPTION3_SEND_YUKON_BINARY_XML = 0x02;
static final byte LOGIN_OPTION3_USER_INSTANCE = 0x04;
static final byte LOGIN_OPTION3_UNKNOWN_COLLATION_HANDLING = 0x08;
static final byte LOGIN_OPTION3_FEATURE_EXTENSION = 0x10;
// Login type flag (bits 5 - 7 reserved for future use)
static final byte LOGIN_SQLTYPE_DEFAULT = 0x00;
static final byte LOGIN_SQLTYPE_TSQL = 0x01;
static final byte LOGIN_SQLTYPE_ANSI_V1 = 0x02;
static final byte LOGIN_SQLTYPE_ANSI89_L1 = 0x03;
static final byte LOGIN_SQLTYPE_ANSI89_L2 = 0x04;
static final byte LOGIN_SQLTYPE_ANSI89_IEF = 0x05;
static final byte LOGIN_SQLTYPE_ANSI89_ENTRY = 0x06;
static final byte LOGIN_SQLTYPE_ANSI89_TRANS = 0x07;
static final byte LOGIN_SQLTYPE_ANSI89_INTER = 0x08;
static final byte LOGIN_SQLTYPE_ANSI89_FULL = 0x09;
static final byte LOGIN_OLEDB_OFF = 0x00;
static final byte LOGIN_OLEDB_ON = 0x10;
static final byte LOGIN_READ_ONLY_INTENT = 0x20;
static final byte LOGIN_READ_WRITE_INTENT = 0x00;
static final byte ENCRYPT_OFF = 0x00;
static final byte ENCRYPT_ON = 0x01;
static final byte ENCRYPT_NOT_SUP = 0x02;
static final byte ENCRYPT_REQ = 0x03;
static final byte ENCRYPT_INVALID = (byte) 0xFF;
static final String getEncryptionLevel(int level) {
switch (level) {
case ENCRYPT_OFF:
return "OFF";
case ENCRYPT_ON:
return "ON";
case ENCRYPT_NOT_SUP:
return "NOT SUPPORTED";
case ENCRYPT_REQ:
return "REQUIRED";
default:
return "unknown encryption level (0x" + Integer.toHexString(level).toUpperCase() + ")";
}
}
// Prelogin packet length, including the tds header,
// version, encrpytion, and traceid data sessions.
// For detailed info, please check the definition of
// preloginRequest in Prelogin function.
static final byte B_PRELOGIN_MESSAGE_LENGTH = 67;
static final byte B_PRELOGIN_MESSAGE_LENGTH_WITH_FEDAUTH = 73;
// Scroll options and concurrency options lifted out
// of the the Yukon cursors spec for sp_cursoropen.
final static int SCROLLOPT_KEYSET = 1;
final static int SCROLLOPT_DYNAMIC = 2;
final static int SCROLLOPT_FORWARD_ONLY = 4;
final static int SCROLLOPT_STATIC = 8;
final static int SCROLLOPT_FAST_FORWARD = 16;
final static int SCROLLOPT_PARAMETERIZED_STMT = 4096;
final static int SCROLLOPT_AUTO_FETCH = 8192;
final static int SCROLLOPT_AUTO_CLOSE = 16384;
final static int CCOPT_READ_ONLY = 1;
final static int CCOPT_SCROLL_LOCKS = 2;
final static int CCOPT_OPTIMISTIC_CC = 4;
final static int CCOPT_OPTIMISTIC_CCVAL = 8;
final static int CCOPT_ALLOW_DIRECT = 8192;
final static int CCOPT_UPDT_IN_PLACE = 16384;
// Result set rows include an extra, "hidden" ROWSTAT column which indicates
// the overall success or failure of the row fetch operation. With a keyset
// cursor, the value in the ROWSTAT column indicates whether the row has been
// deleted from the database.
static final int ROWSTAT_FETCH_SUCCEEDED = 1;
static final int ROWSTAT_FETCH_MISSING = 2;
// ColumnInfo status
final static int COLINFO_STATUS_EXPRESSION = 0x04;
final static int COLINFO_STATUS_KEY = 0x08;
final static int COLINFO_STATUS_HIDDEN = 0x10;
final static int COLINFO_STATUS_DIFFERENT_NAME = 0x20;
final static int MAX_FRACTIONAL_SECONDS_SCALE = 7;
final static Timestamp MAX_TIMESTAMP = Timestamp.valueOf("2079-06-06 23:59:59");
final static Timestamp MIN_TIMESTAMP = Timestamp.valueOf("1900-01-01 00:00:00");
static int nanosSinceMidnightLength(int scale) {
final int[] scaledLengths = {3, 3, 3, 4, 4, 5, 5, 5};
assert scale >= 0;
assert scale <= MAX_FRACTIONAL_SECONDS_SCALE;
return scaledLengths[scale];
}
final static int DAYS_INTO_CE_LENGTH = 3;
final static int MINUTES_OFFSET_LENGTH = 2;
// Number of days in a "normal" (non-leap) year according to SQL Server.
final static int DAYS_PER_YEAR = 365;
final static int BASE_YEAR_1900 = 1900;
final static int BASE_YEAR_1970 = 1970;
final static String BASE_DATE_1970 = "1970-01-01";
static int timeValueLength(int scale) {
return nanosSinceMidnightLength(scale);
}
static int datetime2ValueLength(int scale) {
return DAYS_INTO_CE_LENGTH + nanosSinceMidnightLength(scale);
}
static int datetimeoffsetValueLength(int scale) {
return DAYS_INTO_CE_LENGTH + MINUTES_OFFSET_LENGTH + nanosSinceMidnightLength(scale);
}
// TDS is just a namespace - it can't be instantiated.
private TDS() {
}
}
class Nanos {
static final int PER_SECOND = 1000000000;
static final int PER_MAX_SCALE_INTERVAL = PER_SECOND / (int) Math.pow(10, TDS.MAX_FRACTIONAL_SECONDS_SCALE);
static final int PER_MILLISECOND = PER_SECOND / 1000;
static final long PER_DAY = 24 * 60 * 60 * (long) PER_SECOND;
private Nanos() {
}
}
// Constants relating to the historically accepted Julian-Gregorian calendar cutover date (October 15, 1582).
// Used in processing SQL Server temporal data types whose date component may precede that date.
// Scoping these constants to a class defers their initialization to first use.
class GregorianChange {
// Cutover date for a pure Gregorian calendar - that is, a proleptic Gregorian calendar with
// Gregorian leap year behavior throughout its entire range. This is the cutover date is used
// with temporal server values, which are represented in terms of number of days relative to a
// base date.
static final java.util.Date PURE_CHANGE_DATE = new java.util.Date(Long.MIN_VALUE);
// The standard Julian to Gregorian cutover date (October 15, 1582) that the JDBC temporal
// classes (Time, Date, Timestamp) assume when converting to and from their UTC milliseconds
// representations.
static final java.util.Date STANDARD_CHANGE_DATE = (new GregorianCalendar(Locale.US)).getGregorianChange();
// A hint as to the number of days since 1/1/0001, past which we do not need to
// not rationalize the difference between SQL Server behavior (pure Gregorian)
// and Java behavior (standard Gregorian).
// Not having to rationalize the difference has a substantial (measured) performance benefit
// for temporal getters.
// The hint does not need to be exact, as long as it's later than the actual change date.
static final int DAYS_SINCE_BASE_DATE_HINT = DDC.daysSinceBaseDate(1583, 1, 1);
// Extra days that need to added to a pure gregorian date, post the gergorian
// cut over date, to match the default julian-gregorain calendar date of java.
static final int EXTRA_DAYS_TO_BE_ADDED;
static {
// This issue refers to the following bugs in java(same issue).
// The issue is fixed in JRE 1.7
// and exists in all the older versions.
// Due to the above bug, in older JVM versions(1.6 and before),
// the date calculation is incorrect at the Gregorian cut over date.
// i.e. the next date after Oct 4th 1582 is Oct 17th 1582, where as
// it should have been Oct 15th 1582.
// We intentionally do not make a check based on JRE version.
// If we do so, our code would break if the bug is fixed in a later update
// to an older JRE. So, we check for the existence of the bug instead.
GregorianCalendar cal = new GregorianCalendar(Locale.US);
cal.clear();
cal.set(1, 1, 577738, 0, 0, 0);// 577738 = 1+577737(no of days since epoch that brings us to oct 15th 1582)
if (cal.get(Calendar.DAY_OF_MONTH) == 15) {
// If the date calculation is correct(the above bug is fixed),
// post the default gregorian cut over date, the pure gregorian date
// falls short by two days for all dates compared to julian-gregorian date.
// so, we add two extra days for functional correctness.
// Note: other ways, in which this issue can be fixed instead of
// trying to detect the JVM bug is
// a) use unoptimized code path in the function convertTemporalToObject
// b) use cal.add api instead of cal.set api in the current optimized code path
// In both the above approaches, the code is about 6-8 times slower,
// resulting in an overall perf regression of about (10-30)% for perf test cases
EXTRA_DAYS_TO_BE_ADDED = 2;
}
else
EXTRA_DAYS_TO_BE_ADDED = 0;
}
private GregorianChange() {
}
}
// UTC/GMT time zone singleton. The enum type delays initialization until first use.
enum UTC {
INSTANCE;
static final TimeZone timeZone = new SimpleTimeZone(0, "UTC");
}
final class TDSChannel {
private static final Logger logger = Logger.getLogger("com.microsoft.sqlserver.jdbc.internals.TDS.Channel");
final Logger getLogger() {
return logger;
}
private final String traceID;
final public String toString() {
return traceID;
}
private final SQLServerConnection con;
private final TDSWriter tdsWriter;
final TDSWriter getWriter() {
return tdsWriter;
}
final TDSReader getReader(TDSCommand command) {
return new TDSReader(this, con, command);
}
// Socket for raw TCP/IP communications with SQL Server
private Socket tcpSocket;
// Socket for SSL-encrypted communications with SQL Server
private SSLSocket sslSocket;
// Socket providing the communications interface to the driver.
// For SSL-encrypted connections, this is the SSLSocket wrapped
// around the TCP socket. For unencrypted connections, it is
// just the TCP socket itself.
private Socket channelSocket;
// Implementation of a Socket proxy that can switch from TDS-wrapped I/O
// (using the TDSChannel itself) during SSL handshake to raw I/O over
// the TCP/IP socket.
ProxySocket proxySocket = null;
// I/O streams for raw TCP/IP communications with SQL Server
private InputStream tcpInputStream;
private OutputStream tcpOutputStream;
// I/O streams providing the communications interface to the driver.
// For SSL-encrypted connections, these are streams obtained from
// the SSL socket above. They wrap the underlying TCP streams.
// For unencrypted connections, they are just the TCP streams themselves.
private InputStream inputStream;
private OutputStream outputStream;
/** TDS packet payload logger */
private static Logger packetLogger = Logger.getLogger("com.microsoft.sqlserver.jdbc.internals.TDS.DATA");
private final boolean isLoggingPackets = packetLogger.isLoggable(Level.FINEST);
final boolean isLoggingPackets() {
return isLoggingPackets;
}
// Number of TDS messages sent to and received from the server
int numMsgsSent = 0;
int numMsgsRcvd = 0;
// Last SPID received from the server. Used for logging and to tag subsequent outgoing
// packets to facilitate diagnosing problems from the server side.
private int spid = 0;
void setSPID(int spid) {
this.spid = spid;
}
int getSPID() {
return spid;
}
void resetPooledConnection() {
tdsWriter.resetPooledConnection();
}
TDSChannel(SQLServerConnection con) {
this.con = con;
traceID = "TDSChannel (" + con.toString() + ")";
this.tcpSocket = null;
this.sslSocket = null;
this.channelSocket = null;
this.tcpInputStream = null;
this.tcpOutputStream = null;
this.inputStream = null;
this.outputStream = null;
this.tdsWriter = new TDSWriter(this, con);
}
/**
* Opens the physical communications channel (TCP/IP socket and I/O streams) to the SQL Server.
*/
final void open(String host,
int port,
int timeoutMillis,
boolean useParallel,
boolean useTnir,
boolean isTnirFirstAttempt,
int timeoutMillisForFullTimeout) throws SQLServerException {
if (logger.isLoggable(Level.FINER))
logger.finer(this.toString() + ": Opening TCP socket...");
SocketFinder socketFinder = new SocketFinder(traceID, con);
channelSocket = tcpSocket = socketFinder.findSocket(host, port, timeoutMillis, useParallel, useTnir, isTnirFirstAttempt,
timeoutMillisForFullTimeout);
try {
// Set socket options
tcpSocket.setTcpNoDelay(true);
tcpSocket.setKeepAlive(true);
// set SO_TIMEOUT
int socketTimeout = con.getSocketTimeoutMilliseconds();
tcpSocket.setSoTimeout(socketTimeout);
inputStream = tcpInputStream = tcpSocket.getInputStream();
outputStream = tcpOutputStream = tcpSocket.getOutputStream();
}
catch (IOException ex) {
SQLServerException.ConvertConnectExceptionToSQLServerException(host, port, con, ex);
}
}
/**
* Disables SSL on this TDS channel.
*/
void disableSSL() {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Disabling SSL...");
/*
* The mission: To close the SSLSocket and release everything that it is holding onto other than the TCP/IP socket and streams.
*
* The challenge: Simply closing the SSLSocket tries to do additional, unnecessary shutdown I/O over the TCP/IP streams that are bound to the
* socket proxy, resulting in a hang and confusing SQL Server.
*
* Solution: Rewire the ProxySocket's input and output streams (one more time) to closed streams. SSLSocket sees that the streams are already
* closed and does not attempt to do any further I/O on them before closing itself.
*/
// Create a couple of cheap closed streams
InputStream is = new ByteArrayInputStream(new byte[0]);
try {
is.close();
}
catch (IOException e) {
// No reason to expect a brand new ByteArrayInputStream not to close,
// but just in case...
logger.fine("Ignored error closing InputStream: " + e.getMessage());
}
OutputStream os = new ByteArrayOutputStream();
try {
os.close();
}
catch (IOException e) {
// No reason to expect a brand new ByteArrayOutputStream not to close,
// but just in case...
logger.fine("Ignored error closing OutputStream: " + e.getMessage());
}
// Rewire the proxy socket to the closed streams
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Rewiring proxy streams for SSL socket close");
proxySocket.setStreams(is, os);
// Now close the SSL socket. It will see that the proxy socket's streams
// are closed and not try to do any further I/O over them.
try {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Closing SSL socket");
sslSocket.close();
}
catch (IOException e) {
// Don't care if we can't close the SSL socket. We're done with it anyway.
logger.fine("Ignored error closing SSLSocket: " + e.getMessage());
}
// Do not close the proxy socket. Doing so would close our TCP socket
// to which the proxy socket is bound. Instead, just null out the reference
// to free up the few resources it holds onto.
proxySocket = null;
// Finally, with all of the SSL support out of the way, put the TDSChannel
// back to using the TCP/IP socket and streams directly.
inputStream = tcpInputStream;
outputStream = tcpOutputStream;
channelSocket = tcpSocket;
sslSocket = null;
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " SSL disabled");
}
/**
* Used during SSL handshake, this class implements an InputStream that reads SSL handshake response data (framed in TDS messages) from the TDS
* channel.
*/
private class SSLHandshakeInputStream extends InputStream {
private final TDSReader tdsReader;
private final SSLHandshakeOutputStream sslHandshakeOutputStream;
private final Logger logger;
private final String logContext;
SSLHandshakeInputStream(TDSChannel tdsChannel,
SSLHandshakeOutputStream sslHandshakeOutputStream) {
this.tdsReader = tdsChannel.getReader(null);
this.sslHandshakeOutputStream = sslHandshakeOutputStream;
this.logger = tdsChannel.getLogger();
this.logContext = tdsChannel.toString() + " (SSLHandshakeInputStream):";
}
/**
* If there is no handshake response data available to be read from existing packets then this method ensures that the SSL handshake output
* stream has been flushed to the server, and reads another packet (starting the next TDS response message).
*
* Note that simply using TDSReader.ensurePayload isn't sufficient as it does not automatically start the new response message.
*/
private void ensureSSLPayload() throws IOException {
if (0 == tdsReader.available()) {
if (logger.isLoggable(Level.FINEST))
logger.finest(logContext + " No handshake response bytes available. Flushing SSL handshake output stream.");
try {
sslHandshakeOutputStream.endMessage();
}
catch (SQLServerException e) {
logger.finer(logContext + " Ending TDS message threw exception:" + e.getMessage());
throw new IOException(e.getMessage());
}
if (logger.isLoggable(Level.FINEST))
logger.finest(logContext + " Reading first packet of SSL handshake response");
try {
tdsReader.readPacket();
}
catch (SQLServerException e) {
logger.finer(logContext + " Reading response packet threw exception:" + e.getMessage());
throw new IOException(e.getMessage());
}
}
}
public long skip(long n) throws IOException {
if (logger.isLoggable(Level.FINEST))
logger.finest(logContext + " Skipping " + n + " bytes...");
if (n <= 0)
return 0;
if (n > Integer.MAX_VALUE)
n = Integer.MAX_VALUE;
ensureSSLPayload();
try {
tdsReader.skip((int) n);
}
catch (SQLServerException e) {
logger.finer(logContext + " Skipping bytes threw exception:" + e.getMessage());
throw new IOException(e.getMessage());
}
return n;
}
private final byte oneByte[] = new byte[1];
public int read() throws IOException {
int bytesRead;
while (0 == (bytesRead = readInternal(oneByte, 0, oneByte.length)))
;
assert 1 == bytesRead || -1 == bytesRead;
return 1 == bytesRead ? oneByte[0] : -1;
}
public int read(byte[] b) throws IOException {
return readInternal(b, 0, b.length);
}
public int read(byte b[],
int offset,
int maxBytes) throws IOException {
return readInternal(b, offset, maxBytes);
}
private int readInternal(byte b[],
int offset,
int maxBytes) throws IOException {
if (logger.isLoggable(Level.FINEST))
logger.finest(logContext + " Reading " + maxBytes + " bytes...");
ensureSSLPayload();
try {
tdsReader.readBytes(b, offset, maxBytes);
}
catch (SQLServerException e) {
logger.finer(logContext + " Reading bytes threw exception:" + e.getMessage());
throw new IOException(e.getMessage());
}
return maxBytes;
}
}
/**
* Used during SSL handshake, this class implements an OutputStream that writes SSL handshake request data (framed in TDS messages) to the TDS
* channel.
*/
private class SSLHandshakeOutputStream extends OutputStream {
private final TDSWriter tdsWriter;
/** Flag indicating when it is necessary to start a new prelogin TDS message */
private boolean messageStarted;
private final Logger logger;
private final String logContext;
SSLHandshakeOutputStream(TDSChannel tdsChannel) {
this.tdsWriter = tdsChannel.getWriter();
this.messageStarted = false;
this.logger = tdsChannel.getLogger();
this.logContext = tdsChannel.toString() + " (SSLHandshakeOutputStream):";
}
public void flush() throws IOException {
// It seems that the security provider implementation in some JVMs
// (notably SunJSSE in the 6.0 JVM) likes to add spurious calls to
// flush the SSL handshake output stream during SSL handshaking.
// We need to ignore these calls because the SSL handshake payload
// needs to be completely encapsulated in TDS. The SSL handshake
// input stream always ensures that this output stream has been flushed
// before trying to read the response.
if (logger.isLoggable(Level.FINEST))
logger.finest(logContext + " Ignored a request to flush the stream");
}
void endMessage() throws SQLServerException {
// We should only be asked to end the message if we have started one
assert messageStarted;
if (logger.isLoggable(Level.FINEST))
logger.finest(logContext + " Finishing TDS message");
// Flush any remaining bytes through the writer. Since there may be fewer bytes
// ready to send than a full TDS packet, we end the message here and start a new
// one later if additional handshake data needs to be sent.
tdsWriter.endMessage();
messageStarted = false;
}
private final byte singleByte[] = new byte[1];
public void write(int b) throws IOException {
singleByte[0] = (byte) (b & 0xFF);
writeInternal(singleByte, 0, singleByte.length);
}
public void write(byte[] b) throws IOException {
writeInternal(b, 0, b.length);
}
public void write(byte[] b,
int off,
int len) throws IOException {
writeInternal(b, off, len);
}
private void writeInternal(byte[] b,
int off,
int len) throws IOException {
try {
// Start out the handshake request in a new prelogin message. Subsequent
// writes just add handshake data to the request until flushed.
if (!messageStarted) {
if (logger.isLoggable(Level.FINEST))
logger.finest(logContext + " Starting new TDS packet...");
tdsWriter.startMessage(null, TDS.PKT_PRELOGIN);
messageStarted = true;
}
if (logger.isLoggable(Level.FINEST))
logger.finest(logContext + " Writing " + len + " bytes...");
tdsWriter.writeBytes(b, off, len);
}
catch (SQLServerException e) {
logger.finer(logContext + " Writing bytes threw exception:" + e.getMessage());
throw new IOException(e.getMessage());
}
}
}
/**
* This class implements an InputStream that just forwards all of its methods to an underlying InputStream.
*
* It is more predictable than FilteredInputStream which forwards some of its read methods directly to the underlying stream, but not others.
*/
private final class ProxyInputStream extends InputStream {
private InputStream filteredStream;
ProxyInputStream(InputStream is) {
filteredStream = is;
}
final void setFilteredStream(InputStream is) {
filteredStream = is;
}
public long skip(long n) throws IOException {
long bytesSkipped;
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Skipping " + n + " bytes");
bytesSkipped = filteredStream.skip(n);
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Skipped " + n + " bytes");
return bytesSkipped;
}
public int available() throws IOException {
int bytesAvailable = filteredStream.available();
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " " + bytesAvailable + " bytes available");
return bytesAvailable;
}
private final byte oneByte[] = new byte[1];
public int read() throws IOException {
int bytesRead;
while (0 == (bytesRead = readInternal(oneByte, 0, oneByte.length)))
;
assert 1 == bytesRead || -1 == bytesRead;
return 1 == bytesRead ? oneByte[0] : -1;
}
public int read(byte[] b) throws IOException {
return readInternal(b, 0, b.length);
}
public int read(byte b[],
int offset,
int maxBytes) throws IOException {
return readInternal(b, offset, maxBytes);
}
private int readInternal(byte b[],
int offset,
int maxBytes) throws IOException {
int bytesRead;
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Reading " + maxBytes + " bytes");
try {
bytesRead = filteredStream.read(b, offset, maxBytes);
}
catch (IOException e) {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " " + e.getMessage());
logger.finer(toString() + " Reading bytes threw exception:" + e.getMessage());
throw e;
}
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Read " + bytesRead + " bytes");
return bytesRead;
}
public boolean markSupported() {
boolean markSupported = filteredStream.markSupported();
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Returning markSupported: " + markSupported);
return markSupported;
}
public void mark(int readLimit) {
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Marking next " + readLimit + " bytes");
filteredStream.mark(readLimit);
}
public void reset() throws IOException {
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Resetting to previous mark");
filteredStream.reset();
}
public void close() throws IOException {
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Closing");
filteredStream.close();
}
}
/**
* This class implements an OutputStream that just forwards all of its methods to an underlying OutputStream.
*
* This class essentially does what FilteredOutputStream does, but is more efficient for our usage. FilteredOutputStream transforms block writes
* to sequences of single-byte writes.
*/
final class ProxyOutputStream extends OutputStream {
private OutputStream filteredStream;
ProxyOutputStream(OutputStream os) {
filteredStream = os;
}
final void setFilteredStream(OutputStream os) {
filteredStream = os;
}
public void close() throws IOException {
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Closing");
filteredStream.close();
}
public void flush() throws IOException {
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Flushing");
filteredStream.flush();
}
private final byte singleByte[] = new byte[1];
public void write(int b) throws IOException {
singleByte[0] = (byte) (b & 0xFF);
writeInternal(singleByte, 0, singleByte.length);
}
public void write(byte[] b) throws IOException {
writeInternal(b, 0, b.length);
}
public void write(byte[] b,
int off,
int len) throws IOException {
writeInternal(b, off, len);
}
private void writeInternal(byte[] b,
int off,
int len) throws IOException {
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Writing " + len + " bytes");
filteredStream.write(b, off, len);
}
}
/**
* This class implements a Socket whose I/O streams can be switched from using a TDSChannel for I/O to using its underlying TCP/IP socket.
*
* The SSL socket binds to a ProxySocket. The initial SSL handshake is done over TDSChannel I/O streams so that the handshake payload is framed in
* TDS packets. The I/O streams are then switched to TCP/IP I/O streams using setStreams, and SSL communications continue directly over the TCP/IP
* I/O streams.
*
* Most methods other than those for getting the I/O streams are simply forwarded to the TDSChannel's underlying TCP/IP socket. Methods that
* change the socket binding or provide direct channel access are disallowed.
*/
private class ProxySocket extends Socket {
private final TDSChannel tdsChannel;
private final Logger logger;
private final String logContext;
private final ProxyInputStream proxyInputStream;
private final ProxyOutputStream proxyOutputStream;
ProxySocket(TDSChannel tdsChannel) {
this.tdsChannel = tdsChannel;
this.logger = tdsChannel.getLogger();
this.logContext = tdsChannel.toString() + " (ProxySocket):";
// Create the I/O streams
SSLHandshakeOutputStream sslHandshakeOutputStream = new SSLHandshakeOutputStream(tdsChannel);
SSLHandshakeInputStream sslHandshakeInputStream = new SSLHandshakeInputStream(tdsChannel, sslHandshakeOutputStream);
this.proxyOutputStream = new ProxyOutputStream(sslHandshakeOutputStream);
this.proxyInputStream = new ProxyInputStream(sslHandshakeInputStream);
}
void setStreams(InputStream is,
OutputStream os) {
proxyInputStream.setFilteredStream(is);
proxyOutputStream.setFilteredStream(os);
}
public InputStream getInputStream() throws IOException {
if (logger.isLoggable(Level.FINEST))
logger.finest(logContext + " Getting input stream");
return proxyInputStream;
}
public OutputStream getOutputStream() throws IOException {
if (logger.isLoggable(Level.FINEST))
logger.finest(logContext + " Getting output stream");
return proxyOutputStream;
}
// Allow methods that should just forward to the underlying TCP socket or return fixed values
public InetAddress getInetAddress() {
return tdsChannel.tcpSocket.getInetAddress();
}
public boolean getKeepAlive() throws SocketException {
return tdsChannel.tcpSocket.getKeepAlive();
}
public InetAddress getLocalAddress() {
return tdsChannel.tcpSocket.getLocalAddress();
}
public int getLocalPort() {
return tdsChannel.tcpSocket.getLocalPort();
}
public SocketAddress getLocalSocketAddress() {
return tdsChannel.tcpSocket.getLocalSocketAddress();
}
public boolean getOOBInline() throws SocketException {
return tdsChannel.tcpSocket.getOOBInline();
}
public int getPort() {
return tdsChannel.tcpSocket.getPort();
}
public int getReceiveBufferSize() throws SocketException {
return tdsChannel.tcpSocket.getReceiveBufferSize();
}
public SocketAddress getRemoteSocketAddress() {
return tdsChannel.tcpSocket.getRemoteSocketAddress();
}
public boolean getReuseAddress() throws SocketException {
return tdsChannel.tcpSocket.getReuseAddress();
}
public int getSendBufferSize() throws SocketException {
return tdsChannel.tcpSocket.getSendBufferSize();
}
public int getSoLinger() throws SocketException {
return tdsChannel.tcpSocket.getSoLinger();
}
public int getSoTimeout() throws SocketException {
return tdsChannel.tcpSocket.getSoTimeout();
}
public boolean getTcpNoDelay() throws SocketException {
return tdsChannel.tcpSocket.getTcpNoDelay();
}
public int getTrafficClass() throws SocketException {
return tdsChannel.tcpSocket.getTrafficClass();
}
public boolean isBound() {
return true;
}
public boolean isClosed() {
return false;
}
public boolean isConnected() {
return true;
}
public boolean isInputShutdown() {
return false;
}
public boolean isOutputShutdown() {
return false;
}
public String toString() {
return tdsChannel.tcpSocket.toString();
}
public SocketChannel getChannel() {
return null;
}
// Disallow calls to methods that would change the underlying TCP socket
public void bind(SocketAddress bindPoint) throws IOException {
logger.finer(logContext + " Disallowed call to bind. Throwing IOException.");
throw new IOException();
}
public void connect(SocketAddress endpoint) throws IOException {
logger.finer(logContext + " Disallowed call to connect (without timeout). Throwing IOException.");
throw new IOException();
}
public void connect(SocketAddress endpoint,
int timeout) throws IOException {
logger.finer(logContext + " Disallowed call to connect (with timeout). Throwing IOException.");
throw new IOException();
}
// Ignore calls to methods that would otherwise allow the SSL socket
// to directly manipulate the underlying TCP socket
public void close() throws IOException {
if (logger.isLoggable(Level.FINER))
logger.finer(logContext + " Ignoring close");
}
public void setReceiveBufferSize(int size) throws SocketException {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Ignoring setReceiveBufferSize size:" + size);
}
public void setSendBufferSize(int size) throws SocketException {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Ignoring setSendBufferSize size:" + size);
}
public void setReuseAddress(boolean on) throws SocketException {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Ignoring setReuseAddress");
}
public void setSoLinger(boolean on,
int linger) throws SocketException {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Ignoring setSoLinger");
}
public void setSoTimeout(int timeout) throws SocketException {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Ignoring setSoTimeout");
}
public void setTcpNoDelay(boolean on) throws SocketException {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Ignoring setTcpNoDelay");
}
public void setTrafficClass(int tc) throws SocketException {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Ignoring setTrafficClass");
}
public void shutdownInput() throws IOException {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Ignoring shutdownInput");
}
public void shutdownOutput() throws IOException {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Ignoring shutdownOutput");
}
public void sendUrgentData(int data) throws IOException {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Ignoring sendUrgentData");
}
public void setKeepAlive(boolean on) throws SocketException {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Ignoring setKeepAlive");
}
public void setOOBInline(boolean on) throws SocketException {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Ignoring setOOBInline");
}
}
/**
* This class implements an X509TrustManager that always accepts the X509Certificate chain offered to it.
*
* A PermissiveX509TrustManager is used to "verify" the authenticity of the server when the trustServerCertificate connection property is set to
* true.
*/
private final class PermissiveX509TrustManager extends Object implements X509TrustManager {
private final TDSChannel tdsChannel;
private final Logger logger;
private final String logContext;
PermissiveX509TrustManager(TDSChannel tdsChannel) {
this.tdsChannel = tdsChannel;
this.logger = tdsChannel.getLogger();
this.logContext = tdsChannel.toString() + " (PermissiveX509TrustManager):";
}
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
if (logger.isLoggable(Level.FINER))
logger.finer(logContext + " Trusting client certificate (!)");
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
if (logger.isLoggable(Level.FINER))
logger.finer(logContext + " Trusting server certificate");
}
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
}
/**
* This class implements an X509TrustManager that hostname for validation.
*
* This validates the subject name in the certificate with the host name
*/
private final class HostNameOverrideX509TrustManager extends Object implements X509TrustManager {
private final Logger logger;
private final String logContext;
private final X509TrustManager defaultTrustManager;
private String hostName;
HostNameOverrideX509TrustManager(TDSChannel tdsChannel,
X509TrustManager tm,
String hostName) {
this.logger = tdsChannel.getLogger();
this.logContext = tdsChannel.toString() + " (HostNameOverrideX509TrustManager):";
defaultTrustManager = tm;
// canonical name is in lower case so convert this to lowercase too.
this.hostName = hostName.toLowerCase();
;
}
// Parse name in RFC 2253 format
// Returns the common name if successful, null if failed to find the common name.
// The parser tuned to be safe than sorry so if it sees something it cant parse correctly it returns null
private String parseCommonName(String distinguishedName) {
int index;
// canonical name converts entire name to lowercase
index = distinguishedName.indexOf("cn=");
if (index == -1) {
return null;
}
distinguishedName = distinguishedName.substring(index + 3);
// Parse until a comma or end is reached
// Note the parser will handle gracefully (essentially will return empty string) , inside the quotes (e.g cn="Foo, bar") however
// RFC 952 says that the hostName cant have commas however the parser should not (and will not) crash if it sees a , within quotes.
for (index = 0; index < distinguishedName.length(); index++) {
if (distinguishedName.charAt(index) == ',') {
break;
}
}
String commonName = distinguishedName.substring(0, index);
// strip any quotes
if (commonName.length() > 1 && ('\"' == commonName.charAt(0))) {
if ('\"' == commonName.charAt(commonName.length() - 1))
commonName = commonName.substring(1, commonName.length() - 1);
else {
// Be safe the name is not ended in " return null so the common Name wont match
commonName = null;
}
}
return commonName;
}
private boolean validateServerName(String nameInCert) throws CertificateException {
// Failed to get the common name from DN or empty CN
if (null == nameInCert) {
if (logger.isLoggable(Level.FINER))
logger.finer(logContext + " Failed to parse the name from the certificate or name is empty.");
return false;
}
// Verify that the name in certificate matches exactly with the host name
if (!nameInCert.equals(hostName)) {
if (logger.isLoggable(Level.FINER))
logger.finer(logContext + " The name in certificate " + nameInCert + " does not match with the server name " + hostName + ".");
return false;
}
if (logger.isLoggable(Level.FINER))
logger.finer(logContext + " The name in certificate:" + nameInCert + " validated against server name " + hostName + ".");
return true;
}
public void checkClientTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
if (logger.isLoggable(Level.FINEST))
logger.finest(logContext + " Forwarding ClientTrusted.");
defaultTrustManager.checkClientTrusted(chain, authType);
}
public void checkServerTrusted(X509Certificate[] chain,
String authType) throws CertificateException {
if (logger.isLoggable(Level.FINEST))
logger.finest(logContext + " Forwarding Trusting server certificate");
defaultTrustManager.checkServerTrusted(chain, authType);
if (logger.isLoggable(Level.FINEST))
logger.finest(logContext + " default serverTrusted succeeded proceeding with server name validation");
validateServerNameInCertificate(chain[0]);
}
private void validateServerNameInCertificate(X509Certificate cert) throws CertificateException {
String nameInCertDN = cert.getSubjectX500Principal().getName("canonical");
if (logger.isLoggable(Level.FINER)) {
logger.finer(logContext + " Validating the server name:" + hostName);
logger.finer(logContext + " The DN name in certificate:" + nameInCertDN);
}
boolean isServerNameValidated;
// the name in cert is in RFC2253 format parse it to get the actual subject name
String subjectCN = parseCommonName(nameInCertDN);
isServerNameValidated = validateServerName(subjectCN);
if (!isServerNameValidated) {
Collection<List<?>> sanCollection = cert.getSubjectAlternativeNames();
if (sanCollection != null) {
// find a subjectAlternateName entry corresponding to DNS Name
for (List<?> sanEntry : sanCollection) {
if (sanEntry != null && sanEntry.size() >= 2) {
Object key = sanEntry.get(0);
Object value = sanEntry.get(1);
if (logger.isLoggable(Level.FINER)) {
logger.finer(logContext + "Key: " + key + "; KeyClass:" + (key != null ? key.getClass() : null) + ";value: " + value
+ "; valueClass:" + (value != null ? value.getClass() : null));
}
// "Note that the Collection returned may contain
// more than one name of the same type."
// So, more than one entry of dnsNameType can be present.
// Java docs guarantee that the first entry in the list will be an integer.
// 2 is the sequence no of a dnsName
if ((key != null) && (key instanceof Integer) && ((Integer) key == 2)) {
// As per RFC2459, the DNSName will be in the
// "preferred name syntax" as specified by RFC
// 1034 and the name can be in upper or lower case.
// And no significance is attached to case.
// Java docs guarantee that the second entry in the list
// will be a string for dnsName
if (value != null && value instanceof String) {
String dnsNameInSANCert = (String) value;
// convert to upper case and then to lower case in english locale
// to avoid Turkish i issues.
// Note that, this conversion was not necessary for
// cert.getSubjectX500Principal().getName("canonical");
// as the above API already does this by default as per documentation.
dnsNameInSANCert = dnsNameInSANCert.toUpperCase(Locale.US);
dnsNameInSANCert = dnsNameInSANCert.toLowerCase(Locale.US);
isServerNameValidated = validateServerName(dnsNameInSANCert);
if (isServerNameValidated) {
if (logger.isLoggable(Level.FINER)) {
logger.finer(logContext + " found a valid name in certificate: " + dnsNameInSANCert);
}
break;
}
}
if (logger.isLoggable(Level.FINER)) {
logger.finer(logContext + " the following name in certificate does not match the serverName: " + value);
}
}
}
else {
if (logger.isLoggable(Level.FINER)) {
logger.finer(logContext + " found an invalid san entry: " + sanEntry);
}
}
}
}
}
if (!isServerNameValidated) {
String msg = SQLServerException.getErrString("R_certNameFailed");
throw new CertificateException(msg);
}
}
public X509Certificate[] getAcceptedIssuers() {
return defaultTrustManager.getAcceptedIssuers();
}
}
enum SSLHandhsakeState {
SSL_HANDHSAKE_NOT_STARTED,
SSL_HANDHSAKE_STARTED,
SSL_HANDHSAKE_COMPLETE
};
/**
* Enables SSL Handshake.
*
* @param host
* Server Host Name for SSL Handshake
* @param port
* Server Port for SSL Handshake
* @throws SQLServerException
*/
void enableSSL(String host,
int port) throws SQLServerException {
// If enabling SSL fails, which it can for a number of reasons, the following items
// are used in logging information to the TDS channel logger to help diagnose the problem.
Provider tmfProvider = null; // TrustManagerFactory provider
Provider sslContextProvider = null; // SSLContext provider
Provider ksProvider = null; // KeyStore provider
String tmfDefaultAlgorithm = null; // Default algorithm (typically X.509) used by the TrustManagerFactory
SSLHandhsakeState handshakeState = SSLHandhsakeState.SSL_HANDHSAKE_NOT_STARTED;
boolean isFips = false;
String trustStoreType = null;
String fipsProvider = null;
// If anything in here fails, terminate the connection and throw an exception
try {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Enabling SSL...");
String trustStoreFileName = con.activeConnectionProperties.getProperty(SQLServerDriverStringProperty.TRUST_STORE.toString());
String trustStorePassword = con.activeConnectionProperties.getProperty(SQLServerDriverStringProperty.TRUST_STORE_PASSWORD.toString());
String hostNameInCertificate = con.activeConnectionProperties
.getProperty(SQLServerDriverStringProperty.HOSTNAME_IN_CERTIFICATE.toString());
trustStoreType = con.activeConnectionProperties.getProperty(SQLServerDriverStringProperty.TRUST_STORE_TYPE.toString());
if(StringUtils.isEmpty(trustStoreType)) {
trustStoreType = SQLServerDriverStringProperty.TRUST_STORE_TYPE.getDefaultValue();
}
fipsProvider = con.activeConnectionProperties.getProperty(SQLServerDriverStringProperty.FIPS_PROVIDER.toString());
isFips = Boolean.valueOf(con.activeConnectionProperties.getProperty(SQLServerDriverBooleanProperty.FIPS.toString()));
if (isFips) {
validateFips(fipsProvider, trustStoreType, trustStoreFileName);
}
byte requestedEncryptionLevel = con.getRequestedEncryptionLevel();
assert TDS.ENCRYPT_OFF == requestedEncryptionLevel || // Login only SSL
TDS.ENCRYPT_ON == requestedEncryptionLevel; // Full SSL
byte negotiatedEncryptionLevel = con.getNegotiatedEncryptionLevel();
assert TDS.ENCRYPT_OFF == negotiatedEncryptionLevel || // Login only SSL
TDS.ENCRYPT_ON == negotiatedEncryptionLevel || // Full SSL
TDS.ENCRYPT_REQ == negotiatedEncryptionLevel; // Full SSL
// If we requested login only SSL or full SSL without server certificate validation,
// then we'll "validate" the server certificate using a naive TrustManager that trusts
// everything it sees.
TrustManager[] tm = null;
if (TDS.ENCRYPT_OFF == con.getRequestedEncryptionLevel()
|| (TDS.ENCRYPT_ON == con.getRequestedEncryptionLevel() && con.trustServerCertificate())) {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " SSL handshake will trust any certificate");
tm = new TrustManager[] {new PermissiveX509TrustManager(this)};
}
// Otherwise, we'll validate the certificate using a real TrustManager obtained
// from the a security provider that is capable of validating X.509 certificates.
else {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " SSL handshake will validate server certificate");
KeyStore ks = null;
// If we are using the system default trustStore and trustStorePassword
// then we can skip all of the KeyStore loading logic below.
// The security provider's implementation takes care of everything for us.
if (null == trustStoreFileName && null == trustStorePassword) {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Using system default trust store and password");
}
// Otherwise either the trustStore, trustStorePassword, or both was specified.
// In that case, we need to load up a KeyStore ourselves.
else {
// First, obtain an interface to a KeyStore that can load trust material
// stored in Java Key Store (JKS) format.
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Finding key store interface");
if (isFips) {
ks = KeyStore.getInstance(trustStoreType, fipsProvider);
}
else {
ks = KeyStore.getInstance(trustStoreType);
}
ksProvider = ks.getProvider();
// Next, load up the trust store file from the specified location.
// Note: This function returns a null InputStream if the trust store cannot
// be loaded. This is by design. See the method comment and documentation
// for KeyStore.load for details.
InputStream is = loadTrustStore(trustStoreFileName);
// Finally, load the KeyStore with the trust material (if any) from the
// InputStream and close the stream.
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Loading key store");
try {
ks.load(is, (null == trustStorePassword) ? null : trustStorePassword.toCharArray());
}
finally {
// We are done with the trustStorePassword (if set). Clear it for better security.
con.activeConnectionProperties.remove(SQLServerDriverStringProperty.TRUST_STORE_PASSWORD.toString());
// We are also done with the trust store input stream.
if (null != is) {
try {
is.close();
}
catch (IOException e) {
if (logger.isLoggable(Level.FINE))
logger.fine(toString() + " Ignoring error closing trust material InputStream...");
}
}
}
}
// Either we now have a KeyStore populated with trust material or we are using the
// default source of trust material (cacerts). Either way, we are now ready to
// use a TrustManagerFactory to create a TrustManager that uses the trust material
// to validate the server certificate.
// Next step is to get a TrustManagerFactory that can produce TrustManagers
// that understands X.509 certificates.
TrustManagerFactory tmf = null;
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Locating X.509 trust manager factory");
tmfDefaultAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
tmf = TrustManagerFactory.getInstance(tmfDefaultAlgorithm);
tmfProvider = tmf.getProvider();
// Tell the TrustManagerFactory to give us TrustManagers that we can use to
// validate the server certificate using the trust material in the KeyStore.
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Getting trust manager");
tmf.init(ks);
tm = tmf.getTrustManagers();
// if the host name in cert provided use it or use the host name Only if it is not FIPS
if (!isFips) {
if (null != hostNameInCertificate) {
tm = new TrustManager[] {new HostNameOverrideX509TrustManager(this, (X509TrustManager) tm[0], hostNameInCertificate)};
}
else {
tm = new TrustManager[] {new HostNameOverrideX509TrustManager(this, (X509TrustManager) tm[0], host)};
}
}
} // end if (!con.trustServerCertificate())
// Now, with a real or fake TrustManager in hand, get a context for creating a
// SSL sockets through a SSL socket factory. We require at least TLS support.
SSLContext sslContext = null;
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Getting TLS or better SSL context");
sslContext = SSLContext.getInstance("TLS");
sslContextProvider = sslContext.getProvider();
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Initializing SSL context");
sslContext.init(null, tm, null);
// Got the SSL context. Now create an SSL socket over our own proxy socket
// which we can toggle between TDS-encapsulated and raw communications.
// Initially, the proxy is set to encapsulate the SSL handshake in TDS packets.
proxySocket = new ProxySocket(this);
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Creating SSL socket");
sslSocket = (SSLSocket) sslContext.getSocketFactory().createSocket(proxySocket, host, port, false); // don't close proxy when SSL socket
// is closed
// At long last, start the SSL handshake ...
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Starting SSL handshake");
// TLS 1.2 intermittent exception happens here.
handshakeState = SSLHandhsakeState.SSL_HANDHSAKE_STARTED;
sslSocket.startHandshake();
handshakeState = SSLHandhsakeState.SSL_HANDHSAKE_COMPLETE;
// After SSL handshake is complete, rewire proxy socket to use raw TCP/IP streams ...
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Rewiring proxy streams after handshake");
proxySocket.setStreams(inputStream, outputStream);
// ... and rewire TDSChannel to use SSL streams.
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Getting SSL InputStream");
inputStream = sslSocket.getInputStream();
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Getting SSL OutputStream");
outputStream = sslSocket.getOutputStream();
// SSL is now enabled; switch over the channel socket
channelSocket = sslSocket;
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " SSL enabled");
}
catch (Exception e) {
// Log the original exception and its source at FINER level
if (logger.isLoggable(Level.FINER))
logger.log(Level.FINER, e.getMessage(), e);
// If enabling SSL fails, the following information may help diagnose the problem.
// Do not use Level INFO or above which is sent to standard output/error streams.
// This is because due to an intermittent TLS 1.2 connection issue, we will be retrying the connection and
// do not want to print this message in console.
if (logger.isLoggable(Level.FINER))
logger.log(Level.FINER,
"java.security path: " + JAVA_SECURITY + "\n" + "Security providers: " + Arrays.asList(Security.getProviders()) + "\n"
+ ((null != sslContextProvider) ? ("SSLContext provider info: " + sslContextProvider.getInfo() + "\n"
+ "SSLContext provider services:\n" + sslContextProvider.getServices() + "\n") : "")
+ ((null != tmfProvider) ? ("TrustManagerFactory provider info: " + tmfProvider.getInfo() + "\n") : "")
+ ((null != tmfDefaultAlgorithm) ? ("TrustManagerFactory default algorithm: " + tmfDefaultAlgorithm + "\n") : "")
+ ((null != ksProvider) ? ("KeyStore provider info: " + ksProvider.getInfo() + "\n") : "") + "java.ext.dirs: "
+ System.getProperty("java.ext.dirs"));
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_sslFailed"));
Object[] msgArgs = {e.getMessage()};
// It is important to get the localized message here, otherwise error messages won't match for different locales.
String errMsg = e.getLocalizedMessage();
// The error message may have a connection id appended to it. Extract the message only for comparison.
// This client connection id is appended in method checkAndAppendClientConnId().
if (errMsg.contains(SQLServerException.LOG_CLIENT_CONNECTION_ID_PREFIX)) {
errMsg = errMsg.substring(0, errMsg.indexOf(SQLServerException.LOG_CLIENT_CONNECTION_ID_PREFIX));
}
// Isolate the TLS1.2 intermittent connection error.
if (e instanceof IOException && (SSLHandhsakeState.SSL_HANDHSAKE_STARTED == handshakeState)
&& (errMsg.equals(SQLServerException.getErrString("R_truncatedServerResponse")))) {
con.terminate(SQLServerException.DRIVER_ERROR_INTERMITTENT_TLS_FAILED, form.format(msgArgs), e);
}
else {
con.terminate(SQLServerException.DRIVER_ERROR_SSL_FAILED, form.format(msgArgs), e);
}
}
}
/**
* Validate FIPS if fips set as true
*
* Valid FIPS settings:
* <LI>Encrypt should be true
* <LI>trustServerCertificate should be false
* <LI>if certificate is not installed FIPSProvider & TrustStoreType should be present.
*
* @param fipsProvider
* FIPS Provider
* @param trustStoreType
* @param trustStoreFileName
* @throws SQLServerException
* @since 6.1.4
*/
private void validateFips(final String fipsProvider,
final String trustStoreType,
final String trustStoreFileName) throws SQLServerException {
boolean isValid = false;
boolean isEncryptOn;
boolean isValidTrustStoreType;
boolean isValidTrustStore;
boolean isTrustServerCertificate;
boolean isValidFipsProvider;
String strError = SQLServerException.getErrString("R_invalidFipsConfig");
isEncryptOn = (TDS.ENCRYPT_ON == con.getRequestedEncryptionLevel());
// Here different FIPS provider supports different KeyStore type along with different JVM Implementation.
isValidFipsProvider = !StringUtils.isEmpty(fipsProvider);
isValidTrustStoreType = !StringUtils.isEmpty(trustStoreType);
isValidTrustStore = !StringUtils.isEmpty(trustStoreFileName);
isTrustServerCertificate = con.trustServerCertificate();
if (isEncryptOn && !isTrustServerCertificate) {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Found parameters are encrypt is true & trustServerCertificate false");
isValid = true;
if (isValidTrustStore) {
// In case of valid trust store we need to check fipsProvider and TrustStoreType.
if (!isValidFipsProvider || !isValidTrustStoreType) {
isValid = false;
strError = SQLServerException.getErrString("R_invalidFipsProviderConfig");
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " FIPS provider & TrustStoreType should pass with TrustStore.");
}
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Found FIPS parameters seems to be valid.");
}
}
else {
strError = SQLServerException.getErrString("R_invalidFipsEncryptConfig");
}
if (!isValid) {
throw new SQLServerException(strError, null, 0, null);
}
}
private final static String SEPARATOR = System.getProperty("file.separator");
private final static String JAVA_HOME = System.getProperty("java.home");
private final static String JAVA_SECURITY = JAVA_HOME + SEPARATOR + "lib" + SEPARATOR + "security";
private final static String JSSECACERTS = JAVA_SECURITY + SEPARATOR + "jssecacerts";
private final static String CACERTS = JAVA_SECURITY + SEPARATOR + "cacerts";
/**
* Loads the contents of a trust store into an InputStream.
*
* When a location to a trust store is specified, this method attempts to load that store. Otherwise, it looks for and attempts to load the
* default trust store using essentially the same logic (outlined in the JSSE Reference Guide) as the default X.509 TrustManagerFactory.
*
* @return an InputStream containing the contents of the loaded trust store
* @return null if the trust store cannot be loaded.
*
* Note: It is by design that this function returns null when the trust store cannot be loaded rather than throwing an exception. The
* reason is that KeyStore.load, which uses the returned InputStream, interprets a null InputStream to mean that there are no trusted
* certificates, which mirrors the behavior of the default (no trust store, no password specified) path.
*/
final InputStream loadTrustStore(String trustStoreFileName) {
FileInputStream is = null;
// First case: Trust store filename was specified
if (null != trustStoreFileName) {
try {
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Opening specified trust store: " + trustStoreFileName);
is = new FileInputStream(trustStoreFileName);
}
catch (FileNotFoundException e) {
if (logger.isLoggable(Level.FINE))
logger.fine(toString() + " Trust store not found: " + e.getMessage());
// If the trustStoreFileName connection property is set, but the file is not found,
// then treat it as if the file was empty so that the TrustManager reports
// that no certificate is found.
}
}
// Second case: Trust store filename derived from javax.net.ssl.trustStore system property
else if (null != (trustStoreFileName = System.getProperty("javax.net.ssl.trustStore"))) {
try {
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Opening default trust store (from javax.net.ssl.trustStore): " + trustStoreFileName);
is = new FileInputStream(trustStoreFileName);
}
catch (FileNotFoundException e) {
if (logger.isLoggable(Level.FINE))
logger.fine(toString() + " Trust store not found: " + e.getMessage());
// If the javax.net.ssl.trustStore property is set, but the file is not found,
// then treat it as if the file was empty so that the TrustManager reports
// that no certificate is found.
}
}
// Third case: No trust store specified and no system property set. Use jssecerts/cacerts.
else {
try {
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Opening default trust store: " + JSSECACERTS);
is = new FileInputStream(JSSECACERTS);
}
catch (FileNotFoundException e) {
if (logger.isLoggable(Level.FINE))
logger.fine(toString() + " Trust store not found: " + e.getMessage());
}
// No jssecerts. Try again with cacerts...
if (null == is) {
try {
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Opening default trust store: " + CACERTS);
is = new FileInputStream(CACERTS);
}
catch (FileNotFoundException e) {
if (logger.isLoggable(Level.FINE))
logger.fine(toString() + " Trust store not found: " + e.getMessage());
// No jssecerts or cacerts. Treat it as if the trust store is empty so that
// the TrustManager reports that no certificate is found.
}
}
}
return is;
}
final int read(byte[] data,
int offset,
int length) throws SQLServerException {
try {
return inputStream.read(data, offset, length);
}
catch (IOException e) {
if (logger.isLoggable(Level.FINE))
logger.fine(toString() + " read failed:" + e.getMessage());
if (e instanceof SocketTimeoutException) {
con.terminate(SQLServerException.ERROR_SOCKET_TIMEOUT, e.getMessage(), e);
}
else {
con.terminate(SQLServerException.DRIVER_ERROR_IO_FAILED, e.getMessage(), e);
}
return 0; // Keep the compiler happy.
}
}
final void write(byte[] data,
int offset,
int length) throws SQLServerException {
try {
outputStream.write(data, offset, length);
}
catch (IOException e) {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " write failed:" + e.getMessage());
con.terminate(SQLServerException.DRIVER_ERROR_IO_FAILED, e.getMessage(), e);
}
}
final void flush() throws SQLServerException {
try {
outputStream.flush();
}
catch (IOException e) {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " flush failed:" + e.getMessage());
con.terminate(SQLServerException.DRIVER_ERROR_IO_FAILED, e.getMessage(), e);
}
}
final void close() {
if (null != sslSocket)
disableSSL();
if (null != inputStream) {
if (logger.isLoggable(Level.FINEST))
logger.finest(this.toString() + ": Closing inputStream...");
try {
inputStream.close();
}
catch (IOException e) {
if (logger.isLoggable(Level.FINE))
logger.log(Level.FINE, this.toString() + ": Ignored error closing inputStream", e);
}
}
if (null != outputStream) {
if (logger.isLoggable(Level.FINEST))
logger.finest(this.toString() + ": Closing outputStream...");
try {
outputStream.close();
}
catch (IOException e) {
if (logger.isLoggable(Level.FINE))
logger.log(Level.FINE, this.toString() + ": Ignored error closing outputStream", e);
}
}
if (null != tcpSocket) {
if (logger.isLoggable(Level.FINER))
logger.finer(this.toString() + ": Closing TCP socket...");
try {
tcpSocket.close();
}
catch (IOException e) {
if (logger.isLoggable(Level.FINE))
logger.log(Level.FINE, this.toString() + ": Ignored error closing socket", e);
}
}
}
/**
* Logs TDS packet data to the com.microsoft.sqlserver.jdbc.TDS.DATA logger
*
* @param data
* the buffer containing the TDS packet payload data to log
* @param nStartOffset
* offset into the above buffer from where to start logging
* @param nLength
* length (in bytes) of payload
* @param messageDetail
* other loggable details about the payload
*/
void logPacket(byte data[],
int nStartOffset,
int nLength,
String messageDetail) {
assert 0 <= nLength && nLength <= data.length;
assert 0 <= nStartOffset && nStartOffset <= data.length;
final char hexChars[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
final char printableChars[] = {'.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.',
'.', '.', '.', '.', '.', '.', '.', '.', '.', '.', ' ', '!', '\"', '
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<', '=', '>', '?', '@', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '[', '\\', ']', '^', '_', '`', 'a', 'b', 'c', 'd',
'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '{', '|', '}', '~', '.',
'.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.',
'.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.',
'.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.',
'.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.',
'.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.'};
// Log message body lines have this form:
// "XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX XX ................"
// 012345678911111111112222222222333333333344444444445555555555666666
// 01234567890123456789012345678901234567890123456789012345
final char lineTemplate[] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ',
' ', ' ',
'.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.'};
char logLine[] = new char[lineTemplate.length];
System.arraycopy(lineTemplate, 0, logLine, 0, lineTemplate.length);
// Logging builds up a string buffer for the entire log trace
// before writing it out. So use an initial size large enough
// that the buffer doesn't have to resize itself.
StringBuilder logMsg = new StringBuilder(messageDetail.length() + // Message detail
4 * nLength + // 2-digit hex + space + ASCII, per byte
4 * (1 + nLength / 16) + // 2 extra spaces + CR/LF, per line (16 bytes per line)
80); // Extra fluff: IP:Port, Connection #, SPID, ...
// Format the headline like so:
// /157.55.121.182:2983 Connection 1, SPID 53, Message info here ...
// Note: the log formatter itself timestamps what we write so we don't have
// to do it again here.
logMsg.append(tcpSocket.getLocalAddress().toString() + ":" + tcpSocket.getLocalPort() + " SPID:" + spid + " " + messageDetail + "\r\n");
// Fill in the body of the log message, line by line, 16 bytes per line.
int nBytesLogged = 0;
int nBytesThisLine;
while (true) {
// Fill up the line with as many bytes as we can (up to 16 bytes)
for (nBytesThisLine = 0; nBytesThisLine < 16 && nBytesLogged < nLength; nBytesThisLine++, nBytesLogged++) {
int nUnsignedByteVal = (data[nStartOffset + nBytesLogged] + 256) % 256;
logLine[3 * nBytesThisLine] = hexChars[nUnsignedByteVal / 16];
logLine[3 * nBytesThisLine + 1] = hexChars[nUnsignedByteVal % 16];
logLine[50 + nBytesThisLine] = printableChars[nUnsignedByteVal];
}
// Pad out the remainder with whitespace
for (int nBytesJustified = nBytesThisLine; nBytesJustified < 16; nBytesJustified++) {
logLine[3 * nBytesJustified] = ' ';
logLine[3 * nBytesJustified + 1] = ' ';
}
logMsg.append(logLine, 0, 50 + nBytesThisLine);
if (nBytesLogged == nLength)
break;
logMsg.append("\r\n");
}
packetLogger.finest(logMsg.toString());
}
/**
* Get the current socket SO_TIMEOUT value.
*
* @return the current socket timeout value
* @throws IOException thrown if the socket timeout cannot be read
*/
final int getNetworkTimeout() throws IOException {
return tcpSocket.getSoTimeout();
}
/**
* Set the socket SO_TIMEOUT value.
*
* @param timeout the socket timeout in milliseconds
* @throws IOException thrown if the socket timeout cannot be set
*/
final void setNetworkTimeout(int timeout) throws IOException {
tcpSocket.setSoTimeout(timeout);
}
}
/**
* SocketFinder is used to find a server socket to which a connection can be made. This class abstracts the logic of finding a socket from TDSChannel
* class.
*
* In the case when useParallel is set to true, this is achieved by trying to make parallel connections to multiple IP addresses. This class is
* responsible for spawning multiple threads and keeping track of the search result and the connected socket or exception to be thrown.
*
* In the case where multiSubnetFailover is false, we try our old logic of trying to connect to the first ip address
*
* Typical usage of this class is SocketFinder sf = new SocketFinder(traceId, conn); Socket = sf.getSocket(hostName, port, timeout);
*/
final class SocketFinder {
/**
* Indicates the result of a search
*/
enum Result {
UNKNOWN,// search is still in progress
SUCCESS,// found a socket
FAILURE// failed in finding a socket
}
// Thread pool - the values in the constructor are chosen based on the
// explanation given in design_connection_director_multisubnet.doc
private static final ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 5, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
// When parallel connections are to be used, use minimum timeout slice of 1500 milliseconds.
private static final int minTimeoutForParallelConnections = 1500;
// lock used for synchronization while updating
// data within a socketFinder object
private final Object socketFinderlock = new Object();
// lock on which the parent thread would wait
// after spawning threads.
private final Object parentThreadLock = new Object();
// indicates whether the socketFinder has succeeded or failed
// in finding a socket or is still trying to find a socket
private volatile Result result = Result.UNKNOWN;
// total no of socket connector threads
// spawned by a socketFinder object
private int noOfSpawnedThreads = 0;
// no of threads that finished their socket connection
// attempts and notified socketFinder about their result
private volatile int noOfThreadsThatNotified = 0;
// If a valid connected socket is found, this value would be non-null,
// else this would be null
private volatile Socket selectedSocket = null;
// This would be one of the exceptions returned by the
// socketConnector threads
private volatile IOException selectedException = null;
// Logging variables
private static final Logger logger = Logger.getLogger("com.microsoft.sqlserver.jdbc.internals.SocketFinder");
private final String traceID;
// maximum number of IP Addresses supported
private static final int ipAddressLimit = 64;
// necessary for raising exceptions so that the connection pool can be notified
private final SQLServerConnection conn;
/**
* Constructs a new SocketFinder object with appropriate traceId
*
* @param callerTraceID
* traceID of the caller
* @param sqlServerConnection
* the SQLServer connection
*/
SocketFinder(String callerTraceID,
SQLServerConnection sqlServerConnection) {
traceID = "SocketFinder(" + callerTraceID + ")";
conn = sqlServerConnection;
}
/**
* Used to find a socket to which a connection can be made
*
* @param hostName
* @param portNumber
* @param timeoutInMilliSeconds
* @return connected socket
* @throws IOException
*/
Socket findSocket(String hostName,
int portNumber,
int timeoutInMilliSeconds,
boolean useParallel,
boolean useTnir,
boolean isTnirFirstAttempt,
int timeoutInMilliSecondsForFullTimeout) throws SQLServerException {
assert timeoutInMilliSeconds != 0 : "The driver does not allow a time out of 0";
try {
InetAddress[] inetAddrs = null;
// inetAddrs is only used if useParallel is true or TNIR is true. Skip resolving address if that's not the case.
if (useParallel || useTnir) {
// Ignore TNIR if host resolves to more than 64 IPs. Make sure we are using original timeout for this.
inetAddrs = InetAddress.getAllByName(hostName);
if ((useTnir) && (inetAddrs.length > ipAddressLimit)) {
useTnir = false;
timeoutInMilliSeconds = timeoutInMilliSecondsForFullTimeout;
}
}
if (!useParallel) {
// MSF is false. TNIR could be true or false. DBMirroring could be true or false.
// For TNIR first attempt, we should do existing behavior including how host name is resolved.
if (useTnir && isTnirFirstAttempt) {
return getDefaultSocket(hostName, portNumber, SQLServerConnection.TnirFirstAttemptTimeoutMs);
}
else if (!useTnir) {
return getDefaultSocket(hostName, portNumber, timeoutInMilliSeconds);
}
}
// Code reaches here only if MSF = true or (TNIR = true and not TNIR first attempt)
if (logger.isLoggable(Level.FINER)) {
String loggingString = this.toString() + " Total no of InetAddresses: " + inetAddrs.length + ". They are: ";
for (InetAddress inetAddr : inetAddrs) {
loggingString = loggingString + inetAddr.toString() + ";";
}
logger.finer(loggingString);
}
if (inetAddrs.length > ipAddressLimit) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_ipAddressLimitWithMultiSubnetFailover"));
Object[] msgArgs = {Integer.toString(ipAddressLimit)};
String errorStr = form.format(msgArgs);
// we do not want any retry to happen here. So, terminate the connection
// as the config is unsupported.
conn.terminate(SQLServerException.DRIVER_ERROR_UNSUPPORTED_CONFIG, errorStr);
}
if (Util.isIBM()) {
timeoutInMilliSeconds = Math.max(timeoutInMilliSeconds, minTimeoutForParallelConnections);
if (logger.isLoggable(Level.FINER)) {
logger.finer(this.toString() + "Using Java NIO with timeout:" + timeoutInMilliSeconds);
}
findSocketUsingJavaNIO(inetAddrs, portNumber, timeoutInMilliSeconds);
}
else {
LinkedList<Inet4Address> inet4Addrs = new LinkedList<Inet4Address>();
LinkedList<Inet6Address> inet6Addrs = new LinkedList<Inet6Address>();
for (InetAddress inetAddr : inetAddrs) {
if (inetAddr instanceof Inet4Address) {
inet4Addrs.add((Inet4Address) inetAddr);
}
else {
assert inetAddr instanceof Inet6Address : "Unexpected IP address " + inetAddr.toString();
inet6Addrs.add((Inet6Address) inetAddr);
}
}
// use half timeout only if both IPv4 and IPv6 addresses are present
int timeoutForEachIPAddressType;
if ((!inet4Addrs.isEmpty()) && (!inet6Addrs.isEmpty())) {
timeoutForEachIPAddressType = Math.max(timeoutInMilliSeconds / 2, minTimeoutForParallelConnections);
}
else
timeoutForEachIPAddressType = Math.max(timeoutInMilliSeconds, minTimeoutForParallelConnections);
if (!inet4Addrs.isEmpty()) {
if (logger.isLoggable(Level.FINER)) {
logger.finer(this.toString() + "Using Java NIO with timeout:" + timeoutForEachIPAddressType);
}
// inet4Addrs.toArray(new InetAddress[0]) is java style of converting a linked list to an array of reqd size
findSocketUsingJavaNIO(inet4Addrs.toArray(new InetAddress[0]), portNumber, timeoutForEachIPAddressType);
}
if (!result.equals(Result.SUCCESS)) {
// try threading logic
if (!inet6Addrs.isEmpty()) {
// do not start any threads if there is only one ipv6 address
if (inet6Addrs.size() == 1) {
return getConnectedSocket(inet6Addrs.get(0), portNumber, timeoutForEachIPAddressType);
}
if (logger.isLoggable(Level.FINER)) {
logger.finer(this.toString() + "Using Threading with timeout:" + timeoutForEachIPAddressType);
}
findSocketUsingThreading(inet6Addrs, portNumber, timeoutForEachIPAddressType);
}
}
}
// If the thread continued execution due to timeout, the result may not be known.
// In that case, update the result to failure. Note that this case is possible
// for both IPv4 and IPv6.
// Using double-checked locking for performance reasons.
if (result.equals(Result.UNKNOWN)) {
synchronized (socketFinderlock) {
if (result.equals(Result.UNKNOWN)) {
result = Result.FAILURE;
if (logger.isLoggable(Level.FINER)) {
logger.finer(this.toString() + " The parent thread updated the result to failure");
}
}
}
}
// After we reach this point, there is no need for synchronization any more.
// Because, the result would be known(success/failure).
// And no threads would update SocketFinder
// as their function calls would now be no-ops.
if (result.equals(Result.FAILURE)) {
if (selectedException == null) {
if (logger.isLoggable(Level.FINER)) {
logger.finer(this.toString()
+ " There is no selectedException. The wait calls timed out before any connect call returned or timed out.");
}
String message = SQLServerException.getErrString("R_connectionTimedOut");
selectedException = new IOException(message);
}
throw selectedException;
}
}
catch (InterruptedException ex) {
close(selectedSocket);
SQLServerException.ConvertConnectExceptionToSQLServerException(hostName, portNumber, conn, ex);
}
catch (IOException ex) {
close(selectedSocket);
// The code below has been moved from connectHelper.
// If we do not move it, the functions open(caller of findSocket)
// and findSocket will have to
// declare both IOException and SQLServerException in the throws clause
// as we throw custom SQLServerExceptions(eg:IPAddressLimit, wrapping other exceptions
// like interruptedException) in findSocket.
// That would be a bit awkward, because connecthelper(the caller of open)
// just wraps IOException into SQLServerException and throws SQLServerException.
// Instead, it would be good to wrap all exceptions at one place - Right here, their origin.
SQLServerException.ConvertConnectExceptionToSQLServerException(hostName, portNumber, conn, ex);
}
assert result.equals(Result.SUCCESS) == true;
assert selectedSocket != null : "Bug in code. Selected Socket cannot be null here.";
return selectedSocket;
}
/**
* This function uses java NIO to connect to all the addresses in inetAddrs with in a specified timeout. If it succeeds in connecting, it closes
* all the other open sockets and updates the result to success.
*
* @param inetAddrs
* the array of inetAddress to which connection should be made
* @param portNumber
* the port number at which connection should be made
* @param timeoutInMilliSeconds
* @throws IOException
*/
private void findSocketUsingJavaNIO(InetAddress[] inetAddrs,
int portNumber,
int timeoutInMilliSeconds) throws IOException {
// The driver does not allow a time out of zero.
// Also, the unit of time the user can specify in the driver is seconds.
// So, even if the user specifies 1 second(least value), the least possible
// value that can come here as timeoutInMilliSeconds is 500 milliseconds.
assert timeoutInMilliSeconds != 0 : "The timeout cannot be zero";
assert inetAddrs.length != 0 : "Number of inetAddresses should not be zero in this function";
Selector selector = null;
LinkedList<SocketChannel> socketChannels = new LinkedList<SocketChannel>();
SocketChannel selectedChannel = null;
try {
selector = Selector.open();
for (int i = 0; i < inetAddrs.length; i++) {
SocketChannel sChannel = SocketChannel.open();
socketChannels.add(sChannel);
// make the channel non-blocking
sChannel.configureBlocking(false);
// register the channel for connect event
int ops = SelectionKey.OP_CONNECT;
SelectionKey key = sChannel.register(selector, ops);
sChannel.connect(new InetSocketAddress(inetAddrs[i], portNumber));
if (logger.isLoggable(Level.FINER))
logger.finer(this.toString() + " initiated connection to address: " + inetAddrs[i] + ", portNumber: " + portNumber);
}
long timerNow = System.currentTimeMillis();
long timerExpire = timerNow + timeoutInMilliSeconds;
// Denotes the no of channels that still need to processed
int noOfOutstandingChannels = inetAddrs.length;
while (true) {
long timeRemaining = timerExpire - timerNow;
// if the timeout expired or a channel is selected or there are no more channels left to processes
if ((timeRemaining <= 0) || (selectedChannel != null) || (noOfOutstandingChannels <= 0))
break;
// denotes the no of channels that are ready to be processed. i.e. they are either connected
// or encountered an exception while trying to connect
int readyChannels = selector.select(timeRemaining);
if (logger.isLoggable(Level.FINER))
logger.finer(this.toString() + " no of channels ready: " + readyChannels);
// There are no real time guarantees on the time out of the select API used above.
// This check is necessary
// a) to guard against cases where the select returns faster than expected.
// b) for cases where no channels could connect with in the time out
if (readyChannels != 0) {
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
while (keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
SocketChannel ch = (SocketChannel) key.channel();
if (logger.isLoggable(Level.FINER))
logger.finer(this.toString() + " processing the channel :" + ch);// this traces the IP by default
boolean connected = false;
try {
connected = ch.finishConnect();
// ch.finishConnect should either return true or throw an exception
// as we have subscribed for OP_CONNECT.
assert connected == true : "finishConnect on channel:" + ch + " cannot be false";
selectedChannel = ch;
if (logger.isLoggable(Level.FINER))
logger.finer(this.toString() + " selected the channel :" + selectedChannel);
break;
}
catch (IOException ex) {
if (logger.isLoggable(Level.FINER))
logger.finer(this.toString() + " the exception: " + ex.getClass() + " with message: " + ex.getMessage()
+ " occured while processing the channel: " + ch);
updateSelectedException(ex, this.toString());
// close the channel pro-actively so that we do not
// hang on to network resources
ch.close();
}
// unregister the key and remove from the selector's selectedKeys
key.cancel();
keyIterator.remove();
noOfOutstandingChannels
}
}
timerNow = System.currentTimeMillis();
}
}
catch (IOException ex) {
// in case of an exception, close the selected channel.
// All other channels will be closed in the finally block,
// as they need to be closed irrespective of a success/failure
close(selectedChannel);
throw ex;
}
finally {
// close the selector
// As per java docs, on selector.close(), any uncancelled keys still
// associated with this
// selector are invalidated, their channels are deregistered, and any other
// resources associated with this selector are released.
// So, its not necessary to cancel each key again
close(selector);
// Close all channels except the selected one.
// As we close channels pro-actively in the try block,
// its possible that we close a channel twice.
// Closing a channel second time is a no-op.
// This code is should be in the finally block to guard against cases where
// we pre-maturely exit try block due to an exception in selector or other places.
for (SocketChannel s : socketChannels) {
if (s != selectedChannel) {
close(s);
}
}
}
// if a channel was selected, make the necessary updates
if (selectedChannel != null) {
//the selectedChannel has the address that is connected successfully
//convert it to a java.net.Socket object with the address
SocketAddress iadd = selectedChannel.getRemoteAddress();
selectedSocket = new Socket();
selectedSocket.connect(iadd);
result = Result.SUCCESS;
//close the channel since it is not used anymore
selectedChannel.close();
}
}
// This method contains the old logic of connecting to
// a socket of one of the IPs corresponding to a given host name.
// In the old code below, the logic around 0 timeout has been removed as
// 0 timeout is not allowed. The code has been re-factored so that the logic
// is common for hostName or InetAddress.
private Socket getDefaultSocket(String hostName,
int portNumber,
int timeoutInMilliSeconds) throws IOException {
// Open the socket, with or without a timeout, throwing an UnknownHostException
// if there is a failure to resolve the host name to an InetSocketAddress.
// Note that Socket(host, port) throws an UnknownHostException if the host name
// cannot be resolved, but that InetSocketAddress(host, port) does not - it sets
// the returned InetSocketAddress as unresolved.
InetSocketAddress addr = new InetSocketAddress(hostName, portNumber);
return getConnectedSocket(addr, timeoutInMilliSeconds);
}
private Socket getConnectedSocket(InetAddress inetAddr,
int portNumber,
int timeoutInMilliSeconds) throws IOException {
InetSocketAddress addr = new InetSocketAddress(inetAddr, portNumber);
return getConnectedSocket(addr, timeoutInMilliSeconds);
}
private Socket getConnectedSocket(InetSocketAddress addr,
int timeoutInMilliSeconds) throws IOException {
assert timeoutInMilliSeconds != 0 : "timeout cannot be zero";
if (addr.isUnresolved())
throw new java.net.UnknownHostException();
selectedSocket = new Socket();
selectedSocket.connect(addr, timeoutInMilliSeconds);
return selectedSocket;
}
private void findSocketUsingThreading(LinkedList<Inet6Address> inetAddrs,
int portNumber,
int timeoutInMilliSeconds) throws IOException, InterruptedException {
assert timeoutInMilliSeconds != 0 : "The timeout cannot be zero";
assert inetAddrs.isEmpty() == false : "Number of inetAddresses should not be zero in this function";
LinkedList<Socket> sockets = new LinkedList<Socket>();
LinkedList<SocketConnector> socketConnectors = new LinkedList<SocketConnector>();
try {
// create a socket, inetSocketAddress and a corresponding socketConnector per inetAddress
noOfSpawnedThreads = inetAddrs.size();
for (InetAddress inetAddress : inetAddrs) {
Socket s = new Socket();
sockets.add(s);
InetSocketAddress inetSocketAddress = new InetSocketAddress(inetAddress, portNumber);
SocketConnector socketConnector = new SocketConnector(s, inetSocketAddress, timeoutInMilliSeconds, this);
socketConnectors.add(socketConnector);
}
// acquire parent lock and spawn all threads
synchronized (parentThreadLock) {
for (SocketConnector sc : socketConnectors) {
threadPoolExecutor.execute(sc);
}
long timerNow = System.currentTimeMillis();
long timerExpire = timerNow + timeoutInMilliSeconds;
// The below loop is to guard against the spurious wake up problem
while (true) {
long timeRemaining = timerExpire - timerNow;
if (logger.isLoggable(Level.FINER)) {
logger.finer(this.toString() + " TimeRemaining:" + timeRemaining + "; Result:" + result + "; Max. open thread count: "
+ threadPoolExecutor.getLargestPoolSize() + "; Current open thread count:" + threadPoolExecutor.getActiveCount());
}
// if there is no time left or if the result is determined, break.
// Note that a dirty read of result is totally fine here.
// Since this thread holds the parentThreadLock, even if we do a dirty
// read here, the child thread, after updating the result, would not be
// able to call notify on the parentThreadLock
// (and thus finish execution) as it would be waiting on parentThreadLock
// held by this thread(the parent thread).
// So, this thread will wait again and then be notified by the childThread.
// On the other hand, if we try to take socketFinderLock here to avoid
// dirty read, we would introduce a dead lock due to the
// reverse order of locking in updateResult method.
if (timeRemaining <= 0 || (!result.equals(Result.UNKNOWN)))
break;
parentThreadLock.wait(timeRemaining);
if (logger.isLoggable(Level.FINER)) {
logger.finer(this.toString() + " The parent thread wokeup.");
}
timerNow = System.currentTimeMillis();
}
}
}
finally {
// Close all sockets except the selected one.
// As we close sockets pro-actively in the child threads,
// its possible that we close a socket twice.
// Closing a socket second time is a no-op.
// If a child thread is waiting on the connect call on a socket s,
// closing the socket s here ensures that an exception is thrown
// in the child thread immediately. This mitigates the problem
// of thread explosion by ensuring that unnecessary threads die
// quickly without waiting for "min(timeOut, 21)" seconds
for (Socket s : sockets) {
if (s != selectedSocket) {
close(s);
}
}
}
}
/**
* search result
*/
Result getResult() {
return result;
}
void close(Selector selector) {
if (null != selector) {
if (logger.isLoggable(Level.FINER))
logger.finer(this.toString() + ": Closing Selector");
try {
selector.close();
}
catch (IOException e) {
if (logger.isLoggable(Level.FINE))
logger.log(Level.FINE, this.toString() + ": Ignored the following error while closing Selector", e);
}
}
}
void close(Socket socket) {
if (null != socket) {
if (logger.isLoggable(Level.FINER))
logger.finer(this.toString() + ": Closing TCP socket:" + socket);
try {
socket.close();
}
catch (IOException e) {
if (logger.isLoggable(Level.FINE))
logger.log(Level.FINE, this.toString() + ": Ignored the following error while closing socket", e);
}
}
}
void close(SocketChannel socketChannel) {
if (null != socketChannel) {
if (logger.isLoggable(Level.FINER))
logger.finer(this.toString() + ": Closing TCP socket channel:" + socketChannel);
try {
socketChannel.close();
}
catch (IOException e) {
if (logger.isLoggable(Level.FINE))
logger.log(Level.FINE, this.toString() + "Ignored the following error while closing socketChannel", e);
}
}
}
/**
* Used by socketConnector threads to notify the socketFinder of their connection attempt result(a connected socket or exception). It updates the
* result, socket and exception variables of socketFinder object. This method notifies the parent thread if a socket is found or if all the
* spawned threads have notified. It also closes a socket if it is not selected for use by socketFinder.
*
* @param socket
* the SocketConnector's socket
* @param exception
* Exception that occurred in socket connector thread
* @param threadId
* Id of the calling Thread for diagnosis
*/
void updateResult(Socket socket,
IOException exception,
String threadId) {
if (result.equals(Result.UNKNOWN)) {
if (logger.isLoggable(Level.FINER)) {
logger.finer("The following child thread is waiting for socketFinderLock:" + threadId);
}
synchronized (socketFinderlock) {
if (logger.isLoggable(Level.FINER)) {
logger.finer("The following child thread acquired socketFinderLock:" + threadId);
}
if (result.equals(Result.UNKNOWN)) {
// if the connection was successful and no socket has been
// selected yet
if (exception == null && selectedSocket == null) {
selectedSocket = socket;
result = Result.SUCCESS;
if (logger.isLoggable(Level.FINER)) {
logger.finer("The socket of the following thread has been chosen:" + threadId);
}
}
// if an exception occurred
if (exception != null) {
updateSelectedException(exception, threadId);
}
}
noOfThreadsThatNotified++;
// if all threads notified, but the result is still unknown,
// update the result to failure
if ((noOfThreadsThatNotified >= noOfSpawnedThreads) && result.equals(Result.UNKNOWN)) {
result = Result.FAILURE;
}
if (!result.equals(Result.UNKNOWN)) {
// 1) Note that at any point of time, there is only one
// thread(parent/child thread) competing for parentThreadLock.
// 2) The only time where a child thread could be waiting on
// parentThreadLock is before the wait call in the parentThread
// 3) After the above happens, the parent thread waits to be
// notified on parentThreadLock. After being notified,
// it would be the ONLY thread competing for the lock.
// for the following reasons
// a) The parentThreadLock is taken while holding the socketFinderLock.
// So, all child threads, except one, block on socketFinderLock
// (not parentThreadLock)
// b) After parentThreadLock is notified by a child thread, the result
// would be known(Refer the double-checked locking done at the
// start of this method). So, all child threads would exit
// as no-ops and would never compete with parent thread
// for acquiring parentThreadLock
// 4) As the parent thread is the only thread that competes for the
// parentThreadLock, it need not wait to acquire the lock once it wakes
// up and gets scheduled.
// This results in better performance as it would close unnecessary
// sockets and thus help child threads die quickly.
if (logger.isLoggable(Level.FINER)) {
logger.finer("The following child thread is waiting for parentThreadLock:" + threadId);
}
synchronized (parentThreadLock) {
if (logger.isLoggable(Level.FINER)) {
logger.finer("The following child thread acquired parentThreadLock:" + threadId);
}
parentThreadLock.notify();
}
if (logger.isLoggable(Level.FINER)) {
logger.finer("The following child thread released parentThreadLock and notified the parent thread:" + threadId);
}
}
}
if (logger.isLoggable(Level.FINER)) {
logger.finer("The following child thread released socketFinderLock:" + threadId);
}
}
}
/**
* Updates the selectedException if
* <p>
* a) selectedException is null
* <p>
* b) ex is a non-socketTimeoutException and selectedException is a socketTimeoutException
* <p>
* If there are multiple exceptions, that are not related to socketTimeout the first non-socketTimeout exception is picked. If all exceptions are
* related to socketTimeout, the first exception is picked. Note: This method is not thread safe. The caller should ensure thread safety.
*
* @param ex
* the IOException
* @param traceId
* the traceId of the thread
*/
public void updateSelectedException(IOException ex,
String traceId) {
boolean updatedException = false;
if (selectedException == null) {
selectedException = ex;
updatedException = true;
}
else if ((!(ex instanceof SocketTimeoutException)) && (selectedException instanceof SocketTimeoutException)) {
selectedException = ex;
updatedException = true;
}
if (updatedException) {
if (logger.isLoggable(Level.FINER)) {
logger.finer("The selected exception is updated to the following: ExceptionType:" + ex.getClass() + "; ExceptionMessage:"
+ ex.getMessage() + "; by the following thread:" + traceId);
}
}
}
/**
* Used fof tracing
*
* @return traceID string
*/
public String toString() {
return traceID;
}
}
/**
* This is used to connect a socket in a separate thread
*/
final class SocketConnector implements Runnable {
// socket on which connection attempt would be made
private final Socket socket;
// the socketFinder associated with this connector
private final SocketFinder socketFinder;
// inetSocketAddress to connect to
private final InetSocketAddress inetSocketAddress;
// timeout in milliseconds
private final int timeoutInMilliseconds;
// Logging variables
private static final Logger logger = Logger.getLogger("com.microsoft.sqlserver.jdbc.internals.SocketConnector");
private final String traceID;
// Id of the thread. used for diagnosis
private final String threadID;
// a counter used to give unique IDs to each connector thread.
// this will have the id of the thread that was last created.
private static long lastThreadID = 0;
/**
* Constructs a new SocketConnector object with the associated socket and socketFinder
*/
SocketConnector(Socket socket,
InetSocketAddress inetSocketAddress,
int timeOutInMilliSeconds,
SocketFinder socketFinder) {
this.socket = socket;
this.inetSocketAddress = inetSocketAddress;
this.timeoutInMilliseconds = timeOutInMilliSeconds;
this.socketFinder = socketFinder;
this.threadID = Long.toString(nextThreadID());
this.traceID = "SocketConnector:" + this.threadID + "(" + socketFinder.toString() + ")";
}
/**
* If search for socket has not finished, this function tries to connect a socket(with a timeout) synchronously. It further notifies the
* socketFinder the result of the connection attempt
*/
public void run() {
IOException exception = null;
// Note that we do not need socketFinder lock here
// as we update nothing in socketFinder based on the condition.
// So, its perfectly fine to make a dirty read.
SocketFinder.Result result = socketFinder.getResult();
if (result.equals(SocketFinder.Result.UNKNOWN)) {
try {
if (logger.isLoggable(Level.FINER)) {
logger.finer(
this.toString() + " connecting to InetSocketAddress:" + inetSocketAddress + " with timeout:" + timeoutInMilliseconds);
}
socket.connect(inetSocketAddress, timeoutInMilliseconds);
}
catch (IOException ex) {
if (logger.isLoggable(Level.FINER)) {
logger.finer(this.toString() + " exception:" + ex.getClass() + " with message:" + ex.getMessage()
+ " occured while connecting to InetSocketAddress:" + inetSocketAddress);
}
exception = ex;
}
socketFinder.updateResult(socket, exception, this.toString());
}
}
/**
* Used for tracing
*
* @return traceID string
*/
public String toString() {
return traceID;
}
/**
* Generates the next unique thread id.
*/
private static synchronized long nextThreadID() {
if (lastThreadID == Long.MAX_VALUE) {
if (logger.isLoggable(Level.FINER))
logger.finer("Resetting the Id count");
lastThreadID = 1;
}
else {
lastThreadID++;
}
return lastThreadID;
}
}
/**
* TDSWriter implements the client to server TDS data pipe.
*/
final class TDSWriter {
private static Logger logger = Logger.getLogger("com.microsoft.sqlserver.jdbc.internals.TDS.Writer");
private final String traceID;
final public String toString() {
return traceID;
}
private final TDSChannel tdsChannel;
private final SQLServerConnection con;
// Flag to indicate whether data written via writeXXX() calls
// is loggable. Data is normally loggable. But sensitive
// data, such as user credentials, should never be logged for
// security reasons.
private boolean dataIsLoggable = true;
void setDataLoggable(boolean value) {
dataIsLoggable = value;
}
private TDSCommand command = null;
// TDS message type (Query, RPC, DTC, etc.) sent at the beginning
// of every TDS message header. Value is set when starting a new
// TDS message of the specified type.
private byte tdsMessageType;
private volatile int sendResetConnection = 0;
// Size (in bytes) of the TDS packets to/from the server.
// This size is normally fixed for the life of the connection,
// but it can change once after the logon packet because packet
// size negotiation happens at logon time.
private int currentPacketSize = 0;
// Size of the TDS packet header, which is:
// byte type
// byte status
// short length
// short SPID
// byte packet
// byte window
private final static int TDS_PACKET_HEADER_SIZE = 8;
private final static byte[] placeholderHeader = new byte[TDS_PACKET_HEADER_SIZE];
// Intermediate array used to convert typically "small" values such as fixed-length types
// (byte, int, long, etc.) and Strings from their native form to bytes for sending to
// the channel buffers.
private byte valueBytes[] = new byte[256];
// Monotonically increasing packet number associated with the current message
private volatile int packetNum = 0;
// Bytes for sending decimal/numeric data
private final static int BYTES4 = 4;
private final static int BYTES8 = 8;
private final static int BYTES12 = 12;
private final static int BYTES16 = 16;
public final static int BIGDECIMAL_MAX_LENGTH = 0x11;
// is set to true when EOM is sent for the current message.
// Note that this variable will never be accessed from multiple threads
// simultaneously and so it need not be volatile
private boolean isEOMSent = false;
boolean isEOMSent() {
return isEOMSent;
}
// Packet data buffers
private ByteBuffer stagingBuffer;
private ByteBuffer socketBuffer;
private ByteBuffer logBuffer;
private CryptoMetadata cryptoMeta = null;
TDSWriter(TDSChannel tdsChannel,
SQLServerConnection con) {
this.tdsChannel = tdsChannel;
this.con = con;
traceID = "TDSWriter@" + Integer.toHexString(hashCode()) + " (" + con.toString() + ")";
}
// TDS message start/end operations
void preparePacket() throws SQLServerException {
if (tdsChannel.isLoggingPackets()) {
Arrays.fill(logBuffer.array(), (byte) 0xFE);
logBuffer.clear();
}
// Write a placeholder packet header. This will be replaced
// with the real packet header when the packet is flushed.
writeBytes(placeholderHeader);
}
/**
* Start a new TDS message.
*/
void writeMessageHeader() throws SQLServerException {
// TDS 7.2 & later:
// Include ALL_Headers/MARS header in message's first packet
// Note: The PKT_BULK message does not nees this ALL_HEADERS
if ((TDS.PKT_QUERY == tdsMessageType || TDS.PKT_DTC == tdsMessageType || TDS.PKT_RPC == tdsMessageType)) {
boolean includeTraceHeader = false;
int totalHeaderLength = TDS.MESSAGE_HEADER_LENGTH;
if (TDS.PKT_QUERY == tdsMessageType || TDS.PKT_RPC == tdsMessageType) {
if (con.isDenaliOrLater() && !ActivityCorrelator.getCurrent().IsSentToServer() && Util.IsActivityTraceOn()) {
includeTraceHeader = true;
totalHeaderLength += TDS.TRACE_HEADER_LENGTH;
}
}
writeInt(totalHeaderLength); // allHeaders.TotalLength (DWORD)
writeInt(TDS.MARS_HEADER_LENGTH); // MARS header length (DWORD)
writeShort((short) 2); // allHeaders.HeaderType(MARS header) (USHORT)
writeBytes(con.getTransactionDescriptor());
writeInt(1); // marsHeader.OutstandingRequestCount
if (includeTraceHeader) {
writeInt(TDS.TRACE_HEADER_LENGTH); // trace header length (DWORD)
writeTraceHeaderData();
ActivityCorrelator.setCurrentActivityIdSentFlag(); // set the flag to indicate this ActivityId is sent
}
}
}
void writeTraceHeaderData() throws SQLServerException {
ActivityId activityId = ActivityCorrelator.getCurrent();
final byte[] actIdByteArray = Util.asGuidByteArray(activityId.getId());
long seqNum = activityId.getSequence();
writeShort(TDS.HEADERTYPE_TRACE); // trace header type
writeBytes(actIdByteArray, 0, actIdByteArray.length); // guid part of ActivityId
writeInt((int) seqNum); // sequence number of ActivityId
if (logger.isLoggable(Level.FINER))
logger.finer("Send Trace Header - ActivityID: " + activityId.toString());
}
/**
* Convenience method to prepare the TDS channel for writing and start a new TDS message.
*
* @param command
* The TDS command
* @param tdsMessageType
* The TDS message type (PKT_QUERY, PKT_RPC, etc.)
*/
void startMessage(TDSCommand command,
byte tdsMessageType) throws SQLServerException {
this.command = command;
this.tdsMessageType = tdsMessageType;
this.packetNum = 0;
this.isEOMSent = false;
this.dataIsLoggable = true;
// If the TDS packet size has changed since the last request
// (which should really only happen after the login packet)
// then allocate new buffers that are the correct size.
int negotiatedPacketSize = con.getTDSPacketSize();
if (currentPacketSize != negotiatedPacketSize) {
socketBuffer = ByteBuffer.allocate(negotiatedPacketSize).order(ByteOrder.LITTLE_ENDIAN);
stagingBuffer = ByteBuffer.allocate(negotiatedPacketSize).order(ByteOrder.LITTLE_ENDIAN);
logBuffer = ByteBuffer.allocate(negotiatedPacketSize).order(ByteOrder.LITTLE_ENDIAN);
currentPacketSize = negotiatedPacketSize;
}
socketBuffer.position(socketBuffer.limit());
stagingBuffer.clear();
preparePacket();
writeMessageHeader();
}
final void endMessage() throws SQLServerException {
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Finishing TDS message");
writePacket(TDS.STATUS_BIT_EOM);
}
// If a complete request has not been sent to the server,
// the client MUST send the next packet with both ignore bit (0x02) and EOM bit (0x01)
// set in the status to cancel the request.
final boolean ignoreMessage() throws SQLServerException {
if (packetNum > 0) {
assert !isEOMSent;
if (logger.isLoggable(Level.FINER))
logger.finest(toString() + " Finishing TDS message by sending ignore bit and end of message");
writePacket(TDS.STATUS_BIT_EOM | TDS.STATUS_BIT_ATTENTION);
return true;
}
return false;
}
final void resetPooledConnection() {
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " resetPooledConnection");
sendResetConnection = TDS.STATUS_BIT_RESET_CONN;
}
// Primitive write operations
void writeByte(byte value) throws SQLServerException {
if (stagingBuffer.remaining() >= 1) {
stagingBuffer.put(value);
if (tdsChannel.isLoggingPackets()) {
if (dataIsLoggable)
logBuffer.put(value);
else
logBuffer.position(logBuffer.position() + 1);
}
}
else {
valueBytes[0] = value;
writeWrappedBytes(valueBytes, 1);
}
}
void writeChar(char value) throws SQLServerException {
if (stagingBuffer.remaining() >= 2) {
stagingBuffer.putChar(value);
if (tdsChannel.isLoggingPackets()) {
if (dataIsLoggable)
logBuffer.putChar(value);
else
logBuffer.position(logBuffer.position() + 2);
}
}
else {
Util.writeShort((short) value, valueBytes, 0);
writeWrappedBytes(valueBytes, 2);
}
}
void writeShort(short value) throws SQLServerException {
if (stagingBuffer.remaining() >= 2) {
stagingBuffer.putShort(value);
if (tdsChannel.isLoggingPackets()) {
if (dataIsLoggable)
logBuffer.putShort(value);
else
logBuffer.position(logBuffer.position() + 2);
}
}
else {
Util.writeShort(value, valueBytes, 0);
writeWrappedBytes(valueBytes, 2);
}
}
void writeInt(int value) throws SQLServerException {
if (stagingBuffer.remaining() >= 4) {
stagingBuffer.putInt(value);
if (tdsChannel.isLoggingPackets()) {
if (dataIsLoggable)
logBuffer.putInt(value);
else
logBuffer.position(logBuffer.position() + 4);
}
}
else {
Util.writeInt(value, valueBytes, 0);
writeWrappedBytes(valueBytes, 4);
}
}
/**
* Append a real value in the TDS stream.
*
* @param value
* the data value
*/
void writeReal(Float value) throws SQLServerException {
if (false) // stagingBuffer.remaining() >= 4)
{
stagingBuffer.putFloat(value);
if (tdsChannel.isLoggingPackets()) {
if (dataIsLoggable)
logBuffer.putFloat(value);
else
logBuffer.position(logBuffer.position() + 4);
}
}
else {
writeInt(Float.floatToRawIntBits(value.floatValue()));
}
}
/**
* Append a double value in the TDS stream.
*
* @param value
* the data value
*/
void writeDouble(double value) throws SQLServerException {
if (stagingBuffer.remaining() >= 8) {
stagingBuffer.putDouble(value);
if (tdsChannel.isLoggingPackets()) {
if (dataIsLoggable)
logBuffer.putDouble(value);
else
logBuffer.position(logBuffer.position() + 8);
}
}
else {
long bits = Double.doubleToLongBits(value);
long mask = 0xFF;
int nShift = 0;
for (int i = 0; i < 8; i++) {
writeByte((byte) ((bits & mask) >> nShift));
nShift += 8;
mask = mask << 8;
}
}
}
/**
* Append a big decimal in the TDS stream.
*
* @param bigDecimalVal
* the big decimal data value
* @param srcJdbcType
* the source JDBCType
* @param precision
* the precision of the data value
* @param scale
* the scale of the column
* @throws SQLServerException
*/
void writeBigDecimal(BigDecimal bigDecimalVal,
int srcJdbcType,
int precision,
int scale) throws SQLServerException {
/*
* Length including sign byte One 1-byte unsigned integer that represents the sign of the decimal value (0 => Negative, 1 => positive) One 4-,
* 8-, 12-, or 16-byte signed integer that represents the decimal value multiplied by 10^scale.
*/
/*
* setScale of all BigDecimal value based on metadata as scale is not sent seperately for individual value. Use the rounding used in Server.
* Say, for BigDecimal("0.1"), if scale in metdadata is 0, then ArithmeticException would be thrown if RoundingMode is not set
*/
bigDecimalVal = bigDecimalVal.setScale(scale, RoundingMode.HALF_UP);
// data length + 1 byte for sign
int bLength = BYTES16 + 1;
writeByte((byte) (bLength));
// Byte array to hold all the data and padding bytes.
byte[] bytes = new byte[bLength];
byte[] valueBytes = DDC.convertBigDecimalToBytes(bigDecimalVal, scale);
// removing the precision and scale information from the valueBytes array
System.arraycopy(valueBytes, 2, bytes, 0, valueBytes.length - 2);
writeBytes(bytes);
}
void writeSmalldatetime(String value) throws SQLServerException {
GregorianCalendar calendar = initializeCalender(TimeZone.getDefault());
long utcMillis = 0; // Value to which the calendar is to be set (in milliseconds 1/1/1970 00:00:00 GMT)
java.sql.Timestamp timestampValue = java.sql.Timestamp.valueOf(value);
utcMillis = timestampValue.getTime();
// Load the calendar with the desired value
calendar.setTimeInMillis(utcMillis);
// Number of days since the SQL Server Base Date (January 1, 1900)
int daysSinceSQLBaseDate = DDC.daysSinceBaseDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.DAY_OF_YEAR), TDS.BASE_YEAR_1900);
// Next, figure out the number of milliseconds since midnight of the current day.
int millisSinceMidnight = 1000 * calendar.get(Calendar.SECOND) + // Seconds into the current minute
60 * 1000 * calendar.get(Calendar.MINUTE) + // Minutes into the current hour
60 * 60 * 1000 * calendar.get(Calendar.HOUR_OF_DAY); // Hours into the current day
// The last millisecond of the current day is always rounded to the first millisecond
// of the next day because DATETIME is only accurate to 1/300th of a second.
if (1000 * 60 * 60 * 24 - 1 <= millisSinceMidnight) {
++daysSinceSQLBaseDate;
millisSinceMidnight = 0;
}
// Number of days since the SQL Server Base Date (January 1, 1900)
writeShort((short) daysSinceSQLBaseDate);
int secondsSinceMidnight = (millisSinceMidnight / 1000);
int minutesSinceMidnight = (secondsSinceMidnight / 60);
// Values that are 29.998 seconds or less are rounded down to the nearest minute
minutesSinceMidnight = ((secondsSinceMidnight % 60) > 29.998) ? minutesSinceMidnight + 1 : minutesSinceMidnight;
// Minutes since midnight
writeShort((short) minutesSinceMidnight);
}
void writeDatetime(String value) throws SQLServerException {
GregorianCalendar calendar = initializeCalender(TimeZone.getDefault());
long utcMillis = 0; // Value to which the calendar is to be set (in milliseconds 1/1/1970 00:00:00 GMT)
int subSecondNanos = 0;
java.sql.Timestamp timestampValue = java.sql.Timestamp.valueOf(value);
utcMillis = timestampValue.getTime();
subSecondNanos = timestampValue.getNanos();
// Load the calendar with the desired value
calendar.setTimeInMillis(utcMillis);
// Number of days there have been since the SQL Base Date.
// These are based on SQL Server algorithms
int daysSinceSQLBaseDate = DDC.daysSinceBaseDate(calendar.get(Calendar.YEAR), calendar.get(Calendar.DAY_OF_YEAR), TDS.BASE_YEAR_1900);
// Number of milliseconds since midnight of the current day.
int millisSinceMidnight = (subSecondNanos + Nanos.PER_MILLISECOND / 2) / Nanos.PER_MILLISECOND + // Millis into the current second
1000 * calendar.get(Calendar.SECOND) + // Seconds into the current minute
60 * 1000 * calendar.get(Calendar.MINUTE) + // Minutes into the current hour
60 * 60 * 1000 * calendar.get(Calendar.HOUR_OF_DAY); // Hours into the current day
// The last millisecond of the current day is always rounded to the first millisecond
// of the next day because DATETIME is only accurate to 1/300th of a second.
if (1000 * 60 * 60 * 24 - 1 <= millisSinceMidnight) {
++daysSinceSQLBaseDate;
millisSinceMidnight = 0;
}
// Last-ditch verification that the value is in the valid range for the
// DATETIMEN TDS data type (1/1/1753 to 12/31/9999). If it's not, then
// throw an exception now so that statement execution is safely canceled.
// Attempting to put an invalid value on the wire would result in a TDS
// exception, which would close the connection.
// These are based on SQL Server algorithms
if (daysSinceSQLBaseDate < DDC.daysSinceBaseDate(1753, 1, TDS.BASE_YEAR_1900)
|| daysSinceSQLBaseDate >= DDC.daysSinceBaseDate(10000, 1, TDS.BASE_YEAR_1900)) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_valueOutOfRange"));
Object[] msgArgs = {SSType.DATETIME};
throw new SQLServerException(form.format(msgArgs), SQLState.DATA_EXCEPTION_DATETIME_FIELD_OVERFLOW, DriverError.NOT_SET, null);
}
// Number of days since the SQL Server Base Date (January 1, 1900)
writeInt(daysSinceSQLBaseDate);
// Milliseconds since midnight (at a resolution of three hundredths of a second)
writeInt((3 * millisSinceMidnight + 5) / 10);
}
void writeDate(String value) throws SQLServerException {
GregorianCalendar calendar = initializeCalender(TimeZone.getDefault());
long utcMillis = 0;
java.sql.Date dateValue = java.sql.Date.valueOf(value);
utcMillis = dateValue.getTime();
// Load the calendar with the desired value
calendar.setTimeInMillis(utcMillis);
writeScaledTemporal(calendar, 0, // subsecond nanos (none for a date value)
0, // scale (dates are not scaled)
SSType.DATE);
}
void writeTime(java.sql.Timestamp value,
int scale) throws SQLServerException {
GregorianCalendar calendar = initializeCalender(TimeZone.getDefault());
long utcMillis = 0; // Value to which the calendar is to be set (in milliseconds 1/1/1970 00:00:00 GMT)
int subSecondNanos = 0;
utcMillis = value.getTime();
subSecondNanos = value.getNanos();
// Load the calendar with the desired value
calendar.setTimeInMillis(utcMillis);
writeScaledTemporal(calendar, subSecondNanos, scale, SSType.TIME);
}
void writeDateTimeOffset(Object value,
int scale,
SSType destSSType) throws SQLServerException {
GregorianCalendar calendar = null;
TimeZone timeZone = TimeZone.getDefault(); // Time zone to associate with the value in the Gregorian calendar
long utcMillis = 0; // Value to which the calendar is to be set (in milliseconds 1/1/1970 00:00:00 GMT)
int subSecondNanos = 0;
int minutesOffset = 0;
microsoft.sql.DateTimeOffset dtoValue = (microsoft.sql.DateTimeOffset) value;
utcMillis = dtoValue.getTimestamp().getTime();
subSecondNanos = dtoValue.getTimestamp().getNanos();
minutesOffset = dtoValue.getMinutesOffset();
// If the target data type is DATETIMEOFFSET, then use UTC for the calendar that
// will hold the value, since writeRPCDateTimeOffset expects a UTC calendar.
// Otherwise, when converting from DATETIMEOFFSET to other temporal data types,
// use a local time zone determined by the minutes offset of the value, since
// the writers for those types expect local calendars.
timeZone = (SSType.DATETIMEOFFSET == destSSType) ? UTC.timeZone : new SimpleTimeZone(minutesOffset * 60 * 1000, "");
calendar = new GregorianCalendar(timeZone, Locale.US);
calendar.setLenient(true);
calendar.clear();
calendar.setTimeInMillis(utcMillis);
writeScaledTemporal(calendar, subSecondNanos, scale, SSType.DATETIMEOFFSET);
writeShort((short) minutesOffset);
}
void writeOffsetDateTimeWithTimezone(OffsetDateTime offsetDateTimeValue,
int scale) throws SQLServerException {
GregorianCalendar calendar = null;
TimeZone timeZone;
long utcMillis = 0;
int subSecondNanos = 0;
int minutesOffset = 0;
try {
// offsetTimeValue.getOffset() returns a ZoneOffset object which has only hours and minutes
// components. So the result of the division will be an integer always. SQL Server also supports
// offsets in minutes precision.
minutesOffset = offsetDateTimeValue.getOffset().getTotalSeconds() / 60;
}
catch (Exception e) {
throw new SQLServerException(SQLServerException.getErrString("R_zoneOffsetError"), null, // SQLState is null as this error is generated in
// the driver
0, // Use 0 instead of DriverError.NOT_SET to use the correct constructor
e);
}
subSecondNanos = offsetDateTimeValue.getNano();
// writeScaledTemporal() expects subSecondNanos in 9 digits precssion
// but getNano() used in OffsetDateTime returns precession based on nanoseconds read from csv
// padding zeros to match the expectation of writeScaledTemporal()
int padding = 9 - String.valueOf(subSecondNanos).length();
while (padding > 0) {
subSecondNanos = subSecondNanos * 10;
padding
}
// For TIME_WITH_TIMEZONE, use UTC for the calendar that will hold the value
timeZone = UTC.timeZone;
// The behavior is similar to microsoft.sql.DateTimeOffset
// In Timestamp format, only YEAR needs to have 4 digits. The leading zeros for the rest of the fields can be omitted.
String offDateTimeStr = String.format("%04d", offsetDateTimeValue.getYear()) + '-' + offsetDateTimeValue.getMonthValue() + '-'
+ offsetDateTimeValue.getDayOfMonth() + ' ' + offsetDateTimeValue.getHour() + ':' + offsetDateTimeValue.getMinute() + ':'
+ offsetDateTimeValue.getSecond();
utcMillis = Timestamp.valueOf(offDateTimeStr).getTime();
calendar = initializeCalender(timeZone);
calendar.setTimeInMillis(utcMillis);
// Local timezone value in minutes
int minuteAdjustment = ((TimeZone.getDefault().getRawOffset()) / (60 * 1000));
// check if date is in day light savings and add daylight saving minutes
if (TimeZone.getDefault().inDaylightTime(calendar.getTime()))
minuteAdjustment += (TimeZone.getDefault().getDSTSavings()) / (60 * 1000);
// If the local time is negative then positive minutesOffset must be subtracted from calender
minuteAdjustment += (minuteAdjustment < 0) ? (minutesOffset * (-1)) : minutesOffset;
calendar.add(Calendar.MINUTE, minuteAdjustment);
writeScaledTemporal(calendar, subSecondNanos, scale, SSType.DATETIMEOFFSET);
writeShort((short) minutesOffset);
}
void writeOffsetTimeWithTimezone(OffsetTime offsetTimeValue,
int scale) throws SQLServerException {
GregorianCalendar calendar = null;
TimeZone timeZone;
long utcMillis = 0;
int subSecondNanos = 0;
int minutesOffset = 0;
try {
// offsetTimeValue.getOffset() returns a ZoneOffset object which has only hours and minutes
// components. So the result of the division will be an integer always. SQL Server also supports
// offsets in minutes precision.
minutesOffset = offsetTimeValue.getOffset().getTotalSeconds() / 60;
}
catch (Exception e) {
throw new SQLServerException(SQLServerException.getErrString("R_zoneOffsetError"), null, // SQLState is null as this error is generated in
// the driver
0, // Use 0 instead of DriverError.NOT_SET to use the correct constructor
e);
}
subSecondNanos = offsetTimeValue.getNano();
// writeScaledTemporal() expects subSecondNanos in 9 digits precssion
// but getNano() used in OffsetDateTime returns precession based on nanoseconds read from csv
// padding zeros to match the expectation of writeScaledTemporal()
int padding = 9 - String.valueOf(subSecondNanos).length();
while (padding > 0) {
subSecondNanos = subSecondNanos * 10;
padding
}
// For TIME_WITH_TIMEZONE, use UTC for the calendar that will hold the value
timeZone = UTC.timeZone;
// Using TDS.BASE_YEAR_1900, based on SQL server behavious
// If date only contains a time part, the return value is 1900, the base year.
// In Timestamp format, leading zeros for the fields can be omitted.
String offsetTimeStr = TDS.BASE_YEAR_1900 + "-01-01" + ' ' + offsetTimeValue.getHour() + ':' + offsetTimeValue.getMinute() + ':'
+ offsetTimeValue.getSecond();
utcMillis = Timestamp.valueOf(offsetTimeStr).getTime();
calendar = initializeCalender(timeZone);
calendar.setTimeInMillis(utcMillis);
int minuteAdjustment = (TimeZone.getDefault().getRawOffset()) / (60 * 1000);
// check if date is in day light savings and add daylight saving minutes to Local timezone(in minutes)
if (TimeZone.getDefault().inDaylightTime(calendar.getTime()))
minuteAdjustment += ((TimeZone.getDefault().getDSTSavings()) / (60 * 1000));
// If the local time is negative then positive minutesOffset must be subtracted from calender
minuteAdjustment += (minuteAdjustment < 0) ? (minutesOffset * (-1)) : minutesOffset;
calendar.add(Calendar.MINUTE, minuteAdjustment);
writeScaledTemporal(calendar, subSecondNanos, scale, SSType.DATETIMEOFFSET);
writeShort((short) minutesOffset);
}
void writeLong(long value) throws SQLServerException {
if (stagingBuffer.remaining() >= 8) {
stagingBuffer.putLong(value);
if (tdsChannel.isLoggingPackets()) {
if (dataIsLoggable)
logBuffer.putLong(value);
else
logBuffer.position(logBuffer.position() + 8);
}
}
else {
valueBytes[0] = (byte) ((value >> 0) & 0xFF);
valueBytes[1] = (byte) ((value >> 8) & 0xFF);
valueBytes[2] = (byte) ((value >> 16) & 0xFF);
valueBytes[3] = (byte) ((value >> 24) & 0xFF);
valueBytes[4] = (byte) ((value >> 32) & 0xFF);
valueBytes[5] = (byte) ((value >> 40) & 0xFF);
valueBytes[6] = (byte) ((value >> 48) & 0xFF);
valueBytes[7] = (byte) ((value >> 56) & 0xFF);
writeWrappedBytes(valueBytes, 8);
}
}
void writeBytes(byte[] value) throws SQLServerException {
writeBytes(value, 0, value.length);
}
void writeBytes(byte[] value,
int offset,
int length) throws SQLServerException {
assert length <= value.length;
int bytesWritten = 0;
int bytesToWrite;
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Writing " + length + " bytes");
while ((bytesToWrite = length - bytesWritten) > 0) {
if (0 == stagingBuffer.remaining())
writePacket(TDS.STATUS_NORMAL);
if (bytesToWrite > stagingBuffer.remaining())
bytesToWrite = stagingBuffer.remaining();
stagingBuffer.put(value, offset + bytesWritten, bytesToWrite);
if (tdsChannel.isLoggingPackets()) {
if (dataIsLoggable)
logBuffer.put(value, offset + bytesWritten, bytesToWrite);
else
logBuffer.position(logBuffer.position() + bytesToWrite);
}
bytesWritten += bytesToWrite;
}
}
void writeWrappedBytes(byte value[],
int valueLength) throws SQLServerException {
// This function should only be used to write a value that is longer than
// what remains in the current staging buffer. However, the value must
// be short enough to fit in an empty buffer.
assert valueLength <= value.length;
assert stagingBuffer.remaining() < valueLength;
assert valueLength <= stagingBuffer.capacity();
// Fill any remaining space in the staging buffer
int remaining = stagingBuffer.remaining();
if (remaining > 0) {
stagingBuffer.put(value, 0, remaining);
if (tdsChannel.isLoggingPackets()) {
if (dataIsLoggable)
logBuffer.put(value, 0, remaining);
else
logBuffer.position(logBuffer.position() + remaining);
}
}
writePacket(TDS.STATUS_NORMAL);
// After swapping, the staging buffer should once again be empty, so the
// remainder of the value can be written to it.
stagingBuffer.put(value, remaining, valueLength - remaining);
if (tdsChannel.isLoggingPackets()) {
if (dataIsLoggable)
logBuffer.put(value, remaining, valueLength - remaining);
else
logBuffer.position(logBuffer.position() + remaining);
}
}
void writeString(String value) throws SQLServerException {
int charsCopied = 0;
int length = value.length();
while (charsCopied < length) {
int bytesToCopy = 2 * (length - charsCopied);
if (bytesToCopy > valueBytes.length)
bytesToCopy = valueBytes.length;
int bytesCopied = 0;
while (bytesCopied < bytesToCopy) {
char ch = value.charAt(charsCopied++);
valueBytes[bytesCopied++] = (byte) ((ch >> 0) & 0xFF);
valueBytes[bytesCopied++] = (byte) ((ch >> 8) & 0xFF);
}
writeBytes(valueBytes, 0, bytesCopied);
}
}
void writeStream(InputStream inputStream,
long advertisedLength,
boolean writeChunkSizes) throws SQLServerException {
assert DataTypes.UNKNOWN_STREAM_LENGTH == advertisedLength || advertisedLength >= 0;
long actualLength = 0;
final byte[] streamByteBuffer = new byte[4 * currentPacketSize];
int bytesRead = 0;
int bytesToWrite;
do {
// Read in next chunk
for (bytesToWrite = 0; -1 != bytesRead && bytesToWrite < streamByteBuffer.length; bytesToWrite += bytesRead) {
try {
bytesRead = inputStream.read(streamByteBuffer, bytesToWrite, streamByteBuffer.length - bytesToWrite);
}
catch (IOException e) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorReadingStream"));
Object[] msgArgs = {e.toString()};
error(form.format(msgArgs), SQLState.DATA_EXCEPTION_NOT_SPECIFIC, DriverError.NOT_SET);
}
if (-1 == bytesRead)
break;
// Check for invalid bytesRead returned from InputStream.read
if (bytesRead < 0 || bytesRead > streamByteBuffer.length - bytesToWrite) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorReadingStream"));
Object[] msgArgs = {SQLServerException.getErrString("R_streamReadReturnedInvalidValue")};
error(form.format(msgArgs), SQLState.DATA_EXCEPTION_NOT_SPECIFIC, DriverError.NOT_SET);
}
}
// Write it out
if (writeChunkSizes)
writeInt(bytesToWrite);
writeBytes(streamByteBuffer, 0, bytesToWrite);
actualLength += bytesToWrite;
}
while (-1 != bytesRead || bytesToWrite > 0);
// If we were given an input stream length that we had to match and
// the actual stream length did not match then cancel the request.
if (DataTypes.UNKNOWN_STREAM_LENGTH != advertisedLength && actualLength != advertisedLength) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_mismatchedStreamLength"));
Object[] msgArgs = {Long.valueOf(advertisedLength), Long.valueOf(actualLength)};
error(form.format(msgArgs), SQLState.DATA_EXCEPTION_LENGTH_MISMATCH, DriverError.NOT_SET);
}
}
/*
* Adding another function for writing non-unicode reader instead of re-factoring the writeReader() for performance efficiency. As this method
* will only be used in bulk copy, it needs to be efficient. Note: Any changes in algorithm/logic should propagate to both writeReader() and
* writeNonUnicodeReader().
*/
void writeNonUnicodeReader(Reader reader,
long advertisedLength,
boolean isDestBinary,
Charset charSet) throws SQLServerException {
assert DataTypes.UNKNOWN_STREAM_LENGTH == advertisedLength || advertisedLength >= 0;
long actualLength = 0;
char[] streamCharBuffer = new char[currentPacketSize];
// The unicode version, writeReader() allocates a byte buffer that is 4 times the currentPacketSize, not sure why.
byte[] streamByteBuffer = new byte[currentPacketSize];
int charsRead = 0;
int charsToWrite;
int bytesToWrite;
String streamString;
do {
// Read in next chunk
for (charsToWrite = 0; -1 != charsRead && charsToWrite < streamCharBuffer.length; charsToWrite += charsRead) {
try {
charsRead = reader.read(streamCharBuffer, charsToWrite, streamCharBuffer.length - charsToWrite);
}
catch (IOException e) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorReadingStream"));
Object[] msgArgs = {e.toString()};
error(form.format(msgArgs), SQLState.DATA_EXCEPTION_NOT_SPECIFIC, DriverError.NOT_SET);
}
if (-1 == charsRead)
break;
// Check for invalid bytesRead returned from Reader.read
if (charsRead < 0 || charsRead > streamCharBuffer.length - charsToWrite) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorReadingStream"));
Object[] msgArgs = {SQLServerException.getErrString("R_streamReadReturnedInvalidValue")};
error(form.format(msgArgs), SQLState.DATA_EXCEPTION_NOT_SPECIFIC, DriverError.NOT_SET);
}
}
if (!isDestBinary) {
// Write it out
// This also writes the PLP_TERMINATOR token after all the data in the the stream are sent.
// The Do-While loop goes on one more time as charsToWrite is greater than 0 for the last chunk, and
// in this last round the only thing that is written is an int value of 0, which is the PLP Terminator token(0x00000000).
writeInt(charsToWrite);
for (int charsCopied = 0; charsCopied < charsToWrite; ++charsCopied) {
if (null == charSet) {
streamByteBuffer[charsCopied] = (byte) (streamCharBuffer[charsCopied] & 0xFF);
}
else {
// encoding as per collation
streamByteBuffer[charsCopied] = new String(streamCharBuffer[charsCopied] + "").getBytes(charSet)[0];
}
}
writeBytes(streamByteBuffer, 0, charsToWrite);
}
else {
bytesToWrite = charsToWrite;
if (0 != charsToWrite)
bytesToWrite = charsToWrite / 2;
streamString = new String(streamCharBuffer);
byte[] bytes = ParameterUtils.HexToBin(streamString.trim());
writeInt(bytesToWrite);
writeBytes(bytes, 0, bytesToWrite);
}
actualLength += charsToWrite;
}
while (-1 != charsRead || charsToWrite > 0);
// If we were given an input stream length that we had to match and
// the actual stream length did not match then cancel the request.
if (DataTypes.UNKNOWN_STREAM_LENGTH != advertisedLength && actualLength != advertisedLength) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_mismatchedStreamLength"));
Object[] msgArgs = {Long.valueOf(advertisedLength), Long.valueOf(actualLength)};
error(form.format(msgArgs), SQLState.DATA_EXCEPTION_LENGTH_MISMATCH, DriverError.NOT_SET);
}
}
/*
* Note: There is another method with same code logic for non unicode reader, writeNonUnicodeReader(), implemented for performance efficiency. Any
* changes in algorithm/logic should propagate to both writeReader() and writeNonUnicodeReader().
*/
void writeReader(Reader reader,
long advertisedLength,
boolean writeChunkSizes) throws SQLServerException {
assert DataTypes.UNKNOWN_STREAM_LENGTH == advertisedLength || advertisedLength >= 0;
long actualLength = 0;
char[] streamCharBuffer = new char[2 * currentPacketSize];
byte[] streamByteBuffer = new byte[4 * currentPacketSize];
int charsRead = 0;
int charsToWrite;
do {
// Read in next chunk
for (charsToWrite = 0; -1 != charsRead && charsToWrite < streamCharBuffer.length; charsToWrite += charsRead) {
try {
charsRead = reader.read(streamCharBuffer, charsToWrite, streamCharBuffer.length - charsToWrite);
}
catch (IOException e) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorReadingStream"));
Object[] msgArgs = {e.toString()};
error(form.format(msgArgs), SQLState.DATA_EXCEPTION_NOT_SPECIFIC, DriverError.NOT_SET);
}
if (-1 == charsRead)
break;
// Check for invalid bytesRead returned from Reader.read
if (charsRead < 0 || charsRead > streamCharBuffer.length - charsToWrite) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorReadingStream"));
Object[] msgArgs = {SQLServerException.getErrString("R_streamReadReturnedInvalidValue")};
error(form.format(msgArgs), SQLState.DATA_EXCEPTION_NOT_SPECIFIC, DriverError.NOT_SET);
}
}
// Write it out
if (writeChunkSizes)
writeInt(2 * charsToWrite);
// Convert from Unicode characters to bytes
// Note: The following inlined code is much faster than the equivalent
// call to (new String(streamCharBuffer)).getBytes("UTF-16LE") because it
// saves a conversion to String and use of Charset in that conversion.
for (int charsCopied = 0; charsCopied < charsToWrite; ++charsCopied) {
streamByteBuffer[2 * charsCopied] = (byte) ((streamCharBuffer[charsCopied] >> 0) & 0xFF);
streamByteBuffer[2 * charsCopied + 1] = (byte) ((streamCharBuffer[charsCopied] >> 8) & 0xFF);
}
writeBytes(streamByteBuffer, 0, 2 * charsToWrite);
actualLength += charsToWrite;
}
while (-1 != charsRead || charsToWrite > 0);
// If we were given an input stream length that we had to match and
// the actual stream length did not match then cancel the request.
if (DataTypes.UNKNOWN_STREAM_LENGTH != advertisedLength && actualLength != advertisedLength) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_mismatchedStreamLength"));
Object[] msgArgs = {Long.valueOf(advertisedLength), Long.valueOf(actualLength)};
error(form.format(msgArgs), SQLState.DATA_EXCEPTION_LENGTH_MISMATCH, DriverError.NOT_SET);
}
}
GregorianCalendar initializeCalender(TimeZone timeZone) {
GregorianCalendar calendar = null;
// Create the calendar that will hold the value. For DateTimeOffset values, the calendar's
// time zone is UTC. For other values, the calendar's time zone is a local time zone.
calendar = new GregorianCalendar(timeZone, Locale.US);
// Set the calendar lenient to allow setting the DAY_OF_YEAR and MILLISECOND fields
// to roll other fields to their correct values.
calendar.setLenient(true);
// Clear the calendar of any existing state. The state of a new Calendar object always
// reflects the current date, time, DST offset, etc.
calendar.clear();
return calendar;
}
final void error(String reason,
SQLState sqlState,
DriverError driverError) throws SQLServerException {
assert null != command;
command.interrupt(reason);
throw new SQLServerException(reason, sqlState, driverError, null);
}
/**
* Sends an attention signal to the server, if necessary, to tell it to stop processing the current command on this connection.
*
* If no packets of the command's request have yet been sent to the server, then no attention signal needs to be sent. The interrupt will be
* handled entirely by the driver.
*
* This method does not need synchronization as it does not manipulate interrupt state and writing is guaranteed to occur only from one thread at
* a time.
*/
final boolean sendAttention() throws SQLServerException {
// If any request packets were already written to the server then send an
// attention signal to the server to tell it to ignore the request or
// cancel its execution.
if (packetNum > 0) {
// Ideally, we would want to add the following assert here.
// But to add that the variable isEOMSent would have to be made
// volatile as this piece of code would be reached from multiple
// threads. So, not doing it to avoid perf hit. Note that
// isEOMSent would be updated in writePacket everytime an EOM is sent
// assert isEOMSent;
if (logger.isLoggable(Level.FINE))
logger.fine(this + ": sending attention...");
++tdsChannel.numMsgsSent;
startMessage(command, TDS.PKT_CANCEL_REQ);
endMessage();
return true;
}
return false;
}
private void writePacket(int tdsMessageStatus) throws SQLServerException {
final boolean atEOM = (TDS.STATUS_BIT_EOM == (TDS.STATUS_BIT_EOM & tdsMessageStatus));
final boolean isCancelled = ((TDS.PKT_CANCEL_REQ == tdsMessageType)
|| ((tdsMessageStatus & TDS.STATUS_BIT_ATTENTION) == TDS.STATUS_BIT_ATTENTION));
// Before writing each packet to the channel, check if an interrupt has occurred.
if (null != command && (!isCancelled))
command.checkForInterrupt();
writePacketHeader(tdsMessageStatus | sendResetConnection);
sendResetConnection = 0;
flush(atEOM);
// If this is the last packet then flush the remainder of the request
// through the socket. The first flush() call ensured that data currently
// waiting in the socket buffer was sent, flipped the buffers, and started
// sending data from the staging buffer (flipped to be the new socket buffer).
// This flush() call ensures that all remaining data in the socket buffer is sent.
if (atEOM) {
flush(atEOM);
isEOMSent = true;
++tdsChannel.numMsgsSent;
}
// If we just sent the first login request packet and SSL encryption was enabled
// for login only, then disable SSL now.
if (TDS.PKT_LOGON70 == tdsMessageType && 1 == packetNum && TDS.ENCRYPT_OFF == con.getNegotiatedEncryptionLevel()) {
tdsChannel.disableSSL();
}
// Notify the currently associated command (if any) that we have written the last
// of the response packets to the channel.
if (null != command && (!isCancelled) && atEOM)
command.onRequestComplete();
}
private void writePacketHeader(int tdsMessageStatus) {
int tdsMessageLength = stagingBuffer.position();
++packetNum;
// Write the TDS packet header back at the start of the staging buffer
stagingBuffer.put(TDS.PACKET_HEADER_MESSAGE_TYPE, tdsMessageType);
stagingBuffer.put(TDS.PACKET_HEADER_MESSAGE_STATUS, (byte) tdsMessageStatus);
stagingBuffer.put(TDS.PACKET_HEADER_MESSAGE_LENGTH, (byte) ((tdsMessageLength >> 8) & 0xFF)); // Note: message length is 16 bits,
stagingBuffer.put(TDS.PACKET_HEADER_MESSAGE_LENGTH + 1, (byte) ((tdsMessageLength >> 0) & 0xFF)); // written BIG ENDIAN
stagingBuffer.put(TDS.PACKET_HEADER_SPID, (byte) ((tdsChannel.getSPID() >> 8) & 0xFF)); // Note: SPID is 16 bits,
stagingBuffer.put(TDS.PACKET_HEADER_SPID + 1, (byte) ((tdsChannel.getSPID() >> 0) & 0xFF)); // written BIG ENDIAN
stagingBuffer.put(TDS.PACKET_HEADER_SEQUENCE_NUM, (byte) (packetNum % 256));
stagingBuffer.put(TDS.PACKET_HEADER_WINDOW, (byte) 0); // Window (Reserved/Not used)
// Write the header to the log buffer too if logging.
if (tdsChannel.isLoggingPackets()) {
logBuffer.put(TDS.PACKET_HEADER_MESSAGE_TYPE, tdsMessageType);
logBuffer.put(TDS.PACKET_HEADER_MESSAGE_STATUS, (byte) tdsMessageStatus);
logBuffer.put(TDS.PACKET_HEADER_MESSAGE_LENGTH, (byte) ((tdsMessageLength >> 8) & 0xFF)); // Note: message length is 16 bits,
logBuffer.put(TDS.PACKET_HEADER_MESSAGE_LENGTH + 1, (byte) ((tdsMessageLength >> 0) & 0xFF)); // written BIG ENDIAN
logBuffer.put(TDS.PACKET_HEADER_SPID, (byte) ((tdsChannel.getSPID() >> 8) & 0xFF)); // Note: SPID is 16 bits,
logBuffer.put(TDS.PACKET_HEADER_SPID + 1, (byte) ((tdsChannel.getSPID() >> 0) & 0xFF)); // written BIG ENDIAN
logBuffer.put(TDS.PACKET_HEADER_SEQUENCE_NUM, (byte) (packetNum % 256));
logBuffer.put(TDS.PACKET_HEADER_WINDOW, (byte) 0); // Window (Reserved/Not used);
}
}
void flush(boolean atEOM) throws SQLServerException {
// First, flush any data left in the socket buffer.
tdsChannel.write(socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining());
socketBuffer.position(socketBuffer.limit());
// If there is data in the staging buffer that needs to be written
// to the socket, the socket buffer is now empty, so swap buffers
// and start writing data from the staging buffer.
if (stagingBuffer.position() >= TDS_PACKET_HEADER_SIZE) {
// Swap the packet buffers ...
ByteBuffer swapBuffer = stagingBuffer;
stagingBuffer = socketBuffer;
socketBuffer = swapBuffer;
// ... and prepare to send data from the from the new socket
// buffer (the old staging buffer).
// We need to use flip() rather than rewind() here so that
// the socket buffer's limit is properly set for the last
// packet, which may be shorter than the other packets.
socketBuffer.flip();
stagingBuffer.clear();
// If we are logging TDS packets then log the packet we're about
// to send over the wire now.
if (tdsChannel.isLoggingPackets()) {
tdsChannel.logPacket(logBuffer.array(), 0, socketBuffer.limit(),
this.toString() + " sending packet (" + socketBuffer.limit() + " bytes)");
}
// Prepare for the next packet
if (!atEOM)
preparePacket();
// Finally, start sending data from the new socket buffer.
tdsChannel.write(socketBuffer.array(), socketBuffer.position(), socketBuffer.remaining());
socketBuffer.position(socketBuffer.limit());
}
}
// Composite write operations
/**
* Write out elements common to all RPC values.
*
* @param sName
* the optional parameter name
* @param bOut
* boolean true if the value that follows is being registered as an ouput parameter
* @param tdsType
* TDS type of the value that follows
*/
void writeRPCNameValType(String sName,
boolean bOut,
TDSType tdsType) throws SQLServerException {
int nNameLen = 0;
if (null != sName)
nNameLen = sName.length() + 1; // The @ prefix is required for the param
writeByte((byte) nNameLen); // param name len
if (nNameLen > 0) {
writeChar('@');
writeString(sName);
}
if (null != cryptoMeta)
writeByte((byte) (bOut ? 1 | TDS.AE_METADATA : 0 | TDS.AE_METADATA)); // status
else
writeByte((byte) (bOut ? 1 : 0)); // status
writeByte(tdsType.byteValue()); // type
}
/**
* Append a boolean value in RPC transmission format.
*
* @param sName
* the optional parameter name
* @param booleanValue
* the data value
* @param bOut
* boolean true if the data value is being registered as an ouput parameter
*/
void writeRPCBit(String sName,
Boolean booleanValue,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.BITN);
writeByte((byte) 1); // max length of datatype
if (null == booleanValue) {
writeByte((byte) 0); // len of data bytes
}
else {
writeByte((byte) 1); // length of datatype
writeByte((byte) (booleanValue.booleanValue() ? 1 : 0));
}
}
/**
* Append a short value in RPC transmission format.
*
* @param sName
* the optional parameter name
* @param shortValue
* the data value
* @param bOut
* boolean true if the data value is being registered as an ouput parameter
*/
void writeRPCByte(String sName,
Byte byteValue,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.INTN);
writeByte((byte) 1); // max length of datatype
if (null == byteValue) {
writeByte((byte) 0); // len of data bytes
}
else {
writeByte((byte) 1); // length of datatype
writeByte(byteValue.byteValue());
}
}
/**
* Append a short value in RPC transmission format.
*
* @param sName
* the optional parameter name
* @param shortValue
* the data value
* @param bOut
* boolean true if the data value is being registered as an ouput parameter
*/
void writeRPCShort(String sName,
Short shortValue,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.INTN);
writeByte((byte) 2); // max length of datatype
if (null == shortValue) {
writeByte((byte) 0); // len of data bytes
}
else {
writeByte((byte) 2); // length of datatype
writeShort(shortValue.shortValue());
}
}
/**
* Append an int value in RPC transmission format.
*
* @param sName
* the optional parameter name
* @param intValue
* the data value
* @param bOut
* boolean true if the data value is being registered as an ouput parameter
*/
void writeRPCInt(String sName,
Integer intValue,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.INTN);
writeByte((byte) 4); // max length of datatype
if (null == intValue) {
writeByte((byte) 0); // len of data bytes
}
else {
writeByte((byte) 4); // length of datatype
writeInt(intValue.intValue());
}
}
/**
* Append a long value in RPC transmission format.
*
* @param sName
* the optional parameter name
* @param longValue
* the data value
* @param bOut
* boolean true if the data value is being registered as an ouput parameter
*/
void writeRPCLong(String sName,
Long longValue,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.INTN);
writeByte((byte) 8); // max length of datatype
if (null == longValue) {
writeByte((byte) 0); // len of data bytes
}
else {
writeByte((byte) 8); // length of datatype
writeLong(longValue.longValue());
}
}
/**
* Append a real value in RPC transmission format.
*
* @param sName
* the optional parameter name
* @param floatValue
* the data value
* @param bOut
* boolean true if the data value is being registered as an ouput parameter
*/
void writeRPCReal(String sName,
Float floatValue,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.FLOATN);
// Data and length
if (null == floatValue) {
writeByte((byte) 4); // max length
writeByte((byte) 0); // actual length (0 == null)
}
else {
writeByte((byte) 4); // max length
writeByte((byte) 4); // actual length
writeInt(Float.floatToRawIntBits(floatValue.floatValue()));
}
}
/**
* Append a double value in RPC transmission format.
*
* @param sName
* the optional parameter name
* @param doubleValue
* the data value
* @param bOut
* boolean true if the data value is being registered as an ouput parameter
*/
void writeRPCDouble(String sName,
Double doubleValue,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.FLOATN);
int l = 8;
writeByte((byte) l); // max length of datatype
// Data and length
if (null == doubleValue) {
writeByte((byte) 0); // len of data bytes
}
else {
writeByte((byte) l); // len of data bytes
long bits = Double.doubleToLongBits(doubleValue.doubleValue());
long mask = 0xFF;
int nShift = 0;
for (int i = 0; i < 8; i++) {
writeByte((byte) ((bits & mask) >> nShift));
nShift += 8;
mask = mask << 8;
}
}
}
/**
* Append a big decimal in RPC transmission format.
*
* @param sName
* the optional parameter name
* @param bdValue
* the data value
* @param nScale
* the desired scale
* @param bOut
* boolean true if the data value is being registered as an ouput parameter
*/
void writeRPCBigDecimal(String sName,
BigDecimal bdValue,
int nScale,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.DECIMALN);
writeByte((byte) 0x11); // maximum length
writeByte((byte) SQLServerConnection.maxDecimalPrecision); // precision
byte[] valueBytes = DDC.convertBigDecimalToBytes(bdValue, nScale);
writeBytes(valueBytes, 0, valueBytes.length);
}
/**
* Appends a standard v*max header for RPC parameter transmission.
*
* @param headerLength
* the total length of the PLP data block.
* @param isNull
* true if the value is NULL.
* @param collation
* The SQL collation associated with the value that follows the v*max header. Null for non-textual types.
*/
void writeVMaxHeader(long headerLength,
boolean isNull,
SQLCollation collation) throws SQLServerException {
// Send v*max length indicator 0xFFFF.
writeShort((short) 0xFFFF);
// Send collation if requested.
if (null != collation)
collation.writeCollation(this);
// Handle null here and return, we're done here if it's null.
if (isNull) {
// Null header for v*max types is 0xFFFFFFFFFFFFFFFF.
writeLong(0xFFFFFFFFFFFFFFFFL);
}
else if (DataTypes.UNKNOWN_STREAM_LENGTH == headerLength) {
// Append v*max length.
// UNKNOWN_PLP_LEN is 0xFFFFFFFFFFFFFFFE
writeLong(0xFFFFFFFFFFFFFFFEL);
// NOTE: Don't send the first chunk length, this will be calculated by caller.
}
else {
// For v*max types with known length, length is <totallength8><chunklength4>
// We're sending same total length as chunk length (as we're sending 1 chunk).
writeLong(headerLength);
}
}
/**
* Utility for internal writeRPCString calls
*/
void writeRPCStringUnicode(String sValue) throws SQLServerException {
writeRPCStringUnicode(null, sValue, false, null);
}
/**
* Writes a string value as Unicode for RPC
*
* @param sName
* the optional parameter name
* @param sValue
* the data value
* @param bOut
* boolean true if the data value is being registered as an ouput parameter
* @param collation
* the collation of the data value
*/
void writeRPCStringUnicode(String sName,
String sValue,
boolean bOut,
SQLCollation collation) throws SQLServerException {
boolean bValueNull = (sValue == null);
int nValueLen = bValueNull ? 0 : (2 * sValue.length());
boolean isShortValue = nValueLen <= DataTypes.SHORT_VARTYPE_MAX_BYTES;
// Textual RPC requires a collation. If none is provided, as is the case when
// the SSType is non-textual, then use the database collation by default.
if (null == collation)
collation = con.getDatabaseCollation();
// Use PLP encoding on Yukon and later with long values and OUT parameters
boolean usePLP = (!isShortValue || bOut);
if (usePLP) {
writeRPCNameValType(sName, bOut, TDSType.NVARCHAR);
// Handle Yukon v*max type header here.
writeVMaxHeader(nValueLen, // Length
bValueNull, // Is null?
collation);
// Send the data.
if (!bValueNull) {
if (nValueLen > 0) {
writeInt(nValueLen);
writeString(sValue);
}
// Send the terminator PLP chunk.
writeInt(0);
}
}
else // non-PLP type
{
// Write maximum length of data
if (isShortValue) {
writeRPCNameValType(sName, bOut, TDSType.NVARCHAR);
writeShort((short) DataTypes.SHORT_VARTYPE_MAX_BYTES);
}
else {
writeRPCNameValType(sName, bOut, TDSType.NTEXT);
writeInt(DataTypes.IMAGE_TEXT_MAX_BYTES);
}
collation.writeCollation(this);
// Data and length
if (bValueNull) {
writeShort((short) -1); // actual len
}
else {
// Write actual length of data
if (isShortValue)
writeShort((short) nValueLen);
else
writeInt(nValueLen);
// If length is zero, we're done.
if (0 != nValueLen)
writeString(sValue); // data
}
}
}
void writeTVP(TVP value) throws SQLServerException {
if (!value.isNull()) {
writeByte((byte) 0); // status
}
else {
// Default TVP
writeByte((byte) TDS.TVP_STATUS_DEFAULT); // default TVP
}
writeByte((byte) TDS.TDS_TVP);
/*
* TVP_TYPENAME = DbName OwningSchema TypeName
*/
// Database where TVP type resides
if (null != value.getDbNameTVP()) {
writeByte((byte) value.getDbNameTVP().length());
writeString(value.getDbNameTVP());
}
else
writeByte((byte) 0x00); // empty DB name
// Schema where TVP type resides
if (null != value.getOwningSchemaNameTVP()) {
writeByte((byte) value.getOwningSchemaNameTVP().length());
writeString(value.getOwningSchemaNameTVP());
}
else
writeByte((byte) 0x00); // empty Schema name
// TVP type name
if (null != value.getTVPName()) {
writeByte((byte) value.getTVPName().length());
writeString(value.getTVPName());
}
else
writeByte((byte) 0x00); // empty TVP name
if (!value.isNull()) {
writeTVPColumnMetaData(value);
// optional OrderUnique metadata
writeTvpOrderUnique(value);
}
else {
writeShort((short) TDS.TVP_NULL_TOKEN);
}
// TVP_END_TOKEN
writeByte((byte) 0x00);
try {
writeTVPRows(value);
}
catch (NumberFormatException e) {
throw new SQLServerException(SQLServerException.getErrString("R_TVPInvalidColumnValue"), e);
}
catch (ClassCastException e) {
throw new SQLServerException(SQLServerException.getErrString("R_TVPInvalidColumnValue"), e);
}
}
void writeTVPRows(TVP value) throws SQLServerException {
boolean isShortValue, isNull;
int dataLength;
boolean tdsWritterCached = false;
ByteBuffer cachedTVPHeaders = null;
TDSCommand cachedCommand = null;
boolean cachedRequestComplete = false;
boolean cachedInterruptsEnabled = false;
boolean cachedProcessedResponse = false;
if (!value.isNull()) {
// is used, the tdsWriter of the calling preparedStatement is overwritten by the SQLServerResultSet#next() method when fetching new rows.
// Therefore, we need to send TVP data row by row before fetching new row.
if (TVPType.ResultSet == value.tvpType) {
if ((null != value.sourceResultSet) && (value.sourceResultSet instanceof SQLServerResultSet)) {
SQLServerResultSet sourceResultSet = (SQLServerResultSet) value.sourceResultSet;
SQLServerStatement src_stmt = (SQLServerStatement) sourceResultSet.getStatement();
int resultSetServerCursorId = sourceResultSet.getServerCursorId();
if (con.equals(src_stmt.getConnection()) && 0 != resultSetServerCursorId) {
cachedTVPHeaders = ByteBuffer.allocate(stagingBuffer.capacity()).order(stagingBuffer.order());
cachedTVPHeaders.put(stagingBuffer.array(), 0, stagingBuffer.position());
cachedCommand = this.command;
cachedRequestComplete = command.getRequestComplete();
cachedInterruptsEnabled = command.getInterruptsEnabled();
cachedProcessedResponse = command.getProcessedResponse();
tdsWritterCached = true;
if (sourceResultSet.isForwardOnly()) {
sourceResultSet.setFetchSize(1);
}
}
}
}
Map<Integer, SQLServerMetaData> columnMetadata = value.getColumnMetadata();
Iterator<Entry<Integer, SQLServerMetaData>> columnsIterator;
while (value.next()) {
// restore command and TDS header, which have been overwritten by value.next()
if (tdsWritterCached) {
command = cachedCommand;
stagingBuffer.clear();
logBuffer.clear();
writeBytes(cachedTVPHeaders.array(), 0, cachedTVPHeaders.position());
}
Object[] rowData = value.getRowData();
// ROW
writeByte((byte) TDS.TVP_ROW);
columnsIterator = columnMetadata.entrySet().iterator();
int currentColumn = 0;
while (columnsIterator.hasNext()) {
Map.Entry<Integer, SQLServerMetaData> columnPair = columnsIterator.next();
// If useServerDefault is set, client MUST NOT emit TvpColumnData for the associated column
if (columnPair.getValue().useServerDefault) {
currentColumn++;
continue;
}
JDBCType jdbcType = JDBCType.of(columnPair.getValue().javaSqlType);
String currentColumnStringValue = null;
Object currentObject = null;
if (null != rowData) {
// if rowData has value for the current column, retrieve it. If not, current column will stay null.
if (rowData.length > currentColumn) {
currentObject = rowData[currentColumn];
if (null != currentObject) {
currentColumnStringValue = String.valueOf(currentObject);
}
}
}
try {
switch (jdbcType) {
case BIGINT:
if (null == currentColumnStringValue)
writeByte((byte) 0);
else {
writeByte((byte) 8);
writeLong(Long.valueOf(currentColumnStringValue).longValue());
}
break;
case BIT:
if (null == currentColumnStringValue)
writeByte((byte) 0);
else {
writeByte((byte) 1);
writeByte((byte) (Boolean.valueOf(currentColumnStringValue).booleanValue() ? 1 : 0));
}
break;
case INTEGER:
if (null == currentColumnStringValue)
writeByte((byte) 0);
else {
writeByte((byte) 4);
writeInt(Integer.valueOf(currentColumnStringValue).intValue());
}
break;
case SMALLINT:
case TINYINT:
if (null == currentColumnStringValue)
writeByte((byte) 0);
else {
writeByte((byte) 2); // length of datatype
writeShort(Short.valueOf(currentColumnStringValue).shortValue());
}
break;
case DECIMAL:
case NUMERIC:
if (null == currentColumnStringValue)
writeByte((byte) 0);
else {
writeByte((byte) TDSWriter.BIGDECIMAL_MAX_LENGTH); // maximum length
BigDecimal bdValue = new BigDecimal(currentColumnStringValue);
/*
* setScale of all BigDecimal value based on metadata as scale is not sent seperately for individual value. Use
* the rounding used in Server. Say, for BigDecimal("0.1"), if scale in metdadata is 0, then ArithmeticException
* would be thrown if RoundingMode is not set
*/
bdValue = bdValue.setScale(columnPair.getValue().scale, RoundingMode.HALF_UP);
byte[] valueBytes = DDC.convertBigDecimalToBytes(bdValue, bdValue.scale());
// 1-byte for sign and 16-byte for integer
byte[] byteValue = new byte[17];
// removing the precision and scale information from the valueBytes array
System.arraycopy(valueBytes, 2, byteValue, 0, valueBytes.length - 2);
writeBytes(byteValue);
}
break;
case DOUBLE:
if (null == currentColumnStringValue)
writeByte((byte) 0); // len of data bytes
else {
writeByte((byte) 8); // len of data bytes
long bits = Double.doubleToLongBits(Double.valueOf(currentColumnStringValue).doubleValue());
long mask = 0xFF;
int nShift = 0;
for (int i = 0; i < 8; i++) {
writeByte((byte) ((bits & mask) >> nShift));
nShift += 8;
mask = mask << 8;
}
}
break;
case FLOAT:
case REAL:
if (null == currentColumnStringValue)
writeByte((byte) 0); // actual length (0 == null)
else {
writeByte((byte) 4); // actual length
writeInt(Float.floatToRawIntBits(Float.valueOf(currentColumnStringValue).floatValue()));
}
break;
case DATE:
case TIME:
case TIMESTAMP:
case DATETIMEOFFSET:
case TIMESTAMP_WITH_TIMEZONE:
case TIME_WITH_TIMEZONE:
case CHAR:
case VARCHAR:
case NCHAR:
case NVARCHAR:
case LONGVARCHAR:
case LONGNVARCHAR:
case SQLXML:
isShortValue = (2L * columnPair.getValue().precision) <= DataTypes.SHORT_VARTYPE_MAX_BYTES;
isNull = (null == currentColumnStringValue);
dataLength = isNull ? 0 : currentColumnStringValue.length() * 2;
if (!isShortValue) {
// check null
if (isNull)
// Null header for v*max types is 0xFFFFFFFFFFFFFFFF.
writeLong(0xFFFFFFFFFFFFFFFFL);
else if (DataTypes.UNKNOWN_STREAM_LENGTH == dataLength)
// Append v*max length.
// UNKNOWN_PLP_LEN is 0xFFFFFFFFFFFFFFFE
writeLong(0xFFFFFFFFFFFFFFFEL);
else
// For v*max types with known length, length is <totallength8><chunklength4>
writeLong(dataLength);
if (!isNull) {
if (dataLength > 0) {
writeInt(dataLength);
writeString(currentColumnStringValue);
}
// Send the terminator PLP chunk.
writeInt(0);
}
}
else {
if (isNull)
writeShort((short) -1); // actual len
else {
writeShort((short) dataLength);
writeString(currentColumnStringValue);
}
}
break;
case BINARY:
case VARBINARY:
case LONGVARBINARY:
// Handle conversions as done in other types.
isShortValue = columnPair.getValue().precision <= DataTypes.SHORT_VARTYPE_MAX_BYTES;
isNull = (null == currentObject);
if (currentObject instanceof String)
dataLength = isNull ? 0 : (toByteArray(currentObject.toString())).length;
else
dataLength = isNull ? 0 : ((byte[]) currentObject).length;
if (!isShortValue) {
// check null
if (isNull)
// Null header for v*max types is 0xFFFFFFFFFFFFFFFF.
writeLong(0xFFFFFFFFFFFFFFFFL);
else if (DataTypes.UNKNOWN_STREAM_LENGTH == dataLength)
// Append v*max length.
// UNKNOWN_PLP_LEN is 0xFFFFFFFFFFFFFFFE
writeLong(0xFFFFFFFFFFFFFFFEL);
else
// For v*max types with known length, length is <totallength8><chunklength4>
writeLong(dataLength);
if (!isNull) {
if (dataLength > 0) {
writeInt(dataLength);
if (currentObject instanceof String)
writeBytes(toByteArray(currentObject.toString()));
else
writeBytes((byte[]) currentObject);
}
// Send the terminator PLP chunk.
writeInt(0);
}
}
else {
if (isNull)
writeShort((short) -1); // actual len
else {
writeShort((short) dataLength);
if (currentObject instanceof String)
writeBytes(toByteArray(currentObject.toString()));
else
writeBytes((byte[]) currentObject);
}
}
break;
default:
assert false : "Unexpected JDBC type " + jdbcType.toString();
}
}
catch (IllegalArgumentException e) {
throw new SQLServerException(SQLServerException.getErrString("R_errorConvertingValue"), e);
}
catch (ArrayIndexOutOfBoundsException e) {
throw new SQLServerException(SQLServerException.getErrString("R_CSVDataSchemaMismatch"), e);
}
currentColumn++;
}
// send this row, read its response (throw exception in case of errors) and reset command status
if (tdsWritterCached) {
// TVP_END_TOKEN
writeByte((byte) 0x00);
writePacket(TDS.STATUS_BIT_EOM);
TDSReader tdsReader = tdsChannel.getReader(command);
int tokenType = tdsReader.peekTokenType();
if (TDS.TDS_ERR == tokenType) {
StreamError databaseError = new StreamError();
databaseError.setFromTDS(tdsReader);
SQLServerException.makeFromDatabaseError(con, null, databaseError.getMessage(), databaseError, false);
}
command.setInterruptsEnabled(true);
command.setRequestComplete(false);
}
}
}
// reset command status which have been overwritten
if (tdsWritterCached) {
command.setRequestComplete(cachedRequestComplete);
command.setInterruptsEnabled(cachedInterruptsEnabled);
command.setProcessedResponse(cachedProcessedResponse);
}
else {
// TVP_END_TOKEN
writeByte((byte) 0x00);
}
}
private static byte[] toByteArray(String s) {
return DatatypeConverter.parseHexBinary(s);
}
void writeTVPColumnMetaData(TVP value) throws SQLServerException {
boolean isShortValue;
// TVP_COLMETADATA
writeShort((short) value.getTVPColumnCount());
Map<Integer, SQLServerMetaData> columnMetadata = value.getColumnMetadata();
Iterator<Entry<Integer, SQLServerMetaData>> columnsIterator = columnMetadata.entrySet().iterator();
/*
* TypeColumnMetaData = UserType Flags TYPE_INFO ColName ;
*/
while (columnsIterator.hasNext()) {
Map.Entry<Integer, SQLServerMetaData> pair = columnsIterator.next();
JDBCType jdbcType = JDBCType.of(pair.getValue().javaSqlType);
boolean useServerDefault = pair.getValue().useServerDefault;
// ULONG ; UserType of column
// The value will be 0x0000 with the exceptions of TIMESTAMP (0x0050) and alias types (greater than 0x00FF).
writeInt(0);
/*
* Flags = fNullable ; Column is nullable - %x01 fCaseSen -- Ignored ; usUpdateable -- Ignored ; fIdentity ; Column is identity column -
* %x10 fComputed ; Column is computed - %x20 usReservedODBC -- Ignored ; fFixedLenCLRType-- Ignored ; fDefault ; Column is default value
* - %x200 usReserved -- Ignored ;
*/
short flags = TDS.FLAG_NULLABLE;
if (useServerDefault) {
flags |= TDS.FLAG_TVP_DEFAULT_COLUMN;
}
writeShort(flags);
// Type info
switch (jdbcType) {
case BIGINT:
writeByte(TDSType.INTN.byteValue());
writeByte((byte) 8); // max length of datatype
break;
case BIT:
writeByte(TDSType.BITN.byteValue());
writeByte((byte) 1); // max length of datatype
break;
case INTEGER:
writeByte(TDSType.INTN.byteValue());
writeByte((byte) 4); // max length of datatype
break;
case SMALLINT:
case TINYINT:
writeByte(TDSType.INTN.byteValue());
writeByte((byte) 2); // max length of datatype
break;
case DECIMAL:
case NUMERIC:
writeByte(TDSType.NUMERICN.byteValue());
writeByte((byte) 0x11); // maximum length
writeByte((byte) pair.getValue().precision);
writeByte((byte) pair.getValue().scale);
break;
case DOUBLE:
writeByte(TDSType.FLOATN.byteValue());
writeByte((byte) 8); // max length of datatype
break;
case FLOAT:
case REAL:
writeByte(TDSType.FLOATN.byteValue());
writeByte((byte) 4); // max length of datatype
break;
case DATE:
case TIME:
case TIMESTAMP:
case DATETIMEOFFSET:
case TIMESTAMP_WITH_TIMEZONE:
case TIME_WITH_TIMEZONE:
case CHAR:
case VARCHAR:
case NCHAR:
case NVARCHAR:
case LONGVARCHAR:
case LONGNVARCHAR:
case SQLXML:
writeByte(TDSType.NVARCHAR.byteValue());
isShortValue = (2L * pair.getValue().precision) <= DataTypes.SHORT_VARTYPE_MAX_BYTES;
// Use PLP encoding on Yukon and later with long values
if (!isShortValue) // PLP
{
// Handle Yukon v*max type header here.
writeShort((short) 0xFFFF);
con.getDatabaseCollation().writeCollation(this);
}
else // non PLP
{
writeShort((short) DataTypes.SHORT_VARTYPE_MAX_BYTES);
con.getDatabaseCollation().writeCollation(this);
}
break;
case BINARY:
case VARBINARY:
case LONGVARBINARY:
writeByte(TDSType.BIGVARBINARY.byteValue());
isShortValue = pair.getValue().precision <= DataTypes.SHORT_VARTYPE_MAX_BYTES;
// Use PLP encoding on Yukon and later with long values
if (!isShortValue) // PLP
// Handle Yukon v*max type header here.
writeShort((short) 0xFFFF);
else // non PLP
writeShort((short) DataTypes.SHORT_VARTYPE_MAX_BYTES);
break;
default:
assert false : "Unexpected JDBC type " + jdbcType.toString();
}
// Column name - must be null (from TDS - TVP_COLMETADATA)
writeByte((byte) 0x00);
// [TVP_ORDER_UNIQUE]
// [TVP_COLUMN_ORDERING]
}
}
void writeTvpOrderUnique(TVP value) throws SQLServerException {
/*
* TVP_ORDER_UNIQUE = TVP_ORDER_UNIQUE_TOKEN (Count <Count>(ColNum OrderUniqueFlags))
*/
Map<Integer, SQLServerMetaData> columnMetadata = value.getColumnMetadata();
Iterator<Entry<Integer, SQLServerMetaData>> columnsIterator = columnMetadata.entrySet().iterator();
LinkedList<TdsOrderUnique> columnList = new LinkedList<TdsOrderUnique>();
while (columnsIterator.hasNext()) {
byte flags = 0;
Map.Entry<Integer, SQLServerMetaData> pair = columnsIterator.next();
SQLServerMetaData metaData = pair.getValue();
if (SQLServerSortOrder.Ascending == metaData.sortOrder)
flags = TDS.TVP_ORDERASC_FLAG;
else if (SQLServerSortOrder.Descending == metaData.sortOrder)
flags = TDS.TVP_ORDERDESC_FLAG;
if (metaData.isUniqueKey)
flags |= TDS.TVP_UNIQUE_FLAG;
// Remember this column if any flags were set
if (0 != flags)
columnList.add(new TdsOrderUnique(pair.getKey(), flags));
}
// Write flagged columns
if (!columnList.isEmpty()) {
writeByte((byte) TDS.TVP_ORDER_UNIQUE_TOKEN);
writeShort((short) columnList.size());
for (TdsOrderUnique column : columnList) {
writeShort((short) (column.columnOrdinal + 1));
writeByte(column.flags);
}
}
}
private class TdsOrderUnique {
int columnOrdinal;
byte flags;
TdsOrderUnique(int ordinal,
byte flags) {
this.columnOrdinal = ordinal;
this.flags = flags;
}
}
void setCryptoMetaData(CryptoMetadata cryptoMetaForBulk) {
this.cryptoMeta = cryptoMetaForBulk;
}
CryptoMetadata getCryptoMetaData() {
return cryptoMeta;
}
void writeEncryptedRPCByteArray(byte bValue[]) throws SQLServerException {
boolean bValueNull = (bValue == null);
long nValueLen = bValueNull ? 0 : bValue.length;
boolean isShortValue = (nValueLen <= DataTypes.SHORT_VARTYPE_MAX_BYTES);
boolean isPLP = (!isShortValue) && (nValueLen <= DataTypes.MAX_VARTYPE_MAX_BYTES);
// Handle Shiloh types here.
if (isShortValue) {
writeShort((short) DataTypes.SHORT_VARTYPE_MAX_BYTES);
}
else if (isPLP) {
writeShort((short) DataTypes.SQL_USHORTVARMAXLEN);
}
else {
writeInt(DataTypes.IMAGE_TEXT_MAX_BYTES);
}
// Data and length
if (bValueNull) {
writeShort((short) -1); // actual len
}
else {
if (isShortValue) {
writeShort((short) nValueLen); // actual len
}
else if (isPLP) {
writeLong(nValueLen); // actual length
}
else {
writeInt((int) nValueLen); // actual len
}
// If length is zero, we're done.
if (0 != nValueLen) {
if (isPLP) {
writeInt((int) nValueLen);
}
writeBytes(bValue);
}
if (isPLP) {
writeInt(0); // PLP_TERMINATOR, 0x00000000
}
}
}
void writeEncryptedRPCPLP() throws SQLServerException {
writeShort((short) DataTypes.SQL_USHORTVARMAXLEN);
writeLong((long) 0); // actual length
writeInt(0); // PLP_TERMINATOR, 0x00000000
}
void writeCryptoMetaData() throws SQLServerException {
writeByte(cryptoMeta.cipherAlgorithmId);
writeByte(cryptoMeta.encryptionType.getValue());
writeInt(cryptoMeta.cekTableEntry.getColumnEncryptionKeyValues().get(0).databaseId);
writeInt(cryptoMeta.cekTableEntry.getColumnEncryptionKeyValues().get(0).cekId);
writeInt(cryptoMeta.cekTableEntry.getColumnEncryptionKeyValues().get(0).cekVersion);
writeBytes(cryptoMeta.cekTableEntry.getColumnEncryptionKeyValues().get(0).cekMdVersion);
writeByte(cryptoMeta.normalizationRuleVersion);
}
void writeRPCByteArray(String sName,
byte bValue[],
boolean bOut,
JDBCType jdbcType,
SQLCollation collation) throws SQLServerException {
boolean bValueNull = (bValue == null);
int nValueLen = bValueNull ? 0 : bValue.length;
boolean isShortValue = (nValueLen <= DataTypes.SHORT_VARTYPE_MAX_BYTES);
// Use PLP encoding on Yukon and later with long values and OUT parameters
boolean usePLP = (!isShortValue || bOut);
TDSType tdsType;
if (null != cryptoMeta) {
// send encrypted data as BIGVARBINARY
tdsType = (isShortValue || usePLP) ? TDSType.BIGVARBINARY : TDSType.IMAGE;
collation = null;
}
else
switch (jdbcType) {
case BINARY:
case VARBINARY:
case LONGVARBINARY:
case BLOB:
default:
tdsType = (isShortValue || usePLP) ? TDSType.BIGVARBINARY : TDSType.IMAGE;
collation = null;
break;
case CHAR:
case VARCHAR:
case LONGVARCHAR:
case CLOB:
tdsType = (isShortValue || usePLP) ? TDSType.BIGVARCHAR : TDSType.TEXT;
if (null == collation)
collation = con.getDatabaseCollation();
break;
case NCHAR:
case NVARCHAR:
case LONGNVARCHAR:
case NCLOB:
tdsType = (isShortValue || usePLP) ? TDSType.NVARCHAR : TDSType.NTEXT;
if (null == collation)
collation = con.getDatabaseCollation();
break;
}
writeRPCNameValType(sName, bOut, tdsType);
if (usePLP) {
// Handle Yukon v*max type header here.
writeVMaxHeader(nValueLen, bValueNull, collation);
// Send the data.
if (!bValueNull) {
if (nValueLen > 0) {
writeInt(nValueLen);
writeBytes(bValue);
}
// Send the terminator PLP chunk.
writeInt(0);
}
}
else // non-PLP type
{
// Handle Shiloh types here.
if (isShortValue) {
writeShort((short) DataTypes.SHORT_VARTYPE_MAX_BYTES);
}
else {
writeInt(DataTypes.IMAGE_TEXT_MAX_BYTES);
}
if (null != collation)
collation.writeCollation(this);
// Data and length
if (bValueNull) {
writeShort((short) -1); // actual len
}
else {
if (isShortValue)
writeShort((short) nValueLen); // actual len
else
writeInt(nValueLen); // actual len
// If length is zero, we're done.
if (0 != nValueLen)
writeBytes(bValue);
}
}
}
/**
* Append a timestamp in RPC transmission format as a SQL Server DATETIME data type
*
* @param sName
* the optional parameter name
* @param cal
* Pure Gregorian calendar containing the timestamp, including its associated time zone
* @param subSecondNanos
* the sub-second nanoseconds (0 - 999,999,999)
* @param bOut
* boolean true if the data value is being registered as an ouput parameter
*
*/
void writeRPCDateTime(String sName,
GregorianCalendar cal,
int subSecondNanos,
boolean bOut) throws SQLServerException {
assert (subSecondNanos >= 0) && (subSecondNanos < Nanos.PER_SECOND) : "Invalid subNanoSeconds value: " + subSecondNanos;
assert (cal != null) || (cal == null && subSecondNanos == 0) : "Invalid subNanoSeconds value when calendar is null: " + subSecondNanos;
writeRPCNameValType(sName, bOut, TDSType.DATETIMEN);
writeByte((byte) 8); // max length of datatype
if (null == cal) {
writeByte((byte) 0); // len of data bytes
return;
}
writeByte((byte) 8); // len of data bytes
// We need to extract the Calendar's current date & time in terms
// of the number of days since the SQL Base Date (1/1/1900) plus
// the number of milliseconds since midnight in the current day.
// We cannot rely on any pre-calculated value for the number of
// milliseconds in a day or the number of milliseconds since the
// base date to do this because days with DST changes are shorter
// or longer than "normal" days.
// ASSUMPTION: We assume we are dealing with a GregorianCalendar here.
// If not, we have no basis in which to compare dates. E.g. if we
// are dealing with a Chinese Calendar implementation which does not
// use the same value for Calendar.YEAR as the GregorianCalendar,
// we cannot meaningfully compute a value relative to 1/1/1900.
// First, figure out how many days there have been since the SQL Base Date.
// These are based on SQL Server algorithms
int daysSinceSQLBaseDate = DDC.daysSinceBaseDate(cal.get(Calendar.YEAR), cal.get(Calendar.DAY_OF_YEAR), TDS.BASE_YEAR_1900);
// Next, figure out the number of milliseconds since midnight of the current day.
int millisSinceMidnight = (subSecondNanos + Nanos.PER_MILLISECOND / 2) / Nanos.PER_MILLISECOND + // Millis into the current second
1000 * cal.get(Calendar.SECOND) + // Seconds into the current minute
60 * 1000 * cal.get(Calendar.MINUTE) + // Minutes into the current hour
60 * 60 * 1000 * cal.get(Calendar.HOUR_OF_DAY); // Hours into the current day
// The last millisecond of the current day is always rounded to the first millisecond
// of the next day because DATETIME is only accurate to 1/300th of a second.
if (millisSinceMidnight >= 1000 * 60 * 60 * 24 - 1) {
++daysSinceSQLBaseDate;
millisSinceMidnight = 0;
}
// Last-ditch verification that the value is in the valid range for the
// DATETIMEN TDS data type (1/1/1753 to 12/31/9999). If it's not, then
// throw an exception now so that statement execution is safely canceled.
// Attempting to put an invalid value on the wire would result in a TDS
// exception, which would close the connection.
// These are based on SQL Server algorithms
if (daysSinceSQLBaseDate < DDC.daysSinceBaseDate(1753, 1, TDS.BASE_YEAR_1900)
|| daysSinceSQLBaseDate >= DDC.daysSinceBaseDate(10000, 1, TDS.BASE_YEAR_1900)) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_valueOutOfRange"));
Object[] msgArgs = {SSType.DATETIME};
throw new SQLServerException(form.format(msgArgs), SQLState.DATA_EXCEPTION_DATETIME_FIELD_OVERFLOW, DriverError.NOT_SET, null);
}
// And put it all on the wire...
// Number of days since the SQL Server Base Date (January 1, 1900)
writeInt(daysSinceSQLBaseDate);
// Milliseconds since midnight (at a resolution of three hundredths of a second)
writeInt((3 * millisSinceMidnight + 5) / 10);
}
void writeRPCTime(String sName,
GregorianCalendar localCalendar,
int subSecondNanos,
int scale,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.TIMEN);
writeByte((byte) scale);
if (null == localCalendar) {
writeByte((byte) 0);
return;
}
writeByte((byte) TDS.timeValueLength(scale));
writeScaledTemporal(localCalendar, subSecondNanos, scale, SSType.TIME);
}
void writeRPCDate(String sName,
GregorianCalendar localCalendar,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.DATEN);
if (null == localCalendar) {
writeByte((byte) 0);
return;
}
writeByte((byte) TDS.DAYS_INTO_CE_LENGTH);
writeScaledTemporal(localCalendar, 0, // subsecond nanos (none for a date value)
0, // scale (dates are not scaled)
SSType.DATE);
}
void writeEncryptedRPCTime(String sName,
GregorianCalendar localCalendar,
int subSecondNanos,
int scale,
boolean bOut) throws SQLServerException {
if (con.getSendTimeAsDatetime()) {
throw new SQLServerException(SQLServerException.getErrString("R_sendTimeAsDateTimeForAE"), null);
}
writeRPCNameValType(sName, bOut, TDSType.BIGVARBINARY);
if (null == localCalendar)
writeEncryptedRPCByteArray(null);
else
writeEncryptedRPCByteArray(writeEncryptedScaledTemporal(localCalendar, subSecondNanos, scale, SSType.TIME, (short) 0));
writeByte(TDSType.TIMEN.byteValue());
writeByte((byte) scale);
writeCryptoMetaData();
}
void writeEncryptedRPCDate(String sName,
GregorianCalendar localCalendar,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.BIGVARBINARY);
if (null == localCalendar)
writeEncryptedRPCByteArray(null);
else
writeEncryptedRPCByteArray(writeEncryptedScaledTemporal(localCalendar, 0, // subsecond nanos (none for a date value)
0, // scale (dates are not scaled)
SSType.DATE, (short) 0));
writeByte(TDSType.DATEN.byteValue());
writeCryptoMetaData();
}
void writeEncryptedRPCDateTime(String sName,
GregorianCalendar cal,
int subSecondNanos,
boolean bOut,
JDBCType jdbcType) throws SQLServerException {
assert (subSecondNanos >= 0) && (subSecondNanos < Nanos.PER_SECOND) : "Invalid subNanoSeconds value: " + subSecondNanos;
assert (cal != null) || (cal == null && subSecondNanos == 0) : "Invalid subNanoSeconds value when calendar is null: " + subSecondNanos;
writeRPCNameValType(sName, bOut, TDSType.BIGVARBINARY);
if (null == cal)
writeEncryptedRPCByteArray(null);
else
writeEncryptedRPCByteArray(getEncryptedDateTimeAsBytes(cal, subSecondNanos, jdbcType));
if (JDBCType.SMALLDATETIME == jdbcType) {
writeByte(TDSType.DATETIMEN.byteValue());
writeByte((byte) 4);
}
else {
writeByte(TDSType.DATETIMEN.byteValue());
writeByte((byte) 8);
}
writeCryptoMetaData();
}
// getEncryptedDateTimeAsBytes is called if jdbcType/ssType is SMALLDATETIME or DATETIME
byte[] getEncryptedDateTimeAsBytes(GregorianCalendar cal,
int subSecondNanos,
JDBCType jdbcType) throws SQLServerException {
int daysSinceSQLBaseDate = DDC.daysSinceBaseDate(cal.get(Calendar.YEAR), cal.get(Calendar.DAY_OF_YEAR), TDS.BASE_YEAR_1900);
// Next, figure out the number of milliseconds since midnight of the current day.
int millisSinceMidnight = (subSecondNanos + Nanos.PER_MILLISECOND / 2) / Nanos.PER_MILLISECOND + // Millis into the current second
1000 * cal.get(Calendar.SECOND) + // Seconds into the current minute
60 * 1000 * cal.get(Calendar.MINUTE) + // Minutes into the current hour
60 * 60 * 1000 * cal.get(Calendar.HOUR_OF_DAY); // Hours into the current day
// The last millisecond of the current day is always rounded to the first millisecond
// of the next day because DATETIME is only accurate to 1/300th of a second.
if (millisSinceMidnight >= 1000 * 60 * 60 * 24 - 1) {
++daysSinceSQLBaseDate;
millisSinceMidnight = 0;
}
if (JDBCType.SMALLDATETIME == jdbcType) {
int secondsSinceMidnight = (millisSinceMidnight / 1000);
int minutesSinceMidnight = (secondsSinceMidnight / 60);
// Values that are 29.998 seconds or less are rounded down to the nearest minute
minutesSinceMidnight = ((secondsSinceMidnight % 60) > 29.998) ? minutesSinceMidnight + 1 : minutesSinceMidnight;
// minutesSinceMidnight for (23:59:30)
int maxMinutesSinceMidnight_SmallDateTime = 1440;
// Verification for smalldatetime to be within valid range of (1900.01.01) to (2079.06.06)
// smalldatetime for unencrypted does not allow insertion of 2079.06.06 23:59:59 and it is rounded up
// to 2079.06.07 00:00:00, therefore, we are checking minutesSinceMidnight for that condition. If it's not within valid range, then
// throw an exception now so that statement execution is safely canceled.
// 157 is the calculated day of year from 06-06 , 1440 is minutesince midnight for (23:59:30)
if ((daysSinceSQLBaseDate < DDC.daysSinceBaseDate(1900, 1, TDS.BASE_YEAR_1900)
|| daysSinceSQLBaseDate > DDC.daysSinceBaseDate(2079, 157, TDS.BASE_YEAR_1900))
|| (daysSinceSQLBaseDate == DDC.daysSinceBaseDate(2079, 157, TDS.BASE_YEAR_1900)
&& minutesSinceMidnight >= maxMinutesSinceMidnight_SmallDateTime)) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_valueOutOfRange"));
Object[] msgArgs = {SSType.SMALLDATETIME};
throw new SQLServerException(form.format(msgArgs), SQLState.DATA_EXCEPTION_DATETIME_FIELD_OVERFLOW, DriverError.NOT_SET, null);
}
ByteBuffer days = ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN);
days.putShort((short) daysSinceSQLBaseDate);
ByteBuffer seconds = ByteBuffer.allocate(2).order(ByteOrder.LITTLE_ENDIAN);
seconds.putShort((short) minutesSinceMidnight);
byte[] value = new byte[4];
System.arraycopy(days.array(), 0, value, 0, 2);
System.arraycopy(seconds.array(), 0, value, 2, 2);
return SQLServerSecurityUtility.encryptWithKey(value, cryptoMeta, con);
}
else if (JDBCType.DATETIME == jdbcType) {
// Last-ditch verification that the value is in the valid range for the
// DATETIMEN TDS data type (1/1/1753 to 12/31/9999). If it's not, then
// throw an exception now so that statement execution is safely canceled.
// Attempting to put an invalid value on the wire would result in a TDS
// exception, which would close the connection.
// These are based on SQL Server algorithms
// And put it all on the wire...
if (daysSinceSQLBaseDate < DDC.daysSinceBaseDate(1753, 1, TDS.BASE_YEAR_1900)
|| daysSinceSQLBaseDate >= DDC.daysSinceBaseDate(10000, 1, TDS.BASE_YEAR_1900)) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_valueOutOfRange"));
Object[] msgArgs = {SSType.DATETIME};
throw new SQLServerException(form.format(msgArgs), SQLState.DATA_EXCEPTION_DATETIME_FIELD_OVERFLOW, DriverError.NOT_SET, null);
}
// Number of days since the SQL Server Base Date (January 1, 1900)
ByteBuffer days = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN);
days.putInt(daysSinceSQLBaseDate);
ByteBuffer seconds = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN);
seconds.putInt((3 * millisSinceMidnight + 5) / 10);
byte[] value = new byte[8];
System.arraycopy(days.array(), 0, value, 0, 4);
System.arraycopy(seconds.array(), 0, value, 4, 4);
return SQLServerSecurityUtility.encryptWithKey(value, cryptoMeta, con);
}
assert false : "Unexpected JDBCType type " + jdbcType;
return null;
}
void writeEncryptedRPCDateTime2(String sName,
GregorianCalendar localCalendar,
int subSecondNanos,
int scale,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.BIGVARBINARY);
if (null == localCalendar)
writeEncryptedRPCByteArray(null);
else
writeEncryptedRPCByteArray(writeEncryptedScaledTemporal(localCalendar, subSecondNanos, scale, SSType.DATETIME2, (short) 0));
writeByte(TDSType.DATETIME2N.byteValue());
writeByte((byte) (scale));
writeCryptoMetaData();
}
void writeEncryptedRPCDateTimeOffset(String sName,
GregorianCalendar utcCalendar,
int minutesOffset,
int subSecondNanos,
int scale,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.BIGVARBINARY);
if (null == utcCalendar)
writeEncryptedRPCByteArray(null);
else {
assert 0 == utcCalendar.get(Calendar.ZONE_OFFSET);
writeEncryptedRPCByteArray(
writeEncryptedScaledTemporal(utcCalendar, subSecondNanos, scale, SSType.DATETIMEOFFSET, (short) minutesOffset));
}
writeByte(TDSType.DATETIMEOFFSETN.byteValue());
writeByte((byte) (scale));
writeCryptoMetaData();
}
void writeRPCDateTime2(String sName,
GregorianCalendar localCalendar,
int subSecondNanos,
int scale,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.DATETIME2N);
writeByte((byte) scale);
if (null == localCalendar) {
writeByte((byte) 0);
return;
}
writeByte((byte) TDS.datetime2ValueLength(scale));
writeScaledTemporal(localCalendar, subSecondNanos, scale, SSType.DATETIME2);
}
void writeRPCDateTimeOffset(String sName,
GregorianCalendar utcCalendar,
int minutesOffset,
int subSecondNanos,
int scale,
boolean bOut) throws SQLServerException {
writeRPCNameValType(sName, bOut, TDSType.DATETIMEOFFSETN);
writeByte((byte) scale);
if (null == utcCalendar) {
writeByte((byte) 0);
return;
}
assert 0 == utcCalendar.get(Calendar.ZONE_OFFSET);
writeByte((byte) TDS.datetimeoffsetValueLength(scale));
writeScaledTemporal(utcCalendar, subSecondNanos, scale, SSType.DATETIMEOFFSET);
writeShort((short) minutesOffset);
}
/**
* Returns subSecondNanos rounded to the maximum precision supported. The maximum fractional scale is MAX_FRACTIONAL_SECONDS_SCALE(7). Eg1: if you
* pass 456,790,123 the function would return 456,790,100 Eg2: if you pass 456,790,150 the function would return 456,790,200 Eg3: if you pass
* 999,999,951 the function would return 1,000,000,000 This is done to ensure that we have consistent rounding behaviour in setters and getters.
* Bug #507919
*/
private int getRoundedSubSecondNanos(int subSecondNanos) {
int roundedNanos = ((subSecondNanos + (Nanos.PER_MAX_SCALE_INTERVAL / 2)) / Nanos.PER_MAX_SCALE_INTERVAL) * Nanos.PER_MAX_SCALE_INTERVAL;
return roundedNanos;
}
/**
* Writes to the TDS channel a temporal value as an instance instance of one of the scaled temporal SQL types: DATE, TIME, DATETIME2, or
* DATETIMEOFFSET.
*
* @param cal
* Calendar representing the value to write, except for any sub-second nanoseconds
* @param subSecondNanos
* the sub-second nanoseconds (0 - 999,999,999)
* @param scale
* the scale (in digits: 0 - 7) to use for the sub-second nanos component
* @param ssType
* the SQL Server data type (DATE, TIME, DATETIME2, or DATETIMEOFFSET)
*
* @throws SQLServerException
* if an I/O error occurs or if the value is not in the valid range
*/
private void writeScaledTemporal(GregorianCalendar cal,
int subSecondNanos,
int scale,
SSType ssType) throws SQLServerException {
assert con.isKatmaiOrLater();
assert SSType.DATE == ssType || SSType.TIME == ssType || SSType.DATETIME2 == ssType || SSType.DATETIMEOFFSET == ssType : "Unexpected SSType: "
+ ssType;
// First, for types with a time component, write the scaled nanos since midnight
if (SSType.TIME == ssType || SSType.DATETIME2 == ssType || SSType.DATETIMEOFFSET == ssType) {
assert subSecondNanos >= 0;
assert subSecondNanos < Nanos.PER_SECOND;
assert scale >= 0;
assert scale <= TDS.MAX_FRACTIONAL_SECONDS_SCALE;
int secondsSinceMidnight = cal.get(Calendar.SECOND) + 60 * cal.get(Calendar.MINUTE) + 60 * 60 * cal.get(Calendar.HOUR_OF_DAY);
// Scale nanos since midnight to the desired scale, rounding the value as necessary
long divisor = Nanos.PER_MAX_SCALE_INTERVAL * (long) Math.pow(10, TDS.MAX_FRACTIONAL_SECONDS_SCALE - scale);
// The scaledNanos variable represents the fractional seconds of the value at the scale
// indicated by the scale variable. So, for example, scaledNanos = 3 means 300 nanoseconds
// at scale TDS.MAX_FRACTIONAL_SECONDS_SCALE, but 3000 nanoseconds at
// TDS.MAX_FRACTIONAL_SECONDS_SCALE - 1
long scaledNanos = ((long) Nanos.PER_SECOND * secondsSinceMidnight + getRoundedSubSecondNanos(subSecondNanos) + divisor / 2) / divisor;
// SQL Server rounding behavior indicates that it always rounds up unless
// we are at the max value of the type(NOT every day), in which case it truncates.
// If rounding nanos to the specified scale rolls the value to the next day ...
if (Nanos.PER_DAY / divisor == scaledNanos) {
// If the type is time, always truncate
if (SSType.TIME == ssType) {
--scaledNanos;
}
// If the type is datetime2 or datetimeoffset, truncate only if its the max value supported
else {
assert SSType.DATETIME2 == ssType || SSType.DATETIMEOFFSET == ssType : "Unexpected SSType: " + ssType;
// ... then bump the date, provided that the resulting date is still within
// the valid date range.
// Extreme edge case (literally, the VERY edge...):
// If nanos overflow rolls the date value out of range (that is, we have a value
// a few nanoseconds later than 9999-12-31 23:59:59) then truncate the nanos
// instead of rolling.
// This case is very likely never hit by "real world" applications, but exists
// here as a security measure to ensure that such values don't result in a
// connection-closing TDS exception.
cal.add(Calendar.SECOND, 1);
if (cal.get(Calendar.YEAR) <= 9999) {
scaledNanos = 0;
}
else {
cal.add(Calendar.SECOND, -1);
--scaledNanos;
}
}
}
// Encode the scaled nanos to TDS
int encodedLength = TDS.nanosSinceMidnightLength(scale);
byte[] encodedBytes = scaledNanosToEncodedBytes(scaledNanos, encodedLength);
writeBytes(encodedBytes);
}
// Second, for types with a date component, write the days into the Common Era
if (SSType.DATE == ssType || SSType.DATETIME2 == ssType || SSType.DATETIMEOFFSET == ssType) {
// Computation of the number of days into the Common Era assumes that
// the DAY_OF_YEAR field reflects a pure Gregorian calendar - one that
// uses Gregorian leap year rules across the entire range of dates.
// For the DAY_OF_YEAR field to accurately reflect pure Gregorian behavior,
// we need to use a pure Gregorian calendar for dates that are Julian dates
// under a standard Gregorian calendar and for (Gregorian) dates later than
// the cutover date in the cutover year.
if (cal.getTimeInMillis() < GregorianChange.STANDARD_CHANGE_DATE.getTime()
|| cal.getActualMaximum(Calendar.DAY_OF_YEAR) < TDS.DAYS_PER_YEAR) {
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int date = cal.get(Calendar.DATE);
// Set the cutover as early as possible (pure Gregorian behavior)
cal.setGregorianChange(GregorianChange.PURE_CHANGE_DATE);
// Initialize the date field by field (preserving the "wall calendar" value)
cal.set(year, month, date);
}
int daysIntoCE = DDC.daysSinceBaseDate(cal.get(Calendar.YEAR), cal.get(Calendar.DAY_OF_YEAR), 1);
// Last-ditch verification that the value is in the valid range for the
// DATE/DATETIME2/DATETIMEOFFSET TDS data type (1/1/0001 to 12/31/9999).
// If it's not, then throw an exception now so that statement execution
// is safely canceled. Attempting to put an invalid value on the wire
// would result in a TDS exception, which would close the connection.
if (daysIntoCE < 0 || daysIntoCE >= DDC.daysSinceBaseDate(10000, 1, 1)) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_valueOutOfRange"));
Object[] msgArgs = {ssType};
throw new SQLServerException(form.format(msgArgs), SQLState.DATA_EXCEPTION_DATETIME_FIELD_OVERFLOW, DriverError.NOT_SET, null);
}
byte encodedBytes[] = new byte[3];
encodedBytes[0] = (byte) ((daysIntoCE >> 0) & 0xFF);
encodedBytes[1] = (byte) ((daysIntoCE >> 8) & 0xFF);
encodedBytes[2] = (byte) ((daysIntoCE >> 16) & 0xFF);
writeBytes(encodedBytes);
}
}
/**
* Writes to the TDS channel a temporal value as an instance instance of one of the scaled temporal SQL types: DATE, TIME, DATETIME2, or
* DATETIMEOFFSET.
*
* @param cal
* Calendar representing the value to write, except for any sub-second nanoseconds
* @param subSecondNanos
* the sub-second nanoseconds (0 - 999,999,999)
* @param scale
* the scale (in digits: 0 - 7) to use for the sub-second nanos component
* @param ssType
* the SQL Server data type (DATE, TIME, DATETIME2, or DATETIMEOFFSET)
* @param minutesOffset
* the offset value for DATETIMEOFFSET
* @throws SQLServerException
* if an I/O error occurs or if the value is not in the valid range
*/
byte[] writeEncryptedScaledTemporal(GregorianCalendar cal,
int subSecondNanos,
int scale,
SSType ssType,
short minutesOffset) throws SQLServerException {
assert con.isKatmaiOrLater();
assert SSType.DATE == ssType || SSType.TIME == ssType || SSType.DATETIME2 == ssType || SSType.DATETIMEOFFSET == ssType : "Unexpected SSType: "
+ ssType;
// store the time and minutesOffset portion of DATETIME2 and DATETIMEOFFSET to be used with date portion
byte encodedBytesForEncryption[] = null;
int secondsSinceMidnight = 0;
long divisor = 0;
long scaledNanos = 0;
// First, for types with a time component, write the scaled nanos since midnight
if (SSType.TIME == ssType || SSType.DATETIME2 == ssType || SSType.DATETIMEOFFSET == ssType) {
assert subSecondNanos >= 0;
assert subSecondNanos < Nanos.PER_SECOND;
assert scale >= 0;
assert scale <= TDS.MAX_FRACTIONAL_SECONDS_SCALE;
secondsSinceMidnight = cal.get(Calendar.SECOND) + 60 * cal.get(Calendar.MINUTE) + 60 * 60 * cal.get(Calendar.HOUR_OF_DAY);
// Scale nanos since midnight to the desired scale, rounding the value as necessary
divisor = Nanos.PER_MAX_SCALE_INTERVAL * (long) Math.pow(10, TDS.MAX_FRACTIONAL_SECONDS_SCALE - scale);
// The scaledNanos variable represents the fractional seconds of the value at the scale
// indicated by the scale variable. So, for example, scaledNanos = 3 means 300 nanoseconds
// at scale TDS.MAX_FRACTIONAL_SECONDS_SCALE, but 3000 nanoseconds at
// TDS.MAX_FRACTIONAL_SECONDS_SCALE - 1
scaledNanos = (((long) Nanos.PER_SECOND * secondsSinceMidnight + getRoundedSubSecondNanos(subSecondNanos) + divisor / 2) / divisor)
* divisor / 100;
// for encrypted time value, SQL server cannot do rounding or casting,
// So, driver needs to cast it before encryption.
if (SSType.TIME == ssType && 864000000000L <= scaledNanos) {
scaledNanos = (((long) Nanos.PER_SECOND * secondsSinceMidnight + getRoundedSubSecondNanos(subSecondNanos)) / divisor) * divisor / 100;
}
// SQL Server rounding behavior indicates that it always rounds up unless
// we are at the max value of the type(NOT every day), in which case it truncates.
// If rounding nanos to the specified scale rolls the value to the next day ...
if (Nanos.PER_DAY / divisor == scaledNanos) {
// If the type is time, always truncate
if (SSType.TIME == ssType) {
--scaledNanos;
}
// If the type is datetime2 or datetimeoffset, truncate only if its the max value supported
else {
assert SSType.DATETIME2 == ssType || SSType.DATETIMEOFFSET == ssType : "Unexpected SSType: " + ssType;
// ... then bump the date, provided that the resulting date is still within
// the valid date range.
// Extreme edge case (literally, the VERY edge...):
// If nanos overflow rolls the date value out of range (that is, we have a value
// a few nanoseconds later than 9999-12-31 23:59:59) then truncate the nanos
// instead of rolling.
// This case is very likely never hit by "real world" applications, but exists
// here as a security measure to ensure that such values don't result in a
// connection-closing TDS exception.
cal.add(Calendar.SECOND, 1);
if (cal.get(Calendar.YEAR) <= 9999) {
scaledNanos = 0;
}
else {
cal.add(Calendar.SECOND, -1);
--scaledNanos;
}
}
}
// Encode the scaled nanos to TDS
int encodedLength = TDS.nanosSinceMidnightLength(TDS.MAX_FRACTIONAL_SECONDS_SCALE);
byte[] encodedBytes = scaledNanosToEncodedBytes(scaledNanos, encodedLength);
if (SSType.TIME == ssType) {
byte[] cipherText = SQLServerSecurityUtility.encryptWithKey(encodedBytes, cryptoMeta, con);
return cipherText;
}
else if (SSType.DATETIME2 == ssType) {
// for DATETIME2 sends both date and time part together for encryption
encodedBytesForEncryption = new byte[encodedLength + 3];
System.arraycopy(encodedBytes, 0, encodedBytesForEncryption, 0, encodedBytes.length);
}
else if (SSType.DATETIMEOFFSET == ssType) {
// for DATETIMEOFFSET sends date, time and offset part together for encryption
encodedBytesForEncryption = new byte[encodedLength + 5];
System.arraycopy(encodedBytes, 0, encodedBytesForEncryption, 0, encodedBytes.length);
}
}
// Second, for types with a date component, write the days into the Common Era
if (SSType.DATE == ssType || SSType.DATETIME2 == ssType || SSType.DATETIMEOFFSET == ssType) {
// Computation of the number of days into the Common Era assumes that
// the DAY_OF_YEAR field reflects a pure Gregorian calendar - one that
// uses Gregorian leap year rules across the entire range of dates.
// For the DAY_OF_YEAR field to accurately reflect pure Gregorian behavior,
// we need to use a pure Gregorian calendar for dates that are Julian dates
// under a standard Gregorian calendar and for (Gregorian) dates later than
// the cutover date in the cutover year.
if (cal.getTimeInMillis() < GregorianChange.STANDARD_CHANGE_DATE.getTime()
|| cal.getActualMaximum(Calendar.DAY_OF_YEAR) < TDS.DAYS_PER_YEAR) {
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int date = cal.get(Calendar.DATE);
// Set the cutover as early as possible (pure Gregorian behavior)
cal.setGregorianChange(GregorianChange.PURE_CHANGE_DATE);
// Initialize the date field by field (preserving the "wall calendar" value)
cal.set(year, month, date);
}
int daysIntoCE = DDC.daysSinceBaseDate(cal.get(Calendar.YEAR), cal.get(Calendar.DAY_OF_YEAR), 1);
// Last-ditch verification that the value is in the valid range for the
// DATE/DATETIME2/DATETIMEOFFSET TDS data type (1/1/0001 to 12/31/9999).
// If it's not, then throw an exception now so that statement execution
// is safely canceled. Attempting to put an invalid value on the wire
// would result in a TDS exception, which would close the connection.
if (daysIntoCE < 0 || daysIntoCE >= DDC.daysSinceBaseDate(10000, 1, 1)) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_valueOutOfRange"));
Object[] msgArgs = {ssType};
throw new SQLServerException(form.format(msgArgs), SQLState.DATA_EXCEPTION_DATETIME_FIELD_OVERFLOW, DriverError.NOT_SET, null);
}
byte encodedBytes[] = new byte[3];
encodedBytes[0] = (byte) ((daysIntoCE >> 0) & 0xFF);
encodedBytes[1] = (byte) ((daysIntoCE >> 8) & 0xFF);
encodedBytes[2] = (byte) ((daysIntoCE >> 16) & 0xFF);
byte[] cipherText;
if (SSType.DATE == ssType) {
cipherText = SQLServerSecurityUtility.encryptWithKey(encodedBytes, cryptoMeta, con);
}
else if (SSType.DATETIME2 == ssType) {
// for Max value, does not round up, do casting instead.
if (3652058 == daysIntoCE) { // 9999-12-31
if (864000000000L == scaledNanos) { // 24:00:00 in nanoseconds
// does not round up
scaledNanos = (((long) Nanos.PER_SECOND * secondsSinceMidnight + getRoundedSubSecondNanos(subSecondNanos)) / divisor)
* divisor / 100;
int encodedLength = TDS.nanosSinceMidnightLength(TDS.MAX_FRACTIONAL_SECONDS_SCALE);
byte[] encodedNanoBytes = scaledNanosToEncodedBytes(scaledNanos, encodedLength);
// for DATETIME2 sends both date and time part together for encryption
encodedBytesForEncryption = new byte[encodedLength + 3];
System.arraycopy(encodedNanoBytes, 0, encodedBytesForEncryption, 0, encodedNanoBytes.length);
}
}
// Copy the 3 byte date value
System.arraycopy(encodedBytes, 0, encodedBytesForEncryption, (encodedBytesForEncryption.length - 3), 3);
cipherText = SQLServerSecurityUtility.encryptWithKey(encodedBytesForEncryption, cryptoMeta, con);
}
else {
// for Max value, does not round up, do casting instead.
if (3652058 == daysIntoCE) { // 9999-12-31
if (864000000000L == scaledNanos) { // 24:00:00 in nanoseconds
// does not round up
scaledNanos = (((long) Nanos.PER_SECOND * secondsSinceMidnight + getRoundedSubSecondNanos(subSecondNanos)) / divisor)
* divisor / 100;
int encodedLength = TDS.nanosSinceMidnightLength(TDS.MAX_FRACTIONAL_SECONDS_SCALE);
byte[] encodedNanoBytes = scaledNanosToEncodedBytes(scaledNanos, encodedLength);
// for DATETIMEOFFSET sends date, time and offset part together for encryption
encodedBytesForEncryption = new byte[encodedLength + 5];
System.arraycopy(encodedNanoBytes, 0, encodedBytesForEncryption, 0, encodedNanoBytes.length);
}
}
// Copy the 3 byte date value
System.arraycopy(encodedBytes, 0, encodedBytesForEncryption, (encodedBytesForEncryption.length - 5), 3);
// Copy the 2 byte minutesOffset value
System.arraycopy(ByteBuffer.allocate(Short.SIZE / Byte.SIZE).order(ByteOrder.LITTLE_ENDIAN).putShort(minutesOffset).array(), 0,
encodedBytesForEncryption, (encodedBytesForEncryption.length - 2), 2);
cipherText = SQLServerSecurityUtility.encryptWithKey(encodedBytesForEncryption, cryptoMeta, con);
}
return cipherText;
}
// Invalid type ssType. This condition should never happen.
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_unknownSSType"));
Object[] msgArgs = {ssType};
SQLServerException.makeFromDriverError(null, null, form.format(msgArgs), null, true);
return null;
}
private byte[] scaledNanosToEncodedBytes(long scaledNanos,
int encodedLength) {
byte encodedBytes[] = new byte[encodedLength];
for (int i = 0; i < encodedLength; i++)
encodedBytes[i] = (byte) ((scaledNanos >> (8 * i)) & 0xFF);
return encodedBytes;
}
/**
* Append the data in a stream in RPC transmission format.
*
* @param sName
* the optional parameter name
* @param stream
* is the stream
* @param streamLength
* length of the stream (may be unknown)
* @param bOut
* boolean true if the data value is being registered as an ouput parameter
* @param jdbcType
* The JDBC type used to determine whether the value is textual or non-textual.
* @param collation
* The SQL collation associated with the value. Null for non-textual SQL Server types.
* @throws SQLServerException
*/
void writeRPCInputStream(String sName,
InputStream stream,
long streamLength,
boolean bOut,
JDBCType jdbcType,
SQLCollation collation) throws SQLServerException {
assert null != stream;
assert DataTypes.UNKNOWN_STREAM_LENGTH == streamLength || streamLength >= 0;
// Send long values and values with unknown length
// using PLP chunking on Yukon and later.
boolean usePLP = (DataTypes.UNKNOWN_STREAM_LENGTH == streamLength || streamLength > DataTypes.SHORT_VARTYPE_MAX_BYTES);
if (usePLP) {
assert DataTypes.UNKNOWN_STREAM_LENGTH == streamLength || streamLength <= DataTypes.MAX_VARTYPE_MAX_BYTES;
writeRPCNameValType(sName, bOut, jdbcType.isTextual() ? TDSType.BIGVARCHAR : TDSType.BIGVARBINARY);
// Handle Yukon v*max type header here.
writeVMaxHeader(streamLength, false, jdbcType.isTextual() ? collation : null);
}
// Send non-PLP in all other cases
else {
// If the length of the InputStream is unknown then we need to buffer the entire stream
// in memory so that we can determine its length and send that length to the server
// before the stream data itself.
if (DataTypes.UNKNOWN_STREAM_LENGTH == streamLength) {
// Create ByteArrayOutputStream with initial buffer size of 8K to handle typical
// binary field sizes more efficiently. Note we can grow beyond 8000 bytes.
ByteArrayOutputStream baos = new ByteArrayOutputStream(8000);
streamLength = 0L;
// Since Shiloh is limited to 64K TDS packets, that's a good upper bound on the maximum
// length of InputStream we should try to handle before throwing an exception.
long maxStreamLength = 65535L * con.getTDSPacketSize();
try {
byte buff[] = new byte[8000];
int bytesRead;
while (streamLength < maxStreamLength && -1 != (bytesRead = stream.read(buff, 0, buff.length))) {
baos.write(buff);
streamLength += bytesRead;
}
}
catch (IOException e) {
throw new SQLServerException(e.getMessage(), SQLState.DATA_EXCEPTION_NOT_SPECIFIC, DriverError.NOT_SET, e);
}
if (streamLength >= maxStreamLength) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_invalidLength"));
Object[] msgArgs = {Long.valueOf(streamLength)};
SQLServerException.makeFromDriverError(null, null, form.format(msgArgs), "", true);
}
assert streamLength <= Integer.MAX_VALUE;
stream = new ByteArrayInputStream(baos.toByteArray(), 0, (int) streamLength);
}
assert 0 <= streamLength && streamLength <= DataTypes.IMAGE_TEXT_MAX_BYTES;
boolean useVarType = streamLength <= DataTypes.SHORT_VARTYPE_MAX_BYTES;
writeRPCNameValType(sName, bOut,
jdbcType.isTextual() ? (useVarType ? TDSType.BIGVARCHAR : TDSType.TEXT) : (useVarType ? TDSType.BIGVARBINARY : TDSType.IMAGE));
// Write maximum length, optional collation, and actual length
if (useVarType) {
writeShort((short) DataTypes.SHORT_VARTYPE_MAX_BYTES);
if (jdbcType.isTextual())
collation.writeCollation(this);
writeShort((short) streamLength);
}
else {
writeInt(DataTypes.IMAGE_TEXT_MAX_BYTES);
if (jdbcType.isTextual())
collation.writeCollation(this);
writeInt((int) streamLength);
}
}
// Write the data
writeStream(stream, streamLength, usePLP);
}
/**
* Append the XML data in a stream in RPC transmission format.
*
* @param sName
* the optional parameter name
* @param stream
* is the stream
* @param streamLength
* length of the stream (may be unknown)
* @param bOut
* boolean true if the data value is being registered as an ouput parameter
* @throws SQLServerException
*/
void writeRPCXML(String sName,
InputStream stream,
long streamLength,
boolean bOut) throws SQLServerException {
assert DataTypes.UNKNOWN_STREAM_LENGTH == streamLength || streamLength >= 0;
assert DataTypes.UNKNOWN_STREAM_LENGTH == streamLength || streamLength <= DataTypes.MAX_VARTYPE_MAX_BYTES;
writeRPCNameValType(sName, bOut, TDSType.XML);
writeByte((byte) 0); // No schema
// Handle null here and return, we're done here if it's null.
if (null == stream) {
// Null header for v*max types is 0xFFFFFFFFFFFFFFFF.
writeLong(0xFFFFFFFFFFFFFFFFL);
}
else if (DataTypes.UNKNOWN_STREAM_LENGTH == streamLength) {
// Append v*max length.
// UNKNOWN_PLP_LEN is 0xFFFFFFFFFFFFFFFE
writeLong(0xFFFFFFFFFFFFFFFEL);
// NOTE: Don't send the first chunk length, this will be calculated by caller.
}
else {
// For v*max types with known length, length is <totallength8><chunklength4>
// We're sending same total length as chunk length (as we're sending 1 chunk).
writeLong(streamLength);
}
if (null != stream)
// Write the data
writeStream(stream, streamLength, true);
}
/**
* Append the data in a character reader in RPC transmission format.
*
* @param sName
* the optional parameter name
* @param re
* the reader
* @param reLength
* the reader data length (in characters)
* @param bOut
* boolean true if the data value is being registered as an ouput parameter
* @param collation
* The SQL collation associated with the value. Null for non-textual SQL Server types.
* @throws SQLServerException
*/
void writeRPCReaderUnicode(String sName,
Reader re,
long reLength,
boolean bOut,
SQLCollation collation) throws SQLServerException {
assert null != re;
assert DataTypes.UNKNOWN_STREAM_LENGTH == reLength || reLength >= 0;
// Textual RPC requires a collation. If none is provided, as is the case when
// the SSType is non-textual, then use the database collation by default.
if (null == collation)
collation = con.getDatabaseCollation();
// Send long values and values with unknown length
// using PLP chunking on Yukon and later.
boolean usePLP = (DataTypes.UNKNOWN_STREAM_LENGTH == reLength || reLength > DataTypes.SHORT_VARTYPE_MAX_CHARS);
if (usePLP) {
assert DataTypes.UNKNOWN_STREAM_LENGTH == reLength || reLength <= DataTypes.MAX_VARTYPE_MAX_CHARS;
writeRPCNameValType(sName, bOut, TDSType.NVARCHAR);
// Handle Yukon v*max type header here.
writeVMaxHeader((DataTypes.UNKNOWN_STREAM_LENGTH == reLength) ? DataTypes.UNKNOWN_STREAM_LENGTH : 2 * reLength, // Length (in bytes)
false, collation);
}
// Send non-PLP in all other cases
else {
// Length must be known if we're not sending PLP-chunked data. Yukon is handled above.
// For Shiloh, this is enforced in DTV by converting the Reader to some other length-
// prefixed value in the setter.
assert 0 <= reLength && reLength <= DataTypes.NTEXT_MAX_CHARS;
// For non-PLP types, use the long TEXT type rather than the short VARCHAR
// type if the stream is too long to fit in the latter or if we don't know the length up
// front so we have to assume that it might be too long.
boolean useVarType = reLength <= DataTypes.SHORT_VARTYPE_MAX_CHARS;
writeRPCNameValType(sName, bOut, useVarType ? TDSType.NVARCHAR : TDSType.NTEXT);
// Write maximum length, collation, and actual length of the data
if (useVarType) {
writeShort((short) DataTypes.SHORT_VARTYPE_MAX_BYTES);
collation.writeCollation(this);
writeShort((short) (2 * reLength));
}
else {
writeInt(DataTypes.NTEXT_MAX_CHARS);
collation.writeCollation(this);
writeInt((int) (2 * reLength));
}
}
// Write the data
writeReader(re, reLength, usePLP);
}
}
/**
* TDSPacket provides a mechanism for chaining TDS response packets together in a singly-linked list.
*
* Having both the link and the data in the same class allows TDSReader marks (see below) to automatically hold onto exactly as much response data as
* they need, and no more. Java reference semantics ensure that a mark holds onto its referenced packet and subsequent packets (through next
* references). When all marked references to a packet go away, the packet, and any linked unmarked packets, can be reclaimed by GC.
*/
final class TDSPacket {
final byte[] header = new byte[TDS.PACKET_HEADER_SIZE];
final byte[] payload;
int payloadLength;
volatile TDSPacket next;
final public String toString() {
return "TDSPacket(SPID:" + Util.readUnsignedShortBigEndian(header, TDS.PACKET_HEADER_SPID) + " Seq:" + header[TDS.PACKET_HEADER_SEQUENCE_NUM]
+ ")";
}
TDSPacket(int size) {
payload = new byte[size];
payloadLength = 0;
next = null;
}
final boolean isEOM() {
return TDS.STATUS_BIT_EOM == (header[TDS.PACKET_HEADER_MESSAGE_STATUS] & TDS.STATUS_BIT_EOM);
}
};
/**
* TDSReaderMark encapsulates a fixed position in the response data stream.
*
* Response data is quantized into a linked chain of packets. A mark refers to a specific location in a specific packet and relies on Java's reference
* semantics to automatically keep all subsequent packets accessible until the mark is destroyed.
*/
final class TDSReaderMark {
final TDSPacket packet;
final int payloadOffset;
TDSReaderMark(TDSPacket packet,
int payloadOffset) {
this.packet = packet;
this.payloadOffset = payloadOffset;
}
}
/**
* TDSReader encapsulates the TDS response data stream.
*
* Bytes are read from SQL Server into a FIFO of packets. Reader methods traverse the packets to access the data.
*/
final class TDSReader {
private final static Logger logger = Logger.getLogger("com.microsoft.sqlserver.jdbc.internals.TDS.Reader");
final private String traceID;
final public String toString() {
return traceID;
}
private final TDSChannel tdsChannel;
private final SQLServerConnection con;
private final TDSCommand command;
final TDSCommand getCommand() {
assert null != command;
return command;
}
final SQLServerConnection getConnection() {
return con;
}
private TDSPacket currentPacket = new TDSPacket(0);
private TDSPacket lastPacket = currentPacket;
private int payloadOffset = 0;
private int packetNum = 0;
private boolean isStreaming = true;
private boolean useColumnEncryption = false;
private boolean serverSupportsColumnEncryption = false;
private final byte valueBytes[] = new byte[256];
private static final AtomicInteger lastReaderID = new AtomicInteger(0);
private static int nextReaderID() {
return lastReaderID.incrementAndGet();
}
TDSReader(TDSChannel tdsChannel,
SQLServerConnection con,
TDSCommand command) {
this.tdsChannel = tdsChannel;
this.con = con;
this.command = command; // may be null
// if the logging level is not detailed than fine or more we will not have proper readerids.
if (logger.isLoggable(Level.FINE))
traceID = "TDSReader@" + nextReaderID() + " (" + con.toString() + ")";
else
traceID = con.toString();
if (con.isColumnEncryptionSettingEnabled()) {
useColumnEncryption = true;
}
serverSupportsColumnEncryption = con.getServerSupportsColumnEncryption();
}
final boolean isColumnEncryptionSettingEnabled() {
return useColumnEncryption;
}
final boolean getServerSupportsColumnEncryption() {
return serverSupportsColumnEncryption;
}
final void throwInvalidTDS() throws SQLServerException {
if (logger.isLoggable(Level.SEVERE))
logger.severe(toString() + " got unexpected value in TDS response at offset:" + payloadOffset);
con.throwInvalidTDS();
}
final void throwInvalidTDSToken(String tokenName) throws SQLServerException {
if (logger.isLoggable(Level.SEVERE))
logger.severe(toString() + " got unexpected value in TDS response at offset:" + payloadOffset);
con.throwInvalidTDSToken(tokenName);
}
/**
* Ensures that payload data is available to be read, automatically advancing to (and possibly reading) the next packet.
*
* @return true if additional data is available to be read false if no more data is available
*/
private boolean ensurePayload() throws SQLServerException {
if (payloadOffset == currentPacket.payloadLength)
if (!nextPacket())
return false;
assert payloadOffset < currentPacket.payloadLength;
return true;
}
/**
* Advance (and possibly read) the next packet.
*
* @return true if additional data is available to be read false if no more data is available
*/
private boolean nextPacket() throws SQLServerException {
assert null != currentPacket;
// Shouldn't call this function unless we're at the end of the current packet...
TDSPacket consumedPacket = currentPacket;
assert payloadOffset == consumedPacket.payloadLength;
// If no buffered packets are left then maybe we can read one...
// This action must be synchronized against against another thread calling
// readAllPackets() to read in ALL of the remaining packets of the current response.
if (null == consumedPacket.next) {
readPacket();
if (null == consumedPacket.next)
return false;
}
// Advance to that packet. If we are streaming through the
// response, then unlink the current packet from the next
// before moving to allow the packet to be reclaimed.
TDSPacket nextPacket = consumedPacket.next;
if (isStreaming) {
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Moving to next packet -- unlinking consumed packet");
consumedPacket.next = null;
}
currentPacket = nextPacket;
payloadOffset = 0;
return true;
}
/**
* Reads the next packet of the TDS channel.
*
* This method is synchronized to guard against simultaneously reading packets from one thread that is processing the response and another thread
* that is trying to buffer it with TDSCommand.detach().
*/
synchronized final boolean readPacket() throws SQLServerException {
if (null != command && !command.readingResponse())
return false;
// Number of packets in should always be less than number of packets out.
// If the server has been notified for an interrupt, it may be less by
// more than one packet.
assert tdsChannel.numMsgsRcvd < tdsChannel.numMsgsSent : "numMsgsRcvd:" + tdsChannel.numMsgsRcvd + " should be less than numMsgsSent:"
+ tdsChannel.numMsgsSent;
TDSPacket newPacket = new TDSPacket(con.getTDSPacketSize());
// First, read the packet header.
for (int headerBytesRead = 0; headerBytesRead < TDS.PACKET_HEADER_SIZE;) {
int bytesRead = tdsChannel.read(newPacket.header, headerBytesRead, TDS.PACKET_HEADER_SIZE - headerBytesRead);
if (bytesRead < 0) {
if (logger.isLoggable(Level.FINER))
logger.finer(toString() + " Premature EOS in response. packetNum:" + packetNum + " headerBytesRead:" + headerBytesRead);
con.terminate(SQLServerException.DRIVER_ERROR_IO_FAILED, ((0 == packetNum && 0 == headerBytesRead)
? SQLServerException.getErrString("R_noServerResponse") : SQLServerException.getErrString("R_truncatedServerResponse")));
}
headerBytesRead += bytesRead;
}
// Header size is a 2 byte unsigned short integer in big-endian order.
int packetLength = Util.readUnsignedShortBigEndian(newPacket.header, TDS.PACKET_HEADER_MESSAGE_LENGTH);
// Make header size is properly bounded and compute length of the packet payload.
if (packetLength < TDS.PACKET_HEADER_SIZE || packetLength > con.getTDSPacketSize()) {
logger.warning(toString() + " TDS header contained invalid packet length:" + packetLength + "; packet size:" + con.getTDSPacketSize());
throwInvalidTDS();
}
newPacket.payloadLength = packetLength - TDS.PACKET_HEADER_SIZE;
// Just grab the SPID for logging (another big-endian unsigned short).
tdsChannel.setSPID(Util.readUnsignedShortBigEndian(newPacket.header, TDS.PACKET_HEADER_SPID));
// Packet header looks good enough.
// When logging, copy the packet header to the log buffer.
byte[] logBuffer = null;
if (tdsChannel.isLoggingPackets()) {
logBuffer = new byte[packetLength];
System.arraycopy(newPacket.header, 0, logBuffer, 0, TDS.PACKET_HEADER_SIZE);
}
// Now for the payload...
for (int payloadBytesRead = 0; payloadBytesRead < newPacket.payloadLength;) {
int bytesRead = tdsChannel.read(newPacket.payload, payloadBytesRead, newPacket.payloadLength - payloadBytesRead);
if (bytesRead < 0)
con.terminate(SQLServerException.DRIVER_ERROR_IO_FAILED, SQLServerException.getErrString("R_truncatedServerResponse"));
payloadBytesRead += bytesRead;
}
++packetNum;
lastPacket.next = newPacket;
lastPacket = newPacket;
// When logging, append the payload to the log buffer and write out the whole thing.
if (tdsChannel.isLoggingPackets()) {
System.arraycopy(newPacket.payload, 0, logBuffer, TDS.PACKET_HEADER_SIZE, newPacket.payloadLength);
tdsChannel.logPacket(logBuffer, 0, packetLength,
this.toString() + " received Packet:" + packetNum + " (" + newPacket.payloadLength + " bytes)");
}
// If end of message, then bump the count of messages received and disable
// interrupts. If an interrupt happened prior to disabling, then expect
// to read the attention ack packet as well.
if (newPacket.isEOM()) {
++tdsChannel.numMsgsRcvd;
// Notify the command (if any) that we've reached the end of the response.
if (null != command)
command.onResponseEOM();
}
return true;
}
final TDSReaderMark mark() {
TDSReaderMark mark = new TDSReaderMark(currentPacket, payloadOffset);
isStreaming = false;
if (logger.isLoggable(Level.FINEST))
logger.finest(this.toString() + ": Buffering from: " + mark.toString());
return mark;
}
final void reset(TDSReaderMark mark) {
if (logger.isLoggable(Level.FINEST))
logger.finest(this.toString() + ": Resetting to: " + mark.toString());
currentPacket = mark.packet;
payloadOffset = mark.payloadOffset;
}
final void stream() {
isStreaming = true;
}
/**
* Returns the number of bytes that can be read (or skipped over) from this TDSReader without blocking by the next caller of a method for this
* TDSReader.
*
* @return the actual number of bytes available.
*/
final int available() {
// The number of bytes that can be read without blocking is just the number
// of bytes that are currently buffered. That is the number of bytes left
// in the current packet plus the number of bytes in the remaining packets.
int available = currentPacket.payloadLength - payloadOffset;
for (TDSPacket packet = currentPacket.next; null != packet; packet = packet.next)
available += packet.payloadLength;
return available;
}
/**
*
* @return number of bytes available in the current packet
*/
final int availableCurrentPacket() {
/*
* The number of bytes that can be read from the current chunk, without including the next chunk that is buffered. This is so the driver can
* confirm if the next chunk sent is new packet or just continuation
*/
int available = currentPacket.payloadLength - payloadOffset;
return available;
}
final int peekTokenType() throws SQLServerException {
// Check whether we're at EOF
if (!ensurePayload())
return -1;
// Peek at the current byte (don't increment payloadOffset!)
return currentPacket.payload[payloadOffset] & 0xFF;
}
final short peekStatusFlag() throws SQLServerException {
// skip the current packet(i.e, TDS packet type) and peek into the status flag (USHORT)
if (payloadOffset + 3 <= currentPacket.payloadLength) {
short value = Util.readShort(currentPacket.payload, payloadOffset + 1);
return value;
}
// as per TDS protocol, TDS_DONE packet should always be followed by status flag
// throw exception if status packet is not available
throwInvalidTDS();
return 0;
}
final int readUnsignedByte() throws SQLServerException {
// Ensure that we have a packet to read from.
if (!ensurePayload())
throwInvalidTDS();
return currentPacket.payload[payloadOffset++] & 0xFF;
}
final short readShort() throws SQLServerException {
if (payloadOffset + 2 <= currentPacket.payloadLength) {
short value = Util.readShort(currentPacket.payload, payloadOffset);
payloadOffset += 2;
return value;
}
return Util.readShort(readWrappedBytes(2), 0);
}
final int readUnsignedShort() throws SQLServerException {
if (payloadOffset + 2 <= currentPacket.payloadLength) {
int value = Util.readUnsignedShort(currentPacket.payload, payloadOffset);
payloadOffset += 2;
return value;
}
return Util.readUnsignedShort(readWrappedBytes(2), 0);
}
final String readUnicodeString(int length) throws SQLServerException {
int byteLength = 2 * length;
byte bytes[] = new byte[byteLength];
readBytes(bytes, 0, byteLength);
return Util.readUnicodeString(bytes, 0, byteLength, con);
}
final char readChar() throws SQLServerException {
return (char) readShort();
}
final int readInt() throws SQLServerException {
if (payloadOffset + 4 <= currentPacket.payloadLength) {
int value = Util.readInt(currentPacket.payload, payloadOffset);
payloadOffset += 4;
return value;
}
return Util.readInt(readWrappedBytes(4), 0);
}
final int readIntBigEndian() throws SQLServerException {
if (payloadOffset + 4 <= currentPacket.payloadLength) {
int value = Util.readIntBigEndian(currentPacket.payload, payloadOffset);
payloadOffset += 4;
return value;
}
return Util.readIntBigEndian(readWrappedBytes(4), 0);
}
final long readUnsignedInt() throws SQLServerException {
return readInt() & 0xFFFFFFFFL;
}
final long readLong() throws SQLServerException {
if (payloadOffset + 8 <= currentPacket.payloadLength) {
long value = Util.readLong(currentPacket.payload, payloadOffset);
payloadOffset += 8;
return value;
}
return Util.readLong(readWrappedBytes(8), 0);
}
final void readBytes(byte[] value,
int valueOffset,
int valueLength) throws SQLServerException {
for (int bytesRead = 0; bytesRead < valueLength;) {
// Ensure that we have a packet to read from.
if (!ensurePayload())
throwInvalidTDS();
// Figure out how many bytes to copy from the current packet
// (the lesser of the remaining value bytes and the bytes left in the packet).
int bytesToCopy = valueLength - bytesRead;
if (bytesToCopy > currentPacket.payloadLength - payloadOffset)
bytesToCopy = currentPacket.payloadLength - payloadOffset;
// Copy some bytes from the current packet to the destination value.
if (logger.isLoggable(Level.FINEST))
logger.finest(toString() + " Reading " + bytesToCopy + " bytes from offset " + payloadOffset);
System.arraycopy(currentPacket.payload, payloadOffset, value, valueOffset + bytesRead, bytesToCopy);
bytesRead += bytesToCopy;
payloadOffset += bytesToCopy;
}
}
final byte[] readWrappedBytes(int valueLength) throws SQLServerException {
assert valueLength <= valueBytes.length;
readBytes(valueBytes, 0, valueLength);
return valueBytes;
}
final Object readDecimal(int valueLength,
TypeInfo typeInfo,
JDBCType jdbcType,
StreamType streamType) throws SQLServerException {
if (valueLength > valueBytes.length) {
logger.warning(toString() + " Invalid value length:" + valueLength);
throwInvalidTDS();
}
readBytes(valueBytes, 0, valueLength);
return DDC.convertBigDecimalToObject(Util.readBigDecimal(valueBytes, valueLength, typeInfo.getScale()), jdbcType, streamType);
}
final Object readMoney(int valueLength,
JDBCType jdbcType,
StreamType streamType) throws SQLServerException {
BigInteger bi;
switch (valueLength) {
case 8: // money
{
int intBitsHi = readInt();
int intBitsLo = readInt();
if (JDBCType.BINARY == jdbcType) {
byte value[] = new byte[8];
Util.writeIntBigEndian(intBitsHi, value, 0);
Util.writeIntBigEndian(intBitsLo, value, 4);
return value;
}
bi = BigInteger.valueOf(((long) intBitsHi << 32) | (intBitsLo & 0xFFFFFFFFL));
break;
}
case 4: // smallmoney
if (JDBCType.BINARY == jdbcType) {
byte value[] = new byte[4];
Util.writeIntBigEndian(readInt(), value, 0);
return value;
}
bi = BigInteger.valueOf(readInt());
break;
default:
throwInvalidTDS();
return null;
}
return DDC.convertBigDecimalToObject(new BigDecimal(bi, 4), jdbcType, streamType);
}
final Object readReal(int valueLength,
JDBCType jdbcType,
StreamType streamType) throws SQLServerException {
if (4 != valueLength)
throwInvalidTDS();
return DDC.convertFloatToObject(Float.intBitsToFloat(readInt()), jdbcType, streamType);
}
final Object readFloat(int valueLength,
JDBCType jdbcType,
StreamType streamType) throws SQLServerException {
if (8 != valueLength)
throwInvalidTDS();
return DDC.convertDoubleToObject(Double.longBitsToDouble(readLong()), jdbcType, streamType);
}
final Object readDateTime(int valueLength,
Calendar appTimeZoneCalendar,
JDBCType jdbcType,
StreamType streamType) throws SQLServerException {
// Build and return the right kind of temporal object.
int daysSinceSQLBaseDate;
int ticksSinceMidnight;
int msecSinceMidnight;
switch (valueLength) {
case 8:
// SQL datetime is 4 bytes for days since SQL Base Date
// (January 1, 1900 00:00:00 GMT) and 4 bytes for
// the number of three hundredths (1/300) of a second
// since midnight.
daysSinceSQLBaseDate = readInt();
ticksSinceMidnight = readInt();
if (JDBCType.BINARY == jdbcType) {
byte value[] = new byte[8];
Util.writeIntBigEndian(daysSinceSQLBaseDate, value, 0);
Util.writeIntBigEndian(ticksSinceMidnight, value, 4);
return value;
}
msecSinceMidnight = (ticksSinceMidnight * 10 + 1) / 3; // Convert to msec (1 tick = 1 300th of a sec = 3 msec)
break;
case 4:
// SQL smalldatetime has less precision. It stores 2 bytes
// for the days since SQL Base Date and 2 bytes for minutes
// after midnight.
daysSinceSQLBaseDate = readUnsignedShort();
ticksSinceMidnight = readUnsignedShort();
if (JDBCType.BINARY == jdbcType) {
byte value[] = new byte[4];
Util.writeShortBigEndian((short) daysSinceSQLBaseDate, value, 0);
Util.writeShortBigEndian((short) ticksSinceMidnight, value, 2);
return value;
}
msecSinceMidnight = ticksSinceMidnight * 60 * 1000; // Convert to msec (1 tick = 1 min = 60,000 msec)
break;
default:
throwInvalidTDS();
return null;
}
// Convert the DATETIME/SMALLDATETIME value to the desired Java type.
return DDC.convertTemporalToObject(jdbcType, SSType.DATETIME, appTimeZoneCalendar, daysSinceSQLBaseDate, msecSinceMidnight, 0); // scale
// (ignored
// for
// fixed-scale
// DATETIME/SMALLDATETIME
// types)
}
final Object readDate(int valueLength,
Calendar appTimeZoneCalendar,
JDBCType jdbcType) throws SQLServerException {
if (TDS.DAYS_INTO_CE_LENGTH != valueLength)
throwInvalidTDS();
// Initialize the date fields to their appropriate values.
int localDaysIntoCE = readDaysIntoCE();
// Convert the DATE value to the desired Java type.
return DDC.convertTemporalToObject(jdbcType, SSType.DATE, appTimeZoneCalendar, localDaysIntoCE, 0, // midnight local to app time zone
0); // scale (ignored for DATE)
}
final Object readTime(int valueLength,
TypeInfo typeInfo,
Calendar appTimeZoneCalendar,
JDBCType jdbcType) throws SQLServerException {
if (TDS.timeValueLength(typeInfo.getScale()) != valueLength)
throwInvalidTDS();
// Read the value from the server
long localNanosSinceMidnight = readNanosSinceMidnight(typeInfo.getScale());
// Convert the TIME value to the desired Java type.
return DDC.convertTemporalToObject(jdbcType, SSType.TIME, appTimeZoneCalendar, 0, localNanosSinceMidnight, typeInfo.getScale());
}
final Object readDateTime2(int valueLength,
TypeInfo typeInfo,
Calendar appTimeZoneCalendar,
JDBCType jdbcType) throws SQLServerException {
if (TDS.datetime2ValueLength(typeInfo.getScale()) != valueLength)
throwInvalidTDS();
// Read the value's constituent components
long localNanosSinceMidnight = readNanosSinceMidnight(typeInfo.getScale());
int localDaysIntoCE = readDaysIntoCE();
// Convert the DATETIME2 value to the desired Java type.
return DDC.convertTemporalToObject(jdbcType, SSType.DATETIME2, appTimeZoneCalendar, localDaysIntoCE, localNanosSinceMidnight,
typeInfo.getScale());
}
final Object readDateTimeOffset(int valueLength,
TypeInfo typeInfo,
JDBCType jdbcType) throws SQLServerException {
if (TDS.datetimeoffsetValueLength(typeInfo.getScale()) != valueLength)
throwInvalidTDS();
// The nanos since midnight and days into Common Era parts of DATETIMEOFFSET values
// are in UTC. Use the minutes offset part to convert to local.
long utcNanosSinceMidnight = readNanosSinceMidnight(typeInfo.getScale());
int utcDaysIntoCE = readDaysIntoCE();
int localMinutesOffset = readShort();
// Convert the DATETIMEOFFSET value to the desired Java type.
return DDC.convertTemporalToObject(jdbcType, SSType.DATETIMEOFFSET,
new GregorianCalendar(new SimpleTimeZone(localMinutesOffset * 60 * 1000, ""), Locale.US), utcDaysIntoCE, utcNanosSinceMidnight,
typeInfo.getScale());
}
private int readDaysIntoCE() throws SQLServerException {
byte value[] = new byte[TDS.DAYS_INTO_CE_LENGTH];
readBytes(value, 0, value.length);
int daysIntoCE = 0;
for (int i = 0; i < value.length; i++)
daysIntoCE |= ((value[i] & 0xFF) << (8 * i));
// Theoretically should never encounter a value that is outside of the valid date range
if (daysIntoCE < 0)
throwInvalidTDS();
return daysIntoCE;
}
// Scale multipliers used to convert variable-scaled temporal values to a fixed 100ns scale.
// Using this array is measurably faster than using Math.pow(10, ...)
private final static int[] SCALED_MULTIPLIERS = {10000000, 1000000, 100000, 10000, 1000, 100, 10, 1};
private long readNanosSinceMidnight(int scale) throws SQLServerException {
assert 0 <= scale && scale <= TDS.MAX_FRACTIONAL_SECONDS_SCALE;
byte value[] = new byte[TDS.nanosSinceMidnightLength(scale)];
readBytes(value, 0, value.length);
long hundredNanosSinceMidnight = 0;
for (int i = 0; i < value.length; i++)
hundredNanosSinceMidnight |= (value[i] & 0xFFL) << (8 * i);
hundredNanosSinceMidnight *= SCALED_MULTIPLIERS[scale];
if (!(0 <= hundredNanosSinceMidnight && hundredNanosSinceMidnight < Nanos.PER_DAY / 100))
throwInvalidTDS();
return 100 * hundredNanosSinceMidnight;
}
final static String guidTemplate = "NNNNNNNN-NNNN-NNNN-NNNN-NNNNNNNNNNNN";
final Object readGUID(int valueLength,
JDBCType jdbcType,
StreamType streamType) throws SQLServerException {
// GUIDs must be exactly 16 bytes
if (16 != valueLength)
throwInvalidTDS();
// Read in the GUID's binary value
byte guid[] = new byte[16];
readBytes(guid, 0, 16);
switch (jdbcType) {
case CHAR:
case VARCHAR:
case LONGVARCHAR:
case GUID: {
StringBuilder sb = new StringBuilder(guidTemplate.length());
for (int i = 0; i < 4; i++) {
sb.append(Util.hexChars[(guid[3 - i] & 0xF0) >> 4]);
sb.append(Util.hexChars[guid[3 - i] & 0x0F]);
}
sb.append('-');
for (int i = 0; i < 2; i++) {
sb.append(Util.hexChars[(guid[5 - i] & 0xF0) >> 4]);
sb.append(Util.hexChars[guid[5 - i] & 0x0F]);
}
sb.append('-');
for (int i = 0; i < 2; i++) {
sb.append(Util.hexChars[(guid[7 - i] & 0xF0) >> 4]);
sb.append(Util.hexChars[guid[7 - i] & 0x0F]);
}
sb.append('-');
for (int i = 0; i < 2; i++) {
sb.append(Util.hexChars[(guid[8 + i] & 0xF0) >> 4]);
sb.append(Util.hexChars[guid[8 + i] & 0x0F]);
}
sb.append('-');
for (int i = 0; i < 6; i++) {
sb.append(Util.hexChars[(guid[10 + i] & 0xF0) >> 4]);
sb.append(Util.hexChars[guid[10 + i] & 0x0F]);
}
try {
return DDC.convertStringToObject(sb.toString(), Encoding.UNICODE.charset(), jdbcType, streamType);
}
catch (UnsupportedEncodingException e) {
MessageFormat form = new MessageFormat(SQLServerException.getErrString("R_errorConvertingValue"));
throw new SQLServerException(form.format(new Object[] {"UNIQUEIDENTIFIER", jdbcType}), null, 0, e);
}
}
default: {
if (StreamType.BINARY == streamType || StreamType.ASCII == streamType)
return new ByteArrayInputStream(guid);
return guid;
}
}
}
/**
* Reads a multi-part table name from TDS and returns it as an array of Strings.
*/
final SQLIdentifier readSQLIdentifier() throws SQLServerException {
// Multi-part names should have between 1 and 4 parts
int numParts = readUnsignedByte();
if (!(1 <= numParts && numParts <= 4))
throwInvalidTDS();
// Each part is a length-prefixed Unicode string
String[] nameParts = new String[numParts];
for (int i = 0; i < numParts; i++)
nameParts[i] = readUnicodeString(readUnsignedShort());
// Build the identifier from the name parts
SQLIdentifier identifier = new SQLIdentifier();
identifier.setObjectName(nameParts[numParts - 1]);
if (numParts >= 2)
identifier.setSchemaName(nameParts[numParts - 2]);
if (numParts >= 3)
identifier.setDatabaseName(nameParts[numParts - 3]);
if (4 == numParts)
identifier.setServerName(nameParts[numParts - 4]);
return identifier;
}
final SQLCollation readCollation() throws SQLServerException {
SQLCollation collation = null;
try {
collation = new SQLCollation(this);
}
catch (UnsupportedEncodingException e) {
con.terminate(SQLServerException.DRIVER_ERROR_INVALID_TDS, e.getMessage(), e);
// not reached
}
return collation;
}
final void skip(int bytesToSkip) throws SQLServerException {
assert bytesToSkip >= 0;
while (bytesToSkip > 0) {
// Ensure that we have a packet to read from.
if (!ensurePayload())
throwInvalidTDS();
int bytesSkipped = bytesToSkip;
if (bytesSkipped > currentPacket.payloadLength - payloadOffset)
bytesSkipped = currentPacket.payloadLength - payloadOffset;
bytesToSkip -= bytesSkipped;
payloadOffset += bytesSkipped;
}
}
final void TryProcessFeatureExtAck(boolean featureExtAckReceived) throws SQLServerException {
// in case of redirection, do not check if TDS_FEATURE_EXTENSION_ACK is received or not.
if (null != this.con.getRoutingInfo()) {
return;
}
if (isColumnEncryptionSettingEnabled() && !featureExtAckReceived)
throw new SQLServerException(this, SQLServerException.getErrString("R_AE_NotSupportedByServer"), null, 0, false);
}
}
/**
* Timer for use with Commands that support a timeout.
*
* Once started, the timer runs for the prescribed number of seconds unless stopped. If the timer runs out, it interrupts its associated Command with
* a reason like "timed out".
*/
final class TimeoutTimer implements Runnable {
private static final String threadGroupName = "mssql-jdbc-TimeoutTimer";
private final int timeoutSeconds;
private final TDSCommand command;
private volatile Future<?> task;
private static final ExecutorService executor = Executors.newCachedThreadPool(new ThreadFactory() {
private final ThreadGroup tg = new ThreadGroup(threadGroupName);
private final String threadNamePrefix = tg.getName() + "-";
private final AtomicInteger threadNumber = new AtomicInteger(0);
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(tg, r, threadNamePrefix + threadNumber.incrementAndGet());
t.setDaemon(true);
return t;
}
});
private volatile boolean canceled = false;
TimeoutTimer(int timeoutSeconds,
TDSCommand command) {
assert timeoutSeconds > 0;
assert null != command;
this.timeoutSeconds = timeoutSeconds;
this.command = command;
}
final void start() {
task = executor.submit(this);
}
final void stop() {
task.cancel(true);
canceled = true;
}
public void run() {
int secondsRemaining = timeoutSeconds;
try {
// Poll every second while time is left on the timer.
// Return if/when the timer is canceled.
do {
if (canceled)
return;
Thread.sleep(1000);
}
while (--secondsRemaining > 0);
}
catch (InterruptedException e) {
// re-interrupt the current thread, in order to restore the thread's interrupt status.
Thread.currentThread().interrupt();
return;
}
// If the timer wasn't canceled before it ran out of
// time then interrupt the registered command.
try {
command.interrupt(SQLServerException.getErrString("R_queryTimedOut"));
}
catch (SQLServerException e) {
// Unfortunately, there's nothing we can do if we
// fail to time out the request. There is no way
// to report back what happened.
command.log(Level.FINE, "Command could not be timed out. Reason: " + e.getMessage());
}
}
}
/**
* TDSCommand encapsulates an interruptable TDS conversation.
*
* A conversation may consist of one or more TDS request and response messages. A command may be interrupted at any point, from any thread, and for
* any reason. Acknowledgement and handling of an interrupt is fully encapsulated by this class.
*
* Commands may be created with an optional timeout (in seconds). Timeouts are implemented as a form of interrupt, where the interrupt event occurs
* when the timeout period expires. Currently, only the time to receive the response from the channel counts against the timeout period.
*/
abstract class TDSCommand {
abstract boolean doExecute() throws SQLServerException;
final static Logger logger = Logger.getLogger("com.microsoft.sqlserver.jdbc.internals.TDS.Command");
private final String logContext;
final String getLogContext() {
return logContext;
}
private String traceID;
final public String toString() {
if (traceID == null)
traceID = "TDSCommand@" + Integer.toHexString(hashCode()) + " (" + logContext + ")";
return traceID;
}
final void log(Level level,
String message) {
logger.log(level, toString() + ": " + message);
}
// Optional timer that is set if the command was created with a non-zero timeout period.
// When the timer expires, the command is interrupted.
private final TimeoutTimer timeoutTimer;
// TDS channel accessors
// These are set/reset at command execution time.
// Volatile ensures visibility to execution thread and interrupt thread
private volatile TDSWriter tdsWriter;
private volatile TDSReader tdsReader;
protected TDSWriter getTDSWriter(){
return tdsWriter;
}
// Lock to ensure atomicity when manipulating more than one of the following
// shared interrupt state variables below.
private final Object interruptLock = new Object();
// Flag set when this command starts execution, indicating that it is
// ready to respond to interrupts; and cleared when its last response packet is
// received, indicating that it is no longer able to respond to interrupts.
// If the command is interrupted after interrupts have been disabled, then the
// interrupt is ignored.
private volatile boolean interruptsEnabled = false;
protected boolean getInterruptsEnabled() {
return interruptsEnabled;
}
protected void setInterruptsEnabled(boolean interruptsEnabled) {
synchronized (interruptLock) {
this.interruptsEnabled = interruptsEnabled;
}
}
// Flag set to indicate that an interrupt has happened.
private volatile boolean wasInterrupted = false;
private boolean wasInterrupted() {
return wasInterrupted;
}
// The reason for the interrupt.
private volatile String interruptReason = null;
// Flag set when this command's request to the server is complete.
// If a command is interrupted before its request is complete, it is the executing
// thread's responsibility to send the attention signal to the server if necessary.
// After the request is complete, the interrupting thread must send the attention signal.
private volatile boolean requestComplete;
protected boolean getRequestComplete() {
return requestComplete;
}
protected void setRequestComplete(boolean requestComplete) {
synchronized (interruptLock) {
this.requestComplete = requestComplete;
}
}
// Flag set when an attention signal has been sent to the server, indicating that a
// TDS packet containing the attention ack message is to be expected in the response.
// This flag is cleared after the attention ack message has been received and processed.
private volatile boolean attentionPending = false;
boolean attentionPending() {
return attentionPending;
}
// Flag set when this command's response has been processed. Until this flag is set,
// there may be unprocessed information left in the response, such as transaction
// ENVCHANGE notifications.
private volatile boolean processedResponse;
protected boolean getProcessedResponse() {
return processedResponse;
}
protected void setProcessedResponse(boolean processedResponse) {
synchronized (interruptLock) {
this.processedResponse = processedResponse;
}
}
// Flag set when this command's response is ready to be read from the server and cleared
// after its response has been received, but not necessarily processed, up to and including
// any attention ack. The command's response is read either on demand as it is processed,
// or by detaching.
private volatile boolean readingResponse;
final boolean readingResponse() {
return readingResponse;
}
/**
* Creates this command with an optional timeout.
*
* @param logContext
* the string describing the context for this command.
* @param timeoutSeconds
* (optional) the time before which the command must complete before it is interrupted. A value of 0 means no timeout.
*/
TDSCommand(String logContext,
int timeoutSeconds) {
this.logContext = logContext;
this.timeoutTimer = (timeoutSeconds > 0) ? (new TimeoutTimer(timeoutSeconds, this)) : null;
}
/**
* Executes this command.
*
* @param tdsWriter
* @param tdsReader
* @throws SQLServerException
* on any error executing the command, including cancel or timeout.
*/
boolean execute(TDSWriter tdsWriter,
TDSReader tdsReader) throws SQLServerException {
this.tdsWriter = tdsWriter;
this.tdsReader = tdsReader;
assert null != tdsReader;
try {
return doExecute(); // Derived classes implement the execution details
}
catch (SQLServerException e) {
try {
// If command execution threw an exception for any reason before the request
// was complete then interrupt the command (it may already be interrupted)
// and close it out to ensure that any response to the error/interrupt
// is processed.
// no point in trying to cancel on a closed connection.
if (!requestComplete && !tdsReader.getConnection().isClosed()) {
interrupt(e.getMessage());
onRequestComplete();
close();
}
}
catch (SQLServerException interruptException) {
if (logger.isLoggable(Level.FINE))
logger.fine(this.toString() + ": Ignoring error in sending attention: " + interruptException.getMessage());
}
// throw the original exception even if trying to interrupt fails even in the case
// of trying to send a cancel to the server.
throw e;
}
}
/**
* Provides sane default response handling.
*
* This default implementation just consumes everything in the response message.
*/
void processResponse(TDSReader tdsReader) throws SQLServerException {
if (logger.isLoggable(Level.FINEST))
logger.finest(this.toString() + ": Processing response");
try {
TDSParser.parse(tdsReader, getLogContext());
}
catch (SQLServerException e) {
if (SQLServerException.DRIVER_ERROR_FROM_DATABASE != e.getDriverErrorCode())
throw e;
if (logger.isLoggable(Level.FINEST))
logger.finest(this.toString() + ": Ignoring error from database: " + e.getMessage());
}
}
/**
* Clears this command from the TDS channel so that another command can execute.
*
* This method does not process the response. It just buffers it in memory, including any attention ack that may be present.
*/
final void detach() throws SQLServerException {
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": detaching...");
// Read any remaining response packets from the server.
// This operation may be timed out or cancelled from another thread.
while (tdsReader.readPacket())
;
// Postcondition: the entire response has been read
assert !readingResponse;
}
final void close() {
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": closing...");
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": processing response...");
while (!processedResponse) {
try {
processResponse(tdsReader);
}
catch (SQLServerException e) {
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": close ignoring error processing response: " + e.getMessage());
if (tdsReader.getConnection().isSessionUnAvailable()) {
processedResponse = true;
attentionPending = false;
}
}
}
if (attentionPending) {
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": processing attention ack...");
try {
TDSParser.parse(tdsReader, "attention ack");
}
catch (SQLServerException e) {
if (tdsReader.getConnection().isSessionUnAvailable()) {
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": giving up on attention ack after connection closed by exception: " + e);
attentionPending = false;
}
else {
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": ignored exception: " + e);
}
}
// If the parser returns to us without processing the expected attention ack,
// then assume that no attention ack is forthcoming from the server and
// terminate the connection to prevent any other command from executing.
if (attentionPending) {
logger.severe(this + ": expected attn ack missing or not processed; terminating connection...");
try {
tdsReader.throwInvalidTDS();
}
catch (SQLServerException e) {
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": ignored expected invalid TDS exception: " + e);
assert tdsReader.getConnection().isSessionUnAvailable();
attentionPending = false;
}
}
}
// Postcondition:
// Response has been processed and there is no attention pending -- the command is closed.
// Of course the connection may be closed too, but the command is done regardless...
assert processedResponse && !attentionPending;
}
/**
* Interrupts execution of this command, typically from another thread.
*
* Only the first interrupt has any effect. Subsequent interrupts are ignored. Interrupts are also ignored until enabled. If interrupting the
* command requires an attention signal to be sent to the server, then this method sends that signal if the command's request is already complete.
*
* Signalling mechanism is "fire and forget". It is up to either the execution thread or, possibly, a detaching thread, to ensure that any pending
* attention ack later will be received and processed.
*
* @param reason
* the reason for the interrupt, typically cancel or timeout.
* @throws SQLServerException
* if interrupting fails for some reason. This call does not throw the reason for the interrupt.
*/
void interrupt(String reason) throws SQLServerException {
// Multiple, possibly simultaneous, interrupts may occur.
// Only the first one should be recognized and acted upon.
synchronized (interruptLock) {
if (interruptsEnabled && !wasInterrupted()) {
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": Raising interrupt for reason:" + reason);
wasInterrupted = true;
interruptReason = reason;
if (requestComplete)
attentionPending = tdsWriter.sendAttention();
}
}
}
private boolean interruptChecked = false;
/**
* Checks once whether an interrupt has occurred, and, if it has, throws an exception indicating that fact.
*
* Any calls after the first to check for interrupts are no-ops. This method is called periodically from this command's execution thread to notify
* the app when an interrupt has happened.
*
* It should only be called from places where consistent behavior can be ensured after the exception is thrown. For example, it should not be
* called at arbitrary times while processing the response, as doing so could leave the response token stream in an inconsistent state. Currently,
* response processing only checks for interrupts after every result or OUT parameter.
*
* Request processing checks for interrupts before writing each packet.
*
* @throws SQLServerException
* if this command was interrupted, throws the reason for the interrupt.
*/
final void checkForInterrupt() throws SQLServerException {
// Throw an exception with the interrupt reason if this command was interrupted.
// Note that the interrupt reason may be null. Checking whether the
// command was interrupted does not require the interrupt lock since only one
// of the shared state variables is being manipulated; interruptChecked is not
// shared with the interrupt thread.
if (wasInterrupted() && !interruptChecked) {
interruptChecked = true;
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": throwing interrupt exception, reason: " + interruptReason);
throw new SQLServerException(interruptReason, SQLState.STATEMENT_CANCELED, DriverError.NOT_SET, null);
}
}
/**
* Notifies this command when no more request packets are to be sent to the server.
*
* After the last packet has been sent, the only way to interrupt the request is to send an attention signal from the interrupt() method.
*
* Note that this method is called when the request completes normally (last packet sent with EOM bit) or when it completes after being
* interrupted (0 or more packets sent with no EOM bit).
*/
final void onRequestComplete() throws SQLServerException {
assert !requestComplete;
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": request complete");
synchronized (interruptLock) {
requestComplete = true;
// If this command was interrupted before its request was complete then
// we need to send the attention signal if necessary. Note that if no
// attention signal is sent (i.e. no packets were sent to the server before
// the interrupt happened), then don't expect an attention ack or any
// other response.
if (!interruptsEnabled) {
assert !attentionPending;
assert !processedResponse;
assert !readingResponse;
processedResponse = true;
}
else if (wasInterrupted()) {
if (tdsWriter.isEOMSent()) {
attentionPending = tdsWriter.sendAttention();
readingResponse = attentionPending;
}
else {
assert !attentionPending;
readingResponse = tdsWriter.ignoreMessage();
}
processedResponse = !readingResponse;
}
else {
assert !attentionPending;
assert !processedResponse;
readingResponse = true;
}
}
}
/**
* Notifies this command when the last packet of the response has been read.
*
* When the last packet is read, interrupts are disabled. If an interrupt occurred prior to disabling that caused an attention signal to be sent
* to the server, then an extra packet containing the attention ack is read.
*
* This ensures that on return from this method, the TDS channel is clear of all response packets for this command.
*
* Note that this method is called for the attention ack message itself as well, so we need to be sure not to expect more than one attention
* ack...
*/
final void onResponseEOM() throws SQLServerException {
boolean readAttentionAck = false;
// Atomically disable interrupts and check for a previous interrupt requiring
// an attention ack to be read.
synchronized (interruptLock) {
if (interruptsEnabled) {
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": disabling interrupts");
// Determine whether we still need to read the attention ack packet.
// When a command is interrupted, Yukon (and later) always sends a response
// containing at least a DONE(ERROR) token before it sends the attention ack,
// even if the command's request was not complete.
readAttentionAck = attentionPending;
interruptsEnabled = false;
}
}
// If an attention packet needs to be read then read it. This should
// be done outside of the interrupt lock to avoid unnecessarily blocking
// interrupting threads. Note that it is remotely possible that the call
// to readPacket won't actually read anything if the attention ack was
// already read by TDSCommand.detach(), in which case this method could
// be called from multiple threads, leading to a benign race to clear the
// readingResponse flag.
if (readAttentionAck)
tdsReader.readPacket();
readingResponse = false;
}
/**
* Notifies this command when the end of its response token stream has been reached.
*
* After this call, we are guaranteed that tokens in the response have been processed.
*/
final void onTokenEOF() {
processedResponse = true;
}
/**
* Notifies this command when the attention ack (a DONE token with a special flag) has been processed.
*
* After this call, the attention ack should no longer be expected.
*/
final void onAttentionAck() {
assert attentionPending;
attentionPending = false;
}
/**
* Starts sending this command's TDS request to the server.
*
* @param tdsMessageType
* the type of the TDS message (RPC, QUERY, etc.)
* @return the TDS writer used to write the request.
* @throws SQLServerException
* on any error, including acknowledgement of an interrupt.
*/
final TDSWriter startRequest(byte tdsMessageType) throws SQLServerException {
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": starting request...");
// Start this command's request message
try {
tdsWriter.startMessage(this, tdsMessageType);
}
catch (SQLServerException e) {
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": starting request: exception: " + e.getMessage());
throw e;
}
// (Re)initialize this command's interrupt state for its current execution.
// To ensure atomically consistent behavior, do not leave the interrupt lock
// until interrupts have been (re)enabled.
synchronized (interruptLock) {
requestComplete = false;
readingResponse = false;
processedResponse = false;
attentionPending = false;
wasInterrupted = false;
interruptReason = null;
interruptsEnabled = true;
}
return tdsWriter;
}
/**
* Finishes the TDS request and then starts reading the TDS response from the server.
*
* @return the TDS reader used to read the response.
* @throws SQLServerException
* if there is any kind of error.
*/
final TDSReader startResponse() throws SQLServerException {
return startResponse(false);
}
final TDSReader startResponse(boolean isAdaptive) throws SQLServerException {
// Finish sending the request message. If this command was interrupted
// at any point before endMessage() returns, then endMessage() throws an
// exception with the reason for the interrupt. Request interrupts
// are disabled by the time endMessage() returns.
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": finishing request");
try {
tdsWriter.endMessage();
}
catch (SQLServerException e) {
if (logger.isLoggable(Level.FINEST))
logger.finest(this + ": finishing request: endMessage threw exception: " + e.getMessage());
throw e;
}
// If command execution is subject to timeout then start timing until
// the server returns the first response packet.
if (null != timeoutTimer) {
if (logger.isLoggable(Level.FINEST))
logger.finest(this.toString() + ": Starting timer...");
timeoutTimer.start();
}
if (logger.isLoggable(Level.FINEST))
logger.finest(this.toString() + ": Reading response...");
try {
// Wait for the server to execute the request and read the first packet
// (responseBuffering=adaptive) or all packets (responseBuffering=full)
// of the response.
if (isAdaptive) {
tdsReader.readPacket();
}
else {
while (tdsReader.readPacket())
;
}
}
catch (SQLServerException e) {
if (logger.isLoggable(Level.FINEST))
logger.finest(this.toString() + ": Exception reading response: " + e.getMessage());
throw e;
}
finally {
// If command execution was subject to timeout then stop timing as soon
// as the server returns the first response packet or errors out.
if (null != timeoutTimer) {
if (logger.isLoggable(Level.FINEST))
logger.finest(this.toString() + ": Stopping timer...");
timeoutTimer.stop();
}
}
return tdsReader;
}
}
/**
* UninterruptableTDSCommand encapsulates an uninterruptable TDS conversation.
*
* TDSCommands have interruptability built in. However, some TDSCommands such as DTC commands, connection commands, cursor close and prepared
* statement handle close shouldn't be interruptable. This class provides a base implementation for such commands.
*/
abstract class UninterruptableTDSCommand extends TDSCommand {
UninterruptableTDSCommand(String logContext) {
super(logContext, 0);
}
final void interrupt(String reason) throws SQLServerException {
// Interrupting an uninterruptable command is a no-op. That is,
// it can happen, but it should have no effect.
logger.finest(toString() + " Ignoring interrupt of uninterruptable TDS command; Reason:" + reason);
}
}
|
package com.minelittlepony.model.gear;
import net.minecraft.entity.Entity;
import net.minecraft.util.ResourceLocation;
import com.minelittlepony.model.BodyPart;
import com.minelittlepony.model.capabilities.IModel;
import com.minelittlepony.pony.data.PonyWearable;
import com.minelittlepony.render.model.PlaneRenderer;
import com.minelittlepony.render.model.PonyRenderer;
public class Stetson extends AbstractGear {
private static final ResourceLocation TEXTURE = new ResourceLocation("minelittlepony", "textures/models/stetson.png");
private PlaneRenderer rimshot;
@Override
public void init(float yOffset, float stretch) {
rimshot = new PlaneRenderer(this).size(64, 64)
.tex(16, 33).top(-9, yOffset - 4, -12, 16, 17, stretch)
.tex(0, 33).bottom(-9, yOffset - 3.999F, -12, 16, 17, stretch)
.rotate(-0.3F, 0, 0.1F)
.child(new PonyRenderer(this).size(64, 64)
.tex(0, 0).box(-5, yOffset - 8, -6, 9, 4, 9, stretch)
.tex(0, 13).box(-6, yOffset - 6, -7, 11, 2, 11, stretch));
rimshot.child()
.around(-9, yOffset - 4, -12)
.tex(0, 27).south(0, yOffset - 6, 0, 16, 6, stretch)
.rotate(0.4F, 0, 0);
}
@Override
public BodyPart getGearLocation() {
return BodyPart.HEAD;
}
@Override
public ResourceLocation getTexture(Entity entity) {
return TEXTURE;
}
@Override
public void renderPart(float scale) {
rimshot.render(scale);
}
@Override
public boolean canRender(IModel model, Entity entity) {
return model.isWearing(PonyWearable.STETSON);
}
}
|
package com.rultor.agents.daemons;
import com.jcabi.aspects.Immutable;
import com.jcabi.log.Logger;
import com.jcabi.xml.XML;
import com.rultor.agents.AbstractAgent;
import java.io.IOException;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.xembly.Directive;
import org.xembly.Directives;
/**
* Stops daemon if STOP request is present.
*
* @author Yegor Bugayenko (yegor@teamed.io)
* @version $Id$
* @since 1.50
*/
@Immutable
@ToString
@EqualsAndHashCode(callSuper = false)
public final class StopsDaemon extends AbstractAgent {
/**
* Ctor.
*/
public StopsDaemon() {
super(
"/talk/request[type='stop']",
"/talk/daemon[started and not(code) and not(ended)]"
);
}
@Override
public Iterable<Directive> process(final XML xml) throws IOException {
Logger.info(
this, "docker stop attempt at %s, code=%d",
xml.xpath("/talk/@name").get(0),
new Script().exec(xml, "stop.sh")
);
return new Directives();
}
}
|
package com.sandwell.JavaSimulation;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.filechooser.FileNameExtensionFilter;
import com.jaamsim.input.InputAgent;
import com.jaamsim.input.Parser;
public class FileInput extends Input<URI> {
private String fileType; // the type of file, e.g. "Image" or "3D"
private String[] validFileExtensions; // supported file extensions
private String[] validFileDescriptions; // description of each supported file extension
public FileInput(String key, String cat, URI def) {
super(key, cat, def);
fileType = null;
validFileExtensions = null;
validFileDescriptions = null;
}
@Override
public void parse(StringVector input, Input.ParseContext context)
throws InputErrorException {
Input.assertCount(input, 1);
// Convert the file path to a URI
URI temp = null;
try {
if (context != null)
temp = InputAgent.getFileURI(context.context, input.get(0), context.jail);
else
temp = InputAgent.getFileURI(null, input.get(0), null);
}
catch (URISyntaxException ex) {
throw new InputErrorException("File Entity parse error: %s", ex.getMessage());
}
if (temp == null)
throw new InputErrorException("Unable to parse the file path:\n%s", input.get(0));
if (!temp.isOpaque() && temp.getPath() == null)
throw new InputErrorException("Unable to parse the file path:\n%s", input.get(0));
// Confirm that the file exists
if (!InputAgent.fileExists(temp))
throw new InputErrorException("The specified file does not exist.\n" +
"File path = %s", input.get(0));
if (!isValidExtension(temp))
throw new InputErrorException("Invalid file extension: %s.\nValid extensions are: %s",
temp.getPath(), Arrays.toString(validFileExtensions));
value = temp;
}
@Override
public String getValueString() {
if (value != null)
return InputAgent.getRelativeFilePath(value);
else
return "";
}
public static ArrayList<ArrayList<String>> getTokensFromURI(URI uri){
ArrayList<ArrayList<String>> tokens = new ArrayList<ArrayList<String>>();
ArrayList<String> rec = new ArrayList<String>();
BufferedReader b = null;
try {
InputStream r = uri.toURL().openStream();
b = new BufferedReader(new InputStreamReader(r));
while (true) {
String line = null;
line = b.readLine();
if (line == null)
break;
Parser.tokenize(rec, line, true);
if (rec.size() == 0)
continue;
tokens.add(rec);
rec = new ArrayList<String>();
}
b.close();
return tokens;
}
catch (MalformedURLException e) {}
catch (IOException e) {
try {
if (b != null) b.close();
}
catch (IOException e2) {}
}
return null;
}
/**
* Set the file type description for this file input.
*
* @param type - description of the file type, for example "Image" or "3D".
*/
public void setFileType(String type) {
fileType = type;
}
/**
* Sets the list of supported file extensions for this file input.
*
* @param ext - array of supported file extensions.
*/
public void setValidFileExtensions(String... ext) {
validFileExtensions = ext;
}
/**
* Sets the list of descriptions for the supported file extensions.
*
* @param desc - array of descriptions for the supported file extensions.
*/
public void setValidFileDescriptions(String... desc) {
validFileDescriptions = desc;
}
private String getFileExtention(URI u) {
String name = u.toString();
int idx = name.lastIndexOf(".");
if (idx < 0)
return "";
return name.substring(idx + 1).trim();
}
private boolean isValidExtension(URI u) {
if (validFileExtensions == null)
return true;
String ext = getFileExtention(u);
for (String val : validFileExtensions) {
if (val.equalsIgnoreCase(ext))
return true;
}
return false;
}
/**
* Returns a file name extension filter for a type of file that has
* multiple supported extensions.
*
* @return the file name extension filter for this type of file.
*/
public FileNameExtensionFilter getFileNameExtensionFilter() {
return getFileNameExtensionFilter(fileType, validFileExtensions);
}
/**
* Returns a file name extension filter for a type of file that has
* multiple supported extensions.
*
* @param type - the type of file, for example "Image" or "3D".
* @param fileExt - the valid file extensions for this type of file.
* @return the file name extension filter for this type of file.
*/
public static FileNameExtensionFilter getFileNameExtensionFilter(String type, String[] fileExt) {
if (type == null || fileExt == null)
return null;
StringBuilder desc = new StringBuilder(45);
desc.append("All Supported ").append(type).append(" Files (");
for( int i=0; i<fileExt.length; i++) {
if(i > 0)
desc.append("; ");
desc.append("*.").append(fileExt[i].toLowerCase());
}
desc.append(")");
return new FileNameExtensionFilter(desc.toString(), fileExt);
}
/**
* Returns an array of file name extension filters, one for each of the
* supported file types.
*
* @return an array of file extension filters.
*/
public FileNameExtensionFilter[] getFileNameExtensionFilters() {
return getFileNameExtensionFilters(validFileExtensions, validFileDescriptions);
}
/**
* Returns an array of file name extension filters, one for each of the
* supported file types.
*
* @param fileExt - the valid file extension for each type of file.
* @param fileDesc - the description field for each type of file.
* @return an array of file extension filters.
*/
public static FileNameExtensionFilter[] getFileNameExtensionFilters(String[] fileExt, String[] fileDesc) {
if (fileExt == null || fileDesc == null)
return null;
FileNameExtensionFilter[] filters = new FileNameExtensionFilter[fileExt.length];
for (int i=0; i<fileExt.length; i++) {
filters[i] = new FileNameExtensionFilter(fileDesc[i], fileExt[i]);
}
return filters;
}
@Override
public void parse(StringVector input) throws InputErrorException {
throw new InputErrorException("FileInput.parse() deprecated method called.");
}
}
|
package concurrent.port;
import data.Pair;
import java.io.IOException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
/**
* @author Andrey Antipov (andrey.antipov@maxifier.com) (2016-10-15)
*/
@SuppressWarnings("WeakerAccess")
public class OptimizedBufferedPort<T> implements Port<T> {
private final static Object CLOSE_VALUE = new Object();
private boolean closed = false;
private final Lock portLock = new ReentrantLock();
private final BlockingQueue<T> queue;
private final BlockingQueue rawQueue;
final PortItr portItr;
OptimizedBufferedPort(int bufferSize) {
queue = new ArrayBlockingQueue<>(bufferSize);
rawQueue = queue;
portItr = new PortItr();
}
@Override
public void send(T message) throws InterruptedException {
try {
portLock.lockInterruptibly();
sendBody(message);
} catch (Exception e) {
// if we are receiving any exception then we should cleanup queue and close port
queue.clear();
closed = true;
throw e;
} finally {
portLock.unlock();
}
}
@Override
public boolean sendIfOpen(T message) throws InterruptedException {
try {
portLock.lockInterruptibly();
if (!closed) {
sendBody(message);
}
} catch (Exception e) {
// if we are receiving any exception then we should cleanup queue and close port
queue.clear();
closed = true;
throw e;
} finally {
portLock.unlock();
}
return !closed;
}
private void sendBody(Object message) throws InterruptedException {
if (closed) {
throw new IllegalStateException("Port is closed");
}
if (message == null) {
closed = true;
}
//noinspection unchecked
rawQueue.put(message);
}
@Override
public int remainingCapacity() {
return queue.remainingCapacity();
}
@Override
public boolean sendImmediate(T message) {
//noinspection unchecked
return queue.add(message);
}
@Override
public Response sendImmediateIfOpen(T message) {
final Response result;
portLock.lock();
if (closed) {
result = Response.CLOSED;
} else {
result = sendImmediate(message) ? Response.OK : Response.FULL;
}
portLock.unlock();
return result;
}
@Override
public void close() throws IOException {
portLock.lock();
try {
sendBody(CLOSE_VALUE);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
closed = true;
portLock.unlock();
}
}
public static <T> Pair<Port<T>, Stream<T>> createPortWithStream(int bufferSize) {
final OptimizedBufferedPort<T> port = new OptimizedBufferedPort<>(bufferSize);
return Pair.tup(
port,
StreamSupport.stream(
Spliterators.spliterator(port.portItr, -1, Spliterator.IMMUTABLE),
false));
}
private class PortItr implements Iterator<T> {
private ItrState state = closed
? ItrState.EXCEEDED
: ItrState.WAIT_NEXT_VALUE;
private final Lock itrLock = new ReentrantLock();
private T nextValue;
@Override
public boolean hasNext() {
boolean result = false;
try {
itrLock.lockInterruptibly();
result = hasNextBody();
} catch (InterruptedException e) {
queue.clear();
state = ItrState.EXCEEDED;
Thread.currentThread().interrupt();
} finally {
itrLock.unlock();
}
return result;
}
private boolean hasNextBody() throws InterruptedException {
final boolean result;
switch (state) {
case EXCEEDED:
result = false;
break;
case HAS_NEXT_VALUE:
result = true;
break;
case WAIT_NEXT_VALUE:
if (closed && queue.isEmpty()) {
state = ItrState.EXCEEDED;
result = false;
} else {
nextValue = queue.take();
result = nextValue != CLOSE_VALUE;
state = result ? ItrState.HAS_NEXT_VALUE : ItrState.EXCEEDED;
}
break;
default:
state = ItrState.EXCEEDED;
result = false;
}
return result;
}
@Override
public T next() {
try {
itrLock.lockInterruptibly();
switch (state) {
case EXCEEDED:
throw new NoSuchElementException("Port is closed");
case HAS_NEXT_VALUE:
state = ItrState.WAIT_NEXT_VALUE;
break;
case WAIT_NEXT_VALUE:
if (!hasNextBody()) {
throw new NoSuchElementException("Port is closed");
}
state = ItrState.WAIT_NEXT_VALUE;
break;
}
} catch (InterruptedException e) {
queue.clear();
state = ItrState.EXCEEDED;
Thread.currentThread().interrupt();
throw new NoSuchElementException("Port is closed");
} finally {
itrLock.unlock();
}
return nextValue;
}
}
private enum ItrState {EXCEEDED, WAIT_NEXT_VALUE, HAS_NEXT_VALUE}
}
|
package de.javagl.swing.tasks;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.JTextArea;
import javax.swing.WindowConstants;
/**
* A dialog that may be shown to indicate the progress of a {@link SwingTask}.
*/
class SwingTaskDialog extends JDialog
{
/**
* Serial UID
*/
private static final long serialVersionUID = -4247620980959161270L;
/**
* The text area showing the current {@link SwingTask#getMessage() message}
* of the {@link SwingTask}
*/
private final JTextArea messageArea;
/**
* The progress bar showing the current {@link SwingTask#getProgress()
* progress} of the {@link SwingTask}
*/
private final JProgressBar progressBar;
/**
* Creates a new task dialog
*
* @param parentWindow The parent window
* @param parentComponent The parent component. The dialog will be placed
* relative to this component. If it is <code>null</code>, then the
* dialog will be placed in the center of the screen
* @param title The title of the dialog
* @param swingTask The {@link SwingTask} that is executed
* @param modal Whether the dialog should be modal
* @param cancelable Whether a button for canceling the {@link SwingTask}
* should be available
*/
SwingTaskDialog(Window parentWindow, Component parentComponent,
String title, final SwingTask<?,?> swingTask,
boolean modal, boolean cancelable)
{
super(parentWindow, title);
if (modal)
{
setModalityType(ModalityType.APPLICATION_MODAL);
}
setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
getContentPane().setLayout(new GridLayout(1,1));
JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 10, 5, 10));
messageArea = new JTextArea(1, 30);
messageArea.setFont(new Font("Dialog", Font.BOLD, 12));
messageArea.setEditable(false);
messageArea.setOpaque(false);
messageArea.setWrapStyleWord(true);
messageArea.setLineWrap(true);
String message = swingTask.getMessage();
if (message == null || message.trim().length() == 0)
{
messageArea.setText(" ");
}
else
{
messageArea.setText(message);
}
mainPanel.add(messageArea, BorderLayout.CENTER);
JPanel southPanel = new JPanel(new BorderLayout());
mainPanel.add(southPanel, BorderLayout.SOUTH);
progressBar = new JProgressBar(0, 100);
progressBar.setStringPainted(true);
progressBar.setIndeterminate(true);
southPanel.add(progressBar, BorderLayout.CENTER);
if (cancelable)
{
JButton cancelButton = new JButton("Cancel");
cancelButton.addActionListener(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
swingTask.cancel(true);
}
});
JPanel p = new JPanel(new FlowLayout());
p.add(cancelButton);
southPanel.add(p, BorderLayout.SOUTH);
}
getContentPane().add(mainPanel);
pack();
setLocationRelativeTo(parentComponent);
}
/**
* Set the message that should be displayed in the message area.
* If the message does not fit, then this dialog will be resized
* accordingly.
*
* @param message The message
*/
void setMessage(String message)
{
messageArea.setText(message);
Dimension p = getPreferredSize();
Dimension s = getSize();
if (p.height > s.height)
{
pack();
}
}
/**
* Set the progress that should be displayed in the progress bar.
* The progress is a value between 0.0 and 1.0 (inclusive).
* If the value is negative, then the progress bar will be
* indeterminate.
*
* @param progress The progress.
*/
void setProgress(double progress)
{
if (progress < 0)
{
progressBar.setIndeterminate(true);
progressBar.setStringPainted(false);
}
else
{
int percent = (int)(progress * 100);
percent = Math.max(0, Math.min(100, percent));
progressBar.setIndeterminate(false);
progressBar.setValue(percent);
progressBar.setStringPainted(true);
progressBar.setString(percent+"%");
}
}
}
|
package edu.brandeis.cs.steele.wn;
import java.util.*;
import java.util.logging.*;
import java.nio.*;
import java.nio.charset.*;
import java.nio.channels.*;
import java.io.*;
import edu.brandeis.cs.steele.util.Utils;
/** An implementation of <code>FileManagerInterface</code> that reads files
* from the local file system. A file <code>FileManager</code> caches the
* file position before and after {@link FileManagerInterface#readLineAt
* FileManagerInterface.readLineAt()} in order to eliminate the redundant IO
* activity that a naive implementation of these methods would necessitate.
*
* <p>Instances of this class are guarded. All operations are read-only, but
* are synchronized per file to maintain state including the file pointer's
* position.
*
* @author Oliver Steele, steele@cs.brandeis.edu
* @version 1.0
*/
public class FileManager implements FileManagerInterface {
// Class variables
//intentionally using FileBackedDictionary's logger (for now)
private static final Logger log = Logger.getLogger("edu.brandeis.cs.steele.wn.FileBackedDictionary");
/** The API version, used by <code>RemoteFileManager</code> for constructing a binding name. */
public static final String VERSION = "2.0.0";
// Instance variables
private String searchDirectory;
private Map<String, CharStream> filenameCache = new HashMap<String, CharStream>();
static class NextLineCache {
private String filename;
private int previous;
private int next;
synchronized void setNextLineOffset(final String filename, final int previous, final int next) {
this.filename = filename;
this.previous = previous;
this.next = next;
}
synchronized int matchingOffset(final String filename, final int offset) {
if (this.filename == null ||
previous != offset ||
//false == this.filename.equals(filename)
false == this.filename.equals(filename)
) {
return -1;
} else {
return next;
}
}
} // end class NextLineCache
private NextLineCache nextLineCache = new NextLineCache();
// Constructors
/** FIXME
* Construct a file manager backed by a set of files contained in the default WordNet search directory.
* The default search directory is the location named by the system property WNSEARCHDIR; or, if this
* is undefined, by the directory named WNHOME/Database (under MacOS) or WNHOME/dict (otherwise);
* or, if the WNHOME is undefined, the current directory (under MacOS), "C:\wn16" (Windows),
* or "/usr/local/wordnet1.6" (otherwise).
*/
public FileManager() {
this(getWNSearchDir());
}
/** Construct a file manager backed by a set of files contained in <var>searchDirectory</var>. */
public FileManager(String searchDirectory) {
this.searchDirectory = searchDirectory;
}
static String getWNHome() {
//FIXME see notes in getWNSearchDir()
String home = System.getProperty("WNHOME");
if (home != null && new File(home).exists()) {
return home;
} else {
home = System.getenv("WNHOME");
if (home != null && new File(home).exists()) {
return home;
}
}
log.log(Level.SEVERE, "WNHOME is not defined correctly as either a Java system property or environment variable. "+
System.getenv()+" \n\nsystem properties: "+System.getProperties());
throw new IllegalStateException("WNHOME is not defined correctly as either a Java system property or environment variable. "+
System.getenv()+" \n\nsystem properties: "+System.getProperties());
}
static String getWNSearchDir() {
//FIXME unify logic for this (getWNSearchDir()) and getWNHome() to try both
//system property AND environment variables and check readable
String searchDir = System.getProperty("WNSEARCHDIR");
if (searchDir != null && new File(searchDir).exists()) {
return searchDir;
}
searchDir = System.getenv("WNSEARCHDIR");
if (searchDir != null && new File(searchDir).exists()) {
return searchDir;
}
return getWNHome() + File.separator + "dict";
}
// IO primitives
// NOTE: CharStream is not thread-safe
static abstract class CharStream {
abstract void seek(final int position) throws IOException;
abstract int position() throws IOException;
abstract char charAt(int position) throws IOException;
abstract int length() throws IOException;
/** This works just like {@link RandomAccessFile#readLine} -- doesn't
* support Unicode
*/
abstract String readLine() throws IOException;
void skipLine() throws IOException {
readLine();
}
String readLineWord() throws IOException {
final String ret = readLine();
if (ret == null) {
return null;
}
final int space = ret.indexOf(' ');
assert space >= 0;
return ret.substring(0, space);
}
/**
* Treat file contents like an array of lines and return the zero-based,
* inclusive line corresponding to <var>linenum</var>
*/
String readLineNumber(int linenum) throws IOException {
//TODO when creating the CharStream, add option to "index"/cache these results as either String[] OR String[][]
//where each row is an array of the delimted items on it and a second optional argument
//readLineNumber(int linenum, int wordnum)
//assumption is these CharStream's will be tiny
//and we can still lazy load this
seek(0);
for (int i = 0; i < linenum; i++) {
skipLine();
}
return readLine();
}
} // end class CharStream
static class RAFCharStream extends CharStream {
private final RandomAccessFile raf;
RAFCharStream(final RandomAccessFile raf) {
this.raf = raf;
}
@Override void seek(final int position) throws IOException {
raf.seek(position);
}
@Override int position() throws IOException {
return (int) raf.getFilePointer();
}
@Override char charAt(int position) throws IOException {
seek(position);
return (char)raf.readByte();
}
@Override int length() throws IOException {
return (int) raf.length();
}
@Override String readLine() throws IOException {
return raf.readLine();
}
} // end class RAFCharStream
private static class NIOCharStream extends CharStream {
//FIXME position seems redundant (ByteCharBuffer has position())
protected int position;
//protected final ByteBuffer buf;
protected final ByteCharBuffer buf;
NIOCharStream(final RandomAccessFile raf) throws IOException {
final FileChannel fileChannel = raf.getChannel();
final long size = fileChannel.size();
// program logic currently depends on the entire file being mapped into memory
// size /= 2;
final MappedByteBuffer mmap = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, size);
// this buffer isDirect()
//log.log(Level.FINE, "mmap.fine(): {0}", mmap.isDirect());
//this.buf = mmap;
this.buf = new ByteCharBuffer(mmap, false);
}
@Override void seek(final int position) throws IOException {
// buffer cannot exceed Integer.MAX_VALUE since arrays are limited by this
this.position = position;
}
@Override int position() throws IOException {
return position;
}
@Override char charAt(final int p) throws IOException {
return (char) buf.get(p);
}
@Override int length() throws IOException {
return buf.capacity();
}
@Override String readLine() throws IOException {
final int s = position;
final int e = scanForwardToLineBreak();
assert s >= 0;
assert e >= 0;
final int len = e - s;
if (len <= 0) {
return null;
}
final char[] line = new char[len];
for (int j = s, i = 0; i < line.length; i++, j++) {
// NOTE: casting byte to char here since WordNet is currently
// only ASCII
line[i] = (char) buf.get(j);
}
final String toReturn = new String(line);
return toReturn;
}
@Override void skipLine() throws IOException {
scanForwardToLineBreak();
}
@Override String readLineWord() throws IOException {
final int s = position;
int e = scanForwardToLineBreak();
assert s >= 0;
assert e >= 0;
int len = e - s;
if (len <= 0) {
return null;
}
e = scanToSpace(s);
len = e - s;
final char[] word = new char[len];
for (int j = s, i = 0; i < word.length; i++, j++) {
// NOTE: casting byte to char here since WordNet is currently
// only ASCII
word[i] = (char) buf.get(j);
}
final String toReturn = new String(word);
return toReturn;
}
protected int scanToSpace(int s) {
// scan from current position to first ' '
char c;
while (s < buf.capacity()) {
c = (char) buf.get(s++);
if (c == ' ') {
return s - 1;
}
}
throw new IllegalStateException();
}
protected int scanForwardToLineBreak() {
// scan from current position to first ("\r\n"|"\r"|"\n")
boolean done = false;
boolean crnl = false;
char c;
while (done == false && position < buf.capacity()) {
c = (char) buf.get(position++);
switch(c) {
case '\r':
// if next is \n, skip that too
c = (char) buf.get(position++);
if (c != '\n') {
// put it back
--position;
} else {
crnl = true;
}
done = true;
break;
case '\n':
done = true;
break;
default:
// no-op
}
}
// return exclusive end chopping line break delimitter(s)
return crnl ? position - 2 : position - 1;
}
protected int scanBackwardToLineBreak() {
// scan backwards to first \n
// - if immediately preceding char is \n, keep going
throw new UnsupportedOperationException();
}
} // end class NIOCharStream
/**
* Like a read-only {@link CharBuffer} made from a {@link ByteBuffer} with a
* stride of 1 instead of 2.
*/
private static class ByteCharBuffer implements CharSequence {
private final ByteBuffer bb;
ByteCharBuffer(final ByteBuffer bb) {
this(bb, true);
}
ByteCharBuffer(final ByteBuffer bb, final boolean dupAndClear) {
if (dupAndClear) {
this.bb = bb.duplicate();
this.bb.clear();
} else {
this.bb = bb;
}
}
public int capacity() { return bb.capacity(); }
public ByteCharBuffer clear() { bb.clear(); return this; }
public ByteCharBuffer duplicate() {
return new ByteCharBuffer(bb.duplicate(), false);
}
public ByteCharBuffer flip() { bb.flip(); return this; }
public char get() { return (char) bb.get(); }
public char get(final int index) { return (char) bb.get(index); }
public boolean hasRemaining() { return bb.hasRemaining(); }
public boolean isDirect() { return bb.isDirect(); }
public ByteCharBuffer slice() {
return new ByteCharBuffer(bb.slice(), false);
}
public int limit() { return bb.limit(); }
public ByteCharBuffer limit(final int newLimit){ bb.limit(newLimit); return this; }
public ByteCharBuffer mark() { bb.mark(); return this; }
public int position() { return bb.position(); }
public ByteCharBuffer position(final int newPosition) { bb.position(newPosition); return this; }
public int remaining() { return bb.remaining(); }
public ByteCharBuffer reset() { bb.reset(); return this; }
public ByteCharBuffer rewind() { bb.rewind(); return this; }
/** @inheritDoc */
public char charAt(final int index) { return get(index); }
/** @inheritDoc */
public int length() { return bb.remaining(); }
/** @inheritDoc */
public CharSequence subSequence(final int start, final int end) {
// XXX not sure if a slice should be used here
throw new UnsupportedOperationException("TODO IMPLEMENT ME");
// start and end are relative to position
// this operation should not change position though
// so cannot simply "return this;"
// (position()+start, position()+end]
}
@Override public String toString() {
throw new UnsupportedOperationException("TODO IMPLEMENT ME");
}
} // end class ByteCharBuffer
synchronized CharStream getFileStream(final String filename) throws IOException {
return getFileStream(filename, true);
}
/**
* @param filename
* @param filenameWnRelative is a boolean which indicates that <param>filename</param>
* is relative (or absolute). This facilitates testing and reuse.
* @return CharStream representing <param>filename</param> or null if no such file exists.
*/
synchronized CharStream getFileStream(final String filename, final boolean filenameWnRelative) throws IOException {
CharStream stream = filenameCache.get(filename);
if (stream == null) {
final String pathname =
filenameWnRelative ? searchDirectory + File.separator + filename :
filename;
final File file = new File(pathname);
if (file.exists() && file.canRead()) {
//slow CharStream
//stream = new RAFCharStream(new RandomAccessFile(pathname, "r"));
//fast CharStream stream
stream = new NIOCharStream(new RandomAccessFile(file, "r"));
} else {
//TODO throw an exception to indicate that pathname is non existant/readble
}
filenameCache.put(filename, stream);
}
return stream;
}
// Line-based interface methods
/**
* {@inheritDoc}
*/
public String readLineNumber(final int linenum, final String filename) throws IOException {
final CharStream stream = getFileStream(filename);
if (stream == null) {
return null;
}
synchronized (stream) {
return stream.readLineNumber(linenum);
}
}
/**
* {@inheritDoc}
*/
// Core search routine. Only called from within synchronized blocks.
public String readLineAt(final int offset, final String filename) throws IOException {
final CharStream stream = getFileStream(filename);
synchronized (stream) {
stream.seek(offset);
final String line = stream.readLine();
int nextOffset = stream.position();
if (line == null) {
nextOffset = -1;
}
nextLineCache.setNextLineOffset(filename, offset, nextOffset);
return line;
}
}
/**
* {@inheritDoc}
*/
// Core search routine. Only called from within synchronized blocks.
public int getNextLinePointer(final int offset, final String filename) throws IOException {
final CharStream stream = getFileStream(filename);
synchronized (stream) {
final int next;
if (0 <= (next = nextLineCache.matchingOffset(filename, offset))) {
return next;
}
stream.seek(offset);
stream.skipLine();
return stream.position();
}
}
// Low-level Searching
/**
* {@inheritDoc}
*/
// used by substring search iterator
public int getMatchingLinePointer(int offset, final CharSequence substring, final String filename) throws IOException {
if (substring.length() == 0) {
return -1;
}
final CharStream stream = getFileStream(filename);
synchronized (stream) {
stream.seek(offset);
do {
final String line = stream.readLineWord();
final int nextOffset = stream.position();
if (line == null) {
return -1;
}
nextLineCache.setNextLineOffset(filename, offset, nextOffset);
if (line.contains(substring)) {
return offset;
}
offset = nextOffset;
} while (true);
}
}
/**
* {@inheritDoc}
*/
// used by prefix search iterator
public int getPrefixMatchLinePointer(int offset, final CharSequence prefix, final String filename) throws IOException {
if (prefix.length() == 0) {
return -1;
}
final int foffset = getIndexedLinePointer(prefix, offset, filename, true);
final int zoffset;
if (foffset < 0) {
// invert -(o - 1)
final int moffset = -(foffset + 1);
final String aline = readLineAt(moffset, filename);
if (aline == null || false == Utils.startsWith(aline, prefix)) {
zoffset = foffset;
} else {
zoffset = moffset;
}
} else {
zoffset = foffset;
}
return zoffset;
}
/**
* {@inheritDoc}
* XXX old version only languishing to verify new version
*/
// used by prefix search iterator
int oldGetPrefixMatchLinePointer(int offset, final CharSequence prefix, final String filename) throws IOException {
if (prefix.length() == 0) {
return -1;
}
final CharStream stream = getFileStream(filename);
final int origOffset = offset;
synchronized (stream) {
stream.seek(offset);
do {
final String line = stream.readLineWord();
final int nextOffset = stream.position();
if (line == null) {
return -1;
}
nextLineCache.setNextLineOffset(filename, offset, nextOffset);
if (Utils.startsWith(line, prefix)) {
if (false == checkPrefixBinarySearch(prefix, origOffset, filename)) {
throw new IllegalStateException("search failed for prefix: "+prefix+" filename: "+filename);
}
return offset;
}
offset = nextOffset;
} while (true);
}
}
// throw-away test method until confidence in binary-search based version gets near 100%
private boolean checkPrefixBinarySearch(final CharSequence prefix, final int offset, final String filename) throws IOException {
final int foffset = getIndexedLinePointer(prefix, offset, filename, true);
//XXX System.err.println("foffset: "+foffset+" prefix: \""+prefix+"\"");
final String aline;
int zoffset;
if (foffset < 0) {
// invert -(o - 1)
final int moffset = -(foffset + 1);
zoffset = moffset;
// if moffset < size && line[moffset].startsWith(prefix)
aline = readLineAt(moffset, filename);
} else {
aline = readLineAt(foffset, filename);
zoffset = foffset;
}
//XXX System.err.println("aline: \""+aline+"\" zoffset: "+zoffset);
//System.err.println("line: \""+line+"\" filename: "+filename);
//if (aline != null && aline.startsWith(prefix)) {
// //assert offset >= 0;
// System.err.println("offset >= 0: "+(offset >= 0)+" prefix: \""+prefix+"\"");
//} else {
// //assert offset < 0;
// System.err.println("offset < 0: "+(offset < 0)+" prefix: \""+prefix+"\"");
//System.err.println();
return aline != null && Utils.startsWith(aline, prefix);
}
/**
* {@inheritDoc}
*/
public int getIndexedLinePointer(final CharSequence target, final String filename) throws IOException {
return getIndexedLinePointer(target, 0, filename, true);
}
/**
* {@inheritDoc}
*/
public int getIndexedLinePointer(final CharSequence target, int start, final String filename, final boolean filenameWnRelative) throws IOException {
// This binary search method should be usable by prefix search changing it
// from linear time to logarithmic time.
// - are there counter cases where the first-word binary search would return a different
// result than a "normal" binary search?
// - underscore comes before all lower cased letters
if (target.length() == 0) {
return -1;
}
if (log.isLoggable(Level.FINEST)) {
log.finest("target: "+target+" filename: "+filename);
}
final CharStream stream = getFileStream(filename, filenameWnRelative);
if (stream == null) {
throw new IllegalArgumentException("no stream for "+filename);
}
synchronized (stream) {
int stop = stream.length();
while (true) {
//FIXME fix possible overflow issue with >>>
final int midpoint = (start + stop) / 2;
stream.seek(midpoint);
stream.skipLine();
final int offset = stream.position();
if (log.isLoggable(Level.FINEST)) {
log.finest(" "+start+", "+midpoint+", "+stop+" -> "+offset);
}
if (offset == start) {
// cannot be a match here - would be zero width
return -start - 1;
} else if (offset == stop) {
if (start != 0 && stream.charAt(start - 1) != '\n') {
stream.seek(start + 1);
stream.skipLine();
} else {
stream.seek(start);
}
if (log.isLoggable(Level.FINEST)) {
log.finest(". "+stream.position());
}
//FIXME why is this a while() loop and not an if?
// - scan through short lines?
while (stream.position() < stop) {
final int result = stream.position();
final CharSequence firstWord = stream.readLineWord();
if (log.isLoggable(Level.FINEST)) {
log.finest(" . \""+firstWord+"\" -> "+(0 == compare(target, firstWord)));
}
final int compare = compare(target, firstWord);
if (compare == 0) {
return result;
} else if (compare < 0) {
return -result - 1;
}
}
return -stop - 1;
} // end offset == stop branch
final int result = stream.position();
final CharSequence firstWord = stream.readLineWord();
final int compare = compare(target, firstWord);
if (log.isLoggable(Level.FINEST)) {
log.finest(firstWord + ": " + compare);
}
if (compare == 0) {
return result;
}
if (compare > 0) {
start = offset;
} else {
assert compare < 0;
stop = offset;
}
}
}
}
private static int compare(final CharSequence s1, final CharSequence s2) {
return Utils.WordNetLexicalComparator.TO_LOWERCASE_INSTANCE.compare(s1, s2);
}
}
|
package edu.chl.proton.control;
import edu.chl.proton.model.*;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.*;
import javafx.scene.layout.AnchorPane;
import javafx.stage.FileChooser;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static java.lang.Boolean.TRUE;
public class MainController {
private static IFileHandler file;
private static IDocumentHandler document;
private IStageHandler stage;
SingleSelectionModel<Tab> selectionModel;
@FXML
private TabPane tabPane;
@FXML
private TreeView<File> treeView;
@FXML
private AnchorPane treeViewPane;
@FXML
private SplitPane splitPane;
@FXML
private MenuBar menuBar;
public void initialize() throws IOException {
WorkspaceFactory factory = new WorkspaceFactory();
file = factory.getWorkspace();
document = factory.getWorkspace();
stage = factory.getWorkspace();
tabPane.setTabClosingPolicy(TabPane.TabClosingPolicy.ALL_TABS);
treeView.managedProperty().bind(treeView.visibleProperty());
selectionModel = tabPane.getSelectionModel();
menuBar.useSystemMenuBarProperty().set(true);
addNewTab("Untitled.md");
document.createDocument(DocumentType.MARKDOWN);
File currentDir = new File(file.getCurrentDirectory()); // current directory
findFiles(currentDir, null);
}
private void findFiles(File dir, TreeItem<File> parent) {
TreeItem root = new TreeItem<>(dir);
root.setValue(dir.getName());
if (parent == null) {
root.setExpanded(true);
} else {
root.setExpanded(false);
}
File[] files = dir.listFiles();
for (File file : files) {
if (file.isDirectory()) {
findFiles(file, root);
} else {
TreeItem item = new TreeItem<>(file);
item.setValue(file.getName());
root.getChildren().add(item);
}
}
if(parent == null){
treeView.setRoot(root);
} else {
parent.getChildren().add(root);
}
}
public void addNewTab(String name) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/edu/chl/proton/view/markdown-tab.fxml"));
Tab tab = new Tab(name);
tab.getStyleClass().add("tab");
tab.setContent(loader.load());
selectionModel.select(tab);
tabPane.getTabs().add(tab);
tab.setOnSelectionChanged(e -> document.setCurrentDocument(selectionModel.getSelectedIndex()));
tab.setOnCloseRequest(e -> document.removeDocument(tabPane.getTabs().indexOf(e.getTarget())));
}
@FXML
public void onClickNextTab(ActionEvent event) throws IOException {
selectionModel.selectNext();
document.setCurrentDocument(selectionModel.getSelectedIndex());
}
@FXML
public void onClickPreviousTab(ActionEvent event) throws IOException {
selectionModel.selectPrevious();
document.setCurrentDocument(selectionModel.getSelectedIndex());
}
@FXML
public void onClickNewButton(ActionEvent event) throws IOException {
document.createDocument(DocumentType.MARKDOWN);
addNewTab("Untitled.md");
}
@FXML
public void onClickOpenButton(ActionEvent event) throws IOException {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Open file");
File file = fileChooser.showOpenDialog(stage.getStage());
if (file != null && file.isFile()) {
document.openDocument(file.getPath());
addNewTab(file.getName());
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
List<String> lines = new ArrayList<>();
String line;
while ((line = br.readLine()) != null) {
lines.add(line);
}
document.setText(lines);
}
}
}
@FXML
public void onClickSaveButton(ActionEvent event) throws IOException {
file.saveCurrentDocument();
}
@FXML
public void onClickUndoButton(ActionEvent event) throws IOException {
// Can be really hard to implement.
}
@FXML
public void onClickRedoButton(ActionEvent event) throws IOException {
}
@FXML
public void onClickChangeDirectory(ActionEvent event) throws IOException {
FileChooser fileChooser = new FileChooser();
fileChooser.setTitle("Change directory");
File file = fileChooser.showOpenDialog(stage.getStage());
if (file != null && file.isDirectory()) {
//this.file.setCurrentDirectory(file);
}
}
@FXML
public void onClickToggleTreeViewVisibility(ActionEvent event) throws IOException {
if (treeViewPane.isVisible()) {
treeViewPane.setVisible(false);
treeViewPane.setMaxWidth(0);
treeViewPane.setMinWidth(0);
splitPane.getStyleClass().add("hide");
} else {
treeViewPane.setVisible(true);
treeViewPane.setMaxWidth(250);
treeViewPane.setMinWidth(150);
splitPane.getStyleClass().removeAll("hide");
}
}
public void onClickRenameFile(ActionEvent actionEvent) {
String path = "./Rename.txt";
String title = "Set new name";
TextPrompt prompt = new TextPrompt(stage.getStage(),title,path);
int pLength = prompt.getResult().length();
while ( (pLength <7)==TRUE ||
!((prompt.getResult()).substring(pLength-4).equals(".pdf") ||
(prompt.getResult()).substring(pLength-4).equals(".txt")) ||
!(prompt.getResult().substring(0,2).equals("./"))
)
{
Alert alert = new Alert(Alert.AlertType.CONFIRMATION, "Write a correct file name.", ButtonType.OK);
alert.showAndWait();
prompt = new TextPrompt(stage.getStage(), title, prompt.getResult());
pLength=prompt.getResult().length();
}
}
public void onClickSaveAs(ActionEvent actionEvent) {
String path = "./oldName.txt";
String title = "Save file as";
TextPrompt prompt = new TextPrompt(stage.getStage(),title,path);
int pLength = prompt.getResult().length();
}
}
|
package edu.mssm.pharm.maayanlab.Enrichr;
// Generated Dec 13, 2012 12:26:26 PM by Hibernate Tools 4.0.0
import static javax.persistence.GenerationType.IDENTITY;
import java.io.Serializable;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Date;
import java.util.Random;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
* User generated by hbm2java
*/
@Entity
@Table(name = "users", catalog = "enrichr")
public class User implements Serializable {
private static final long serialVersionUID = 1893085998342363733L;
private Integer userid;
private String email;
private String salt;
private String password;
private String first;
private String last;
private String institute;
private Date accessed;
public User() {
}
public User(String email, String password) {
this(email, password, null, null, null);
}
public User(String email, String password, String first, String last, String institute) {
this.setEmail(email);
this.setSalt(generateSalt());
this.setPassword(hash(this.salt + password));
this.setFirst(first);
this.setLast(last);
this.setInstitute(institute);
}
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "userid", unique = true, nullable = false)
public Integer getUserid() {
return this.userid;
}
// Shouldn't be used because auto-incremented by db
public void setUserid(Integer userid) {
this.userid = userid;
}
@Column(name = "email", unique = true, nullable = false, length = 100)
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
@Column(name = "salt", nullable = false, length = 16)
public String getSalt() {
return this.salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
private String generateSalt() {
Random r = new SecureRandom();
byte[] saltBytes = new byte[8];
r.nextBytes(saltBytes);
return new BigInteger(1, saltBytes).toString(16);
}
@Column(name = "password", nullable = false, length = 32)
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean checkPassword(String password) {
return this.password.equals(hash(this.salt + password));
}
private String hash(String saltedPassword) {
String hash = null;
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(saltedPassword.getBytes());
hash = new BigInteger(1, digest.digest()).toString(16);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return hash;
}
@Column(name = "first", length = 50)
public String getFirst() {
return this.first;
}
public void setFirst(String first) {
if (first !=null && !first.isEmpty())
this.first = first;
}
@Column(name = "last", length = 200)
public String getLast() {
return this.last;
}
public void setLast(String last) {
if (last != null && !last.isEmpty())
this.last = last;
}
@Column(name = "institute", length = 200)
public String getInstitute() {
return this.institute;
}
public void setInstitute(String institute) {
if (institute != null && !institute.isEmpty())
this.institute = institute;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "accessed", nullable = false, length = 19)
public Date getAccessed() {
return this.accessed;
}
// Shouldn't be used because it uses default timestamp by db
public void setAccessed(Date accessed) {
this.accessed = accessed;
}
// Use this to update timestamp
public void updateAccessed() {
this.accessed = null;
}
@Override
public String toString() {
StringBuilder output = new StringBuilder();
output.append("userid: ").append(userid).append(", ")
.append("email: ").append(email).append(", ")
.append("salt: ").append(salt).append(", ")
.append("password: ").append(password);
if (first != null)
output.append(",").append("first: ").append(first);
if (last != null)
output.append(", ").append("last: ").append(last);
if (institute != null)
output.append(", ").append("institute: ").append(institute);
output.append(", ").append("accessed: ").append(accessed);
return output.toString();
}
}
|
package focusedCrawler.link;
import java.util.Comparator;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.PriorityQueue;
import focusedCrawler.util.LinkRelevance;
public class DownloadScheduler {
private static class DomainNode {
final String domainName;
final Deque<LinkRelevance> links;
long lastAccessTime;
public DomainNode(String domainName, long lastAccessTime) {
this.domainName = domainName;
this.links = new LinkedList<>();
this.lastAccessTime = lastAccessTime;
}
}
private final PriorityQueue<DomainNode> domainsQueue;
private final PriorityQueue<DomainNode> emptyDomainsQueue;
private final Map<String, DomainNode> domains;
private final long minimumAccessTime;
private int numberOfLinks = 0;
public DownloadScheduler(int minimumAccessTimeInterval) {
this.minimumAccessTime = minimumAccessTimeInterval;
this.domains = new HashMap<>();
this.emptyDomainsQueue = createDomainPriorityQueue();
this.domainsQueue = createDomainPriorityQueue();
}
private PriorityQueue<DomainNode> createDomainPriorityQueue() {
int initialCapacity = 10;
return new PriorityQueue<DomainNode>(initialCapacity, new Comparator<DomainNode>() {
@Override
public int compare(DomainNode o1, DomainNode o2) {
return Long.compare(o1.lastAccessTime, o2.lastAccessTime);
}
});
}
public synchronized void addLink(LinkRelevance link) {
removeExpiredNodes();
String domainName = link.getTopLevelDomainName();
DomainNode domainNode = domains.get(domainName);
if(domainNode == null) {
domainNode = new DomainNode(domainName, 0l);
domains.put(domainName, domainNode);
}
if(domainNode.links.isEmpty()) {
emptyDomainsQueue.remove(domainNode);
domainsQueue.add(domainNode);
}
domainNode.links.addLast(link);
numberOfLinks++;
}
private synchronized void removeExpiredNodes() {
while(true) {
DomainNode node = emptyDomainsQueue.peek();
if(node == null) {
break;
}
long expirationTime = node.lastAccessTime + minimumAccessTime;
if(System.currentTimeMillis() > expirationTime) {
emptyDomainsQueue.poll();
domains.remove(node.domainName);
} else {
break;
}
}
}
public LinkRelevance nextLink() {
long expirationTime;
LinkRelevance linkRelevance;
synchronized(this) {
DomainNode domainNode = domainsQueue.poll();
if(domainNode == null) {
return null;
}
linkRelevance = domainNode.links.removeFirst();
expirationTime = domainNode.lastAccessTime + minimumAccessTime;
domainNode.lastAccessTime = System.currentTimeMillis();
if(domainNode.links.isEmpty()) {
emptyDomainsQueue.add(domainNode);
} else {
domainsQueue.add(domainNode);
}
numberOfLinks
}
long waitTime = expirationTime - System.currentTimeMillis();
if(waitTime > 0) {
try {
Thread.sleep(waitTime);
} catch (InterruptedException e) {
throw new RuntimeException(getClass()+" interrupted.", e);
}
}
return linkRelevance;
}
public int numberOfNonExpiredDomains() {
removeExpiredNodes();
return domains.size();
}
public int numberOfEmptyDomains() {
return emptyDomainsQueue.size();
}
public int numberOfLinks() {
return numberOfLinks;
}
public boolean hasPendingLinks() {
return numberOfLinks() > 0;
}
}
|
package gui.modal;
import gui.events.CameraShotCreationEvent;
import gui.headerarea.DoubleTextField;
import gui.root.RootPane;
import gui.styling.StyledButton;
import gui.styling.StyledCheckbox;
import java.util.ArrayList;
import java.util.List;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Point3D;
import javafx.geometry.Pos;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.effect.BlurType;
import javafx.scene.effect.DropShadow;
import javafx.scene.effect.InnerShadow;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import lombok.Getter;
import lombok.Setter;
/**
* Class responsible for displaying a modal view for the creation of shots.
* @author alex
*/
public class CameraShotCreationModalView extends ModalView {
/*
* Tweakable styling variables.
*/
// width and height of screen. 680 and 290 work very, very well.
private static final int width = 680;
private static final int height = 290;
// simple background styles of the three main areas.
private String topStyle = "-fx-background-color: rgb(240,240,240);"
+ "-fx-text-fill: black; -fx-font-size: 20;";
private String centerStyle = "-fx-background-color: rgb(230, 230, 230);";
private String bottomStyle = "-fx-background-color: rgb(240, 240, 240);";
// variables for the Create and Cancel buttons
private int buttonWidth = 90;
private int buttonHeight = 25;
private Point3D createButtonColor = new Point3D(200, 200, 200);
private Point3D cancelButtonColor = new Point3D(200, 200, 200);
private int buttonFontSize = 16;
private int buttonSpacing = 20;
// color of the "active" element of a checkbox
private Point3D checkboxColor = new Point3D(250, 120, 50);
// variables for the title label
private int titlelabelOffsetFromLeft = 20;
// variables for the shadow effects
private double softShadowRadius = 15;
private double softShadowCutoff = 0.2;
private double softShadowOpacity = 0.05;
private double hardShadowRadius = 1;
private double hardShadowCutoff = 1;
private double hardShadowOpacity = 0.15;
/*
* Other variables.
*/
// No touching these constants. They work well for all general cases,
// and there is no reason to change them ever again.
private static final int GENERAL_SIZE = 10000;
private static final int GENERAL_SPACING = 10;
private static final int GENERAL_PADDING = 20;
private static final int TEXT_AREA_MIN_WIDTH = 350;
private static final int CAMERA_AREA_MIN_WIDTH = 250;
private int numberOfCameras;
@Setter
private String defaultStartCount = "0";
@Setter
private String defaultEndCount = "1";
private VBox viewPane;
private HBox contentPane;
private HBox buttonPane;
private FlowPane checkboxPane;
private List<StyledCheckbox> cameraCheckboxes;
private TextField descriptionField;
private TextField nameField;
private Label titleLabel;
@Getter
private StyledButton creationButton;
@Getter
private StyledButton cancelButton;
@Getter
private DoubleTextField startField;
@Getter
private DoubleTextField endField;
private InnerShadow topInnerShadow;
private InnerShadow topOuterShadow;
private DropShadow bottomOuterShadow;
private EventHandler<CameraShotCreationEvent> cameraShotCreationEventHandler;
/**
* Constructor with default modal size.
* @param rootPane Pane to display modal on top of
* @param numberOfCamerasInTimeline Amount of cameras in timeline
* @param creationHandler Event handler for the creation of a shot
*/
public CameraShotCreationModalView(RootPane rootPane, int numberOfCamerasInTimeline,
EventHandler<CameraShotCreationEvent> creationHandler) {
this(rootPane, numberOfCamerasInTimeline, creationHandler, width, height);
}
/**
* Constructor.
* @param rootPane Pane to display modal on top of
* @param numberOfCamerasInTimeline Amount of cameras in timeline
* @param creationHandler Event handler for the creation of a shot
* @param modalWidth Modal display width
* @param modalHeight Modal display height
*/
public CameraShotCreationModalView(RootPane rootPane, int numberOfCamerasInTimeline,
EventHandler<CameraShotCreationEvent> creationHandler,
int modalWidth, int modalHeight) {
super(rootPane, modalWidth, modalHeight);
this.numberOfCameras = numberOfCamerasInTimeline;
this.cameraShotCreationEventHandler = creationHandler;
initializeCreationView();
}
/**
* Initialize and display the modal view.
*/
private void initializeCreationView() {
// force minimum size
getModalStage().setMinWidth(width);
getModalStage().setMinHeight(height);
// Create a new VBox for vertical layout
this.viewPane = new VBox();
// Add label at top
initTitleLabel();
// add space for textfields and checkboxes
this.contentPane = new HBox();
this.contentPane.setAlignment(Pos.CENTER);
this.contentPane.setPadding(new Insets(0, GENERAL_PADDING, 0, 0));
this.contentPane.setPrefHeight(GENERAL_SIZE);
this.contentPane.setSpacing(40.0);
this.contentPane.setStyle(centerStyle);
this.viewPane.getChildren().add(contentPane);
// actually add textfields and checkboxes
initTextFields();
initCamCheckBoxes();
// add buttons at bottom.
initButtons();
// once we're done, setup shadows etc.
initEffects();
super.setModalView(this.viewPane);
super.displayModal();
}
/**
* Initialize title label.
*/
private void initTitleLabel() {
titleLabel = new Label("Add a new shot...");
titleLabel.setStyle(topStyle);
titleLabel.setAlignment(Pos.CENTER_LEFT);
titleLabel.setPadding(new Insets(0, 0, 0, titlelabelOffsetFromLeft));
titleLabel.setPrefWidth(GENERAL_SIZE);
titleLabel.setPrefHeight(GENERAL_SIZE);
this.viewPane.getChildren().add(titleLabel);
}
/**
* Sets up effects and adds them to the appropriate panes.
*/
private void initEffects() {
topInnerShadow = new InnerShadow(BlurType.GAUSSIAN, Color.rgb(0, 0, 0, hardShadowOpacity),
hardShadowRadius, hardShadowCutoff, 0, -2);
topOuterShadow = new InnerShadow(BlurType.GAUSSIAN, Color.rgb(0, 0, 0, softShadowOpacity),
softShadowRadius, softShadowCutoff, 0, 1);
bottomOuterShadow = new DropShadow(BlurType.GAUSSIAN, Color.rgb(0, 0, 0, softShadowOpacity),
softShadowRadius, softShadowCutoff, 0, -1);
titleLabel.setEffect(topInnerShadow);
contentPane.setEffect(topOuterShadow);
buttonPane.setEffect(bottomOuterShadow);
}
/**
* Initializes pane with buttons at bottom.
*/
private void initButtons() {
// setup button pane
this.buttonPane = new HBox();
this.buttonPane.setSpacing(buttonSpacing);
this.buttonPane.setAlignment(Pos.CENTER_LEFT);
this.buttonPane.setPrefHeight(GENERAL_SIZE);
this.buttonPane.setStyle(bottomStyle);
this.buttonPane.setPadding(new Insets(0, 0, 0, titlelabelOffsetFromLeft));
this.viewPane.getChildren().add(buttonPane);
// Add cancel button
cancelButton = new StyledButton("Cancel");
cancelButton.setOnMouseReleased(e -> {
getModalStage().close(); // kill window
}
);
cancelButton.setPrefWidth(buttonWidth);
cancelButton.setPrefHeight(buttonHeight);
cancelButton.setFontSize(buttonFontSize);
cancelButton.setButtonColor(createButtonColor);
cancelButton.setAlignment(Pos.CENTER);
// Add creation button
creationButton = new StyledButton("Create");
creationButton.setOnMouseReleased(this::createShot);
creationButton.setPrefWidth(buttonWidth);
creationButton.setPrefHeight(buttonHeight);
creationButton.setFontSize(buttonFontSize);
creationButton.setButtonColor(cancelButtonColor);
creationButton.setAlignment(Pos.CENTER);
this.buttonPane.getChildren().addAll(creationButton, cancelButton);
}
/**
* Initialize all textfields, add them to a left-central VBox.
*/
private void initTextFields() {
VBox content = new VBox(GENERAL_SPACING);
content.setAlignment(Pos.CENTER_LEFT);
content.setMinWidth(TEXT_AREA_MIN_WIDTH);
content.setPrefWidth(GENERAL_SIZE);
content.setPrefHeight(GENERAL_SIZE);
content.setPadding(new Insets(GENERAL_PADDING));
// init name field
final Label nameLabel = new Label("Shot Name: ");
nameField = new TextField();
HBox nameBox = new HBox(GENERAL_SPACING);
nameBox.getChildren().addAll(nameLabel, nameField);
nameBox.setAlignment(Pos.CENTER_RIGHT);
// init description field
final Label descripLabel = new Label("Shot Description: ");
descriptionField = new TextField();
HBox descripBox = new HBox(GENERAL_SPACING);
descripBox.getChildren().addAll(descripLabel, descriptionField);
descripBox.setAlignment(Pos.CENTER_RIGHT);
// init start count field
final Label startLabel = new Label("Start:");
startField = new DoubleTextField(this.defaultStartCount);
HBox startBox = new HBox(GENERAL_SPACING);
startBox.getChildren().addAll(startLabel, startField);
startBox.setAlignment(Pos.CENTER_RIGHT);
// init end count field
final Label endLabel = new Label("End:");
endField = new DoubleTextField(this.defaultEndCount);
HBox endBox = new HBox(GENERAL_SPACING);
endBox.getChildren().addAll(endLabel, endField);
endBox.setAlignment(Pos.CENTER_RIGHT);
// add all to scene
content.getChildren().addAll(nameBox, descripBox, startBox, endBox);
this.contentPane.getChildren().add(content);
}
/**
* Initialize the checkboxes with labels for each camera, in a flowpane.
*/
private void initCamCheckBoxes() {
// Create new FlowPane to hold the checkboxes.
this.checkboxPane = new FlowPane();
this.checkboxPane.setHgap(GENERAL_PADDING);
this.checkboxPane.setVgap(GENERAL_PADDING);
this.checkboxPane.setMinWidth(CAMERA_AREA_MIN_WIDTH);
this.checkboxPane.setPrefWidth(GENERAL_SIZE);
this.checkboxPane.setAlignment(Pos.CENTER);
// add checkboxes
cameraCheckboxes = new ArrayList<>();
int j = 0;
for (int i = 0; i < numberOfCameras; i++) {
j = (j > 4) ? 0 : j + 1;
String checkBoxString = "Camera " + (i + 1);
StyledCheckbox checkBox = new StyledCheckbox(checkBoxString);
checkBox.setMarkColor(checkboxColor);
cameraCheckboxes.add(checkBox);
}
// add all to scene
this.checkboxPane.getChildren().addAll(cameraCheckboxes);
this.contentPane.getChildren().add(this.checkboxPane);
}
/**
* Validate and then pass shot information along.
* @param event Creation button event
*/
private void createShot(MouseEvent event) {
if (validateShot()) {
super.hideModal();
this.cameraShotCreationEventHandler.handle(this.buildCreationEvent());
}
}
/**
* Validates that the fields are correctly filled, and if not, displays
* a corresponding error message.
* @return whether or not the fields are valid
*/
private boolean validateShot() {
String errorString = "";
boolean aCameraSelected = false;
for (CheckBox cb : this.cameraCheckboxes) {
if (cb.isSelected()) {
aCameraSelected = true;
}
}
if (!aCameraSelected) {
errorString = "Please select at least one camera for this shot.";
}
double startVal = Double.parseDouble(startField.getText());
double endVal = Double.parseDouble(endField.getText());
if (startVal >= endVal) {
errorString = "Please make sure that the shot ends after it begins.\n";
}
if (descriptionField.getText().isEmpty()) {
errorString = "Please add a description.\n";
}
if (nameField.getText().isEmpty()) {
errorString = "Please name your shot.\n";
}
if (errorString.isEmpty()) {
return true;
} else {
titleLabel.setText(errorString);
titleLabel.setTextFill(Color.RED);
return false;
}
}
/**
* Build the shot creation event.
* @return the shot creation event
*/
private CameraShotCreationEvent buildCreationEvent() {
String shotName = this.nameField.getText();
String shotDescrip = this.descriptionField.getText();
List<Integer> camerasInShot = getCamerasInShot();
double startPoint = Double.parseDouble(this.startField.getText());
double endPoint = Double.parseDouble(this.endField.getText());
return new CameraShotCreationEvent(shotName, shotDescrip, camerasInShot,
startPoint, endPoint);
}
/**
* Builds a list of which camera centerarea are in the shot.
* @return list of cameras in shot
*/
private List<Integer> getCamerasInShot() {
List<Integer> camsInShot = new ArrayList<>();
for (int i = 0; i < cameraCheckboxes.size(); i++) {
if (cameraCheckboxes.get(i).isSelected()) {
camsInShot.add(i);
}
}
return camsInShot;
}
}
|
* Updated July 2016 - now can size and position the image used for HPixelColorist
* New positioning options are .loc(x,y) or can use .offsetX(x) and .offsetY(y)
* Size options are .autoSize() and .size(width/height) or can separately use .height() or .width()
* If you find any issues or have any feedback, you can contact me via twitter (@Garth_D) *
*
*/
package hype.extended.colorist;
import hype.H;
import hype.HDrawable;
import hype.interfaces.HImageHolder;
import hype.interfaces.HColorist;
import hype.HImage;
import processing.core.PImage;
import processing.core.PVector;
import static processing.core.PApplet.abs;
import static processing.core.PApplet.constrain;
public class HPixelColorist implements HColorist, HImageHolder {
private PImage img;
private boolean fillFlag, strokeFlag;
private float offsetX=0;
private float offsetY=0;
private int imgHeight = 0;
private int imgWidth = 0;
private boolean autoSize;
public HPixelColorist() {
fillAndStroke();
}
public HPixelColorist loc(float x, float y) {
offsetX(x);
offsetY(y);
return this;
}
public PVector loc() {
return new PVector(offsetX, offsetY);
}
public HPixelColorist offsetX(float x) {
float tx = x < 0 ? abs(x) : -x;
offsetX = tx;
return this;
}
public float offsetX() {
return offsetX;
}
public HPixelColorist offsetY(float y) {
float ty = y < 0 ? abs(y) : -y;
offsetY = ty;
return this;
}
public float offsetY() {
return offsetY;
}
public HPixelColorist autoSize() {
if (imgHeight==0&&imgWidth==0) {
autoSize = true;
image(img);
}
return this;
}
public HPixelColorist size(int w, int h) {
width(w);
height(h);
image(img);
return this;
}
public PVector size() {
return new PVector(imgWidth, imgHeight);
}
public HPixelColorist width(int w) {
if (autoSize == false) {
if (w < 0) {
w = abs(w);
}
imgWidth = w;
image(img);
}
return this;
}
public int width() {
return imgWidth;
}
public HPixelColorist height(int h) {
if (autoSize == false) {
if (h < 0) {
h = abs(h);
}
imgHeight = h;
image(img);
}
return this;
}
public int height() {
return imgHeight;
}
public HPixelColorist(Object imgArg) {
this();
image(imgArg);
}
@Override
public HPixelColorist image(Object imgArg) {
img = H.getImage(imgArg);
if (autoSize) {
imgWidth = H.app().width;
imgHeight = H.app().height;
}
if (imgWidth!=0 && imgHeight!=0) {
img.resize(imgWidth, imgHeight);
}
return this;
}
@Override
public PImage image() {
return img;
}
/** @deprecated */
public HPixelColorist setImage(Object imgArg) {
if (imgArg instanceof PImage) {
img = (PImage) imgArg;
} else if (imgArg instanceof HImage) {
img = ((HImage) imgArg).image();
} else if (imgArg instanceof String) {
img = H.app().loadImage((String) imgArg);
} else if (imgArg == null) {
img = null;
}
return this;
}
/** @deprecated */
public PImage getImage() {
return img;
}
public int getColor(float x, float y) {
x = abs(x);
y = abs(y);
return (img==null)? 0 : img.get(Math.round(x+offsetX), Math.round(y+offsetY));
}
@Override
public HPixelColorist fillOnly() {
fillFlag = true;
strokeFlag = false;
return this;
}
@Override
public HPixelColorist strokeOnly() {
fillFlag = false;
strokeFlag = true;
return this;
}
@Override
public HPixelColorist fillAndStroke() {
fillFlag = strokeFlag = true;
return this;
}
@Override
public boolean appliesFill() {
return fillFlag;
}
@Override
public boolean appliesStroke() {
return strokeFlag;
}
@Override
public HDrawable applyColor(HDrawable drawable) {
int clr = getColor(drawable.x(), drawable.y());
if (clr==0) {
return drawable;
}
if (fillFlag)
drawable.fill(clr, drawable.alpha());
if (strokeFlag)
drawable.stroke(clr);
return drawable;
}
}
|
package innovimax.mixthem.arguments;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* <p>Mix-them command line arguments management.</p>
* @author Innovimax
* @version 1.0
*/
public class Arguments {
private Rule rule = null;
private List<String> ruleParams = null;
private File file1 = null;
private File file2 = null;
private void setRule(Rule rule) {
this.rule = rule;
}
public Rule getRule() {
return this.rule;
}
void setRuleParameters(List<String> ruleParams) {
this.ruleParams = ruleParams;
}
public List<String> getRuleParameters() {
return this.ruleParams;
}
void setFirstFile(File file1) {
this.file1 = file1;
}
public File getFirstFile() {
return this.file1;
}
void setSecondFile(File file2) {
this.file2 = file2;
}
public File getSecondFile() {
return this.file2;
}
public static Arguments checkArguments(String[] args) throws ArgumentException {
Arguments mixArgs = new Arguments();
int index = 0;
Rule rule = findRuleArgument(args, index, "rule");
List<String> ruleParams = null;
if (rule != null) {
index++;
ruleParams = findRuleParameters(args, index, rule);
index += ruleParams.size();
} else {
rule = Rule._ADD;
}
File file1 = findFileArgument(args, index, "file1");
File file2 = findFileArgument(args, ++index, "file2");
mixArgs.setRule(rule);
mixArgs.setRuleParameters(ruleParams);
mixArgs.setFirstFile(file1);
mixArgs.setSecondFile(file2);
return mixArgs;
}
private static Rule findRuleArgument(String[] args, int index, String name) throws ArgumentException {
Rule rule = null;
if (args.length > index) {
final String ruleString = args[index];
if (ruleString.startsWith("-")) {
rule = Rule.findByName(ruleString.substring(1));
if (rule == null) {
throw new ArgumentException(name + " argument is incorrect: " + ruleString);
}
}
}
return rule;
}
private static List<String> findRuleParameters(String[] args, int index, Rule rule) throws ArgumentException {
List<String> params = new ArrayList<String>();
Iterator<RuleParam> iterator = rule.getParams().iterator();
if (iterator.hasNext()) {
RuleParam param = iterator.next();
if (args.length > index) {
String arg = args[index];
if (arg.startsWith("
final String paramString = arg.substring(1);
if (param.checkValue(paramString)) {
params.add(paramString);
index++;
} else {
if (param.isRequired()) {
throw new ArgumentException("[" + param.getName() + "] parameter is incorrect: " + paramString);
}
}
} else {
if (param.isRequired()) {
throw new ArgumentException("[" + param.getName() + "] parameter is required.");
}
}
} else {
if (param.isRequired()) {
throw new ArgumentException("[" + param.getName() + "] parameter is required.");
}
}
}
return params;
}
private static File findFileArgument(String[] args, int index, String name) throws ArgumentException {
File file = null;
if (args.length > index) {
String filepath = args[index];
file = new File(filepath);
final Path path = file.toPath();
if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
if (!Files.isReadable(path)) {
throw new ArgumentException(name + " cannot be read: " + filepath);
}
} else {
throw new ArgumentException(name + " not found: " + filepath);
}
} else {
throw new ArgumentException(name + " argument missing.");
}
return file;
}
public static void printUsage() {
System.out.println(" ");
System.out.println("Usage:");
System.out.println(" ");
System.out.println(" mix-them file1 file2");
System.out.println(" (will generate any file based on file1 and file2)");
System.out.println(" ");
System.out.println(" mix-them -[rule] file1 file2");
System.out.println(" (will generate a file based on the rule)");
System.out.println(" ");
System.out.println(" Here are the list of rules");
for(Rule rule : Rule.values()) {
System.out.print(" - " + rule.getName());
for(RuleParam param : rule.getParams()) {
if (param.isRequired()) {
System.out.print(" #" + param.getName());
} else {
System.out.print(" [#" + param.getName() + "]");
}
}
System.out.println(": " + rule.getDescription());
}
System.out.println(" ");
}
}
|
package innovimax.mixthem.arguments;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* <p>Mix-them command line arguments management.</p>
* @author Innovimax
* @version 1.0
*/
public class Arguments {
private Rule rule = null;
private List<String> ruleParams = null;
private File file1 = null;
private File file2 = null;
private void setRule(Rule rule) {
this.rule = rule;
}
public Rule getRule() {
return this.rule;
}
void setRuleParameters(List<String> ruleParams) {
this.ruleParams = ruleParams;
}
public List<String> getRuleParameters() {
return this.ruleParams;
}
void setFirstFile(File file1) {
this.file1 = file1;
}
public File getFirstFile() {
return this.file1;
}
void setSecondFile(File file2) {
this.file2 = file2;
}
public File getSecondFile() {
return this.file2;
}
public static Arguments checkArguments(String[] args) throws ArgumentException {
Arguments mixArgs = new Arguments();
int index = 0;
Rule rule = findRuleArgument(args, index, "rule");
List<String> ruleParams = null;
if (rule != null) {
index++;
ruleParams = findRuleParameters(args, index, rule);
index += ruleParams.size();
} else {
rule = Rule._ADD;
}
File file1 = findFileArgument(args, index, "file1");
File file2 = findFileArgument(args, ++index, "file2");
mixArgs.setRule(rule);
mixArgs.setRuleParameters(ruleParams);
mixArgs.setFirstFile(file1);
mixArgs.setSecondFile(file2);
return mixArgs;
}
private static Rule findRuleArgument(String[] args, int index, String name) throws ArgumentException {
Rule rule = null;
if (args.length > index) {
final String ruleString = args[index];
if (ruleString.startsWith("-")) {
rule = Rule.findByName(ruleString.substring(1));
if (rule == null) {
throw new ArgumentException(name + " argument is incorrect: " + ruleString);
}
}
}
return rule;
}
private static List<String> findRuleParameters(String[] args, int index, Rule rule) throws ArgumentException {
List<String> params = new ArrayList<String>();
Iterator<RuleParam> iterator = rule.getParams().iterator();
if (iterator.hasNext()) {
RuleParam param = iterator.next();
if (args.length > index) {
String arg = args[index];
if (arg.startsWith("
final String paramString = arg.substring(1);
if (param.checkValue(paramString)) {
params.add(paramString);
index++;
} else {
if (param.isRequired()) {
throw new ArgumentException("[" + param.getName() + "] parameter is incorrect: " + paramString);
}
}
} else {
if (param.isRequired()) {
throw new ArgumentException("[" + param.getName() + "] parameter is required.");
}
}
} else {
if (param.isRequired()) {
throw new ArgumentException("[" + param.getName() + "] parameter is required.");
}
}
}
return params;
}
private static Map<RuleParam, ParamValue> getRuleParameters(String[] args, int index, Rule rule) throws ArgumentException {
Map<RuleParam, ParamValue> map = new HashMap<RuleParam, ParamValue>();
Iterator<RuleParam> iterator = rule.getParams().iterator();
if (iterator.hasNext()) {
RuleParam param = iterator.next();
if (args.length > index) {
String arg = args[index];
if (arg.startsWith("
final String paramString = arg.substring(1);
try {
ParamValue value = param.createValue(paramString);
map.put(param, value);
index++;
} catch (NumberFormatException e) {
throw new ArgumentException("[" + param.getName() + "] parameter is incorrect: " + paramString);
}
} else {
if (param.isRequired()) {
throw new ArgumentException("[" + param.getName() + "] parameter is required.");
}
}
} else {
if (param.isRequired()) {
throw new ArgumentException("[" + param.getName() + "] parameter is required.");
}
}
}
return map;
}
private static File findFileArgument(String[] args, int index, String name) throws ArgumentException {
File file = null;
if (args.length > index) {
String filepath = args[index];
file = new File(filepath);
final Path path = file.toPath();
if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
if (!Files.isReadable(path)) {
throw new ArgumentException(name + " cannot be read: " + filepath);
}
} else {
throw new ArgumentException(name + " not found: " + filepath);
}
} else {
throw new ArgumentException(name + " argument missing.");
}
return file;
}
public static void printUsage() {
System.out.println(" ");
System.out.println("Usage:");
System.out.println(" ");
System.out.println(" mix-them file1 file2");
System.out.println(" (will generate any file based on file1 and file2)");
System.out.println(" ");
System.out.println(" mix-them -[rule] file1 file2");
System.out.println(" (will generate a file based on the rule)");
System.out.println(" ");
System.out.println(" Here are the list of rules");
for(Rule rule : Rule.values()) {
System.out.print(" - " + rule.getName());
for(RuleParam param : rule.getParams()) {
if (param.isRequired()) {
System.out.print(" #" + param.getName());
} else {
System.out.print(" [#" + param.getName() + "]");
}
}
System.out.println(": " + rule.getDescription());
}
System.out.println(" ");
}
}
|
package io.sigpipe.sing.dataset;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.math3.analysis.integration.SimpsonIntegrator;
import io.sigpipe.sing.adapters.ReadMetadata;
import io.sigpipe.sing.dataset.feature.Feature;
import io.sigpipe.sing.dataset.feature.FeatureType;
import io.sigpipe.sing.stat.OnlineKDE;
import io.sigpipe.sing.stat.SquaredError;
public class AutoQuantizer {
private static final String[] FEATURE_NAMES = {
"temperature_surface",
"temperature_tropopause",
"relative_humidity_zerodegc_isotherm",
"total_precipitation_surface_3_hour_accumulation",
"snow_depth_surface",
"snow_cover_surface",
"pressure_tropopause",
"precipitable_water_entire_atmosphere",
"visibility_surface",
"upward_short_wave_rad_flux_surface",
"surface_wind_gust_surface",
"total_cloud_cover_entire_atmosphere",
"upward_long_wave_rad_flux_surface",
"vegitation_type_as_in_sib_surface",
"albedo_surface",
"convective_inhibition_surface",
"pressure_surface",
"transpiration_stress-onset_soil_moisture_surface",
"soil_porosity_surface",
"vegetation_surface",
"downward_long_wave_rad_flux_surface",
"planetary_boundary_layer_height_surface",
//"lightning_surface",
//"ice_cover_ice1_no_ice0_surface",
//"categorical_snow_yes1_no0_surface",
};
public static Quantizer fromKDE(OnlineKDE kde, int ticks) {
SimpsonIntegrator integrator = new SimpsonIntegrator();
double tickSize = 1.0 / (double) ticks;
double start = kde.expandedMin();
double end = kde.expandedMax();
double step = ((end - start) / (double) ticks) * 0.01;
List<Feature> tickList = new ArrayList<>();
for (int t = 0; t < ticks; ++t) {
double total = 0.0;
tickList.add(new Feature(start));
double increment = step;
while (total < tickSize) {
double integral = integrator.integrate(
Integer.MAX_VALUE, kde, start, start + increment);
if (total + integral > (tickSize * 1.05)) {
//System.err.println("Oversized: " + t + " ; " + total + " + " + integral + " [" + tickSize + "]");
increment = increment / 2.0;
continue;
}
total += integral;
start = start + increment;
if (start > end) {
break;
}
}
}
tickList.add(new Feature(start));
return new Quantizer(tickList);
}
public static Quantizer fromList(List<Feature> features, int ticks) {
/* Seed the oKDE */
int seedSize = 1000;
List<Double> seedValues = new ArrayList<>();
for (int i = 0; i < seedSize; ++i) {
seedValues.add(features.get(i).getDouble());
}
OnlineKDE kde = new OnlineKDE(seedValues);
/* Populate the rest of the data */
for (int i = seedSize; i < features.size(); i += 50) {
kde.updateDistribution(features.get(i).getDouble());
}
return AutoQuantizer.fromKDE(kde, ticks);
}
public static void main(String[] args)
throws Exception {
for (String name : FEATURE_NAMES) {
List<Feature> features = new ArrayList<>();
for (String fileName : args) {
System.err.println("Reading: " + fileName);
List<Metadata> meta = ReadMetadata.readMetaBlob(new File(fileName));
for (Metadata m : meta) {
Feature f = m.getAttribute(name);
if (f != null) {
features.add(m.getAttribute(name));
} else {
System.err.println("null feature: " + name);
}
}
}
Quantizer q = null;
int ticks = 10;
double err = Double.MAX_VALUE;
while (err > 0.025) {
q = AutoQuantizer.fromList(features, ticks);
//System.out.println(q);
List<Feature> quantized = new ArrayList<>();
for (Feature f : features) {
/* Find the midpoint */
Feature initial = q.quantize(f.convertTo(FeatureType.DOUBLE));
Feature next = q.nextTick(initial);
if (next == null) {
next = initial;
}
Feature difference = next.subtract(initial);
Feature midpoint = difference.divide(new Feature(2.0f));
Feature prediction = initial.add(midpoint);
quantized.add(prediction);
//System.out.println(f.getFloat() + " " + predicted.getFloat());
}
SquaredError se = new SquaredError(features, quantized);
System.out.println(name + " " + q.numTicks() + " " + se.RMSE() + " "
+ se.NRMSE() + " " + se.CVRMSE());
err = se.NRMSE();
ticks += 1;
}
System.out.println(q);
}
}
}
|
package jline.console.completer;
import static jline.internal.Preconditions.checkNotNull;
/**
* {@link Completer} for {@link Enum} names.
*
* @author <a href="mailto:jason@planet57.com">Jason Dillon</a>
* @since 2.3
*/
public class EnumCompleter
extends StringsCompleter
{
public EnumCompleter(Class<? extends Enum<?>> source) {
this(source, true);
}
public EnumCompleter(Class<? extends Enum<?>> source, boolean toLowerCase) {
checkNotNull(source);
for (Enum<?> n : source.getEnumConstants()) {
this.getStrings().add(toLowerCase ? n.name().toLowerCase() : n.name());
}
}
}
|
package kalang.compiler.compile;
import kalang.compiler.ast.*;
import kalang.compiler.core.*;
import kalang.compiler.exception.Exceptions;
import javax.annotation.Nullable;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class MethodContext {
public static final int NULLSTATE_MUST_NULL = 0,
NULLSTATE_MUST_NONNULL = 1,
NULLSTATE_UNKNOWN = 2,
NULLSTATE_NULLABLE = 3;
public final ClassNode classNode;
public final MethodNode method;
public boolean returned = false;
public VarTable<String,LocalVarNode> varTables = new VarTable();
public VarTable<VarObject, Type> overrideTypes = new VarTable();
public VarTable<VarObject,Integer> nullState = new VarTable();
public MethodContext(ClassNode classNode, MethodNode methodNode) {
this.classNode = classNode;
this.method = methodNode;
}
public void newFrame(){
this.varTables = varTables.newStack();
}
public void popFrame(){
this.varTables = this.varTables.popStack();
}
public void onAssign(ExprNode to,ExprNode expr){
removeOverrideType(to);
if(to instanceof VarExpr){
((VarExpr)to).removeOverrideType();
}else if(to instanceof ParameterExpr){
((ParameterExpr) to).removeOverrideType();
}
VarObject key = getOverrideTypeKey(to);
if(key!=null){
Type toType = to.getType();
if(toType instanceof ObjectType){
Type type = expr.getType();
int ns;
if(Types.NULL_TYPE.equals(type)){
ns = NULLSTATE_MUST_NULL;
}else if(type instanceof ObjectType){
ns = getNullState(((ObjectType) type).getNullable());
}else{
throw Exceptions.unexpectedValue(type);
}
nullState.put(key, ns);
}
}
}
public void onIf(ExprNode expr, boolean onTrue){
if(expr instanceof InstanceOfExpr && onTrue){
InstanceOfExpr ie = (InstanceOfExpr) expr;
changeTypeTemporarilyIfCould(ie.getExpr(), Types.getClassType(ie.getTarget().getReferencedClassNode()));
} else if(expr instanceof CompareBinaryExpr) {
CompareBinaryExpr ce = (CompareBinaryExpr) expr;
ExprNode e1 = ce.getExpr1();
ExprNode e2 = ce.getExpr2();
boolean isEQ = ce.getOperation().equals(CompareBinaryExpr.OP_EQ);
if (e1.getType().equals(Types.NULL_TYPE)) {
onNull(e2, onTrue, isEQ);
} else if (e2.getType().equals(Types.NULL_TYPE)) {
onNull(e1, onTrue, isEQ);
}
} else if (expr instanceof StaticInvokeExpr) {
StaticInvokeExpr sie = (StaticInvokeExpr) expr;
ExprNode[] args = sie.getArguments();
if (args==null || args.length != 2) {
return;
}
String invokeClass = sie.getInvokeClass().getReferencedClassNode().name;
if (!Objects.class.getName().equals(invokeClass)) {
return;
}
String methodName = sie.getMethod().getName();
if (!"equals".equals(methodName) && !"deepEquals".equals(methodName)) {
return;
}
if (Types.NULL_TYPE.equals(args[0].getType())) {
onNull(args[1],onTrue,true);
} else if (Types.NULL_TYPE.equals(args[1].getType())) {
onNull(args[0],onTrue,true);
}
} else if(expr instanceof UnaryExpr){
onIf(((UnaryExpr) expr).getExpr(),!onTrue);
} else if(expr instanceof LogicBinaryExpr){
LogicBinaryExpr le = (LogicBinaryExpr) expr;
if(le.getOperation().equals(LogicBinaryExpr.OP_LOGIC_AND)){
if(onTrue){
onIf(le.getExpr1(),true);
onIf(le.getExpr2(),true);
}
}else if(le.getOperation().equals(LogicBinaryExpr.OP_LOGIC_OR)){
if(!onTrue){
onIf(le.getExpr1(),false);
onIf(le.getExpr2(),false);
}
}
}
}
public Type getVarObjectType(VarObject p) {
Type type = overrideTypes.get(p);
if(type==null) type = p.getType();
//TODO handle other object type
if(type instanceof ClassType){
Integer ns = nullState.get(p);
NullableKind nullable;
if(ns==null){
nullable = ((ObjectType) type).getNullable();
}else if(ns==NULLSTATE_MUST_NONNULL){
nullable = NullableKind.NONNULL;
}else if(ns==NULLSTATE_UNKNOWN){
nullable = NullableKind.UNKNOWN;
}else if(ns==NULLSTATE_MUST_NULL|| ns== NULLSTATE_NULLABLE){
nullable = NullableKind.NULLABLE;
}else{
throw Exceptions.unexpectedValue(ns);
}
return Types.getClassType((ClassType)type,nullable);
}else{
return type;
}
}
public void handleMultiBranchedAssign(Map<VarObject,Integer>... assignedTable){
if(assignedTable.length<2){
throw Exceptions.illegalArgument(assignedTable);
}
HashMap<VarObject,Integer> ret = new HashMap();
ret.putAll(assignedTable[0]);
for(int i=1;i<assignedTable.length;i++){
Map<VarObject,Integer> current = new HashMap(ret);
Map<VarObject,Integer> other = assignedTable[i];
for(Map.Entry<VarObject,Integer> e: current.entrySet()){
Integer oneNullable = e.getValue();
Integer otherNullable = other.get(e.getKey());
if(oneNullable.equals(otherNullable)) continue;
if(otherNullable==null) ret.remove(e.getKey());
else{
int ns;
if(
(oneNullable.equals(NULLSTATE_MUST_NONNULL) && otherNullable.equals(NULLSTATE_UNKNOWN)) || (otherNullable.equals(NULLSTATE_MUST_NONNULL) && oneNullable.equals(NULLSTATE_UNKNOWN))
){
ns = NULLSTATE_UNKNOWN;
}else{
ns = NULLSTATE_NULLABLE;
}
ret.put(e.getKey(),ns);
}
}
}
for(Map.Entry<VarObject,Integer> e:ret.entrySet()){
nullState.put(e.getKey(), e.getValue());
}
}
@Nullable
public LocalVarNode getNamedLocalVar(String name){
return varTables.get(name);
}
public void newOverrideTypeStack(){
overrideTypes = new VarTable(overrideTypes);
}
public void popOverrideTypeStack(){
overrideTypes = overrideTypes.getParent();
}
@Nullable
public ParameterNode getNamedParameter(String name){
for (ParameterNode p : method.getParameters()) {
if (name.equals(p.getName())) {
return p;
}
}
return null;
}
private void changeTypeTemporarilyIfCould(ExprNode expr,Type type){
VarObject key = getOverrideTypeKey(expr);
if(key!=null){
overrideTypes.put(key, type);
}
}
private void onNull(ExprNode expr,boolean onTrue,boolean isEQ){
boolean mustNull = (onTrue && isEQ) || (!onTrue && !isEQ);
VarObject key = this.getOverrideTypeKey(expr);
if(key!=null){
nullState.put(key,mustNull ? NULLSTATE_MUST_NULL : NULLSTATE_MUST_NONNULL);
}
}
@Nullable
private VarObject getOverrideTypeKey(ExprNode expr){
VarObject key ;
//It isn't supported to override type of field because it is not safe
if(expr instanceof VarExpr){
key = ((VarExpr) expr).getVar();
}else if(expr instanceof ParameterExpr){
key = ((ParameterExpr) expr).getParameter();
}else{
key = null;
}
return key;
}
private void removeOverrideType(ExprNode expr){
VarObject key = getOverrideTypeKey(expr);
if(key!=null) overrideTypes.remove(key, true);
}
private int getNullState(NullableKind nullable){
int ns;
if(nullable==NullableKind.NONNULL){
ns = NULLSTATE_MUST_NONNULL;
}else if(nullable==NullableKind.NULLABLE){
ns = NULLSTATE_NULLABLE;
}else if(nullable==NullableKind.UNKNOWN){
ns = NULLSTATE_UNKNOWN;
}else{
throw Exceptions.unexpectedValue(nullable);
}
return ns;
}
}
|
package mingzuozhibi.action;
import mingzuozhibi.persist.AutoLogin;
import mingzuozhibi.persist.User;
import mingzuozhibi.support.Dao;
import mingzuozhibi.support.JsonArg;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;
import java.util.Set;
import java.util.UUID;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@RestController
public class SessionController extends BaseController {
public static final Set<GrantedAuthority> GUEST_AUTHORITIES = Stream.of("NONE")
.map(SimpleGrantedAuthority::new).collect(Collectors.toSet());
@Autowired
private Dao dao;
@Autowired
private UserDetailsService userDetailsService;
@GetMapping(value = "/api/session", produces = MEDIA_TYPE)
public String sessionQuery() {
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
if (!isLogged(authentication)) {
if (checkAutoLogin()) {
String username = authentication.getName();
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
doLoginSuccess(userDetails.getPassword(), userDetails);
onLoginSuccess(username, false);
if (LOGGER.isInfoEnabled()) {
infoRequest("[: ][username={}]", username);
}
} else {
getAttributes().getResponse().addHeader("X-AUTO-LOGIN", "");
}
}
JSONObject session = buildSession();
if (LOGGER.isDebugEnabled()) {
debugRequest("[: session={}]", session);
}
return objectResult(session);
}
private boolean checkAutoLogin() {
String header = getAttributes().getRequest().getHeader("X-AUTO-LOGIN");
if (header == null || header.isEmpty()) {
if (LOGGER.isDebugEnabled()) {
debugRequest("[: X-AUTO-LOGIN]");
}
return false;
}
if (header.length() != 36) {
if (LOGGER.isWarnEnabled()) {
warnRequest("[: X-AUTO-LOGIN][token={}]", header);
}
return false;
}
AutoLogin autoLogin = dao.lookup(AutoLogin.class, "token", header);
if (autoLogin == null) {
if (LOGGER.isDebugEnabled()) {
debugRequest("[: ][token={}]", header);
}
return false;
}
String username = autoLogin.getUser().getUsername();
if (autoLogin.getExpired().isBefore(LocalDateTime.now())) {
if (LOGGER.isDebugEnabled()) {
debugRequest("[: TOKEN][username={}][expired={}]",
username, autoLogin.getExpired());
}
return false;
}
if (!autoLogin.getUser().isEnabled()) {
if (LOGGER.isInfoEnabled()) {
infoRequest("[: ][username={}]", username);
}
return false;
}
return true;
}
@PostMapping(value = "/api/session/login", produces = MEDIA_TYPE)
public String sessionLogin(
@JsonArg("$.username") String username,
@JsonArg("$.password") String password) {
try {
UserDetails userDetails = userDetailsService.loadUserByUsername(username);
if (!userDetails.getPassword().equals(password)) {
if (LOGGER.isDebugEnabled()) {
debugRequest("[: username={}]", username);
}
return errorMessage("");
}
if (!userDetails.isEnabled()) {
if (LOGGER.isDebugEnabled()) {
debugRequest("[: username={}]", username);
}
return errorMessage("");
}
doLoginSuccess(password, userDetails);
onLoginSuccess(username, true);
JSONObject session = buildSession();
if (LOGGER.isInfoEnabled()) {
infoRequest("[: session={}]", session);
}
return objectResult(session);
} catch (UsernameNotFoundException e) {
if (LOGGER.isDebugEnabled()) {
debugRequest("[: username={}]", username);
}
return errorMessage("");
}
}
private void doLoginSuccess(String password, UserDetails userDetails) {
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
userDetails, password, userDetails.getAuthorities());
token.setDetails(new WebAuthenticationDetails(getAttributes().getRequest()));
SecurityContext context = SecurityContextHolder.getContext();
context.setAuthentication(token);
getAttributes().getRequest().changeSessionId();
}
private void onLoginSuccess(String username, boolean putAutoLoginToken) {
dao.execute(session -> {
User user = dao.lookup(User.class, "username", username);
user.setLastLoggedIn(LocalDateTime.now().withNano(0));
if (putAutoLoginToken) {
String header = UUID.randomUUID().toString();
getAttributes().getResponse().addHeader("X-AUTO-LOGIN", header);
LocalDateTime expired = LocalDateTime.now().withNano(0).plusDays(14);
dao.save(new AutoLogin(user, header, expired));
}
});
}
@PostMapping(value = "/api/session/logout", produces = MEDIA_TYPE)
public String sessionLogout() {
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
context.setAuthentication(new AnonymousAuthenticationToken(
UUID.randomUUID().toString(), "Guest", GUEST_AUTHORITIES)
);
dao.execute(session -> {
User user = dao.lookup(User.class, "username", authentication.getName());
dao.findBy(AutoLogin.class, "user", user).forEach(autoLogin -> {
if (LOGGER.isDebugEnabled()) {
debugRequest("[: ][token={}]", autoLogin.getToken());
}
dao.delete(autoLogin);
});
});
getAttributes().getResponse().addHeader("X-AUTO-LOGIN", "");
getAttributes().getRequest().getSession().invalidate();
if (LOGGER.isInfoEnabled()) {
infoRequest("[: username={}]", authentication.getName());
}
return objectResult(buildSession());
}
public static JSONObject buildSession() {
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
JSONObject object = new JSONObject();
object.put("userName", authentication.getName());
object.put("isLogged", isLogged(authentication));
object.put("userRoles", getUserRoles(authentication));
return object;
}
private static boolean isLogged(Authentication authentication) {
return authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.anyMatch(Predicate.isEqual("ROLE_BASIC"));
}
public static JSONArray getUserRoles(Authentication authentication) {
JSONArray userRoles = new JSONArray();
authentication.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.forEach(userRoles::put);
return userRoles;
}
}
|
package net.imagej.ops.filter;
import java.util.List;
import java.util.Random;
import net.imagej.ops.AbstractNamespace;
import net.imagej.ops.Namespace;
import net.imagej.ops.OpMethod;
import net.imagej.ops.Ops;
import net.imagej.ops.filter.gauss.DefaultGaussRAI;
import net.imagej.ops.filter.gauss.GaussRAISingleSigma;
import net.imglib2.RandomAccessible;
import net.imglib2.RandomAccessibleInterval;
import net.imglib2.algorithm.neighborhood.Shape;
import net.imglib2.img.Img;
import net.imglib2.img.ImgFactory;
import net.imglib2.outofbounds.OutOfBoundsFactory;
import net.imglib2.type.Type;
import net.imglib2.type.numeric.ComplexType;
import net.imglib2.type.numeric.RealType;
import net.imglib2.type.numeric.complex.ComplexFloatType;
import org.scijava.plugin.Plugin;
/**
* The filter namespace contains ops that filter data.
*
* @author Curtis Rueden
*/
@Plugin(type = Namespace.class)
public class FilterNamespace extends AbstractNamespace {
// -- addNoise --
@OpMethod(op = net.imagej.ops.Ops.Filter.AddNoise.class)
public Object addNoise(final Object... args) {
return ops().run(net.imagej.ops.Ops.Filter.AddNoise.class, args);
}
@OpMethod(op = net.imagej.ops.filter.addNoise.AddNoiseRealType.class)
public <I extends RealType<I>, O extends RealType<O>> O addNoise(final O out,
final I in, final double rangeMin, final double rangeMax,
final double rangeStdDev, final Random rng)
{
@SuppressWarnings("unchecked")
final O result =
(O) ops().run(net.imagej.ops.filter.addNoise.AddNoiseRealType.class, out,
in, rangeMin, rangeMax, rangeStdDev, rng);
return result;
}
// -- convolve --
/** Executes the "convolve" operation on the given arguments. */
@OpMethod(op = Ops.Filter.Convolve.class)
public Object convolve(final Object... args) {
return ops().run(Ops.Filter.Convolve.NAME, args);
}
/** Executes the "convolve" operation on the given arguments. */
@OpMethod(ops = { net.imagej.ops.filter.convolve.ConvolveFFTImg.class,
net.imagej.ops.filter.convolve.ConvolveNaiveImg.class })
public <I extends RealType<I>, O extends RealType<O>, K extends RealType<K>>
Img<O> convolve(final Img<I> in, final RandomAccessibleInterval<K> kernel)
{
@SuppressWarnings("unchecked")
final Img<O> result =
(Img<O>) ops().run(Ops.Filter.Convolve.NAME, in, kernel);
return result;
}
/** Executes the "convolve" operation on the given arguments. */
@OpMethod(ops = { net.imagej.ops.filter.convolve.ConvolveFFTImg.class,
net.imagej.ops.filter.convolve.ConvolveNaiveImg.class })
public <I extends RealType<I>, O extends RealType<O>, K extends RealType<K>>
Img<O> convolve(final Img<O> out, final Img<I> in,
final RandomAccessibleInterval<K> kernel)
{
@SuppressWarnings("unchecked")
final Img<O> result =
(Img<O>) ops().run(Ops.Filter.Convolve.NAME, out, in, kernel);
return result;
}
/** Executes the "convolve" operation on the given arguments. */
@OpMethod(ops = { net.imagej.ops.filter.convolve.ConvolveFFTImg.class,
net.imagej.ops.filter.convolve.ConvolveNaiveImg.class })
public <I extends RealType<I>, O extends RealType<O>, K extends RealType<K>>
Img<O> convolve(final Img<O> out, final Img<I> in,
final RandomAccessibleInterval<K> kernel, final long... borderSize)
{
@SuppressWarnings("unchecked")
final Img<O> result =
(Img<O>) ops().run(Ops.Filter.Convolve.NAME, out, in, kernel, borderSize);
return result;
}
/** Executes the "convolve" operation on the given arguments. */
@OpMethod(ops = { net.imagej.ops.filter.convolve.ConvolveFFTImg.class,
net.imagej.ops.filter.convolve.ConvolveNaiveImg.class })
public <I extends RealType<I>, O extends RealType<O>, K extends RealType<K>>
Img<O> convolve(final Img<O> out, final Img<I> in,
final RandomAccessibleInterval<K> kernel, final long[] borderSize,
final OutOfBoundsFactory<I, RandomAccessibleInterval<I>> obfInput)
{
@SuppressWarnings("unchecked")
final Img<O> result =
(Img<O>) ops().run(Ops.Filter.Convolve.NAME, out, in, kernel, borderSize,
obfInput);
return result;
}
/** Executes the "convolve" operation on the given arguments. */
@OpMethod(ops = { net.imagej.ops.filter.convolve.ConvolveFFTImg.class,
net.imagej.ops.filter.convolve.ConvolveNaiveImg.class })
public <I extends RealType<I>, O extends RealType<O>, K extends RealType<K>>
Img<O> convolve(final Img<O> out, final Img<I> in,
final RandomAccessibleInterval<K> kernel, final long[] borderSize,
final OutOfBoundsFactory<I, RandomAccessibleInterval<I>> obfInput,
final OutOfBoundsFactory<K, RandomAccessibleInterval<K>> obfKernel)
{
@SuppressWarnings("unchecked")
final Img<O> result =
(Img<O>) ops().run(Ops.Filter.Convolve.NAME, out, in, kernel, borderSize,
obfInput, obfKernel);
return result;
}
/** Executes the "convolve" operation on the given arguments. */
@OpMethod(ops = { net.imagej.ops.filter.convolve.ConvolveFFTImg.class,
net.imagej.ops.filter.convolve.ConvolveNaiveImg.class })
public <I extends RealType<I>, O extends RealType<O>, K extends RealType<K>>
Img<O> convolve(final Img<O> out, final Img<I> in,
final RandomAccessibleInterval<K> kernel, final long[] borderSize,
final OutOfBoundsFactory<I, RandomAccessibleInterval<I>> obfInput,
final OutOfBoundsFactory<K, RandomAccessibleInterval<K>> obfKernel,
final Type<O> outType)
{
@SuppressWarnings("unchecked")
final Img<O> result =
(Img<O>) ops().run(Ops.Filter.Convolve.NAME, out, in, kernel, borderSize,
obfInput, obfKernel, outType);
return result;
}
/** Executes the "convolve" operation on the given arguments. */
@OpMethod(ops = { net.imagej.ops.filter.convolve.ConvolveFFTImg.class,
net.imagej.ops.filter.convolve.ConvolveNaiveImg.class })
public <I extends RealType<I>, O extends RealType<O>, K extends RealType<K>>
Img<O> convolve(final Img<O> out, final Img<I> in,
final RandomAccessibleInterval<K> kernel, final long[] borderSize,
final OutOfBoundsFactory<I, RandomAccessibleInterval<I>> obfInput,
final OutOfBoundsFactory<K, RandomAccessibleInterval<K>> obfKernel,
final Type<O> outType, final ImgFactory<O> outFactory)
{
@SuppressWarnings("unchecked")
final Img<O> result =
(Img<O>) ops().run(Ops.Filter.Convolve.NAME, out, in, kernel, borderSize,
obfInput, obfKernel, outType, outFactory);
return result;
}
/** Executes the "convolve" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.convolve.ConvolveFFTImg.class)
public
<I extends RealType<I>, O extends RealType<O>, K extends RealType<K>, C extends ComplexType<C>>
Img<O> convolve(final Img<O> out, final Img<I> in,
final RandomAccessibleInterval<K> kernel, final long[] borderSize,
final OutOfBoundsFactory<I, RandomAccessibleInterval<I>> obfInput,
final OutOfBoundsFactory<K, RandomAccessibleInterval<K>> obfKernel,
final Type<O> outType, final ImgFactory<O> outFactory,
final ComplexType<C> fftType)
{
@SuppressWarnings("unchecked")
final Img<O> result =
(Img<O>) ops().run(net.imagej.ops.filter.convolve.ConvolveFFTImg.class,
out, in, kernel, borderSize, obfInput, obfKernel, outType, outFactory,
fftType);
return result;
}
/** Executes the "convolve" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.convolve.ConvolveFFTImg.class)
public
<I extends RealType<I>, O extends RealType<O>, K extends RealType<K>, C extends ComplexType<C>>
Img<O> convolve(final Img<O> out, final Img<I> in,
final RandomAccessibleInterval<K> kernel, final long[] borderSize,
final OutOfBoundsFactory<I, RandomAccessibleInterval<I>> obfInput,
final OutOfBoundsFactory<K, RandomAccessibleInterval<K>> obfKernel,
final Type<O> outType, final ImgFactory<O> outFactory,
final ComplexType<C> fftType, final ImgFactory<C> fftFactory)
{
@SuppressWarnings("unchecked")
final Img<O> result =
(Img<O>) ops().run(net.imagej.ops.filter.convolve.ConvolveFFTImg.class,
out, in, kernel, borderSize, obfInput, obfKernel, outType, outFactory,
fftType, fftFactory);
return result;
}
/** Executes the "convolve" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.convolve.ConvolveNaive.class)
public <I extends RealType<I>, K extends RealType<K>, O extends RealType<O>>
RandomAccessibleInterval<O> convolve(final RandomAccessibleInterval<O> out,
final RandomAccessible<I> in, final RandomAccessibleInterval<K> kernel)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<O> result =
(RandomAccessibleInterval<O>) ops().run(
net.imagej.ops.filter.convolve.ConvolveNaive.class, out, in, kernel);
return result;
}
/** Executes the "convolve" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.convolve.ConvolveFFTRAI.class)
public
<I extends RealType<I>, O extends RealType<O>, K extends RealType<K>, C extends ComplexType<C>>
void convolve(final RandomAccessibleInterval<I> raiExtendedInput)
{
ops().run(net.imagej.ops.filter.convolve.ConvolveFFTRAI.class,
raiExtendedInput);
}
/** Executes the "convolve" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.convolve.ConvolveFFTRAI.class)
public
<I extends RealType<I>, O extends RealType<O>, K extends RealType<K>, C extends ComplexType<C>>
void convolve(final RandomAccessibleInterval<I> raiExtendedInput,
final RandomAccessibleInterval<K> raiExtendedKernel)
{
ops().run(net.imagej.ops.filter.convolve.ConvolveFFTRAI.class,
raiExtendedInput, raiExtendedKernel);
}
/** Executes the "convolve" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.convolve.ConvolveFFTRAI.class)
public
<I extends RealType<I>, O extends RealType<O>, K extends RealType<K>, C extends ComplexType<C>>
void
convolve(final RandomAccessibleInterval<I> raiExtendedInput,
final RandomAccessibleInterval<K> raiExtendedKernel, final Img<C> fftInput)
{
ops().run(net.imagej.ops.filter.convolve.ConvolveFFTRAI.class,
raiExtendedInput, raiExtendedKernel, fftInput);
}
/** Executes the "convolve" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.convolve.ConvolveFFTRAI.class)
public
<I extends RealType<I>, O extends RealType<O>, K extends RealType<K>, C extends ComplexType<C>>
void convolve(final RandomAccessibleInterval<I> raiExtendedInput,
final RandomAccessibleInterval<K> raiExtendedKernel,
final Img<C> fftInput, final Img<C> fftKernel)
{
ops().run(net.imagej.ops.filter.convolve.ConvolveFFTRAI.class,
raiExtendedInput, raiExtendedKernel, fftInput, fftKernel);
}
/** Executes the "convolve" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.convolve.ConvolveFFTRAI.class)
public
<I extends RealType<I>, O extends RealType<O>, K extends RealType<K>, C extends ComplexType<C>>
void convolve(final RandomAccessibleInterval<I> raiExtendedInput,
final RandomAccessibleInterval<K> raiExtendedKernel,
final Img<C> fftInput, final Img<C> fftKernel,
final RandomAccessibleInterval<O> output)
{
ops().run(net.imagej.ops.filter.convolve.ConvolveFFTRAI.class,
raiExtendedInput, raiExtendedKernel, fftInput, fftKernel, output);
}
/** Executes the "convolve" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.convolve.ConvolveFFTRAI.class)
public
<I extends RealType<I>, O extends RealType<O>, K extends RealType<K>, C extends ComplexType<C>>
void convolve(final RandomAccessibleInterval<I> raiExtendedInput,
final RandomAccessibleInterval<K> raiExtendedKernel,
final Img<C> fftInput, final Img<C> fftKernel,
final RandomAccessibleInterval<O> output, final boolean performInputFFT)
{
ops().run(net.imagej.ops.filter.convolve.ConvolveFFTRAI.class,
raiExtendedInput, raiExtendedKernel, fftInput, fftKernel, output,
performInputFFT);
}
/** Executes the "convolve" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.convolve.ConvolveFFTRAI.class)
public
<I extends RealType<I>, O extends RealType<O>, K extends RealType<K>, C extends ComplexType<C>>
void convolve(final RandomAccessibleInterval<I> raiExtendedInput,
final RandomAccessibleInterval<K> raiExtendedKernel,
final Img<C> fftInput, final Img<C> fftKernel,
final RandomAccessibleInterval<O> output, final boolean performInputFFT,
final boolean performKernelFFT)
{
ops().run(net.imagej.ops.filter.convolve.ConvolveFFTRAI.class,
raiExtendedInput, raiExtendedKernel, fftInput, fftKernel, output,
performInputFFT, performKernelFFT);
}
// -- correlate --
/** Executes the "correlate" operation on the given arguments. */
@OpMethod(op = Ops.Filter.Correlate.class)
public Object correlate(final Object... args) {
return ops().run(Ops.Filter.Correlate.NAME, args);
}
/** Executes the "correlate" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.correlate.CorrelateFFTImg.class)
public
<I extends RealType<I>, O extends RealType<O>, K extends RealType<K>, C extends ComplexType<C>>
Img<O> correlate(final Img<I> in, final RandomAccessibleInterval<K> kernel)
{
@SuppressWarnings("unchecked")
final Img<O> result =
(Img<O>) ops().run(net.imagej.ops.filter.correlate.CorrelateFFTImg.class,
in, kernel);
return result;
}
/** Executes the "correlate" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.correlate.CorrelateFFTImg.class)
public
<I extends RealType<I>, O extends RealType<O>, K extends RealType<K>, C extends ComplexType<C>>
Img<O> correlate(final Img<O> out, final Img<I> in,
final RandomAccessibleInterval<K> kernel)
{
@SuppressWarnings("unchecked")
final Img<O> result =
(Img<O>) ops().run(net.imagej.ops.filter.correlate.CorrelateFFTImg.class,
out, in, kernel);
return result;
}
/** Executes the "correlate" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.correlate.CorrelateFFTImg.class)
public
<I extends RealType<I>, O extends RealType<O>, K extends RealType<K>, C extends ComplexType<C>>
Img<O> correlate(final Img<O> out, final Img<I> in,
final RandomAccessibleInterval<K> kernel, final long... borderSize)
{
@SuppressWarnings("unchecked")
final Img<O> result =
(Img<O>) ops().run(net.imagej.ops.filter.correlate.CorrelateFFTImg.class,
out, in, kernel, borderSize);
return result;
}
/** Executes the "correlate" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.correlate.CorrelateFFTImg.class)
public
<I extends RealType<I>, O extends RealType<O>, K extends RealType<K>, C extends ComplexType<C>>
Img<O> correlate(final Img<O> out, final Img<I> in,
final RandomAccessibleInterval<K> kernel, final long[] borderSize,
final OutOfBoundsFactory<I, RandomAccessibleInterval<I>> obfInput)
{
@SuppressWarnings("unchecked")
final Img<O> result =
(Img<O>) ops().run(net.imagej.ops.filter.correlate.CorrelateFFTImg.class,
out, in, kernel, borderSize, obfInput);
return result;
}
/** Executes the "correlate" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.correlate.CorrelateFFTImg.class)
public
<I extends RealType<I>, O extends RealType<O>, K extends RealType<K>, C extends ComplexType<C>>
Img<O> correlate(final Img<O> out, final Img<I> in,
final RandomAccessibleInterval<K> kernel, final long[] borderSize,
final OutOfBoundsFactory<I, RandomAccessibleInterval<I>> obfInput,
final OutOfBoundsFactory<K, RandomAccessibleInterval<K>> obfKernel)
{
@SuppressWarnings("unchecked")
final Img<O> result =
(Img<O>) ops().run(net.imagej.ops.filter.correlate.CorrelateFFTImg.class,
out, in, kernel, borderSize, obfInput, obfKernel);
return result;
}
/** Executes the "correlate" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.correlate.CorrelateFFTImg.class)
public
<I extends RealType<I>, O extends RealType<O>, K extends RealType<K>, C extends ComplexType<C>>
Img<O> correlate(final Img<O> out, final Img<I> in,
final RandomAccessibleInterval<K> kernel, final long[] borderSize,
final OutOfBoundsFactory<I, RandomAccessibleInterval<I>> obfInput,
final OutOfBoundsFactory<K, RandomAccessibleInterval<K>> obfKernel,
final Type<O> outType)
{
@SuppressWarnings("unchecked")
final Img<O> result =
(Img<O>) ops().run(net.imagej.ops.filter.correlate.CorrelateFFTImg.class,
out, in, kernel, borderSize, obfInput, obfKernel, outType);
return result;
}
/** Executes the "correlate" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.correlate.CorrelateFFTImg.class)
public
<I extends RealType<I>, O extends RealType<O>, K extends RealType<K>, C extends ComplexType<C>>
Img<O> correlate(final Img<O> out, final Img<I> in,
final RandomAccessibleInterval<K> kernel, final long[] borderSize,
final OutOfBoundsFactory<I, RandomAccessibleInterval<I>> obfInput,
final OutOfBoundsFactory<K, RandomAccessibleInterval<K>> obfKernel,
final Type<O> outType, final ImgFactory<O> outFactory)
{
@SuppressWarnings("unchecked")
final Img<O> result =
(Img<O>) ops().run(net.imagej.ops.filter.correlate.CorrelateFFTImg.class,
out, in, kernel, borderSize, obfInput, obfKernel, outType, outFactory);
return result;
}
/** Executes the "correlate" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.correlate.CorrelateFFTImg.class)
public
<I extends RealType<I>, O extends RealType<O>, K extends RealType<K>, C extends ComplexType<C>>
Img<O> correlate(final Img<O> out, final Img<I> in,
final RandomAccessibleInterval<K> kernel, final long[] borderSize,
final OutOfBoundsFactory<I, RandomAccessibleInterval<I>> obfInput,
final OutOfBoundsFactory<K, RandomAccessibleInterval<K>> obfKernel,
final Type<O> outType, final ImgFactory<O> outFactory,
final ComplexType<C> fftType)
{
@SuppressWarnings("unchecked")
final Img<O> result =
(Img<O>) ops().run(net.imagej.ops.filter.correlate.CorrelateFFTImg.class,
out, in, kernel, borderSize, obfInput, obfKernel, outType, outFactory,
fftType);
return result;
}
/** Executes the "correlate" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.correlate.CorrelateFFTImg.class)
public
<I extends RealType<I>, O extends RealType<O>, K extends RealType<K>, C extends ComplexType<C>>
Img<O> correlate(final Img<O> out, final Img<I> in,
final RandomAccessibleInterval<K> kernel, final long[] borderSize,
final OutOfBoundsFactory<I, RandomAccessibleInterval<I>> obfInput,
final OutOfBoundsFactory<K, RandomAccessibleInterval<K>> obfKernel,
final Type<O> outType, final ImgFactory<O> outFactory,
final ComplexType<C> fftType, final ImgFactory<C> fftFactory)
{
@SuppressWarnings("unchecked")
final Img<O> result =
(Img<O>) ops().run(net.imagej.ops.filter.correlate.CorrelateFFTImg.class,
out, in, kernel, borderSize, obfInput, obfKernel, outType, outFactory,
fftType, fftFactory);
return result;
}
/** Executes the "correlate" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.correlate.CorrelateFFTRAI.class)
public
<I extends RealType<I>, O extends RealType<O>, K extends RealType<K>, C extends ComplexType<C>>
void correlate(final RandomAccessibleInterval<I> raiExtendedInput)
{
ops().run(net.imagej.ops.filter.correlate.CorrelateFFTRAI.class,
raiExtendedInput);
}
/** Executes the "correlate" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.correlate.CorrelateFFTRAI.class)
public
<I extends RealType<I>, O extends RealType<O>, K extends RealType<K>, C extends ComplexType<C>>
void correlate(final RandomAccessibleInterval<I> raiExtendedInput,
final RandomAccessibleInterval<K> raiExtendedKernel)
{
ops().run(net.imagej.ops.filter.correlate.CorrelateFFTRAI.class,
raiExtendedInput, raiExtendedKernel);
}
/** Executes the "correlate" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.correlate.CorrelateFFTRAI.class)
public
<I extends RealType<I>, O extends RealType<O>, K extends RealType<K>, C extends ComplexType<C>>
void
correlate(final RandomAccessibleInterval<I> raiExtendedInput,
final RandomAccessibleInterval<K> raiExtendedKernel, final Img<C> fftInput)
{
ops().run(net.imagej.ops.filter.correlate.CorrelateFFTRAI.class,
raiExtendedInput, raiExtendedKernel, fftInput);
}
/** Executes the "correlate" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.correlate.CorrelateFFTRAI.class)
public
<I extends RealType<I>, O extends RealType<O>, K extends RealType<K>, C extends ComplexType<C>>
void correlate(final RandomAccessibleInterval<I> raiExtendedInput,
final RandomAccessibleInterval<K> raiExtendedKernel,
final Img<C> fftInput, final Img<C> fftKernel)
{
ops().run(net.imagej.ops.filter.correlate.CorrelateFFTRAI.class,
raiExtendedInput, raiExtendedKernel, fftInput, fftKernel);
}
/** Executes the "correlate" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.correlate.CorrelateFFTRAI.class)
public
<I extends RealType<I>, O extends RealType<O>, K extends RealType<K>, C extends ComplexType<C>>
void correlate(final RandomAccessibleInterval<I> raiExtendedInput,
final RandomAccessibleInterval<K> raiExtendedKernel,
final Img<C> fftInput, final Img<C> fftKernel,
final RandomAccessibleInterval<O> output)
{
ops().run(net.imagej.ops.filter.correlate.CorrelateFFTRAI.class,
raiExtendedInput, raiExtendedKernel, fftInput, fftKernel, output);
}
/** Executes the "correlate" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.correlate.CorrelateFFTRAI.class)
public
<I extends RealType<I>, O extends RealType<O>, K extends RealType<K>, C extends ComplexType<C>>
void correlate(final RandomAccessibleInterval<I> raiExtendedInput,
final RandomAccessibleInterval<K> raiExtendedKernel,
final Img<C> fftInput, final Img<C> fftKernel,
final RandomAccessibleInterval<O> output, final boolean performInputFFT)
{
ops().run(net.imagej.ops.filter.correlate.CorrelateFFTRAI.class,
raiExtendedInput, raiExtendedKernel, fftInput, fftKernel, output,
performInputFFT);
}
/** Executes the "correlate" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.correlate.CorrelateFFTRAI.class)
public
<I extends RealType<I>, O extends RealType<O>, K extends RealType<K>, C extends ComplexType<C>>
void correlate(final RandomAccessibleInterval<I> raiExtendedInput,
final RandomAccessibleInterval<K> raiExtendedKernel,
final Img<C> fftInput, final Img<C> fftKernel,
final RandomAccessibleInterval<O> output, final boolean performInputFFT,
final boolean performKernelFFT)
{
ops().run(net.imagej.ops.filter.correlate.CorrelateFFTRAI.class,
raiExtendedInput, raiExtendedKernel, fftInput, fftKernel, output,
performInputFFT, performKernelFFT);
}
// -- fft --
/** Executes the "fft" operation on the given arguments. */
@OpMethod(op = Ops.Filter.FFT.class)
public Object fft(final Object... args) {
return ops().run(Ops.Filter.FFT.NAME, args);
}
/** Executes the "fft" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.fft.FFTImg.class)
public <T extends RealType<T>, I extends Img<T>> Img<ComplexFloatType> fft(
final Img<I> in)
{
@SuppressWarnings("unchecked")
final Img<ComplexFloatType> result =
(Img<ComplexFloatType>) ops().run(net.imagej.ops.filter.fft.FFTImg.class,
in);
return result;
}
/** Executes the "fft" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.fft.FFTImg.class)
public <T extends RealType<T>, I extends Img<T>> Img<ComplexFloatType> fft(
final Img<ComplexFloatType> out, final Img<I> in)
{
@SuppressWarnings("unchecked")
final Img<ComplexFloatType> result =
(Img<ComplexFloatType>) ops().run(net.imagej.ops.filter.fft.FFTImg.class,
out, in);
return result;
}
/** Executes the "fft" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.fft.FFTImg.class)
public <T extends RealType<T>, I extends Img<T>> Img<ComplexFloatType> fft(
final Img<ComplexFloatType> out, final Img<I> in, final long... borderSize)
{
@SuppressWarnings("unchecked")
final Img<ComplexFloatType> result =
(Img<ComplexFloatType>) ops().run(net.imagej.ops.filter.fft.FFTImg.class,
out, in, borderSize);
return result;
}
/** Executes the "fft" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.fft.FFTImg.class)
public <T extends RealType<T>, I extends Img<T>> Img<ComplexFloatType> fft(
final Img<ComplexFloatType> out, final Img<I> in, final long[] borderSize,
final Boolean fast)
{
@SuppressWarnings("unchecked")
final Img<ComplexFloatType> result =
(Img<ComplexFloatType>) ops().run(net.imagej.ops.filter.fft.FFTImg.class,
out, in, borderSize, fast);
return result;
}
/** Executes the "fft" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.fft.FFTImg.class)
public <T extends RealType<T>, I extends Img<T>> Img<ComplexFloatType> fft(
final Img<ComplexFloatType> out, final Img<I> in, final long[] borderSize,
final Boolean fast,
final OutOfBoundsFactory<T, RandomAccessibleInterval<T>> obf)
{
@SuppressWarnings("unchecked")
final Img<ComplexFloatType> result =
(Img<ComplexFloatType>) ops().run(net.imagej.ops.filter.fft.FFTImg.class,
out, in, borderSize, fast, obf);
return result;
}
/** Executes the "fft" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.fft.FFTRAI.class)
public <T extends RealType<T>, C extends ComplexType<C>>
RandomAccessibleInterval<C> fft(final RandomAccessibleInterval<C> out,
final RandomAccessibleInterval<T> in)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<C> result =
(RandomAccessibleInterval<C>) ops().run(
net.imagej.ops.filter.fft.FFTRAI.class, out, in);
return result;
}
/** Executes the "fft" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.fft.FFTRAI.class)
public <T extends RealType<T>, C extends ComplexType<C>>
RandomAccessibleInterval<C> fft(final RandomAccessibleInterval<C> out,
final RandomAccessibleInterval<T> in,
final OutOfBoundsFactory<T, RandomAccessibleInterval<T>> obf)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<C> result =
(RandomAccessibleInterval<C>) ops().run(
net.imagej.ops.filter.fft.FFTRAI.class, out, in, obf);
return result;
}
/** Executes the "fft" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.fft.FFTRAI.class)
public <T extends RealType<T>, C extends ComplexType<C>>
RandomAccessibleInterval<C> fft(final RandomAccessibleInterval<C> out,
final RandomAccessibleInterval<T> in,
final OutOfBoundsFactory<T, RandomAccessibleInterval<T>> obf,
final long... paddedSize)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<C> result =
(RandomAccessibleInterval<C>) ops().run(
net.imagej.ops.filter.fft.FFTRAI.class, out, in, obf, paddedSize);
return result;
}
// -- fftSize --
/** Executes the "fftSize" operation on the given arguments. */
@OpMethod(op = Ops.Filter.FFTSize.class)
public Object fftSize(final Object... args) {
return ops().run(Ops.Filter.FFTSize.NAME, args);
}
/** Executes the "fftSize" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.fftSize.ComputeFFTSize.class)
public List<long[]> fftSize(final long[] inputSize, final long[] paddedSize,
final long[] fftSize, final Boolean forward, final Boolean fast)
{
@SuppressWarnings("unchecked")
final List<long[]> result =
(List<long[]>) ops().run(
net.imagej.ops.filter.fftSize.ComputeFFTSize.class, inputSize,
paddedSize, fftSize, forward, fast);
return result;
}
// -- dog --
@OpMethod(op = Ops.Filter.DoG.class)
public Object dog(Object... args) {
return ops().run(Ops.Filter.DoG.class, args);
}
@OpMethod(op = net.imagej.ops.filter.dog.DefaultDoG.class)
public <T extends RealType<T>, V extends RealType<V>>
RandomAccessibleInterval<V> dog(final RandomAccessibleInterval<V> out,
final RandomAccessibleInterval<T> in, final double[] sigmas1,
final double[] sigmas2,
final OutOfBoundsFactory<T, RandomAccessibleInterval<T>> outOfBounds)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<V> result =
(RandomAccessibleInterval<V>) ops().run(
net.imagej.ops.filter.dog.DefaultDoG.class, out, in, sigmas1, sigmas2,
outOfBounds);
return result;
}
@OpMethod(op = net.imagej.ops.filter.dog.DefaultDoG.class)
public <T extends RealType<T>, V extends RealType<V>>
RandomAccessibleInterval<V> dog(final RandomAccessibleInterval<V> out,
final RandomAccessibleInterval<T> in, final double[] sigmas1,
final double... sigmas2)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<V> result =
(RandomAccessibleInterval<V>) ops().run(
net.imagej.ops.filter.dog.DefaultDoG.class, out, in, sigmas1, sigmas2);
return result;
}
@OpMethod(op = net.imagej.ops.filter.dog.DefaultDoG.class)
public <T extends RealType<T>, V extends RealType<V>>
RandomAccessibleInterval<V> dog(final RandomAccessibleInterval<T> in,
final double[] sigmas1, final double... sigmas2)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<V> result =
(RandomAccessibleInterval<V>) ops().run(
net.imagej.ops.filter.dog.DefaultDoG.class, in, sigmas1, sigmas2);
return result;
}
@OpMethod(op = net.imagej.ops.filter.dog.DefaultDoGSingleSigmas.class)
public <T extends RealType<T>, V extends RealType<V>>
RandomAccessibleInterval<V> dog(final RandomAccessibleInterval<V> out,
final RandomAccessibleInterval<T> in, final double sigma1,
final double sigma2,
final OutOfBoundsFactory<T, RandomAccessibleInterval<T>> outOfBounds)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<V> result =
(RandomAccessibleInterval<V>) ops().run(
net.imagej.ops.filter.dog.DefaultDoGSingleSigmas.class, out, in,
sigma1, sigma2, outOfBounds);
return result;
}
@OpMethod(op = net.imagej.ops.filter.dog.DefaultDoGSingleSigmas.class)
public <T extends RealType<T>, V extends RealType<V>>
RandomAccessibleInterval<V> dog(final RandomAccessibleInterval<V> out,
final RandomAccessibleInterval<T> in, final double sigma1,
final double sigma2)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<V> result =
(RandomAccessibleInterval<V>) ops().run(
net.imagej.ops.filter.dog.DefaultDoGSingleSigmas.class, out, in,
sigma1, sigma2);
return result;
}
@OpMethod(op = net.imagej.ops.filter.dog.DefaultDoGSingleSigmas.class)
public <T extends RealType<T>, V extends RealType<V>>
RandomAccessibleInterval<V> dog(final RandomAccessibleInterval<T> in,
final double sigma1, final double sigma2)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<V> result =
(RandomAccessibleInterval<V>) ops().run(
net.imagej.ops.filter.dog.DefaultDoGSingleSigmas.class, null, in,
sigma1, sigma2);
return result;
}
// -- gauss --
/** Executes the "gauss" operation on the given arguments. */
@OpMethod(op = Ops.Filter.Gauss.class)
public Object gauss(final Object... args) {
return ops().run(Ops.Filter.Gauss.NAME, args);
}
/** Executes the "gauss" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.gauss.DefaultGaussRAI.class)
public <T extends RealType<T>, V extends RealType<V>>
RandomAccessibleInterval<V> gauss(final RandomAccessibleInterval<V> out,
final RandomAccessibleInterval<T> in, final double[] sigmas,
final OutOfBoundsFactory<T, RandomAccessibleInterval<T>> outOfBounds)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<V> result =
(RandomAccessibleInterval<V>) ops().run(DefaultGaussRAI.class, out, in,
sigmas, outOfBounds);
return result;
}
/** Executes the "gauss" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.gauss.DefaultGaussRAI.class)
public <T extends RealType<T>, V extends RealType<V>>
RandomAccessibleInterval<V> gauss(final RandomAccessibleInterval<V> out,
final RandomAccessibleInterval<T> in, final double... sigmas)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<V> result =
(RandomAccessibleInterval<V>) ops().run(DefaultGaussRAI.class, out, in,
sigmas);
return result;
}
/** Executes the "gauss" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.gauss.DefaultGaussRAI.class)
public <T extends RealType<T>, V extends RealType<V>>
RandomAccessibleInterval<V> gauss(final RandomAccessibleInterval<T> in,
final double... sigmas)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<V> result =
(RandomAccessibleInterval<V>) ops()
.run(DefaultGaussRAI.class, in, sigmas);
return result;
}
/** Executes the "gauss" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.gauss.GaussRAISingleSigma.class)
public <T extends RealType<T>, V extends RealType<V>>
RandomAccessibleInterval<V> gauss(RandomAccessibleInterval<V> out,
RandomAccessibleInterval<T> in, double sigma)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<V> result =
(RandomAccessibleInterval<V>) ops().run(GaussRAISingleSigma.class, out,
in, sigma);
return result;
}
/** Executes the "gauss" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.gauss.GaussRAISingleSigma.class)
public <T extends RealType<T>, V extends RealType<V>>
RandomAccessibleInterval<V> gauss(RandomAccessibleInterval<V> out,
RandomAccessibleInterval<T> in, double sigma,
OutOfBoundsFactory<T, RandomAccessibleInterval<T>> outOfBounds)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<V> result =
(RandomAccessibleInterval<V>) ops().run(GaussRAISingleSigma.class, out,
in, sigma, outOfBounds);
return result;
}
@OpMethod(op = net.imagej.ops.filter.gauss.GaussRAISingleSigma.class)
public <T extends RealType<T>, V extends RealType<V>>
RandomAccessibleInterval<V> gauss(final RandomAccessibleInterval<T> in,
final double sigma)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<V> result =
(RandomAccessibleInterval<V>) ops().run(
net.imagej.ops.filter.gauss.GaussRAISingleSigma.class, in, sigma);
return result;
}
// -- ifft --
/** Executes the "ifft" operation on the given arguments. */
@OpMethod(op = Ops.Filter.IFFT.class)
public Object ifft(final Object... args) {
return ops().run(Ops.Filter.IFFT.NAME, args);
}
/** Executes the "ifft" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.ifft.IFFTImg.class)
public <T extends RealType<T>, O extends Img<T>> Img<O> ifft(
final Img<O> out, final Img<ComplexFloatType> in)
{
@SuppressWarnings("unchecked")
final Img<O> result =
(Img<O>) ops().run(net.imagej.ops.filter.ifft.IFFTImg.class, out, in);
return result;
}
/** Executes the "ifft" operation on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.ifft.IFFTRAI.class)
public <C extends ComplexType<C>, T extends RealType<T>>
RandomAccessibleInterval<T> ifft(final RandomAccessibleInterval<T> out,
final RandomAccessibleInterval<C> in)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<T> result =
(RandomAccessibleInterval<T>) ops().run(
net.imagej.ops.filter.ifft.IFFTRAI.class, out, in);
return result;
}
// -- non-linear filters --
/** Executes the "max" filter on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.max.MaxFilterOp.class)
public <T extends RealType<T>> RandomAccessibleInterval<T> max(
final RandomAccessibleInterval<T> out,
final RandomAccessibleInterval<T> in, Shape shape)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<T> result =
(RandomAccessibleInterval<T>) ops().run(
net.imagej.ops.filter.max.MaxFilterOp.class, out, in, shape);
return result;
}
/** Executes the "max" filter on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.max.MaxFilterOp.class)
public <T extends RealType<T>> RandomAccessibleInterval<T> max(
final RandomAccessibleInterval<T> out,
final RandomAccessibleInterval<T> in, Shape shape,
OutOfBoundsFactory<T, RandomAccessibleInterval<T>> oob)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<T> result =
(RandomAccessibleInterval<T>) ops().run(
net.imagej.ops.filter.max.MaxFilterOp.class, out, in, shape, oob);
return result;
}
/** Executes the "min" filter on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.min.MinFilterOp.class)
public <T extends RealType<T>> RandomAccessibleInterval<T> min(
final RandomAccessibleInterval<T> out,
final RandomAccessibleInterval<T> in, Shape shape)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<T> result =
(RandomAccessibleInterval<T>) ops().run(
net.imagej.ops.filter.min.MinFilterOp.class, out, in, shape);
return result;
}
/** Executes the "min" filter on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.min.MinFilterOp.class)
public <T extends RealType<T>> RandomAccessibleInterval<T> min(
final RandomAccessibleInterval<T> out,
final RandomAccessibleInterval<T> in, Shape shape,
OutOfBoundsFactory<T, RandomAccessibleInterval<T>> oob)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<T> result =
(RandomAccessibleInterval<T>) ops().run(
net.imagej.ops.filter.min.MinFilterOp.class, out, in, shape, oob);
return result;
}
/** Executes the "mean" filter on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.mean.MeanFilterOp.class)
public <T extends RealType<T>> RandomAccessibleInterval<T> mean(
final RandomAccessibleInterval<T> out,
final RandomAccessibleInterval<T> in, Shape shape)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<T> result =
(RandomAccessibleInterval<T>) ops().run(
net.imagej.ops.filter.mean.MeanFilterOp.class, out, in, shape);
return result;
}
/** Executes the "mean" filter on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.mean.MeanFilterOp.class)
public <T extends RealType<T>> RandomAccessibleInterval<T> mean(
final RandomAccessibleInterval<T> out,
final RandomAccessibleInterval<T> in, Shape shape,
OutOfBoundsFactory<T, RandomAccessibleInterval<T>> oob)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<T> result =
(RandomAccessibleInterval<T>) ops().run(
net.imagej.ops.filter.mean.MeanFilterOp.class, out, in, shape, oob);
return result;
}
/** Executes the "median" filter on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.median.MedianFilterOp.class)
public <T extends RealType<T>> RandomAccessibleInterval<T> median(
final RandomAccessibleInterval<T> out,
final RandomAccessibleInterval<T> in, Shape shape)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<T> result =
(RandomAccessibleInterval<T>) ops().run(
net.imagej.ops.filter.median.MedianFilterOp.class, out, in, shape);
return result;
}
/** Executes the "median" filter on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.median.MedianFilterOp.class)
public <T extends RealType<T>> RandomAccessibleInterval<T> median(
final RandomAccessibleInterval<T> out,
final RandomAccessibleInterval<T> in, Shape shape,
OutOfBoundsFactory<T, RandomAccessibleInterval<T>> oob)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<T> result =
(RandomAccessibleInterval<T>) ops().run(
net.imagej.ops.filter.median.MedianFilterOp.class, out, in, shape, oob);
return result;
}
/** Executes the "sigma" filter on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.sigma.SigmaFilterOp.class)
public <T extends RealType<T>> RandomAccessibleInterval<T> sigma(
final RandomAccessibleInterval<T> out,
final RandomAccessibleInterval<T> in, Shape shape)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<T> result =
(RandomAccessibleInterval<T>) ops().run(
net.imagej.ops.filter.sigma.SigmaFilterOp.class, out, in, shape);
return result;
}
/** Executes the "sigma" filter on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.sigma.SigmaFilterOp.class)
public <T extends RealType<T>> RandomAccessibleInterval<T> sigma(
final RandomAccessibleInterval<T> out,
final RandomAccessibleInterval<T> in, Shape shape,
OutOfBoundsFactory<T, RandomAccessibleInterval<T>> oob)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<T> result =
(RandomAccessibleInterval<T>) ops().run(
net.imagej.ops.filter.sigma.SigmaFilterOp.class, out, in, shape, oob);
return result;
}
/** Executes the "variance" filter on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.variance.VarianceFilterOp.class)
public <T extends RealType<T>> RandomAccessibleInterval<T> variance(
final RandomAccessibleInterval<T> out,
final RandomAccessibleInterval<T> in, Shape shape)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<T> result =
(RandomAccessibleInterval<T>) ops().run(
net.imagej.ops.filter.variance.VarianceFilterOp.class, out, in, shape);
return result;
}
/** Executes the "variance" filter on the given arguments. */
@OpMethod(op = net.imagej.ops.filter.variance.VarianceFilterOp.class)
public <T extends RealType<T>> RandomAccessibleInterval<T> variance(
final RandomAccessibleInterval<T> out,
final RandomAccessibleInterval<T> in, Shape shape,
OutOfBoundsFactory<T, RandomAccessibleInterval<T>> oob)
{
@SuppressWarnings("unchecked")
final RandomAccessibleInterval<T> result =
(RandomAccessibleInterval<T>) ops().run(
net.imagej.ops.filter.variance.VarianceFilterOp.class, out, in, shape,
oob);
return result;
}
// -- Namespace methods --
@Override
public String getName() {
return "filter";
}
}
|
package net.slightlymagic.ticTacToe;
import java.io.IOException;
import java.util.Scanner;
import net.slightlymagic.ticTacToe.action.NewGameAction;
import net.slightlymagic.ticTacToe.action.PlacePieceAction;
import at.pria.koza.harmonic.Action;
import at.pria.koza.harmonic.Engine;
import at.pria.koza.harmonic.State;
import at.pria.koza.polybuf.PolybufConfig;
/**
* <p>
* The class TicTacToe.
* </p>
*
* @version V0.0 14.05.2013
* @author SillyFreak
*/
public class TicTacToe {
public static void main(String[] args) throws IOException, ClassNotFoundException {
try (Scanner sc = new Scanner(System.in);) {
Host host1 = new Host(), host2 = new Host();
config(host1);
config(host2);
host1.newGame();
host2.connectToGame(host1);
for(int i = 0;; i++) {
if(i % 2 == 0) {
makeMove(host1, sc);
host2.synchronize(host1);
if(!host2.getGame().isGameRunning()) {
print(host2.getGame());
System.out.println("===# " + host2.getGame().getWinner().getPlayerId());
break;
}
} else {
makeMove(host2, sc);
host1.synchronize(host2);
if(!host1.getGame().isGameRunning()) {
print(host1.getGame());
System.out.println("===# " + host1.getGame().getWinner().getPlayerId());
break;
}
}
}
System.out.println(host1.getEngine());
for(State s = host1.getEngine().getHead(); s != null; s = s.getParent())
System.out.println(s);
System.out.println(host2.getEngine());
for(State s = host2.getEngine().getHead(); s != null; s = s.getParent())
System.out.println(s);
}
}
private static void makeMove(Host current, Scanner sc) {
TTTGame game = current.getGame();
print(game);
int x = sc.nextInt(), y = sc.nextInt();
Action action = new PlacePieceAction(current.getEngine(), game, game.getNextPlayer(), x, y);
current.getBranchManager().execute(action);
}
private static void print(TTTGame game) {
System.out.printf("%s%s%s|%n%s%s%s|%n%s%s%s|%n",
p(game, 0, 0), p(game, 1, 0), p(game, 2, 0),
p(game, 0, 1), p(game, 1, 1), p(game, 2, 1),
p(game, 0, 2), p(game, 1, 2), p(game, 2, 2));
}
private static void config(Host host) {
Engine engine = host.getEngine();
PolybufConfig config = host.getConfig();
PlacePieceAction.configure(config, engine);
NewGameAction.configure(config, engine);
}
private static String p(TTTGame game, int x, int y) {
TTTPiece piece = game.getPiece(x, y);
return piece == null? " ":"" + piece.getOwner().getPlayerId();
}
}
|
package net.slightlymagic.ticTacToe;
import java.io.IOException;
import java.util.Scanner;
import net.slightlymagic.ticTacToe.action.NewGameAction;
import net.slightlymagic.ticTacToe.action.PlacePieceAction;
import at.pria.koza.harmonic.Action;
import at.pria.koza.harmonic.Engine;
import at.pria.koza.harmonic.State;
import at.pria.koza.polybuf.PolybufConfig;
import at.pria.koza.polybuf.PolybufInput;
import at.pria.koza.polybuf.PolybufOutput;
import at.pria.koza.polybuf.proto.Polybuf.Obj;
/**
* <p>
* The class TicTacToe.
* </p>
*
* @version V0.0 14.05.2013
* @author SillyFreak
*/
public class TicTacToe {
public static void main(String[] args) throws IOException, ClassNotFoundException {
try (Scanner sc = new Scanner(System.in);) {
Engine eng1 = new Engine(), eng2 = new Engine();
PolybufConfig conf1 = config(eng1), conf2 = config(eng2);
TTTGame game1, game2;
{
NewGameAction action1 = new NewGameAction(eng1);
game1 = execute(action1).getGame();
Obj obj = new PolybufOutput(conf1).writeObject(eng1.getHead());
State s = (State) new PolybufInput(conf2).readObject(obj);
eng2.setHead(s);
game2 = ((NewGameAction) s.getAction()).getGame();
}
while(game2.isGameRunning()) {
int x = sc.nextInt(), y = sc.nextInt();
Action action1 = new PlacePieceAction(eng1, game1, game1.getNextPlayer(), x, y);
execute(action1);
Obj obj = new PolybufOutput(conf1).writeObject(eng1.getHead());
State s = (State) new PolybufInput(conf2).readObject(obj);
eng2.setHead(s);
System.out.printf("%s%s%s|%n%s%s%s|%n%s%s%s|%n",
p(game2, 0, 0), p(game2, 1, 0), p(game2, 2, 0),
p(game2, 0, 1), p(game2, 1, 1), p(game2, 2, 1),
p(game2, 0, 2), p(game2, 1, 2), p(game2, 2, 2));
}
System.out.println("===# " + game2.getWinner().getPlayerId());
System.out.println(eng1);
for(State s = eng1.getHead(); s != null; s = s.getParent())
System.out.println(s);
System.out.println(eng2);
for(State s = eng2.getHead(); s != null; s = s.getParent())
System.out.println(s);
}
}
private static PolybufConfig config(Engine engine) {
PolybufConfig config = new PolybufConfig();
PlacePieceAction.configure(config, engine);
NewGameAction.configure(config, engine);
State.configure(config, engine);
return config;
}
private static <T extends Action> T execute(T action) {
Engine engine = action.getEngine();
State state = new State(engine.getHead(), action);
engine.setHead(state);
return action;
}
private static String p(TTTGame game, int x, int y) {
TTTPiece piece = game.getPiece(x, y);
return piece == null? " ":"" + piece.getOwner().getPlayerId();
}
}
|
package nl.peterbloem.motive;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.nodes.DGraph;
import org.nodes.Graph;
import org.nodes.UGraph;
import org.nodes.models.DSequenceEstimator;
import static org.nodes.models.DSequenceEstimator.D;
import org.nodes.models.StructureModel;
import org.nodes.util.Fibonacci;
import nl.peterbloem.kit.Global;
import nl.peterbloem.kit.Pair;
/**
* A copy of the motif model that searches for a good subselection in the
* available instances.
*
* @author Peter
*
*/
public class MotifSearchModel
{
public static <L> double size(Graph<L> graph, Graph<L> sub, List<List<Integer>> occurrences, final StructureModel<Graph<?>> model, boolean resetWiring)
{
return size(graph, sub, occurrences, model, resetWiring, -1);
}
public static <L> double size(Graph<L> graph, Graph<L> sub, List<List<Integer>> occurrences, final StructureModel<Graph<?>> model, boolean resetWiring, int depth)
{
Function<Graph<L>> function = new Function<Graph<L>>()
{
public double size(Graph<L> graph, Graph<L> sub,
List<List<Integer>> occurrences, boolean resetWiring)
{
return MotifModel.size(graph, sub, occurrences, model, resetWiring);
}
};
FindPhi<Graph<L>> find
= new FindPhi<Graph<L>>(graph, sub, occurrences, resetWiring, depth, function);
return find.size();
}
public static <L> double sizeBeta(Graph<L> graph, Graph<L> sub, List<List<Integer>> occurrences, boolean resetWiring, final int iterations, final double alpha)
{
return sizeBeta(graph, sub, occurrences, resetWiring, iterations, alpha, -1);
}
public static <L> double sizeBeta(Graph<L> graph, Graph<L> sub, List<List<Integer>> occurrences, boolean resetWiring, final int iterations, final double alpha, int depth)
{
Function<Graph<L>> function = new Function<Graph<L>>()
{
public double size(Graph<L> graph, Graph<L> sub,
List<List<Integer>> occurrences, boolean resetWiring)
{
return MotifModel.sizeBeta(graph, sub, occurrences, resetWiring, iterations, alpha);
}
};
FindPhi<Graph<L>> find
= new FindPhi<Graph<L>>(graph, sub, occurrences, resetWiring, depth, function);
return find.size();
}
public static double sizeER(Graph<?> graph, Graph<?> sub, List<List<Integer>> occurrences, boolean resetWiring)
{
return sizeER(graph, sub, occurrences, resetWiring, -1);
}
public static double sizeER(Graph<?> graph, Graph<?> sub, List<List<Integer>> occurrences, boolean resetWiring, int depth)
{
Function<Graph<?>> function = new Function<Graph<?>>()
{
public double size(Graph<?> graph, Graph<?> sub,
List<List<Integer>> occurrences, boolean resetWiring)
{
return MotifModel.sizeER(graph, sub, occurrences, resetWiring);
}
};
FindPhi<Graph<?>> find
= new FindPhi<Graph<?>>(graph, sub, occurrences, resetWiring, depth, function);
return find.size();
}
public static double sizeEL(Graph<?> graph, Graph<?> sub, List<List<Integer>> occurrences, boolean resetWiring)
{
return sizeEL(graph, sub, occurrences, resetWiring, -1);
}
public static double sizeEL(Graph<?> graph, Graph<?> sub, List<List<Integer>> occurrences, boolean resetWiring, int depth)
{
Function<Graph<?>> function = new Function<Graph<?>>()
{
public double size(Graph<?> graph, Graph<?> sub,
List<List<Integer>> occurrences, boolean resetWiring)
{
return MotifModel.sizeEL(graph, sub, occurrences, resetWiring);
}
};
FindPhi<Graph<?>> find
= new FindPhi<Graph<?>>(graph, sub, occurrences, resetWiring, depth, function);
return find.size();
}
public static double sizeELInst(UGraph<?> graph, final List<Integer> degrees, UGraph<?> sub, List<List<Integer>> occurrences, boolean resetWiring, int depth)
{
Function<UGraph<?>> function = new Function<UGraph<?>>()
{
public double size(UGraph<?> graph, UGraph<?> sub,
List<List<Integer>> occurrences, boolean resetWiring)
{
return MotifModel.sizeEL(graph, degrees, sub, occurrences, resetWiring);
}
};
FindPhi<UGraph<?>> find
= new FindPhi<UGraph<?>>(graph, sub, occurrences, resetWiring, depth, function);
return find.size();
}
public static double sizeELInst(DGraph<?> graph, final List<D> degrees, DGraph<?> sub, List<List<Integer>> occurrences, boolean resetWiring, int depth)
{
Function<DGraph<?>> function = new Function<DGraph<?>>()
{
public double size(DGraph<?> graph, DGraph<?> sub,
List<List<Integer>> occurrences, boolean resetWiring)
{
return MotifModel.sizeEL(graph, degrees, sub, occurrences, resetWiring);
}
};
FindPhi<DGraph<?>> find
= new FindPhi<DGraph<?>>(graph, sub, occurrences, resetWiring, depth, function);
return find.size();
}
public static double sizeERInst(UGraph<?> graph, UGraph<?> sub, List<List<Integer>> occurrences, boolean resetWiring, int depth)
{
Function<UGraph<?>> function = new Function<UGraph<?>>()
{
public double size(UGraph<?> graph, UGraph<?> sub,
List<List<Integer>> occurrences, boolean resetWiring)
{
return MotifModel.sizeERInst(graph,sub, occurrences, resetWiring);
}
};
FindPhi<UGraph<?>> find
= new FindPhi<UGraph<?>>(graph, sub, occurrences, resetWiring, depth, function);
return find.size();
}
public static double sizeERInst(DGraph<?> graph, DGraph<?> sub, List<List<Integer>> occurrences, boolean resetWiring, int depth)
{
Function<DGraph<?>> function = new Function<DGraph<?>>()
{
public double size(DGraph<?> graph, DGraph<?> sub,
List<List<Integer>> occurrences, boolean resetWiring)
{
return MotifModel.sizeERInst(graph, sub, occurrences, resetWiring);
}
};
FindPhi<DGraph<?>> find
= new FindPhi<DGraph<?>>(graph, sub, occurrences, resetWiring, depth, function);
return find.size();
}
private static interface Function<G extends Graph<? extends Object>> {
public double size(G graph, G sub, List<List<Integer>> occurrences, boolean resetWiring);
}
/**
* Fibonacci search: find the number of occurrences for which the compression is optimal.
*
* @author Peter
*
* @param <G>
*/
private static class FindPhi<G extends Graph<? extends Object>>
{
int maxDepth = -1;
G data;
G motif;
List<List<Integer>> occurrences;
Function<G> function;
boolean resetWiring;
int cutoff;
double size;
public FindPhi(G data, G motif,
List<List<Integer>> occurrences,
boolean resetWiring,
int maxDepth,
Function<G> function)
{
this.data = data;
this.motif = motif;
this.occurrences = occurrences;
this.resetWiring = resetWiring;
this.function = function;
this.maxDepth = maxDepth;
int n = occurrences.size();
int to = Fibonacci.isFibonacci(n) ? n : (int)Fibonacci.get((int) Math.ceil(Fibonacci.getIndexApprox(n)));
// always consider 0 occurrences
sample(0);
find(0, to, 0);
// Global.log().info("Search finished. Samples taken: " + cache.size());
}
public double size()
{
return size;
}
public int cutoff()
{
return cutoff;
}
private void find(int from, int to, int depth)
{
int range = to - from;
if(range <= 2) // base case: from and to are neighbouring integers
{
// return the best of from, from +1 and to
int x0 = from, x1 = from + 1, x2 = to;
sample(x0);
sample(x1);
sample(x2);
}
if( range <= 2 || (maxDepth >= 0 && depth > maxDepth))
{ // return best value found
size = Double.POSITIVE_INFINITY;
cutoff = -1;
for(int key : cache.keySet())
{
double value = cache.get(key);
if(size > value)
{
size = value;
cutoff = key;
}
}
return;
}
int r0 = (int)Fibonacci.previous(range);
int mid1 = to - r0;
int mid2 = from + r0;
double y1 = sample(mid1);
double y2 = sample(mid2);
if(y1 > y2)
find(mid1, to, depth + 1);
else
find(from, mid2, depth + 1);
}
private Map<Integer, Double> cache = new LinkedHashMap<Integer, Double>();
public double sample(int n)
{
if(! cache.containsKey(n))
{
double size = function.size(data, motif, occurrences.subList(0, Math.min(occurrences.size(), n)), resetWiring);
cache.put(n, size);
// Global.log().info("compression at " + n + " occurrences: " + size);
return size;
}
return cache.get(n);
}
}
}
|
/**
* Origin: jbox2d
*/
package com.almasb.fxgl.core.math;
import com.almasb.fxgl.core.pool.Poolable;
import java.io.Serializable;
/**
* A 2D column vector with float precision.
* Can be used to represent a point in 2D space.
* Can be used instead of JavaFX Point2D to avoid object allocations.
* This is also preferred for private fields.
*/
public final class Vec2 implements Serializable, Poolable {
private static final long serialVersionUID = 1L;
public float x, y;
public Vec2() {
this(0, 0);
}
public Vec2(float x, float y) {
this.x = x;
this.y = y;
}
/**
* Convenience ctor for double values.
* Note: values will be typecast to float.
*
* @param x x component
* @param y y component
*/
public Vec2(double x, double y) {
this((float) x, (float) y);
}
public Vec2(Vec2 toCopy) {
this(toCopy.x, toCopy.y);
}
/**
* Zero out this vector.
*/
public void setZero() {
x = 0.0f;
y = 0.0f;
}
/**
* Set this vector component-wise.
*
* @param x x component
* @param y y component
* @return this vector
*/
public Vec2 set(float x, float y) {
this.x = x;
this.y = y;
return this;
}
/**
* Set this vector to another vector.
*
* @return this vector
*/
public Vec2 set(Vec2 v) {
this.x = v.x;
this.y = v.y;
return this;
}
/**
* Return the sum of this vector and another; does not alter either one.
*
* @return new vector
*/
public Vec2 add(Vec2 v) {
return new Vec2(x + v.x, y + v.y);
}
/**
* Return the difference of this vector and another; does not alter either one.
*
* @return new vector
*/
public Vec2 sub(Vec2 v) {
return new Vec2(x - v.x, y - v.y);
}
/**
* Return this vector multiplied by a scalar; does not alter this vector.
*
* @return new vector
*/
public Vec2 mul(float a) {
return new Vec2(x * a, y * a);
}
/**
* Return the negation of this vector; does not alter this vector.
*
* @return new vector
*/
public Vec2 negate() {
return new Vec2(-x, -y);
}
/**
* Flip the vector and return it - alters this vector.
*
* @return this vector
*/
public Vec2 negateLocal() {
x = -x;
y = -y;
return this;
}
/**
* Add another vector to this one and returns result - alters this vector.
*
* @return this vector
*/
public Vec2 addLocal(Vec2 v) {
x += v.x;
y += v.y;
return this;
}
/**
* Adds values to this vector and returns result - alters this vector.
*
* @return this vector
*/
public Vec2 addLocal(float x, float y) {
this.x += x;
this.y += y;
return this;
}
/**
* Subtract another vector from this one and return result - alters this vector.
*
* @return this vector
*/
public Vec2 subLocal(Vec2 v) {
x -= v.x;
y -= v.y;
return this;
}
/**
* Multiply this vector by a number and return result - alters this vector.
*
* @return this vector
*/
public Vec2 mulLocal(float a) {
x *= a;
y *= a;
return this;
}
/**
* Get the skew vector such that dot(skew_vec, other) == cross(vec, other).
*
* @return new vector
*/
public Vec2 skew() {
return new Vec2(-y, x);
}
/**
* Get the skew vector such that dot(skew_vec, other) == cross(vec, other);
* does not alter this vector.
*
* @param out the out vector to alter
*/
public void skew(Vec2 out) {
out.x = -y;
out.y = x;
}
/**
* @return the length of this vector
*/
public float length() {
return FXGLMath.sqrt(x * x + y * y);
}
/**
* @return the squared length of this vector
*/
public float lengthSquared() {
return (x * x + y * y);
}
public float distance(float otherX, float otherY) {
float dx = otherX - x;
float dy = otherY - y;
return (float) Math.sqrt(dx * dx + dy * dy);
}
public float distanceSquared(float otherX, float otherY) {
float dx = otherX - x;
float dy = otherY - y;
return dx * dx + dy * dy;
}
public boolean distanceLessThanOrEqual(float otherX, float otherY, float distance) {
return distanceSquared(otherX, otherY) <= distance * distance;
}
public boolean distanceGreaterThanOrEqual(float otherX, float otherY, float distance) {
return distanceSquared(otherX, otherY) >= distance * distance;
}
/**
* Normalize this vector and return the length before normalization. Alters this vector.
*/
public float normalize() {
float length = length();
if (length < FXGLMath.EPSILON) {
return 0f;
}
float invLength = 1.0f / length;
x *= invLength;
y *= invLength;
return length;
}
/**
* Normalizes and returns this vector. Alters this vector.
*
* @return this vector
*/
public Vec2 normalizeLocal() {
normalize();
return this;
}
/**
* True if the vector represents a pair of valid, non-infinite floating point numbers.
*/
public boolean isValid() {
return !Float.isNaN(x) && !Float.isInfinite(x) && !Float.isNaN(y) && !Float.isInfinite(y);
}
/**
* Return a new vector that has positive components.
*
* @return new vector
*/
public Vec2 abs() {
return new Vec2(FXGLMath.abs(x), FXGLMath.abs(y));
}
/**
* Modify this vector to have only positive components.
*
* @return this vector
*/
public Vec2 absLocal() {
x = FXGLMath.abs(x);
y = FXGLMath.abs(y);
return this;
}
/**
* @return angle in degrees (-180, 180] between this vector and X axis (1, 0)
*/
public float angle() {
return angle(1, 0);
}
/**
* @param other other vector
* @return angle in degrees (-180, 180] between this vector and other
*/
public float angle(Vec2 other) {
return angle(other.x, other.y);
}
/**
* @param otherX x component of other vector
* @param otherY y component of other vector
* @return angle in degrees (-180, 180] between this vector and other
*/
public float angle(float otherX, float otherY) {
double angle1 = Math.toDegrees(Math.atan2(y, x));
double angle2 = Math.toDegrees(Math.atan2(otherY, otherX));
return (float) (angle1 - angle2);
// final float ax = otherX;
// final float ay = otherY;
// final float delta = (ax * x + ay * y) /
// (float)Math.sqrt((ax * ax + ay * ay) * (x * x + y * y));
// if (delta > 1.0) {
// return 0;
// if (delta < -1.0) {
// return 180;
// return (float) Math.toDegrees(Math.acos(delta));
}
/**
* @return a copy of this vector
*/
@SuppressWarnings("CloneDoesntCallSuperClone")
@Override
public Vec2 clone() {
return new Vec2(x, y);
}
/**
* @return a copy of this vector (new instance)
*/
public Vec2 copy() {
return clone();
}
@Override
public String toString() {
return "(" + x + "," + y + ")";
}
@Override
public void reset() {
setZero();
}
/* STATIC */
public static Vec2 fromAngle(double degrees) {
return new Vec2(FXGLMath.cosDeg((float)degrees), FXGLMath.sinDeg((float)degrees));
}
public static Vec2 abs(Vec2 a) {
return new Vec2(FXGLMath.abs(a.x), FXGLMath.abs(a.y));
}
public static void absToOut(Vec2 a, Vec2 out) {
out.x = FXGLMath.abs(a.x);
out.y = FXGLMath.abs(a.y);
}
public static float dot(final Vec2 a, final Vec2 b) {
return a.x * b.x + a.y * b.y;
}
public static float cross(final Vec2 a, final Vec2 b) {
return a.x * b.y - a.y * b.x;
}
public static Vec2 cross(Vec2 a, float s) {
return new Vec2(s * a.y, -s * a.x);
}
public static void crossToOut(Vec2 a, float s, Vec2 out) {
final float tempy = -s * a.x;
out.x = s * a.y;
out.y = tempy;
}
public static void crossToOutUnsafe(Vec2 a, float s, Vec2 out) {
assert (out != a);
out.x = s * a.y;
out.y = -s * a.x;
}
public static Vec2 cross(float s, Vec2 a) {
return new Vec2(-s * a.y, s * a.x);
}
public static void crossToOut(float s, Vec2 a, Vec2 out) {
final float tempY = s * a.x;
out.x = -s * a.y;
out.y = tempY;
}
public static void crossToOutUnsafe(float s, Vec2 a, Vec2 out) {
assert (out != a);
out.x = -s * a.y;
out.y = s * a.x;
}
public static void negateToOut(Vec2 a, Vec2 out) {
out.x = -a.x;
out.y = -a.y;
}
public static Vec2 min(Vec2 a, Vec2 b) {
return new Vec2(a.x < b.x ? a.x : b.x, a.y < b.y ? a.y : b.y);
}
public static Vec2 max(Vec2 a, Vec2 b) {
return new Vec2(a.x > b.x ? a.x : b.x, a.y > b.y ? a.y : b.y);
}
public static void minToOut(Vec2 a, Vec2 b, Vec2 out) {
out.x = a.x < b.x ? a.x : b.x;
out.y = a.y < b.y ? a.y : b.y;
}
public static void maxToOut(Vec2 a, Vec2 b, Vec2 out) {
out.x = a.x > b.x ? a.x : b.x;
out.y = a.y > b.y ? a.y : b.y;
}
/**
* @see Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + Float.floatToIntBits(x);
result = prime * result + Float.floatToIntBits(y);
return result;
}
/**
* @see Object#equals(Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
Vec2 other = (Vec2) obj;
if (Float.floatToIntBits(x) != Float.floatToIntBits(other.x)) return false;
if (Float.floatToIntBits(y) != Float.floatToIntBits(other.y)) return false;
return true;
}
}
|
package com.galactichorse;
import com.google.api.server.spi.config.*;
import com.hp.hpl.jena.rdf.model.*;
import org.apache.jena.riot.Lang;
import java.io.*;
import java.util.Collection;
import java.util.Map;
@Api(name = "ontology")
public class Ontology {
private static final String ONTOLOGY_PATH = "WEB-INF/accessibility-ontology.ttl";
private static final Lang ONTOLOGY_INPUT_LANGUAGE = Lang.TURTLE;
private static final Lang ONTOLOGY_OUTPUT_LANGUAGE = Lang.JSONLD;
@ApiMethod(name = "get", httpMethod = ApiMethod.HttpMethod.GET)
public OntologyBean getOntologyJsonld() throws IOException {
OntologyBean ob = new OntologyBean();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
getOntologyModel().write(baos, ONTOLOGY_OUTPUT_LANGUAGE.getLabel());
ob.setJsonld(baos.toString());
return ob;
}
public static Model getOntologyModel() throws FileNotFoundException {
File file = new File(ONTOLOGY_PATH);
InputStream inputStream = new FileInputStream(file);
Model model = ModelFactory.createOntologyModel();
model.read(inputStream, null, ONTOLOGY_INPUT_LANGUAGE.getLabel());
return model;
}
}
class OntologyBean {
private String jsonld;
private Map<String,Collection<LinkBean>> _links;
public String getJsonld() {
return jsonld;
}
public void setJsonld(String jsonld) {
this.jsonld = jsonld;
}
}
class LinkBean {
private String href;
private Boolean templated;
private String type;
private String deprecation;
private String name;
private String profile;
private String title;
private String hreflang;
}
|
package org.apache.flume.sink.kafka;
import java.util.Properties;
import java.util.Map;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.flume.Channel;
import org.apache.flume.ChannelException;
import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.EventDeliveryException;
import org.apache.flume.Transaction;
import org.apache.flume.conf.Configurable;
import org.apache.flume.sink.AbstractSink;
import org.apache.flume.instrumentation.SinkCounter;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
public class KafkaSink extends AbstractSink implements Configurable {
private static final Logger log = LoggerFactory.getLogger(KafkaSink.class);
private Properties props;
private SinkCounter sinkCounter;
private Producer<byte[], byte[]> producer;
@Override
public Status process() throws EventDeliveryException {
Channel channel = getChannel();
Transaction tx = channel.getTransaction();
String topic = props.getProperty("topic");
int maxBatchSize = Integer.parseInt(props.getProperty("batch.size", "100"));
Status status = Status.READY;
try {
tx.begin();
List<KeyedMessage<byte[], byte[]>> batch = Lists.newLinkedList();
for (int i = 0; i < maxBatchSize; i++) {
Event event = channel.take();
if (event == null)
break;
String t;
if (topic == null || topic.isEmpty()) {
t = event.getHeaders().get("topic");
if (t == null || t.isEmpty()) {
log.error(getName() + " " + this
+ "Unable to send event without topic header");
continue;
}
} else {
t = topic;
}
String key = event.getHeaders().get("key");
if (key == null) {
batch.add(
new KeyedMessage<byte[], byte[]>(t, event.getBody())
);
} else {
batch.add(
new KeyedMessage<byte[], byte[]>(t, key.getBytes(), event.getBody())
);
}
}
int batchSize = batch.size();
if (batchSize == 0) {
sinkCounter.incrementBatchEmptyCount();
status = Status.BACKOFF;
} else {
if (batchSize < maxBatchSize) {
sinkCounter.incrementBatchUnderflowCount();
} else {
sinkCounter.incrementBatchCompleteCount();
}
sinkCounter.addToEventDrainAttemptCount(batchSize);
producer.send(batch);
}
tx.commit();
sinkCounter.addToEventDrainSuccessCount(batchSize);
} catch (Throwable t) {
tx.rollback();
if (t instanceof Error) {
throw (Error) t;
} else if (t instanceof ChannelException) {
log.error(getName() + " " + this
+ "Unable to get event from channel "
+ channel.getName() + ". Exception folows." + t);
status = Status.BACKOFF;
} else {
throw new EventDeliveryException("Failed to send events", t);
}
} finally {
tx.close();
}
return status;
}
@Override
public void configure(final Context context) {
if (sinkCounter == null) {
sinkCounter = new SinkCounter(getName());
}
props = new Properties();
final Properties producer_props = new Properties();
Map<String, String> contextMap = context.getParameters();
for (String key : contextMap.keySet()) {
if (key.equals("type") ||
key.equals("channel") ||
key.equals("topic") ||
key.equals("batch.size")) {
props.setProperty(key, context.getString(key));
log.info("key={},value={}", key, context.getString(key));
}
else
{
producer_props.setProperty(key, context.getString(key));
log.info("key={},value={}", key, context.getString(key));
}
}
ProducerConfig config = new ProducerConfig(producer_props);
producer = new Producer<byte[], byte[]>(config);
}
@Override
public synchronized void start() {
log.info("Starting {} {}", this, getName());
sinkCounter.start();
super.start();
log.info("Started {} {}", this, getName());
}
@Override
public synchronized void stop() {
log.info("Stoping {} {}", this, getName());
sinkCounter.stop();
super.stop();
log.info("Stopped {} {}", this, getName());
}
}
|
package org.asciidoctor.maven;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;
import org.asciidoctor.AsciiDocDirectoryWalker;
import org.asciidoctor.Asciidoctor;
import org.asciidoctor.Attributes;
import org.asciidoctor.DirectoryWalker;
import org.asciidoctor.Options;
import org.asciidoctor.OptionsBuilder;
import org.asciidoctor.SafeMode;
/**
* Basic maven plugin to render asciidoc files using asciidoctor, a ruby port.
*/
@Mojo(name = "process-asciidoc")
public class AsciidoctorMojo extends AbstractMojo {
// copied from org.asciidoctor.AsciiDocDirectoryWalker.ASCIIDOC_REG_EXP_EXTENSION
// should probably be configured in AsciidoctorMojo through @Parameter 'extension'
protected static final String ASCIIDOC_REG_EXP_EXTENSION = ".*\\.a((sc(iidoc)?)|d(oc)?)$";
@Parameter(property = AsciidoctorMaven.PREFIX + "sourceDir", defaultValue = "${basedir}/src/main/asciidoc", required = true)
protected File sourceDirectory;
@Parameter(property = AsciidoctorMaven.PREFIX + "outputDir", defaultValue = "${project.build.directory}/generated-docs", required = true)
protected File outputDirectory;
@Parameter(property = AsciidoctorMaven.PREFIX + Options.ATTRIBUTES, required = false)
protected Map<String, Object> attributes = new HashMap<String, Object>();
@Parameter(property = AsciidoctorMaven.PREFIX + Options.BACKEND, defaultValue = "docbook", required = true)
protected String backend = "";
@Parameter(property = AsciidoctorMaven.PREFIX + Options.COMPACT, required = false)
protected boolean compact = false;
@Parameter(property = AsciidoctorMaven.PREFIX + Options.DOCTYPE, defaultValue = "article", required = true)
protected String doctype = "article";
@Parameter(property = AsciidoctorMaven.PREFIX + Options.ERUBY, required = false)
protected String eruby = "";
@Parameter(property = AsciidoctorMaven.PREFIX + "headerFooter", required = false)
protected boolean headerFooter = true;
@Parameter(property = AsciidoctorMaven.PREFIX + "templateDir", required = false)
protected File templateDir;
@Parameter(property = AsciidoctorMaven.PREFIX + "templateEngine", required = false)
protected String templateEngine = "";
@Parameter(property = AsciidoctorMaven.PREFIX + "imagesDir", required = false)
protected String imagesDir = "images"; // use a string because otherwise html doc uses absolute path
@Parameter(property = AsciidoctorMaven.PREFIX + "sourceHighlighter", required = false)
protected String sourceHighlighter = "";
@Parameter(property = AsciidoctorMaven.PREFIX + Attributes.TITLE, required = false)
protected String title = "";
@Parameter(property = AsciidoctorMaven.PREFIX + "sourceDocumentName", required = false)
protected File sourceDocumentName;
@Parameter
protected List<Synchronization> synchronizations = new ArrayList<Synchronization>();
@Parameter(property = AsciidoctorMaven.PREFIX + "extensions")
protected List<String> extensions = new ArrayList<String>();
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
ensureOutputExists();
final Asciidoctor asciidoctorInstance = getAsciidoctorInstance();
final OptionsBuilder optionsBuilder = OptionsBuilder.options().toDir(outputDirectory).compact(compact)
.safe(SafeMode.UNSAFE).eruby(eruby).backend(backend).docType(doctype).headerFooter(headerFooter);
if (templateEngine != null) {
optionsBuilder.templateEngine(templateEngine);
}
if (templateDir != null) {
optionsBuilder.templateDir(templateDir);
}
optionsBuilder.attributes(attributes);
if (sourceDocumentName == null) {
for (final File f : scanSourceFiles()) {
renderFile(asciidoctorInstance, optionsBuilder.asMap(), f);
}
} else {
renderFile(asciidoctorInstance, optionsBuilder.asMap(), sourceDocumentName);
}
if (synchronizations != null) {
synchronize();
}
}
protected Asciidoctor getAsciidoctorInstance() throws MojoExecutionException {
return Asciidoctor.Factory.create();
}
private List<File> scanSourceFiles() {
final List<File> asciidoctorFiles;
if (extensions == null || extensions.isEmpty()) {
final DirectoryWalker directoryWalker = new AsciiDocDirectoryWalker(sourceDirectory.getAbsolutePath());
asciidoctorFiles = directoryWalker.scan();
} else {
final DirectoryWalker directoryWalker = new CustomExtensionDirectoryWalker(sourceDirectory.getAbsolutePath(), extensions);
asciidoctorFiles = directoryWalker.scan();
}
return asciidoctorFiles;
}
private void synchronize() {
for (final Synchronization synchronization : synchronizations) {
synchronize(synchronization);
}
}
protected void renderFile(Asciidoctor asciidoctorInstance, Map<String, Object> options, File f) {
asciidoctorInstance.renderFile(f, options);
logRenderedFile(f);
}
protected void logRenderedFile(File f) {
getLog().info("Rendered " + f.getAbsolutePath());
}
protected void synchronize(final Synchronization synchronization) {
if (synchronization.getSource().isDirectory()) {
try {
FileUtils.copyDirectory(synchronization.getSource(), synchronization.getTarget());
} catch (IOException e) {
getLog().error(String.format("Can't synchronize %s -> %s", synchronization.getSource(), synchronization.getTarget()));
}
} else {
try {
FileUtils.copyFile(synchronization.getSource(), synchronization.getTarget());
} catch (IOException e) {
getLog().error(String.format("Can't synchronize %s -> %s", synchronization.getSource(), synchronization.getTarget()));
}
}
}
protected void ensureOutputExists() {
if (!outputDirectory.exists()) {
if (!outputDirectory.mkdirs()) {
getLog().error("Can't create " + outputDirectory.getPath());
}
}
}
public File getSourceDirectory() {
return sourceDirectory;
}
public void setSourceDirectory(File sourceDirectory) {
this.sourceDirectory = sourceDirectory;
}
public File getOutputDirectory() {
return outputDirectory;
}
public void setOutputDirectory(File outputDirectory) {
this.outputDirectory = outputDirectory;
}
public String getBackend() {
return backend;
}
public void setBackend(String backend) {
this.backend = backend;
}
public String getDoctype() {
return doctype;
}
public void setDoctype(String doctype) {
this.doctype = doctype;
}
public Map<String, Object> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, Object> attributes) {
this.attributes = attributes;
}
public boolean isCompact() {
return compact;
}
public void setCompact(boolean compact) {
this.compact = compact;
}
public boolean isHeaderFooter() {
return headerFooter;
}
public void setHeaderFooter(boolean headerFooter) {
this.headerFooter = headerFooter;
}
public File getTemplateDir() {
return templateDir;
}
public void setTemplateDir(File templateDir) {
this.templateDir = templateDir;
}
public String getTemplateEngine() {
return templateEngine;
}
public void setTemplateEngine(String templateEngine) {
this.templateEngine = templateEngine;
}
public String getImagesDir() {
return imagesDir;
}
public void setImagesDir(String imagesDir) {
this.imagesDir = imagesDir;
}
public String getSourceHighlighter() {
return sourceHighlighter;
}
public void setSourceHighlighter(String sourceHighlighter) {
this.sourceHighlighter = sourceHighlighter;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<String> getExtensions() {
return extensions;
}
public void setExtensions(final List<String> extensions) {
this.extensions = extensions;
}
public String getEruby() {
return eruby;
}
public void setEruby(String eruby) {
this.eruby = eruby;
}
public File getSourceDocumentName() {
return sourceDocumentName;
}
public void setSourceDocumentName(File sourceDocumentName) {
this.sourceDocumentName = sourceDocumentName;
}
public List<Synchronization> getSynchronizations() {
return synchronizations;
}
public void setSynchronizations(List<Synchronization> synchronizations) {
this.synchronizations = synchronizations;
}
private static class CustomExtensionDirectoryWalker extends DirectoryWalker {
private final List<String> extensions;
public CustomExtensionDirectoryWalker(final String absolutePath, final List<String> extensions) {
super(absolutePath);
this.extensions = extensions;
}
@Override
protected boolean isAcceptedFile(final File filename) {
final String name = filename.getName();
for (final String extension : extensions) {
if (name.endsWith(extension)) {
return true;
}
}
return false;
}
}
}
|
package org.c4sg.controller;
import io.swagger.annotations.*;
import org.c4sg.dto.CreateProjectDTO;
import org.c4sg.dto.JobTitleDTO;
import org.c4sg.dto.ProjectDTO;
import org.c4sg.exception.BadRequestException;
import org.c4sg.exception.NotFoundException;
import org.c4sg.exception.ProjectServiceException;
import org.c4sg.exception.UserProjectException;
import org.c4sg.service.ProjectService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import javax.validation.Valid;
import javax.validation.constraints.Pattern;
import java.net.URI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@CrossOrigin
@RestController
@RequestMapping("/api/projects")
@Api(description = "Operations about Projects", tags = "project")
@Validated
public class ProjectController {
@Autowired
private ProjectService projectService;
private final Logger logger = LoggerFactory.getLogger(ProjectController.class);
@CrossOrigin
@RequestMapping(method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ApiOperation(value = "Find all projects", notes = "Returns a collection of projects")
public List<ProjectDTO> getProjects() {
System.out.println("************** ProjectController.getProjects() **************");
return projectService.findProjects();
}
@CrossOrigin
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ApiOperation(value = "Find project by ID", notes = "Returns a single project")
public ProjectDTO getProject(
@ApiParam(value = "ID of project to return", required = true) @PathVariable("id") int id) {
System.out.println("************** ProjectController.getProject()"
+ ": id=" + id
+ " **************");
return projectService.findById(id);
}
@CrossOrigin
@RequestMapping(value = "/organization", method = RequestMethod.GET)
@ApiOperation(value = "Find projects by Organization ID and projet status", notes = "Returns a list of projects")
public List<ProjectDTO> getProjectsByOrganization(
@ApiParam(value = "ID of an organization", required = true) @RequestParam("organizationId") int organizationId,
@ApiParam(value = "project status, A-ACTIVE, C-Closed, N-New", allowableValues = "A, C, N") @RequestParam (required = false) String projectStatus)
throws ProjectServiceException {
System.out.println("************** ProjectController.getProjectsByOrganization()"
+ ": organizationId=" + organizationId
+ "; projectStatus=" + projectStatus
+ " **************");
return projectService.findByOrganization(organizationId, projectStatus);
}
@CrossOrigin
@RequestMapping(value = "/search", method = RequestMethod.GET)
@ApiOperation(value = "Find ACTIVE project by keyWord or skills", notes = "Returns a collection of active projects")
public Page<ProjectDTO> getProjects(
@ApiParam(value = "Keyword of the project") @RequestParam(required=false) String keyWord,
@ApiParam(value = "Job Titles of the project") @RequestParam(required = false) List<Integer> jobTitles,
@ApiParam(value = "Skills of the project") @RequestParam(required = false) List<Integer> skills,
@ApiParam(value = "Status of the project") @Pattern(regexp="[AC]") @RequestParam(required = false) String status,
@ApiParam(value = "Location of the project") @Pattern(regexp="[YN]") @RequestParam(required = false) String remote,
@ApiParam(value = "Results page you want to retrieve (0..N)", required=false) @RequestParam(required=false) Integer page,
@ApiParam(value = "Number of records per page",required=false) @RequestParam(required=false) Integer size) {
System.out.println("************** ProjectController.getProjects()"
+ ": keyWord=" + keyWord
+ "; jobTitles=" + jobTitles
+ "; skills=" + skills
+ "; status=" + status
+ "; remote=" + remote
+ "; page=" + page
+ "; size=" + size
+ " **************");
return projectService.search(keyWord, jobTitles, skills, status, remote, page, size);
}
@CrossOrigin
@RequestMapping(value = "/user", method = RequestMethod.GET)
@ApiOperation(
value = "Find projects by user",
notes = "Returns a list of projects searched by user ID and user-project status (applied/bookmarked). "
+ "If user-project status is not provided, returns all projects related to the user. "
+ "The projects are sorted in descending order of the timestamp they are bounded to the user.",
response =ProjectDTO.class ,
responseContainer = "List")
@ApiResponses(value = {@ApiResponse(code = 404, message = "Missing required input")})
public List<ProjectDTO> getUserProjects(
@ApiParam(value = "User ID", required = true) @RequestParam Integer userId,
@ApiParam(value = "User project status, A-Applied, B-Bookmarked, C-Accepted, D-Declined", allowableValues = "A, B, C, D")
@RequestParam (required = false) String userProjectStatus)
throws ProjectServiceException {
System.out.println("************** ProjectController.getUserProjects()"
+ ": UserId=" + userId
+ "; Status=" + userProjectStatus
+ " **************");
List<ProjectDTO> projects = new ArrayList<ProjectDTO>();
if(userProjectStatus.equals("B")){
projects = projectService.getBookmarkByUser(userId);
}else{
projects = projectService.getApplicationByUserAndStatus(userId, userProjectStatus);
}
return projects;
}
@CrossOrigin
@RequestMapping(method = RequestMethod.POST)
@ApiOperation(value = "Add a new project")
public Map<String, Object> createProject(
@ApiParam(value = "Project object to return", required = true) @RequestBody @Valid CreateProjectDTO createProjectDTO) {
logger.debug("************** ProjectController.createProject()"
+ ": createProjectDTO=" + createProjectDTO
+ " **************");
Map<String, Object> responseData = null;
try {
ProjectDTO createProject = projectService.createProject(createProjectDTO);
responseData = Collections.synchronizedMap(new HashMap<>());
responseData.put("project", createProject);
} catch (Exception e) {
logger.error("Exception -", e);
}
return responseData;
}
@CrossOrigin
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
@ApiOperation(value = "Deletes a project")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteProject(
@ApiParam(value = "Project id to delete", required = true) @PathVariable("id") int id) {
System.out.println("************** ProjectController.deleteProject()"
+ ": id=" + id
+ " **************");
try {
projectService.deleteProject(id);
} catch (Exception e) {
System.out.println(e);
}
}
@CrossOrigin
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
@ApiOperation(value = "Update an existing project")
public Map<String, Object> updateProject(
@ApiParam(value = "Updated project object", required = true) @RequestBody @Valid ProjectDTO project) {
System.out.println("************** ProjectController.updateProject()"
+ ": project=" + project
+ " **************");
Map<String, Object> responseData = null;
try {
ProjectDTO updateProject = projectService.updateProject(project);
responseData = Collections.synchronizedMap(new HashMap<>());
responseData.put("project", updateProject);
} catch (Exception e) {
System.out.println(e);
}
return responseData;
}
@CrossOrigin
@RequestMapping(value = "/{id}/users/{userId}", method = RequestMethod.POST)
@ApiOperation(value = "Create a relation between user and project")
@ApiResponses(value = {
@ApiResponse(code = 404, message = "ID of project or user invalid")
})
//TODO: Replace explicit user{id} with AuthN user id.
public ResponseEntity<?> createUserProject(
@ApiParam(value = "ID of user", required = true) @PathVariable("userId") Integer userId,
@ApiParam(value = "ID of project", required = true) @PathVariable("id") Integer projectId,
@ApiParam(value = "User project status, A-Applied, B-Bookmarked, C-Approved, D-Declined", allowableValues = "A, B, C, D", required = true)
@RequestParam("userProjectStatus") String userProjectStatus) {
System.out.println("************** ProjectController.createUserProject()"
+ ": userId=" + userId
+ "; projectId=" + projectId
+ "; userProjectStatus=" + userProjectStatus
+ " **************");
try {
//comment and resumeFlag will be accepted as inputs to the REST API in the future
String comment = "";
String resumeFlag = "N";
if(userProjectStatus.equals("B"))
{
projectService.saveBookmark(userId, projectId);
}
else{
projectService.saveApplication(userId, projectId, userProjectStatus, comment, resumeFlag);
}
//projectService.saveUserProject(userId, projectId, userProjectStatus);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}/users/{userId}")
.buildAndExpand(projectId, userId, userProjectStatus).toUri();
return ResponseEntity.created(location).build();
} catch (NullPointerException e) {
throw new NotFoundException("ID of project or user invalid");
}
catch (UserProjectException | BadRequestException e) {
throw e;
}
}
@CrossOrigin
@RequestMapping(value = "/{id}/image", params = "imgUrl", method = RequestMethod.PUT)
@ApiOperation(value = "Upload a project image")
public void saveImage(
@ApiParam(value = "project Id", required = true) @PathVariable("id") Integer id,
@ApiParam(value = "Image Url", required = true) @RequestParam("imgUrl") String url) {
System.out.println("************** ProjectController.saveImage()"
+ ": id=" + id
+ "; url=" + url
+ " **************");
projectService.saveImage(id, url);
}
@CrossOrigin
@RequestMapping(value="/jobTitles", method = RequestMethod.GET)
@ApiOperation(value = "Get a list of job titles")
public List<JobTitleDTO> getJobTitles() {
System.out.println("************** ProjectController.getJobTitles() **************");
return projectService.findJobTitles();
}
}
|
package org.commcare.cases.query;
import org.commcare.cases.query.queryset.CurrentModelQuerySet;
import org.commcare.cases.query.queryset.QuerySetCache;
import org.javarosa.core.model.condition.EvaluationContext;
import org.javarosa.core.model.trace.EvaluationTrace;
public class QueryContext {
public static final int BULK_QUERY_THRESHOLD = 50;
//TODO: This is a bad reason to keep the EC around here, and locks the lifecycle of this object
//into the EC
private EvaluationContext traceRoot;
private QueryCache cache;
private QueryContext potentialSpawnedContext;
//Until we can keep track more robustly of the individual spheres of 'bulk' models
//we'll just keep track of the dominant factor in our queries to know what to expect
//WRT whether optimizatons will help or hurt
private int contextScope = 1;
public QueryContext() {
cache = new QueryCache();
}
public QueryContext(QueryContext parent) {
this.traceRoot = parent.traceRoot;
this.cache = new QueryCache(parent.cache);
this.contextScope = parent.contextScope;
}
public QueryContext checkForDerivativeContextAndReturn(int newScope) {
QueryContext newContext;
potentialSpawnedContext = null;
newContext = new QueryContext(this);
newContext.contextScope = newScope;
if(dominates(newContext.contextScope, this.contextScope)) {
this.reportContextEscalation(newContext, "New");
return newContext;
} else {
return this;
}
}
public QueryContext testForInlineScopeEscalation(int newScope) {
if(dominates(newScope, contextScope)) {
potentialSpawnedContext = new QueryContext(this);
potentialSpawnedContext.contextScope = newScope;
reportContextEscalation(potentialSpawnedContext, "Temporary");
return potentialSpawnedContext;
} else {
return this;
}
}
public int getScope() {
return this.contextScope;
}
private boolean dominates(int newScope, int existingScope) {
return newScope > existingScope &&
newScope > BULK_QUERY_THRESHOLD &&
newScope / existingScope > 10;
}
private void reportContextEscalation(QueryContext newContext, String label) {
EvaluationTrace trace = new EvaluationTrace(label + " Query Context [" + newContext.contextScope +"]");
trace.setOutcome("");
reportTrace(trace);
}
public void reportTrace(EvaluationTrace trace) {
traceRoot.reportSubtrace(trace);
}
public void setTraceRoot(EvaluationContext traceRoot) {
this.traceRoot = traceRoot;
}
public <T extends QueryCacheEntry> T getQueryCache(Class<T> cacheType) {
return cache.getQueryCache(cacheType);
}
public <T extends QueryCacheEntry> T getQueryCacheOrNull(Class<T> cacheType) {
return cache.getQueryCacheOrNull(cacheType);
}
public void setHackyOriginalContextBody(CurrentModelQuerySet hackyOriginalContextBody) {
getQueryCache(QuerySetCache.class).
addModelQuerySet(CurrentModelQuerySet.CURRENT_QUERY_SET_ID, hackyOriginalContextBody);
}
}
|
package org.devdom.tracker.util;
import facebook4j.conf.ConfigurationBuilder;
import java.util.HashMap;
import java.util.Map;
public class Configuration{
private Configuration(){ }
public static int POSTS_LIMIT = 200;
public static int LIKES_LIMIT = 300;
public static int OFFSET = 200;
public static String JPA_PU = "jpa";
public static String[] SEEK_GROUPS = {"161328360736390" /*Hackers and Founders - Santo Domingo*/,
"264382946926439" /*#VivaPHP!*/,
"358999187465748" /*CodigoLibre_Developers*/,
"201514949865358" /*Developers Dominicanos*/,
"132533423551389" /*developers X*/,
"150647751783730" /*Javascript Dominica na*/,
"455974804478621" /*Mobile Developer Group*/,
"220361121324698" /*DevelopersRD*/,
"179210165492903" /*Caribbean SQL*/,
"137759453068575"/*Python Dominicana*/};
public static ConfigurationBuilder getFacebookConfig(){
return new ConfigurationBuilder()
.setDebugEnabled(true)
.setOAuthPermissions("user_about_me,user_actions.music,user_actions.news,user_actions.video,user_activities,user_birthday,user_groups,user_hometown,user_interests,user_likes,user_location,user_notes,user_questions,user_relationship_details");
}
public static Map JPAConfig(){
Map<String, String> properties = new HashMap<>();
properties.put("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver");
return properties;
}
}
|
package org.gitlab4j.api;
import java.util.List;
import java.util.stream.Stream;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.Response;
import org.gitlab4j.api.models.AccessLevel;
import org.gitlab4j.api.models.ProtectedBranch;
public class ProtectedBranchesApi extends AbstractApi {
public ProtectedBranchesApi(GitLabApi gitLabApi) {
super(gitLabApi);
}
/**
* Gets a list of protected branches from a project.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/protected_branches</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @return the list of protected branches for the project
* @throws GitLabApiException if any exception occurs
*/
public List<ProtectedBranch> getProtectedBranches(Object projectIdOrPath) throws GitLabApiException {
return (getProtectedBranches(projectIdOrPath, this.getDefaultPerPage()).all());
}
/**
* Gets a Pager of protected branches from a project.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/protected_branches</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param itemsPerPage the number of instances that will be fetched per page
* @return the Pager of protected branches for the project
* @throws GitLabApiException if any exception occurs
*/
public Pager<ProtectedBranch> getProtectedBranches(Object projectIdOrPath, int itemsPerPage) throws GitLabApiException {
return (new Pager<ProtectedBranch>(this, ProtectedBranch.class, itemsPerPage, null,
"projects", getProjectIdOrPath(projectIdOrPath), "protected_branches"));
}
/**
* Gets a Stream of protected branches from a project.
*
* <pre><code>GitLab Endpoint: GET /projects/:id/protected_branches</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @return the Stream of protected branches for the project
* @throws GitLabApiException if any exception occurs
*/
public Stream<ProtectedBranch> getProtectedBranchesStream(Object projectIdOrPath) throws GitLabApiException {
return (getProtectedBranches(projectIdOrPath, this.getDefaultPerPage()).stream());
}
/**
* Unprotects the given protected branch or wildcard protected branch.
*
* <pre><code>GitLab Endpoint: DELETE /projects/:id/protected_branches/:name</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param branchName the name of the branch to un-protect, can be a wildcard
* @throws GitLabApiException if any exception occurs
*/
public void unprotectBranch(Integer projectIdOrPath, String branchName) throws GitLabApiException {
delete(Response.Status.NO_CONTENT, null, "projects", getProjectIdOrPath(projectIdOrPath), "protected_branches", urlEncode(branchName));
}
/**
* Protects a single repository branch or several project repository branches using a wildcard protected branch.
*
* <pre><code>GitLab Endpoint: POST /projects/:id/protected_branches</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param branchName the name of the branch to protect, can be a wildcard
* @return the branch info for the protected branch
* @throws GitLabApiException if any exception occurs
*/
public ProtectedBranch protectBranch(Integer projectIdOrPath, String branchName) throws GitLabApiException {
return protectBranch(projectIdOrPath, branchName, AccessLevel.MAINTAINER, AccessLevel.MAINTAINER);
}
/**
* Protects a single repository branch or several project repository branches using a wildcard protected branch.
*
* <pre><code>GitLab Endpoint: POST /projects/:id/protected_branches</code></pre>
*
* @param projectIdOrPath the project in the form of an Integer(ID), String(path), or Project instance
* @param branchName the name of the branch to protect, can be a wildcard
* @param pushAccessLevel Access levels allowed to push (defaults: 40, maintainer access level)
* @param mergeAccessLevel Access levels allowed to merge (defaults: 40, maintainer access level)
* @return the branch info for the protected branch
* @throws GitLabApiException if any exception occurs
*/
public ProtectedBranch protectBranch(Integer projectIdOrPath, String branchName, AccessLevel pushAccessLevel, AccessLevel mergeAccessLevel) throws GitLabApiException {
Form formData = new GitLabApiForm()
.withParam("name", branchName, true)
.withParam("push_access_level", pushAccessLevel.toValue(), false)
.withParam("merge_access_level", mergeAccessLevel.toValue(), false);
Response response = post(Response.Status.CREATED, formData.asMap(),
"projects", getProjectIdOrPath(projectIdOrPath), "protected_branches");
return (response.readEntity(ProtectedBranch.class));
}
}
|
package org.irmacard.api.common;
public class ClientRequest<T> {
private int timeout = 0;
private String data;
private T request;
private String callbackUrl;
public ClientRequest() {}
public ClientRequest(String data, T request) {
this.request = request;
this.data = data;
}
public ClientRequest(String data, T request, int timeout) {
this.timeout = timeout;
this.request = request;
this.data = data;
}
public ClientRequest(String data, T request, int timeout, String callbackUrl) {
this(data, request, timeout);
this.callbackUrl = callbackUrl;
}
public String getCallbackUrl() {
return callbackUrl;
}
public int getTimeout() {
return timeout;
}
public void setTimeout(int timeout) {
this.timeout = timeout;
}
public T getRequest() {
return request;
}
public String getData() {
return data;
}
}
|
package org.jabref.model.groups;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import javafx.scene.paint.Color;
import org.jabref.model.entry.BibEntry;
import org.jabref.model.search.SearchMatcher;
import org.jabref.model.strings.StringUtil;
import de.jensd.fx.glyphs.materialdesignicons.MaterialDesignIcon;
import org.apache.commons.lang3.EnumUtils;
/**
* Base class for all groups.
*/
public abstract class AbstractGroup implements SearchMatcher {
/**
* The group's name.
*/
protected final String name;
/**
* The hierarchical context of the group.
*/
protected final GroupHierarchyType context;
protected Optional<Color> color = Optional.empty();
protected boolean isExpanded = true;
protected Optional<String> description = Optional.empty();
protected Optional<String> iconCode = Optional.empty();
protected MaterialDesignIcon icon = null;
protected AbstractGroup(String name, GroupHierarchyType context) {
this.name = name;
this.context = Objects.requireNonNull(context);
}
@Override
public String toString() {
return "AbstractGroup{" +
"name='" + name + '\'' +
", context=" + context +
", color=" + color +
", isExpanded=" + isExpanded +
", description=" + description +
", iconCode=" + iconCode +
'}';
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if ((other == null) || (getClass() != other.getClass())) {
return false;
}
AbstractGroup that = (AbstractGroup) other;
return Objects.equals(this.name, that.name) && Objects.equals(this.description, that.description)
&& Objects.equals(this.context, that.context);
}
@Override
public int hashCode() {
return Objects.hash(name, description, context);
}
public Optional<Color> getColor() {
return color;
}
public void setColor(String colorString) {
if (StringUtil.isBlank(colorString)) {
color = Optional.empty();
} else {
setColor(Color.valueOf(colorString));
}
}
public void setColor(Color color) {
this.color = Optional.of(color);
}
public boolean isExpanded() {
return isExpanded;
}
public void setExpanded(boolean expanded) {
isExpanded = expanded;
}
public Optional<String> getDescription() {
return description;
}
public void setDescription(String description) {
this.description = Optional.of(description);
}
public Optional<String> getIconCode() {
if (icon != null) {
return Optional.of(icon.unicode());
}
return iconCode;
}
public void setIconCode(String iconCode) {
this.iconCode = Optional.of(iconCode);
this.icon = EnumUtils.getEnum(MaterialDesignIcon.class, iconCode.toUpperCase(Locale.ENGLISH));
}
/**
* Returns the way this group relates to its sub- or supergroup.
*/
public GroupHierarchyType getHierarchicalContext() {
return context;
}
/**
* Returns this group's name, e.g. for display in a list/tree.
*/
public final String getName() {
return name;
}
/**
* @return true if this group contains the specified entry, false otherwise.
*/
public abstract boolean contains(BibEntry entry);
@Override
public boolean isMatch(BibEntry entry) {
return contains(entry);
}
/**
* @return true if this group contains any of the specified entries, false otherwise.
*/
public boolean containsAny(List<BibEntry> entries) {
for (BibEntry entry : entries) {
if (contains(entry)) {
return true;
}
}
return false;
}
/**
* @return true if this group contains all of the specified entries, false otherwise.
*/
public boolean containsAll(List<BibEntry> entries) {
for (BibEntry entry : entries) {
if (!contains(entry)) {
return false;
}
}
return true;
}
/**
* Returns true if this group is dynamic, i.e. uses a search definition or
* equiv. that might match new entries, or false if this group contains a
* fixed set of entries and thus will never match a new entry that was not
* explicitly added to it.
*/
public abstract boolean isDynamic();
/**
* @return A deep copy of this object.
*/
public abstract AbstractGroup deepCopy();
}
|
package org.jboss.rhiot.services;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.jboss.rhiot.services.api.IRHIoTTagScanner;
import org.jboss.rhiot.services.fsm.GameStateMachine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;
/**
* Expose some of the RHIoTTagScanner information via REST
*/
@SuppressWarnings("PackageAccessibility")
public class RHIoTServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final Logger log = LoggerFactory.getLogger(RHIoTServlet.class);
private RHIoTTagScanner scanner;
private String cloudPassword;
public RHIoTServlet(RHIoTTagScanner scanner) {
this.scanner = scanner;
}
public String getCloudPassword() {
return cloudPassword;
}
public void setCloudPassword(String cloudPassword) {
this.cloudPassword = cloudPassword;
}
/**
* POST endpoint for adding a tag name to address mapping. This requires a json array of name,address pairs.
* @param req - request object
* @param resp - response object
* @throws ServletException
* @throws IOException
*/
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
JsonParser parser = new JsonParser();
JsonElement json = parser.parse(req.getReader());
JsonArray array = json.getAsJsonArray();
for (int n = 0; n < array.size(); n++) {
JsonObject info = array.get(n).getAsJsonObject();
String name = info.get("name").getAsString();
String address = info.get("address").getAsString();
scanner.updateTagInfo(address, name);
}
resp.setStatus(HttpServletResponse.SC_OK);
}
/**
* Entry point for handling the simple GET type of REST calls
* @param req - request object
* @param resp - response object
* @throws ServletException
* @throws IOException
*/
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String pathInfo = req.getPathInfo();
log.info(String.format("doGet(%s)\n", pathInfo));
int status = HttpServletResponse.SC_OK;
if (pathInfo.startsWith(IRHIoTTagScanner.CLOUD_PW_PATH))
sendPassword(resp);
else if (pathInfo.startsWith(IRHIoTTagScanner.TAG_INFO_PATH))
sendTagInfo(resp);
else if (pathInfo.startsWith(IRHIoTTagScanner.GAMESM_DIGRAPH_PATH))
sendGameSMDigraph(req, resp);
else if (pathInfo.startsWith(IRHIoTTagScanner.GAMESM_INFO_PATH))
sendGameSMInfo(req, resp);
else
status = HttpServletResponse.SC_BAD_REQUEST;
if (status != HttpServletResponse.SC_OK)
resp.sendError(status);
else
resp.setStatus(status);
}
/**
* Send the cloud account password
* @param resp
* @throws IOException
*/
private void sendPassword(HttpServletResponse resp) throws IOException {
resp.setContentType("application/txt");
resp.getWriter().write(cloudPassword);
}
/**
* Generate and send the game state machine digraph for plotting via graphviz
* @param req - request object
* @param resp - response object
* @throws IOException
*/
private void sendGameSMDigraph(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String address = req.getParameter("address");
resp.setContentType("application/txt");
GameStateMachine gsm = scanner.getGameSM(address);
String digraph = gsm.exportAsString();
resp.getWriter().write(digraph);
}
/**
* Return the current game state and trigger a game information message
* @param req - request object
* @param resp - response object
* @throws IOException
*/
private void sendGameSMInfo(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String address = req.getParameter("address");
resp.setContentType("application/txt");
String state = scanner.getAndPublishGameSMInfo(address);
resp.getWriter().write(state);
}
/**
* Return a json representation of the registered tag address to name mappings
* @param resp - response object
* @throws IOException
*/
private void sendTagInfo(HttpServletResponse resp) throws IOException {
resp.setContentType("application/json");
Map<String, String> infos = scanner.getTags();
log.debug(String.format("\tTag count: %d\n", infos.size()));
JsonArray jsonArray = new JsonArray();
for (String addressKey : infos.keySet()) {
JsonObject je = new JsonObject();
String name = infos.get(addressKey);
je.addProperty("address", addressKey);
je.addProperty("name", name);
log.debug(String.format("\t\tAddress: %s; name: %s\n", addressKey, name));
jsonArray.add(je);
}
Gson gson = new GsonBuilder().create();
String jsonOutput = gson.toJson(jsonArray);
resp.getWriter().write(jsonOutput);
log.debug(String.format("\tTags: %s\n", jsonOutput));
}
}
|
package org.jenkinsci.plugins.ease;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import com.apperian.api.ApperianApi;
import com.apperian.api.ConnectionException;
import com.apperian.api.applications.AppType;
import com.apperian.api.applications.Application;
import com.apperian.api.applications.Application.Version;
import com.apperian.api.signing.PlatformType;
import com.apperian.api.signing.SigningCredential;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.QueryParameter;
import hudson.Extension;
import hudson.FilePath;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
public class EaseUpload implements Describable<EaseUpload>, Serializable, Cloneable {
private static final long serialVersionUID = 1L;
private String prodEnv;
private String customApperianUrl;
private String appId;
private String filename;
private String apiTokenId;
private String author;
private String version;
private String versionNotes;
private boolean signApp;
private String credential;
private boolean enableApp;
private transient FilePath filePath;
private transient Formatter<String> envVariablesFormatter = null;
@DataBoundConstructor
public EaseUpload(
String prodEnv,
String customApperianUrl,
String apiTokenId,
String appId,
String filename,
String author,
String version,
String versionNotes,
boolean signApp,
String credential,
boolean enableApp) {
this.prodEnv = Utils.trim(prodEnv);
this.customApperianUrl = Utils.trim(customApperianUrl);
this.apiTokenId = Utils.trim(apiTokenId);
this.appId = Utils.trim(appId);
this.filename = Utils.trim(filename);
this.author = Utils.trim(author);
this.version = Utils.trim(version);
this.versionNotes = Utils.trim(versionNotes);
this.signApp = signApp;
this.credential = credential;
this.enableApp = enableApp;
}
public static class Builder {
private EaseUpload easeUpload;
public Builder(String prodEnv, String customApperianUrl, String apiTokenId) {
easeUpload = new EaseUpload(prodEnv,
customApperianUrl,
apiTokenId,
null,
null,
null,
null,
null,
false,
null,
false);
}
public Builder withAppId(String appId) {
easeUpload.appId = appId;
return this;
}
public Builder withFilename(String filename) {
easeUpload.filename = filename;
return this;
}
public Builder withAuthor(String author) {
easeUpload.author = author;
return this;
}
public Builder withVersion(String version) {
easeUpload.version = version;
return this;
}
public Builder withVersionNotes(String versionNotes) {
easeUpload.versionNotes = versionNotes;
return this;
}
public Builder withEnableApp(boolean enableApp) {
easeUpload.enableApp = enableApp;
return this;
}
public Builder withSignApp(boolean signApp) {
easeUpload.signApp = signApp;
return this;
}
public Builder withCredential(String credential) {
easeUpload.credential = credential;
return this;
}
public EaseUpload build() {
return easeUpload;
}
}
public String getProdEnv() {
return prodEnv;
}
public String getCustomApperianUrl() {
return customApperianUrl;
}
public String getAppId() {
return appId;
}
public String getFilename() {
return filename;
}
public String getApiTokenId() {
return apiTokenId;
}
public String getAuthor() {
return author;
}
public String getVersion() {
return version;
}
public String getVersionNotes() {
return versionNotes;
}
public boolean isSignApp() {
return signApp;
}
public String getCredential() {
return credential;
}
public boolean isEnableApp() {
return enableApp;
}
public FilePath getFilePath() {
return filePath;
}
public String applyEnvVariablesFormatter(String value) {
if (envVariablesFormatter != null) {
value = envVariablesFormatter.format(value);
}
return value;
}
public void setEnvVariablesFormatter(Formatter<String> envVariablesFormatter) {
this.envVariablesFormatter = envVariablesFormatter;
}
public void checkConfiguration() throws Exception{
if (Utils.isEmptyString(appId)) {
throw new Exception("The app id is empty");
}
checkHasAuthFields();
if (Utils.isEmptyString(filename)){
throw new Exception("The Filename is empty");
}
}
public boolean searchFileInWorkspace(FilePath workspacePath,
PrintStream buildLog) throws IOException, InterruptedException {
FilePath[] paths = workspacePath.list(applyEnvVariablesFormatter(this.filename));
if (paths.length != 1) {
buildLog.println("Found " + (paths.length == 0 ? "no files" : " ambiguous list " + Arrays.asList(paths)) +
" as candidates for pattern '" + this.filename + "'");
return false;
}
this.filePath = paths[0];
return true;
}
public boolean validateHasAuthFields() {
try {
checkHasAuthFields();
return true;
} catch (Exception e) {
return false;
}
}
public void checkHasAuthFields() throws Exception{
if (Utils.isEmptyString(apiTokenId)) {
throw new Exception("Api Token is empty");
}
if (Utils.isEmptyString(this.prodEnv)) {
throw new Exception("Production environment is empty");
}
ProductionEnvironment productionEnvironment = ProductionEnvironment.fromNameOrNA(this.prodEnv);
if (productionEnvironment == null) {
throw new Exception("Production environment is invalid");
}
if (productionEnvironment == ProductionEnvironment.CUSTOM) {
if (!Utils.isValidURL(customApperianUrl)) {
throw new Exception("API URL is not a valid URL");
}
}
}
@Override
public Descriptor<EaseUpload> getDescriptor() {
return new DescriptorImpl();
}
@Extension
public static final class DescriptorImpl extends Descriptor<EaseUpload> {
private static final transient Logger logger = Logger.getLogger(DescriptorImpl.class.getName());
private transient ApperianApiFactory apperianApiFactory = new ApperianApiFactory();
private transient CredentialsManager credentialsManager = new CredentialsManager();
@Override
public String getDisplayName() {
return "Apperian Upload";
}
public ListBoxModel doFillProdEnvItems() {
ListBoxModel resultListBox = new ListBoxModel();
for (ProductionEnvironment prodEnv : ProductionEnvironment.values()) {
resultListBox.add(prodEnv.getTitle(), prodEnv.name());
}
return resultListBox;
}
public ListBoxModel doFillApiTokenIdItems() {
ListBoxModel resultListBox = new ListBoxModel();
CredentialsManager credentialsManager = new CredentialsManager();
List<ApiToken> credentials = credentialsManager.getCredentials();
resultListBox.add("<Select an API token>", "");
for (ApiToken easeUser : credentials) {
resultListBox.add(easeUser.getDescription(), easeUser.getApiTokenId());
}
return resultListBox;
}
public ListBoxModel doFillAppIdItems(@QueryParameter("prodEnv") final String prodEnv,
@QueryParameter("customApperianUrl") String customApperianUrl,
@QueryParameter("apiTokenId") final String apiTokenId) {
EaseUpload upload = new EaseUpload.Builder(prodEnv, customApperianUrl, apiTokenId).build();
if (!upload.validateHasAuthFields()) {
ListBoxModel listBoxModel = new ListBoxModel();
listBoxModel.add("(credentials required)", "");
return listBoxModel;
}
ApperianApi apperianApi = createApperianApi(upload);
try {
List<Application> apps = apperianApi.listApplications();
ListBoxModel listItems = new ListBoxModel();
for (Application app : apps) {
if (app.isAppTypeSupportedByPlugin()){
Version version = app.getVersion();
listItems.add(version.getAppName() + " v" + version.getVersionNum() + " type:" + app.getTypeName(),
app.getId());
}
}
return listItems;
} catch (ConnectionException e) {
ListBoxModel listBoxModel = new ListBoxModel();
listBoxModel.add("(" + e.getMessage() + ")", "");
return listBoxModel;
} catch (Exception e) {
logger.throwing(EaseRecorder.class.getName(), "doFillAppItems", e);
ListBoxModel listBoxModel = new ListBoxModel();
listBoxModel.add("(error: " + e.getMessage() + ")", "");
return listBoxModel;
}
}
public ListBoxModel doFillCredentialItems(@QueryParameter("prodEnv") final String prodEnv,
@QueryParameter("customApperianUrl") String customApperianUrl,
@QueryParameter("apiTokenId") final String apiTokenId,
@QueryParameter("appId") final String appId) {
EaseUpload upload = new EaseUpload.Builder(prodEnv, customApperianUrl, apiTokenId).build();
if (!upload.validateHasAuthFields()) {
ListBoxModel listItems = new ListBoxModel();
listItems.add("(credentials required)", "");
return listItems;
}
boolean hasAppId = !Utils.isEmptyString(appId);
ApperianApi apperianApi = createApperianApi(upload);
try {
PlatformType typeFilter = null;
if (hasAppId) {
List<Application> apps = apperianApi.listApplications();
for (Application application : apps) {
if (appId.trim().equals(application.getId())) {
if (!application.isAppTypeSupportedByPlugin()) {
continue;
}
AppType appType = application.getAppType();
if (AppType.ANDROID.equals(appType)) {
typeFilter = PlatformType.ANDROID;
} else if (AppType.IOS.equals(appType)) {
typeFilter = PlatformType.IOS;
}
break;
}
}
}
List<SigningCredential> credentials = apperianApi.listCredentials();
ListBoxModel listItems = new ListBoxModel();
for (SigningCredential credential : credentials) {
if (typeFilter != null) {
if (!typeFilter.equals(credential.getPlatform())) {
continue;
}
}
listItems.add(credential.getDescription() +
" exp:" + Utils.transformDate(credential.getExpirationDate()) +
(typeFilter == null ? " platform:" + credential.getPlatform().getDisplayName() : ""),
credential.getCredentialId());
}
return listItems;
} catch (ConnectionException e) {
ListBoxModel listBoxModel = new ListBoxModel();
listBoxModel.add("(" + e.getMessage() + ")", "");
return listBoxModel;
}
}
public FormValidation doTestConnection(@QueryParameter("prodEnv") final String prodEnv,
@QueryParameter("customApperianUrl") String customApperianUrl,
@QueryParameter("apiTokenId") final String apiTokenId)
throws IOException, ServletException {
EaseUpload upload = new EaseUpload.Builder(prodEnv, customApperianUrl, apiTokenId).build();
try {
upload.checkHasAuthFields();
} catch (Exception e) {
return FormValidation.error(e.getMessage());
}
ApperianApi apperianApi = createApperianApi(upload);
try {
// To check the connection we just use the endpoint to get the user details to see if it works
apperianApi.getUserDetails();
return FormValidation.ok("Connection OK");
} catch (ConnectionException e) {
return FormValidation.error(e.getMessage());
}
}
private ApperianApi createApperianApi(EaseUpload upload) {
String environment = upload.prodEnv;
String customApperianUrl = upload.customApperianUrl;
String apiToken = credentialsManager.getCredentialWithId(upload.apiTokenId);
return apperianApiFactory.create(environment, customApperianUrl, apiToken);
}
}
}
|
package org.lightmare.libraries;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.log4j.Logger;
import org.lightmare.libraries.loaders.EjbClassLoader;
import org.lightmare.utils.CollectionUtils;
import org.lightmare.utils.ObjectUtils;
import org.lightmare.utils.fs.FileUtils;
import org.lightmare.utils.reflect.MetaUtils;
/**
* Class for load jar or class files from specified path
*
* @author levan
*
*/
public class LibraryLoader {
// Method name to add URL to class loader
private static final String ADD_URL_METHOD_NAME = "addURL";
private static final String CLOSE_METHOD_NAME = "close";
private static final String LOADER_THREAD_NAME = "library-class-loader-thread";
private static Method addURLMethod;
private static final Lock LOCK = new ReentrantLock();
private static final Logger LOG = Logger.getLogger(LibraryLoader.class);
/**
* implementation of {@link Callable}<ClassLoader> interface to initialize
* {@link ClassLoader} in separate thread
*
* @author levan
*
*/
private static class LibraryLoaderInit implements Callable<ClassLoader> {
private URL[] urls;
private ClassLoader parent;
public LibraryLoaderInit(final URL[] urls, final ClassLoader parent) {
this.urls = urls;
this.parent = parent;
}
@Override
public ClassLoader call() throws Exception {
ClassLoader loader = cloneContextClassLoader(urls, parent);
return loader;
}
}
/**
* Gets {@link URLClassLoader} class addURL method
*
* @return Method
* @throws IOException
*/
private static Method getURLMethod() throws IOException {
if (addURLMethod == null) {
LOCK.lock();
try {
if (addURLMethod == null
&& MetaUtils.hasMethod(URLClassLoader.class,
ADD_URL_METHOD_NAME)) {
addURLMethod = MetaUtils.getDeclaredMethod(
URLClassLoader.class, ADD_URL_METHOD_NAME,
URL.class);
}
} finally {
LOCK.unlock();
}
}
return addURLMethod;
}
/**
* If passed {@link ClassLoader} is instance of {@link URLClassLoader} then
* gets {@link URL}[] of this {@link ClassLoader} calling
* {@link URLClassLoader#getURLs()} method
*
* @param loader
* @return {@link URL}[]
*/
private static URL[] getURLs(ClassLoader loader) {
URL[] urls;
if (loader instanceof URLClassLoader) {
urls = ((URLClassLoader) loader).getURLs();
} else {
urls = CollectionUtils.emptyArray(URL.class);
}
return urls;
}
/**
* Initializes and returns enriched {@link ClassLoader} in separated
* {@link Thread} to load bean and library classes
*
* @param urls
* @return {@link ClassLoader}
* @throws IOException
*/
public static ClassLoader initializeLoader(final URL[] urls)
throws IOException {
ClassLoader parent = getContextClassLoader();
LibraryLoaderInit initializer = new LibraryLoaderInit(urls, parent);
FutureTask<ClassLoader> task = new FutureTask<ClassLoader>(initializer);
Thread thread = new Thread(task);
thread.setName(LOADER_THREAD_NAME);
thread.setPriority(Thread.MAX_PRIORITY);
thread.start();
ClassLoader ejbLoader;
try {
ejbLoader = task.get();
} catch (InterruptedException ex) {
throw new IOException(ex);
} catch (ExecutionException ex) {
throw new IOException(ex);
}
return ejbLoader;
}
/**
* Gets current {@link Thread}'s context {@link ClassLoader} object
*
* @return {@link ClassLoader}
*/
public static ClassLoader getContextClassLoader() {
PrivilegedAction<ClassLoader> action = new PrivilegedAction<ClassLoader>() {
public ClassLoader run() {
Thread currentThread = Thread.currentThread();
ClassLoader classLoader = currentThread.getContextClassLoader();
return classLoader;
}
};
ClassLoader loader = AccessController.doPrivileged(action);
return loader;
}
/**
* Gets new {@link ClassLoader} enriched with passed {@link URL} array and
* parent {@link ClassLoader} classes
*
* @param urls
* @param parent
* @return {@link ClassLoader}
* @throws IOException
*/
public static ClassLoader getEnrichedLoader(URL[] urls, ClassLoader parent) {
ClassLoader enrichedLoader;
if (CollectionUtils.valid(urls)) {
if (parent == null) {
parent = getContextClassLoader();
}
enrichedLoader = EjbClassLoader.newInstance(urls, parent);
} else {
enrichedLoader = null;
}
return enrichedLoader;
}
/**
* Gets new {@link ClassLoader} enriched with passed {@link File} and it's
* sub files {@link URL}s and parent {@link ClassLoader} classes
*
* @param file
* @param urls
* @return {@link ClassLoader}
* @throws IOException
*/
public static ClassLoader getEnrichedLoader(File file, Set<URL> urls)
throws IOException {
FileUtils.getSubfiles(file, urls);
URL[] paths = CollectionUtils.toArray(urls, URL.class);
ClassLoader parent = getContextClassLoader();
ClassLoader enrichedLoader = getEnrichedLoader(paths, parent);
return enrichedLoader;
}
/**
* Initializes new {@link ClassLoader} from loaded {@link URL}'s from
* enriched {@link ClassLoader} for beans and libraries
*
* @param urls
* @return {@link ClassLoader}
* @throws IOException
*/
public static ClassLoader cloneContextClassLoader(final URL[] urls,
ClassLoader parent) throws IOException {
URLClassLoader loader = (URLClassLoader) getEnrichedLoader(urls, parent);
try {
// get all resources for cloning
URL[] urlArray = loader.getURLs();
URL[] urlClone = urlArray.clone();
if (parent == null) {
parent = getContextClassLoader();
}
ClassLoader clone = EjbClassLoader.newInstance(urlClone, parent);
return clone;
} finally {
closeClassLoader(loader);
// dereference cloned class loader instance
loader = null;
}
}
/**
* Merges two {@link ClassLoader}s in one
*
* @param newLoader
* @param oldLoader
* @return {@link ClassLoader}
*/
public static ClassLoader createCommon(ClassLoader newLoader,
ClassLoader oldLoader) {
URL[] urls = getURLs(oldLoader);
ClassLoader commonLoader = URLClassLoader.newInstance(urls, oldLoader);
urls = getURLs(newLoader);
commonLoader = getEnrichedLoader(urls, newLoader);
return commonLoader;
}
/**
* Sets passed {@link Thread}'s context class loader appropriated
* {@link ClassLoader} instance
*
* @param thread
* @param loader
*/
public static void loadCurrentLibraries(Thread thread, ClassLoader loader) {
if (ObjectUtils.notNull(loader)) {
thread.setContextClassLoader(loader);
}
}
/**
* Sets passed {@link ClassLoader} instance as current {@link Thread}'s
* context class loader
*
* @param loader
*/
public static void loadCurrentLibraries(ClassLoader loader) {
Thread thread = Thread.currentThread();
loadCurrentLibraries(thread, loader);
}
/**
* Adds {@link URL} array to system {@link ClassLoader} instance
*
* @param urls
* @param method
* @param urlLoader
* @throws IOException
*/
public static void loadURLToSystem(URL[] urls, Method method,
URLClassLoader urlLoader) throws IOException {
for (URL url : urls) {
MetaUtils.invokePrivate(method, urlLoader, url);
}
}
/**
* Loads all files and sub files {@link URL}s to system class loader
*
* @param libraryPath
* @throws IOException
*/
private static void loadLibraryFromPath(String libraryPath)
throws IOException {
File file = new File(libraryPath);
if (file.exists()) {
Set<URL> urls = new HashSet<URL>();
FileUtils.getSubfiles(file, urls);
URL[] paths = CollectionUtils.toArray(urls, URL.class);
ClassLoader systemLoader = ClassLoader.getSystemClassLoader();
if (systemLoader instanceof URLClassLoader) {
URLClassLoader urlLoader = (URLClassLoader) systemLoader;
Method method = getURLMethod();
if (ObjectUtils.notNull(method)) {
loadURLToSystem(paths, method, urlLoader);
}
}
}
}
/**
* Loads jar or <code>.class</code> files to the current thread from
* libraryPaths recursively
*
* @param libraryPaths
* @throws IOException
*/
public static void loadLibraries(String... libraryPaths) throws IOException {
if (CollectionUtils.valid(libraryPaths)) {
for (String libraryPath : libraryPaths) {
loadLibraryFromPath(libraryPath);
}
}
}
/**
* Loads passed classes to specified {@link ClassLoader} instance
*
* @param classes
* @param loader
*/
public static void loadClasses(Collection<String> classes,
ClassLoader loader) throws IOException {
if (CollectionUtils.valid(classes) && ObjectUtils.notNull(loader)) {
for (String className : classes) {
try {
loader.loadClass(className);
} catch (ClassNotFoundException ex) {
throw new IOException(ex);
}
}
}
}
/**
* Loads passed classes to specified current {@link Thread}'s context class
* loader
*
* @param classes
*/
public static void loadClasses(Collection<String> classes)
throws IOException {
ClassLoader loader = getContextClassLoader();
loadClasses(classes, loader);
}
/**
* Closes passed {@link ClassLoader} if it is instance of
* {@link URLClassLoader} class
*
* @param loader
* @throws IOException
*/
public static void closeClassLoader(ClassLoader loader) throws IOException {
if (ObjectUtils.notNull(loader) && loader instanceof URLClassLoader) {
try {
URLClassLoader urlClassLoader = ObjectUtils.cast(loader,
URLClassLoader.class);
urlClassLoader.clearAssertionStatus();
// Finds if loader associated class or superclass has "close"
// method
Class<?> loaderClass = loader.getClass();
boolean hasMethod = MetaUtils.hasPublicMethod(loaderClass,
CLOSE_METHOD_NAME);
if (hasMethod) {
urlClassLoader.close();
}
} catch (Throwable th) {
LOG.error(th.getMessage(), th);
}
}
}
}
|
package org.mycat.web.service;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.utils.ZKPaths;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.data.Stat;
import org.hx.rainbow.common.context.RainbowContext;
import org.hx.rainbow.common.core.service.BaseService;
import org.hx.rainbow.common.util.ObjectId;
//import org.mycat.web.ZkTestReadConfig;
import org.mycat.web.model.Menu;
import org.mycat.web.util.DataSourceUtils;
import org.mycat.web.util.MycatPathConstant;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSONObject;
@Lazy
@Service("zkConfigService")
public class ZkConfigService extends BaseService {
private static final String NAMESPACE = "SYSZOOKEEPER";
private static final String MENU_TYPE_ZONE = "1";
private static final String MENU_TYPE_CLUSTER_GROUP = "2";
private static final String MENU_TYPE_CLUSTER_NODE = "3";
private static final String MENU_TYPE_HOST_GROUP = "4";
private static final String MENU_TYPE_HOST_NODE = "5";
private static final String MENU_TYPE_PROJECT_GROUP = "6";
private static final String MENU_TYPE_PROJECT_NODE = "7";
private static final String MENU_TYPE_NODE = "8";
public RainbowContext query(RainbowContext context) {
//super.query(context, NAMESPACE);
String zkpath=(String)context.getAttr("zkpath");
String zkid=(String)context.getAttr("zkid");
String config=(String)context.getAttr("config");
List<String> configid=ZookeeperService.getInstance().getChilds(MycatPathConstant.MYCAT_NAME_SPACE+"/"+zkpath+"/"+zkid+"/"+config+"-config");
for(int i = 0; i < configid.size(); i++) {
Map<String, Object> attr = new HashMap<String, Object>();
attr.put("id", i);
attr.put("child", configid.get(i));
context.getRows().add(attr);
}
context.setMsg("OK!");
context.setSuccess(true);
return context;
}
private List<Map<String, Object>> getMmgrid(List<Map<String, Object>> mapList,String child){
List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
for (int i=0;i<mapList.size();i++){
//Iterator it = mapList.get(i).keySet().iterator();
int l=1;
for(Map.Entry<String, Object> entry:mapList.get(i).entrySet()) {
Map<String, Object> map=new HashMap<>();
map.put("name", l++);
map.put("param", entry.getKey());
map.put("value", entry.getValue());
rows.add(map);
}
}
return rows;
}
public RainbowContext queryChilds(RainbowContext context) throws Exception {
String zkpath=(String)context.getAttr("zkpath");
String zkid=(String)context.getAttr("zkid");
String config=(String)context.getAttr("config");
String ds=(String)context.getAttr("ds");
if (!(ds == null || ds.isEmpty())){
ds="/"+ds;
}
String childPath =ZKPaths.makePath(MycatPathConstant.MYCAT_NAME_SPACE+"/"+zkpath,"/"+zkid);
context.addRows(getMmgrid(ZookeeperService.getInstance().getNodeOrChildNodes(childPath,config+"-config",ds),ds));
//context.addRows(getMmgrid(ZookeeperService.getInstance().getNodeOrChildNodes(childPath+ds),ds));
context.setTotal(context.getRows().size());
context.setMsg("OK!");
context.setSuccess(true);
return context;
}
public synchronized RainbowContext insert(RainbowContext context) throws Exception {
String ip=(String)context.getAttr("ip");
String port=(String)context.getAttr("port");
if (ZookeeperService.getInstance().Connected(ip+":"+port)){
ZookeeperService.getInstance().UpdateZkConfig();
context.setMsg("!");
context.setSuccess(true);
return context;
}
else {
context.setMsg("!");
context.setSuccess(true);
return context;
}
}
public RainbowContext update(RainbowContext context) {
super.update(context, NAMESPACE);
context.getAttr().clear();
return context;
}
public RainbowContext delete(RainbowContext context) {
super.delete(context, NAMESPACE);
context.getAttr().clear();
return context;
}
public RainbowContext allZone(RainbowContext context){
if (ZookeeperService.getInstance().Connected()){
return zkConnectOK(context);
}
else {
return zkConnectFail(context);
}
}
private RainbowContext zkConnectFail(RainbowContext context){
List<Menu> menus =new ArrayList<Menu>();
Menu firstMenu4 = new Menu("1","","",MENU_TYPE_PROJECT_GROUP);
Menu firstMenu4Sub = new Menu("1_1","","page/zk/zkconfig.html",MENU_TYPE_NODE);
firstMenu4.getSubMenus().add(firstMenu4Sub);
menus.add(firstMenu4);
Map<String, Object> attr = new HashMap<String, Object>();
attr.put("menu", menus);
context.addRow(attr);
return context;
}
private RainbowContext zkConnectOK(RainbowContext context){
List<Menu> menus =new ArrayList<Menu>();
Menu mycatMenu= new Menu("1","Mycat-","",MENU_TYPE_PROJECT_GROUP);
Menu mycatMenuSub1= new Menu("1-1","mycat","page/manger/mycat.html",MENU_TYPE_NODE);
Menu mycatMenuSub2= new Menu("1-2","mycat-VM","page/manger/jmx.html",MENU_TYPE_NODE);
Menu mycatMenuSub3= new Menu("1-3","mycat","page/manger/sysparam.html",MENU_TYPE_NODE);
Menu mycatMenuSub4= new Menu("1-4","mycat","page/manger/syslog.html",MENU_TYPE_NODE);
Menu mycatMenuSub5= new Menu("1-5","Zookeeper","page/manger/zkread.html",MENU_TYPE_NODE);
mycatMenu.getSubMenus().add(mycatMenuSub1);
mycatMenu.getSubMenus().add(mycatMenuSub2);
mycatMenu.getSubMenus().add(mycatMenuSub3);
mycatMenu.getSubMenus().add(mycatMenuSub4);
mycatMenu.getSubMenus().add(mycatMenuSub5);
menus.add(mycatMenu);
Menu monitorMenu= new Menu("2","Mycat-","",MENU_TYPE_PROJECT_GROUP);
Menu monitorMenuSub1= new Menu("2-1","mycat","page/monitor/jrds.html",MENU_TYPE_NODE);
Menu monitorMenuSub2= new Menu("2-2","mycatJVM","page/monitor/jrdsjvm.html",MENU_TYPE_NODE);
Menu monitorMenuSub3= new Menu("2-3","mycat","page/monitor/datahostinfo.html",MENU_TYPE_NODE);
Menu monitorMenuSub4= new Menu("2-4","","page/monitor/masterslaveinfo.html",MENU_TYPE_NODE);
//Menu monitorMenuSub4= new Menu("2-4","","page/monitor/datahostinfo.html",MENU_TYPE_NODE);
//Menu monitorMenuSub5= new Menu("2-5","","page/monitor/masterslaveinfo.html",MENU_TYPE_NODE);
monitorMenu.getSubMenus().add(monitorMenuSub1);
monitorMenu.getSubMenus().add(monitorMenuSub2);
monitorMenu.getSubMenus().add(monitorMenuSub3);
monitorMenu.getSubMenus().add(monitorMenuSub4);
menus.add(monitorMenu);
Menu firstMenu4 = new Menu("4","SQL-","",MENU_TYPE_PROJECT_GROUP);
Menu firstMenu4Sub = new Menu("4_1","SQL","page/sql/sqltj.html",MENU_TYPE_NODE);
Menu firstMenu4Sub2 = new Menu("4_2","SQL","page/sql/sqltable.html",MENU_TYPE_NODE);
Menu firstMenu4Sub3 = new Menu("4_3","SQL","page/sql/sql.html",MENU_TYPE_NODE);
Menu firstMenu4Sub4 = new Menu("4_4","SQL","page/sql/sqlhigh.html",MENU_TYPE_NODE);
Menu firstMenu4Sub5= new Menu("4_5","SQL","page/sql/sqlslow.html",MENU_TYPE_NODE);
Menu firstMenu4Sub6 = new Menu("4_6","SQL","page/sql/sqlparse.html",MENU_TYPE_NODE);
firstMenu4.getSubMenus().add(firstMenu4Sub);
firstMenu4.getSubMenus().add(firstMenu4Sub2);
firstMenu4.getSubMenus().add(firstMenu4Sub3);
firstMenu4.getSubMenus().add(firstMenu4Sub4);
firstMenu4.getSubMenus().add(firstMenu4Sub5);
firstMenu4.getSubMenus().add(firstMenu4Sub6);
menus.add(firstMenu4);
Menu mycatzone=getMycatZoneMenu();
/* 2015-12-3 sohudo
Menu firstMenu5 = new Menu("5","MySQL Group1","",MENU_TYPE_PROJECT_GROUP);
Menu firstMenu5Sub1 = new Menu("5-1","MySQLGroup","page/manger/myrep.html",MENU_TYPE_NODE);
Menu firstMenu5Sub2 = new Menu("5-2","MySQL Server1","page/manger/mysql.html",MENU_TYPE_NODE);
firstMenu5.getSubMenus().add(firstMenu5Sub1);
firstMenu5.getSubMenus().add(firstMenu5Sub2);
//menus.add(firstMenu5);
mycatzone.getSubMenus().add(firstMenu5);
Menu firstMenu6 = new Menu("6","ZONE","",MENU_TYPE_PROJECT_GROUP);
Menu firstMenuSsubb1 = new Menu("6_1_1","Server","page/cluster/mycat_server_list.html",MENU_TYPE_CLUSTER_NODE);
Menu firstMenuSsuba1 = new Menu("6_1_1","cluster","page/cluster/mycat_cluster_list.html",MENU_TYPE_CLUSTER_NODE);
Menu firstMenuSsubb2 = new Menu("6_1_1","zone","page/cluster/mycat_zone_list.html",MENU_TYPE_CLUSTER_NODE);
firstMenu6.getSubMenus().add(firstMenuSsuba1);
firstMenu6.getSubMenus().add(firstMenuSsubb2);
firstMenu6.getSubMenus().add(firstMenuSsubb1);
menus.add(firstMenu6);
*/
/* 2015-12-3 sohudo
Menu firstMenuSub3 = new Menu("5_3","Mycat LB","",MENU_TYPE_HOST_GROUP);
Menu firstMenuSub3_1 = new Menu("5_3_1","LB Host1","",MENU_TYPE_HOST_NODE);
Menu firstMenuSub3_2 = new Menu("5_3_2","LB Host2","",MENU_TYPE_HOST_NODE);
firstMenuSub3.getSubMenus().add(firstMenuSub3_1);
firstMenuSub3.getSubMenus().add(firstMenuSub3_2);
mycatzone.getSubMenus().add(firstMenuSub3);
*/
menus.add(mycatzone);
//context.addAttr("menu",menus);
Map<String, Object> attr = new HashMap<String, Object>();
attr.put("menu", menus);
context.addRow(attr);
return context;
}
private Menu getMycatZoneMenu(){
Menu mycatZone = new Menu("5","Mycat Zone","",MENU_TYPE_ZONE);
List<String> cluster=ZookeeperService.getInstance().getChilds("/");
if (cluster!=null){
for(int i = 0; i < cluster.size(); i++) {
if (!cluster.get(i).equals("mycat-eye")){
Menu clusterMenu = new Menu("5."+i,cluster.get(i),"",MENU_TYPE_CLUSTER_GROUP);
List<String> mycatid=ZookeeperService.getInstance().getChilds("/"+cluster.get(i));
if (mycatid!=null){
for(int j = 0; j < mycatid.size(); j++) {
Menu mycatMenu = new Menu("5."+i+j,mycatid.get(j),"page/zk/zkread.html?zkpath="+cluster.get(i)+"&zkid="+mycatid.get(j),MENU_TYPE_NODE);
/*
List<String> configid=ZookeeperService.getInstance().getChilds(CONFIG_MYCAT_ZONE+"/"+cluster.get(i)+"/"+mycatid.get(i));
if (configid!=null){
for(int m = 0; m < configid.size(); m++) {
Menu configMenu = new Menu("5."+i+j+m,"Mycat"+configid.get(m),"page/zk/zkread.html?zkpath="+cluster.get(i)+"&zkid="+mycatid.get(i),MENU_TYPE_CLUSTER_NODE);
mycatMenu.getSubMenus().add(configMenu);
}
}
*/
clusterMenu.getSubMenus().add(mycatMenu);
}
}
mycatZone.getSubMenus().add(clusterMenu);
}
}
}
return mycatZone;
}
public RainbowContext getZkconfig(RainbowContext context) throws Exception {
String cluster = (String)context.getAttr("ds");
try {
if(cluster==null){
context.setSuccess(false);
context.setMsg("!");
return context;
}
} catch (Exception e) {
}
RainbowContext query = new RainbowContext();
context.getAttr().clear();
//ZkTestReadConfig.readZkinfo(context,ZookeeperService.getInstance().getZookeeper(),"/"+cluster);
return context;
}
}
|
package org.schors.vertx.telegram;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpClientRequest;
import org.telegram.telegrambots.Constants;
import org.telegram.telegrambots.api.methods.BotApiMethod;
import org.telegram.telegrambots.api.methods.send.SendChatAction;
import org.telegram.telegrambots.api.methods.send.SendDocument;
import org.telegram.telegrambots.api.methods.send.SendMessage;
import java.io.File;
public class TelegramBot {
private Vertx vertx;
private HttpClient client;
private TelegramOptions botOptions;
private UpdateReceiver receiver;
public TelegramBot(Vertx vertx, TelegramOptions options) {
this.vertx = vertx;
this.botOptions = options;
HttpClientOptions httpOptions = new HttpClientOptions()
// .setKeepAlive(true)
.setSsl(true)
// .setOpenSslEngineOptions(new OpenSSLEngineOptions())
// .setUseAlpn(true)
.setTrustAll(true)
.setIdleTimeout(this.getOptions().getPollingTimeout())
.setMaxPoolSize(this.getOptions().getMaxConnections())
.setDefaultHost(Constants.BASEHOST)
.setDefaultPort(443)
.setLogActivity(true);
if (options.getProxyOptions() != null)
httpOptions.setProxyOptions(options.getProxyOptions());
client = vertx.createHttpClient(httpOptions);
}
public static TelegramBot create(Vertx vertx) {
return create(vertx, new TelegramOptions());
}
public static TelegramBot create(Vertx vertx, TelegramOptions options) {
return new TelegramBot(vertx, options);
}
public TelegramBot receiver(UpdateReceiver updateReceiver) {
this.receiver = updateReceiver;
updateReceiver.bot(this);
return this;
}
public TelegramBot start() {
receiver.start();
return this;
}
public TelegramBot stop() {
receiver.stop();
return this;
}
public Vertx getVertx() {
return vertx;
}
public TelegramOptions getOptions() {
return botOptions;
}
public HttpClient getClient() {
return client;
}
private void send(BotApiMethod message) {
client
.post(Constants.BASEURL + getOptions().getBotToken() + "/" + message.getPath())
.handler(response -> {
response.bodyHandler(event -> {
});
})
.exceptionHandler(e -> {
})
.setTimeout(75000)
.putHeader("Content-Type", "application/json")
.end(message.toJson().encode(), "UTF-8");
}
public void sendMessage(SendMessage message) {
send(message);
}
public void sendChatAction(SendChatAction chatAction) {
send(chatAction);
}
public void sendDocument(SendDocument document) {
vertx.executeBlocking(future -> {
HttpClientRequest request = client
.post(Constants.BASEURL + getOptions().getBotToken() + "/" + SendDocument.PATH)
.handler(response -> {
response.bodyHandler(event -> {
});
})
.exceptionHandler(e -> {
})
.setTimeout(75000)
.setChunked(true);
MultipartHelper multipartHelper = new MultipartHelper(request)
.start()
.putTextBody(SendDocument.CHATID_FIELD, document.getChatId())
.putBinaryBody(SendDocument.DOCUMENT_FIELD, new File(document.getDocument()), "application/octet-stream", document.getDocumentName());
if (document.getReplyMarkup() != null) {
multipartHelper.putTextBody(SendDocument.REPLYMARKUP_FIELD, document.getReplyMarkup().toJson().encode());
}
if (document.getReplyToMessageId() != null) {
multipartHelper.putTextBody(SendDocument.REPLYTOMESSAGEID_FIELD, document.getReplyToMessageId().toString());
}
if (document.getCaption() != null) {
multipartHelper.putTextBody(SendDocument.CAPTION_FIELD, document.getCaption());
}
if (document.getDisableNotification() != null) {
multipartHelper.putTextBody(SendDocument.DISABLENOTIFICATION_FIELD, document.getDisableNotification().toString());
}
multipartHelper.stop();
request.end();
}, event -> {
});
}
}
|
package org.skyscreamer.jsonassert;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.skyscreamer.jsonassert.comparator.JSONComparator;
public class JSONAssert {
private JSONAssert() {}
/**
* Asserts that the JSONObject provided matches the expected string. If it isn't it throws an
* {@link AssertionError}.
*
* @param expectedStr Expected JSON string
* @param actual JSONObject to compare
* @param strict Enables strict checking
* @throws JSONException
*/
public static void assertEquals(String expectedStr, JSONObject actual, boolean strict)
throws JSONException {
assertEquals(expectedStr, actual, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
}
/**
* Asserts that the JSONObject provided does not match the expected string. If it is it throws an
* {@link AssertionError}.
*
* @see #assertEquals(String, JSONObject, boolean)
*
* @param expectedStr Expected JSON string
* @param actual JSONObject to compare
* @param strict Enables strict checking
* @throws JSONException
*/
public static void assertNotEquals(String expectedStr, JSONObject actual, boolean strict)
throws JSONException {
assertNotEquals(expectedStr, actual, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
}
/**
* Asserts that the JSONObject provided matches the expected string. If it isn't it throws an
* {@link AssertionError}.
*
* @param expectedStr Expected JSON string
* @param actual JSONObject to compare
* @param compareMode Specifies which comparison mode to use
* @throws JSONException
*/
public static void assertEquals(String expectedStr, JSONObject actual, JSONCompareMode compareMode)
throws JSONException {
Object expected = JSONParser.parseJSON(expectedStr);
if (expected instanceof JSONObject) {
assertEquals((JSONObject)expected, actual, compareMode);
}
else {
throw new AssertionError("Expecting a JSON array, but passing in a JSON object");
}
}
/**
* Asserts that the JSONObject provided does not match the expected string. If it is it throws an
* {@link AssertionError}.
*
* @see #assertEquals(String, JSONObject, JSONCompareMode)
*
* @param expectedStr Expected JSON string
* @param actual JSONObject to compare
* @param compareMode Specifies which comparison mode to use
* @throws JSONException
*/
public static void assertNotEquals(String expectedStr, JSONObject actual, JSONCompareMode compareMode)
throws JSONException {
Object expected = JSONParser.parseJSON(expectedStr);
if (expected instanceof JSONObject) {
assertNotEquals((JSONObject) expected, actual, compareMode);
}
else {
throw new AssertionError("Expecting a JSON array, but passing in a JSON object");
}
}
/**
* Asserts that the JSONArray provided matches the expected string. If it isn't it throws an
* {@link AssertionError}.
*
* @param expectedStr Expected JSON string
* @param actual JSONArray to compare
* @param strict Enables strict checking
* @throws JSONException
*/
public static void assertEquals(String expectedStr, JSONArray actual, boolean strict)
throws JSONException {
assertEquals(expectedStr, actual, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
}
/**
* Asserts that the JSONArray provided does not match the expected string. If it is it throws an
* {@link AssertionError}.
*
* @param expectedStr Expected JSON string
* @param actual JSONArray to compare
* @param strict Enables strict checking
* @throws JSONException
*/
public static void assertNotEquals(String expectedStr, JSONArray actual, boolean strict)
throws JSONException {
assertNotEquals(expectedStr, actual, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
}
/**
* Asserts that the JSONArray provided matches the expected string. If it isn't it throws an
* {@link AssertionError}.
*
* @param expectedStr Expected JSON string
* @param actual JSONArray to compare
* @param compareMode Specifies which comparison mode to use
* @throws JSONException
*/
public static void assertEquals(String expectedStr, JSONArray actual, JSONCompareMode compareMode)
throws JSONException {
Object expected = JSONParser.parseJSON(expectedStr);
if (expected instanceof JSONArray) {
assertEquals((JSONArray) expected, actual, compareMode);
}
else {
throw new AssertionError("Expecting a JSON object, but passing in a JSON array");
}
}
/**
* Asserts that the JSONArray provided does not match the expected string. If it is it throws an
* {@link AssertionError}.
*
* @param expectedStr Expected JSON string
* @param actual JSONArray to compare
* @param compareMode Specifies which comparison mode to use
* @throws JSONException
*/
public static void assertNotEquals(String expectedStr, JSONArray actual, JSONCompareMode compareMode)
throws JSONException {
Object expected = JSONParser.parseJSON(expectedStr);
if (expected instanceof JSONArray) {
assertNotEquals((JSONArray) expected, actual, compareMode);
}
else {
throw new AssertionError("Expecting a JSON object, but passing in a JSON array");
}
}
/**
* Asserts that the JSONArray provided matches the expected string. If it isn't it throws an
* {@link AssertionError}.
*
* @param expectedStr Expected JSON string
* @param actualStr String to compare
* @param strict Enables strict checking
* @throws JSONException
*/
public static void assertEquals(String expectedStr, String actualStr, boolean strict)
throws JSONException {
assertEquals(expectedStr, actualStr, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
}
/**
* Asserts that the JSONArray provided does not match the expected string. If it is it throws an
* {@link AssertionError}.
*
* @param expectedStr Expected JSON string
* @param actualStr String to compare
* @param strict Enables strict checking
* @throws JSONException
*/
public static void assertNotEquals(String expectedStr, String actualStr, boolean strict)
throws JSONException {
assertNotEquals(expectedStr, actualStr, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
}
/**
* Asserts that the JSONArray provided matches the expected string. If it isn't it throws an
* {@link AssertionError}.
*
* @param expectedStr Expected JSON string
* @param actualStr String to compare
* @param compareMode Specifies which comparison mode to use
* @throws JSONException
*/
public static void assertEquals(String expectedStr, String actualStr, JSONCompareMode compareMode)
throws JSONException {
if (expectedStr==actualStr) return;
if (expectedStr==null){
throw new AssertionError("Expected string is null.");
}else if (actualStr==null){
throw new AssertionError("Actual string is null.");
}
JSONCompareResult result = JSONCompare.compareJSON(expectedStr, actualStr, compareMode);
if (result.failed()) {
throw new AssertionError(result.getMessage());
}
}
/**
* Asserts that the JSONArray provided does not match the expected string. If it is it throws an
* {@link AssertionError}.
*
* @param expectedStr Expected JSON string
* @param actualStr String to compare
* @param compareMode Specifies which comparison mode to use
* @throws JSONException
*/
public static void assertNotEquals(String expectedStr, String actualStr, JSONCompareMode compareMode)
throws JSONException {
JSONCompareResult result = JSONCompare.compareJSON(expectedStr, actualStr, compareMode);
if (result.passed()) {
throw new AssertionError(result.getMessage());
}
}
/**
* Asserts that the json string provided matches the expected string. If it isn't it throws an
* {@link AssertionError}.
*
* @param expectedStr Expected JSON string
* @param actualStr String to compare
* @param comparator Comparator
* @throws JSONException
*/
public static void assertEquals(String expectedStr, String actualStr, JSONComparator comparator)
throws JSONException {
JSONCompareResult result = JSONCompare.compareJSON(expectedStr, actualStr, comparator);
if (result.failed()) {
throw new AssertionError(result.getMessage());
}
}
/**
* Asserts that the json string provided does not match the expected string. If it is it throws an
* {@link AssertionError}.
*
* @param expectedStr Expected JSON string
* @param actualStr String to compare
* @param comparator Comparator
* @throws JSONException
*/
public static void assertNotEquals(String expectedStr, String actualStr, JSONComparator comparator)
throws JSONException {
JSONCompareResult result = JSONCompare.compareJSON(expectedStr, actualStr, comparator);
if (result.passed()) {
throw new AssertionError(result.getMessage());
}
}
/**
* Asserts that the JSONObject provided matches the expected JSONObject. If it isn't it throws an
* {@link AssertionError}.
*
* @param expected Expected JSONObject
* @param actual JSONObject to compare
* @param strict Enables strict checking
* @throws JSONException
*/
public static void assertEquals(JSONObject expected, JSONObject actual, boolean strict)
throws JSONException {
assertEquals(expected, actual, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
}
/**
* Asserts that the JSONObject provided does not match the expected JSONObject. If it is it throws an
* {@link AssertionError}.
*
* @param expected Expected JSONObject
* @param actual JSONObject to compare
* @param strict Enables strict checking
* @throws JSONException
*/
public static void assertNotEquals(JSONObject expected, JSONObject actual, boolean strict)
throws JSONException {
assertNotEquals(expected, actual, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
}
/**
* Asserts that the JSONObject provided matches the expected JSONObject. If it isn't it throws an
* {@link AssertionError}.
*
* @param expected Expected JSONObject
* @param actual JSONObject to compare
* @param compareMode Specifies which comparison mode to use
* @throws JSONException
*/
public static void assertEquals(JSONObject expected, JSONObject actual, JSONCompareMode compareMode)
throws JSONException
{
JSONCompareResult result = JSONCompare.compareJSON(expected, actual, compareMode);
if (result.failed()) {
throw new AssertionError(result.getMessage());
}
}
/**
* Asserts that the JSONObject provided does not match the expected JSONObject. If it is it throws an
* {@link AssertionError}.
*
* @param expected Expected JSONObject
* @param actual JSONObject to compare
* @param compareMode Specifies which comparison mode to use
* @throws JSONException
*/
public static void assertNotEquals(JSONObject expected, JSONObject actual, JSONCompareMode compareMode)
throws JSONException
{
JSONCompareResult result = JSONCompare.compareJSON(expected, actual, compareMode);
if (result.passed()) {
throw new AssertionError(result.getMessage());
}
}
/**
* Asserts that the JSONArray provided matches the expected JSONArray. If it isn't it throws an
* {@link AssertionError}.
*
* @param expected Expected JSONArray
* @param actual JSONArray to compare
* @param strict Enables strict checking
* @throws JSONException
*/
public static void assertEquals(JSONArray expected, JSONArray actual, boolean strict)
throws JSONException {
assertEquals(expected, actual, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
}
/**
* Asserts that the JSONArray provided does not match the expected JSONArray. If it is it throws an
* {@link AssertionError}.
*
* @param expected Expected JSONArray
* @param actual JSONArray to compare
* @param strict Enables strict checking
* @throws JSONException
*/
public static void assertNotEquals(JSONArray expected, JSONArray actual, boolean strict)
throws JSONException {
assertNotEquals(expected, actual, strict ? JSONCompareMode.STRICT : JSONCompareMode.LENIENT);
}
/**
* Asserts that the JSONArray provided matches the expected JSONArray. If it isn't it throws an
* {@link AssertionError}.
*
* @param expected Expected JSONArray
* @param actual JSONArray to compare
* @param compareMode Specifies which comparison mode to use
* @throws JSONException
*/
public static void assertEquals(JSONArray expected, JSONArray actual, JSONCompareMode compareMode)
throws JSONException {
JSONCompareResult result = JSONCompare.compareJSON(expected, actual, compareMode);
if (result.failed()) {
throw new AssertionError(result.getMessage());
}
}
/**
* Asserts that the JSONArray provided does not match the expected JSONArray. If it is it throws an
* {@link AssertionError}.
*
* @param expected Expected JSONArray
* @param actual JSONArray to compare
* @param compareMode Specifies which comparison mode to use
* @throws JSONException
*/
public static void assertNotEquals(JSONArray expected, JSONArray actual, JSONCompareMode compareMode)
throws JSONException {
JSONCompareResult result = JSONCompare.compareJSON(expected, actual, compareMode);
if (result.passed()) {
throw new AssertionError(result.getMessage());
}
}
}
|
package org.testeditor.fixture.web;
import java.io.File;
import java.text.MessageFormat;
import java.util.List;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.Select;
import org.testeditor.fixture.core.elementlist.ElementListService;
import org.testeditor.fixture.core.exceptions.ElementKeyNotFoundException;
import org.testeditor.fixture.core.exceptions.StopTestException;
import org.testeditor.fixture.core.interaction.StoppableFixture;
import org.testeditor.fixture.core.utils.ExceptionUtils;
import org.testeditor.fixture.core.utils.StringUtils;
/**
* Provides methods for basic Web GUI-testing like click on type input. Projects
* may inherit from this generic fixture and could use the protected methods for
* any extensions.
*/
public class WebFixture implements StoppableFixture {
protected static final String LINUX = "Linux";
protected static final String MAC_OS = "Mac OS";
protected static final String WINDOWS = "Windows";
private static final Logger LOGGER = Logger.getLogger(WebFixture.class);
private Integer waitInMillis = 250;
private Integer waitCounter = 100;
private ElementListService elementListService;
protected WebDriver webDriver;
private int timeout;
/**
* Creates the element list instance representing the GUI-Map for widget
* element id's of an application and the user defined names for this
* represented GUI element. Often used in a FitNesse ScenarioLibrary for
* configuration purpose. <br />
*
* FitNesse usage..: |set elementlist|arg1| <br/>
* FitNesse example: |set elementlist|../ElementList/content.txt| <br />
* <br />
*
* @param elementList
* relative path of the element list content.txt wiki site on a
* FitNesse Server where WikiPages is the directory where all the
* Wiki Sites of the recent project are
*/
public void setElementlist(String elementList) {
elementListService = ElementListService.instanceFor(elementList);
}
/**
* @return the elementListService
*/
protected ElementListService getElementlist() {
return elementListService;
}
/**
* @return the webDriver
*/
protected WebDriver getWebDriver() {
return webDriver;
}
/**
* The value is used by the Method waitForElement.
*
* @param waitInMillis
* the waitInMillis to set
*/
public void setWaitInMillis(Integer waitInMillis) {
this.waitInMillis = waitInMillis;
}
/**
* @return the waitInMillis as an {@link Integer}
*/
protected Integer getWaitInMillis() {
return waitInMillis;
}
/**
* The value is used by the Method waitForElement.
*
* @param waitCounter
* the waitCounter to set
*/
public void setWaitCounter(Integer waitCounter) {
this.waitCounter = waitCounter;
}
/**
* @return the waitCounter
*/
protected Integer getWaitCounter() {
return waitCounter;
}
/**
* Opens a specific browser (e.g. Firefox, Google-Chrome or Microsoft
* Internet Explorer), it is possible to use 'firefox', 'chrome' or 'ie' as
* the browserName. <br />
*
* FitNesse usage..: |open Browser|arg1| <br />
* FitNesse example: |open Browser|firefox| <br />
* <br />
*
* Please note that for Firefox there is a system property
* 'webdriver.firefox.bin' which should be set to the path of the used
* browser.
*
* @param browserName
* name of browser ('ie', 'chrome' or 'firefox')
* @param browserPath
* path to the browser
* @return true, if browser starts successful, otherwise false
*/
public boolean openBrowser(String browserName, String browserPath) {
String osName = System.getProperty("os.name");
LOGGER.debug("open browser IN PROCESS - operating System: " + osName + ", browserName: " + browserName);
try {
if ("firefox".equalsIgnoreCase(browserName)) {
openFirefox(osName, browserPath);
} else if ("ie".equalsIgnoreCase(browserName)) {
DesiredCapabilities cap = DesiredCapabilities.internetExplorer();
cap.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, "true");
webDriver = new InternetExplorerDriver(cap);
} else if ("chrome".equalsIgnoreCase(browserName)) {
System.setProperty("webdriver.chrome.driver", browserPath);
webDriver = new ChromeDriver();
} else {
String logMessage = "browser '" + browserName + " not available";
LOGGER.error(logMessage);
throw new StopTestException(logMessage);
}
} catch (WebDriverException e) {
// here will be thrown an exception if installed browser was not
// found
LOGGER.error(e.getMessage(), e);
throw new StopTestException(e.getMessage());
}
return true;
}
/**
* Helper method for openBrowser which handles the specifics to open
* Firefox.
*
* @param osName
* the name of the OS (should contain "Windows", "Mac OS" or
* "Linux")
* @param browserPath
* path to the (portable) Firefox executable to be started
*/
private void openFirefox(String osName, String browserPath) {
try {
if (browserPath != null && !browserPath.equals("")) {
if (osName.contains(WINDOWS)) {
System.setProperty("webdriver.firefox.bin", browserPath);
} else if (osName.contains(LINUX)) {
System.setProperty("webdriver.firefox.bin", browserPath);
System.setProperty("webdriver.firefox.profile", "testing");
} else if (osName.contains(MAC_OS)) {
System.setProperty("webdriver.firefox.bin", browserPath);
}
// check if given browser path exists
// and throw an exception if not exists
if (!(new File(browserPath)).exists()) {
String logMessage = "browserPath '" + browserPath + " does not exist";
LOGGER.error(logMessage);
throw new StopTestException(logMessage);
}
}
webDriver = new FirefoxDriver();
} catch (WebDriverException e) {
// here will be thrown an exception if installed browser was not
// found
LOGGER.error(e.getMessage(), e);
throw new StopTestException(e.getMessage());
}
}
public boolean navigateToUrl(String url) {
webDriver.get(url);
return true;
}
/**
* Checks if a given value is empty (i.e. a <code>null</code>-value or an
* empty string.
*
* FitNesse usage..: |assert|arg1|is empty| <br />
* FitNesse example: |assert|Some Text|is empty| <br />
* <br />
*
* @param value
* the value to compare
* @return <code>true</code> if <code>value</code> is an empty string,
* <code>false</code> otherwise
*/
public boolean assertIsEmpty(String value) {
boolean result = false;
if (value == null || value.trim().isEmpty()) {
result = true;
}
return result;
}
/**
* Checks if a given value is not empty (i.e. not a <code>null</code>-value
* or an empty string.
*
* FitNesse usage..: |assert|arg1|is not empty| <br />
* FitNesse example: |assert|Some Text|is not empty| <br />
* <br />
*
* @param value
* the value to compare
* @return <code>true</code> if <code>value</code> is not an empty string,
* <code>false</code> otherwise
*/
public boolean assertIsNotEmpty(String value) {
return !assertIsEmpty(value);
}
/**
* Compares a given value with another value for equality.
*
* FitNesse usage..: |assert|arg1|is equal to|arg2| <br />
* FitNesse example: |assert|Some Text|is equal to|Some Other Text| <br />
* <br />
*
* @param first
* the first value to compare
* @param second
* the second value to compare
* @return <code>true</code> if <code>first</code> is equal to
* <code>second</code>, <code>false</code> otherwise
*/
public boolean assertIsEqualTo(String first, String second) {
boolean result = false;
if (first == null && second == null) {
result = true;
} else if (first != null && second != null && (first.trim()).equals(second.trim())) {
result = true;
}
return result;
}
/**
* Compares a given value with another value for inequality.
*
* FitNesse usage..: |assert|arg1|is not equal to|arg2| <br />
* FitNesse example: |assert|Some Text|is not equal to|Some Other Text| <br />
* <br />
*
* @param first
* the first value to compare
* @param second
* the second value to compare
* @return <code>true</code> if <code>first</code> is not equal to
* <code>second</code>, <code>false</code> otherwise
*/
public boolean assertIsNotEqualTo(String first, String second) {
return !assertIsEqualTo(first, second);
}
/**
* Checks if a given string is found within another string.
*
* FitNesse usage..: |assert|arg1|contains|arg2| <br />
* FitNesse example: |assert|Some Text|contains|me Te| <br />
* <br />
*
* @param first
* the string to analyze
* @param second
* the string to be found within <code>first</code>
* @return <code>true</code> if <code>first</code> contains
* <code>second</code>, <code>false</code> otherwise
*/
public boolean assertContains(String first, String second) {
boolean result = false;
if (first == null && second == null) {
result = true;
} else if (first != null && second != null && first.contains(second.trim())) {
result = true;
}
return result;
}
/**
* Searches elements using XPath from the element list. This test asserts,
* that the XPath query yields at least one hit.<br />
* <br />
*
* FitNesse usage..: |assert element|arg1|found|[arg2, arg3, ...]| <br />
* FitNesse example: |assert element|TextboxInRow{0}Col{1}|found|[5, 3]| <br />
* <br />
*
* @param elementListKey
* key to find the technical locator
* @param replaceArgs
* values to replace the place holders in the element list entry
* with
* @return true, if at least one element matches the XPath query; false
* otherwise.
*/
public boolean assertElementFound(String elementListKey, String... replaceArgs) {
boolean result = false;
WebElement element = findWebelement(elementListKey, replaceArgs);
if (element != null) {
result = true;
}
return result;
}
/**
* Searches elements by key from the element list. This method asserts, that
* the element does not exists.
*
* FitNesse usage..: |assert element|arg1|not found|[arg2, arg3, ...]| <br />
* FitNesse example: |assert element|TextboxInRow{0}Col{1}|not found|[5, 3]| <br />
* <br />
*
* @param elementListKey
* key to find the technical locator
* @param replaceArgs
* values to replace the place holders in the element list entry
* with
* @return true, if no elements with the given key exists; false otherwise.
*/
public boolean assertElementNotFound(String elementListKey, String... replaceArgs) {
boolean result = false;
Integer waitCounterOriginalValue = waitCounter;
// If the target element cannot be found, don't wait too.
waitCounter = 2;
try {
// If no exception is thrown, then the target element was found...
WebElement element = findWebelement(elementListKey, false, replaceArgs);
if (element == null) {
result = true;
}
} catch (TimeoutException e) {
// Search for the target element timed out, which is exactly what we
// wanted. In this case the exception will be silently discarded and
// the result of this method is true.
result = true;
}
// Restore the original timeout wait counter.
waitCounter = waitCounterOriginalValue;
return result;
}
public boolean enterSpecialKey(String key) {
boolean result = false;
Keys seleniumKey = Keys.NULL;
try {
seleniumKey = Keys.valueOf(key.toUpperCase());
} catch (IllegalArgumentException e) {
String message = "The specified key \"" + key
+ "\" is invalid and could not be found in selenium enum Keys!";
LOGGER.error(message, e);
throw new StopTestException(message);
}
Actions action = new Actions(webDriver);
action.sendKeys(seleniumKey).build().perform();
result = true;
return result;
}
/**
* Finds a textbox by its Element List key and gets its value. <br />
* <br />
*
* FitNesse usage..: |$var=|read textbox;|arg1|[arg2, arg3, ...]| <br />
* FitNesse example: |$result=|read textbox;|TextboxInRow{0}Col{1}|[5, 3]| <br />
* <br />
*
* @param elementListKey
* key to find the technical locator
* @param replaceArgs
* values to replace the place holders in the element list entry
* with
* @return the value of the target element; empty String, if the element
* could not be found or is not visible (i.e. hidden using CSS,
* etc.).
*/
public String readTextbox(String elementListKey, String... replaceArgs) {
return readAttributeFromField("value", elementListKey, replaceArgs);
}
/**
* Finds a combobox by its Element List key and gets its value. <br />
* <br />
*
* FitNesse usage..: |$var=|read combobox;|arg1|[arg2, arg3, ...]| <br />
* FitNesse example: |$result=|read combobox;|ComboboxInRow{0}Col{1}|[5, 3]| <br />
* <br />
*
* @param elementListKey
* key to find the technical locator
* @param replaceArgs
* values to replace the place holders in the element list entry
* with
* @return the value of the target element; empty String, if the element
* could not be found or is not visible (i.e. hidden using CSS,
* etc.).
*/
public String readCombobox(String elementListKey, String... replaceArgs) {
return readAttributeFromField("value", elementListKey, replaceArgs);
}
/**
* Finds a checkbox by its Element List key and gets its value. <br />
* <br />
*
* FitNesse usage..: |$var=|read checkbox;|arg1|[arg2, arg3, ...]| <br />
* FitNesse example: |$result=|read checkbox;|CheckboxInRow{0}Col{1}|[5, 3]| <br />
* <br />
*
* @param elementListKey
* key to find the technical locator
* @param replaceArgs
* values to replace the place holders in the element list entry
* with
* @return true, if the target element is checked; false, if the element is
* not checked or the element could not be found or is not visible
* (i.e. hidden using CSS, etc.).
*/
public boolean readCheckbox(String elementListKey, String... replaceArgs) {
boolean result = false;
WebElement element = findWebelement(elementListKey, replaceArgs);
if (element != null && element.isDisplayed()) {
result = element.isSelected();
}
return result;
}
/**
* Finds an element by its Element List key and gets the value of an
* associated attribute (e.g. <code>"value"</code> or
* <code>"innerText"</code> ). <br />
* <br />
*
* FitNesse usage..: |$var=|read attribute|arg1|from field;|arg2|[arg3,
* arg4, ...]| <br />
* FitNesse example: |$result=|read attribute|value|from
* field;|CheckboxInRow{0}Col{1}|[5, 3]| <br />
* <br />
*
* @param attribute
* the attribute to get from the target element
* @param elementListKey
* key to find the technical locator
* @param replaceArgs
* values to replace the place holders in the element list entry
* with
* @return the value associated with the given <code>attribute</code> of the
* target element; empty String, if the element could not be found
* or is not visible (i.e. hidden using CSS, etc.).
*/
public String readAttributeFromField(String attribute, String elementListKey, String... replaceArgs) {
String result = privateReadAttributeFromField(attribute, elementListKey, replaceArgs);
return result;
}
/**
*
* @param attribute
* the attribute to get from the target element
* @param elementListKey
* key to find the technical locator
* @param replaceArgs
* values to replace the place holders in the element list entry
* with
* @return the value associated with the given <code>attribute</code> of the
* target element; empty String, if the element could not be found
* or is not visible (i.e. hidden using CSS, etc.).
*/
private String privateReadAttributeFromField(String attribute, String elementListKey, String... replaceArgs) {
String result = "";
WebElement element = findWebelement(elementListKey, replaceArgs);
if (element != null && element.isDisplayed()) {
if (attribute.equalsIgnoreCase("innertext")) {
result = element.getText();
} else {
result = element.getAttribute(attribute);
}
}
return result;
}
/**
* Inserts the given value into an input field and checks if input was
* successful. The technical locator of the field gets identified by the
* element list matching the given key. <br />
*
* FitNesse usage..: |insert|arg1|into field;|arg2|[arg3, arg4, ...]| <br />
* FitNesse example: |insert|Some Text|into field;|TextboxInRow{0}Col{1}|[5,
* 3]| <br />
* <br />
*
* @param elementListKey
* key to find the technical locator
* @param value
* value for the input
* @param replaceArgs
* values to replace the place holders in the element list entry
* with
* @return true if input was successful, otherwise false
*/
public boolean insertIntoField(String value, String elementListKey, String... replaceArgs) {
boolean result = false;
WebElement element = findWebelement(elementListKey, replaceArgs);
if (element != null && element.isDisplayed()) {
element.click();
element.sendKeys(value);
String expectedValue = null;
if (element.getTagName().equalsIgnoreCase("select")) {
Select s = new Select(element);
expectedValue = s.getFirstSelectedOption().getText();
} else {
expectedValue = readAttributeFromField("value", elementListKey, replaceArgs);
}
if (assertIsEqualTo(value, expectedValue)) {
result = true;
} else {
throw new StopTestException("Value wasn't inserted correctly");
}
}
return result;
}
/**
* Works just like
* <code>insertIntoField(value, elementListKey, replaceArgs)</code> except
* the argument <code>replaceArgs</code> is always an empty array.
*
* @param elementListKey
* key to find the technical locator
* @param value
* value for the input
* @return true if input was successful, otherwise false
*/
public boolean insertIntoField(String value, String elementListKey) {
return insertIntoField(value, elementListKey, new String[] {});
}
/**
* Clears a given input field. The technical locator of the field gets
* identified by the element list matching the given key.<br />
*
* FitNesse usage..: |clear;|arg1|[arg2, arg3, ...]| <br />
* FitNesse example: |clear;|TextboxInRow{0}Col{1}|[5, 3]| <br />
* <br />
*
* @param elementListKey
* key to find the technical locator
* @param replaceArgs
* values to replace the place holders in the element list entry
* with
* @return true if clear was successful, otherwise false
*/
public boolean clear(String elementListKey, String... replaceArgs) {
boolean result = false;
WebElement element = findWebelement(elementListKey, replaceArgs);
if (element != null && element.isDisplayed()) {
element.clear();
result = true;
}
return result;
}
/**
* Works just like <code>clear(elementListKey, replaceArgs)</code> except
* the argument <code>replaceArgs</code> is always an empty array.
*
* @param elementListKey
* key to find the technical locator
* @return true if clear was successful, otherwise false
*/
public boolean clear(String elementListKey) {
return clear(elementListKey, new String[] {});
}
/**
* Checks if a given input field is enabled (i.e. editable). The technical
* locator of the field gets identified by the element list matching the
* given key.<br />
*
* FitNesse usage..: |assert element|arg1|enabled|[arg2, arg3, ...]| <br />
* FitNesse example: |assert element|TextboxInRow{0}Col{1}|enabled|[5, 3]| <br />
* <br />
*
* @param elementListKey
* key to find the technical locator
* @param replaceArgs
* values to replace the place holders in the element list entry
* with
* @return true if the field is enabled, otherwise false
*/
public boolean assertElementEnabled(String elementListKey, String... replaceArgs) {
boolean result = false;
WebElement element = findWebelement(elementListKey, replaceArgs);
if (element != null && element.isDisplayed() && element.isEnabled()) {
result = true;
}
return result;
}
/**
* Checks if a given input field is not enabled (i.e. not editable). The
* technical locator of the field gets identified by the element list
* matching the given key.<br />
*
* FitNesse usage..: |assert element|arg1|disabled|[arg2, arg3, ...]| <br />
* FitNesse example: |assert element|TextboxInRow{0}Col{1}|disabled|[5, 3]| <br />
* <br />
*
* @param elementListKey
* key to find the technical locator
* @param replaceArgs
* values to replace the place holders in the element list entry
* with
* @return true if the field is not enabled, otherwise false
*/
public boolean assertElementDisabled(String elementListKey, String... replaceArgs) {
return !assertElementEnabled(elementListKey, replaceArgs);
}
/**
* Waits for the given period of time before executing the next command.<br />
*
* FitNesse usage..: |wait seconds|arg1| <br />
* FitNesse example: |wait seconds|2| <br />
* <br />
*
* @param timeToWait
* Time to wait in seconds
* @return always true to show inside FitNesse a positive result
*/
public boolean waitSeconds(long timeToWait) {
waitTime(timeToWait * 1000);
return true;
}
/**
* Waits for the given period.
*
* @param milliseconds
* Time to wait in milliseconds
*/
protected void waitTime(long milliseconds) {
try {
Thread.sleep(milliseconds);
} catch (InterruptedException e) {
LOGGER.error(e.getMessage());
}
}
/**
* Clicks on a element or button. <br />
* <br />
*
* FitNesse usage..: |click;|arg1|[arg2, arg3, ...]| <br />
* FitNesse example: |click;|ButtonInRow{0}Col{1}|[5, 3]| <br />
* <br />
*
* @param elementListKey
* key to find the technical locator
* @param replaceArgs
* values to replace the place holders in the element list entry
* with
* @return true if click was successful; otherwise false
*/
public boolean click(String elementListKey, String... replaceArgs) {
boolean result = false;
WebElement element = findWebelement(elementListKey, replaceArgs);
if (element != null && element.isDisplayed()) {
element.click();
result = true;
}
return result;
}
/**
* Works just like <code>click(elementListKey, replaceArgs)</code> except
* the argument <code>replaceArgs</code> is always an empty array.
*
* @param elementListKey
* key to find the technical locator
* @return true if click was successful; otherwise false
*/
public boolean click(String elementListKey) {
return click(elementListKey, new String[] {});
}
/**
* Double clicks on a element or button. <br />
* <br />
*
* FitNesse usage..: |double click;|arg1|[arg2, arg3, ...]| <br />
* FitNesse example: |double click;|ButtonInRow{0}Col{1}|[5, 3]| <br />
* <br />
*
* @param elementListKey
* key to find the technical locator
* @param replaceArgs
* values to replace the place holders in the element list entry
* with
* @return true if click was successful; otherwise false
*/
public boolean doubleClick(String elementListKey, String... replaceArgs) {
boolean result = false;
WebElement element = findWebelement(elementListKey, replaceArgs);
if (element != null && element.isDisplayed()) {
Actions action = new Actions(webDriver);
action.doubleClick(element).build().perform();
result = true;
}
return result;
}
/**
* Searches for a given text in the HTML source and returns true if found.
* If the text is not found immediately, this method will retry for as long
* as this class would normally also wait for a widget to found.
*
* FitNesse usage..: |wait for text|arg1| <br />
* FitNesse example: |wait for text|Login successful| <br />
* <br />
*
* @param text
* to be searched for
* @return true if the String-Value of <code>text</code> is present; throws
* a StopTestException otherwise.
*/
public boolean waitForText(String text) {
boolean result = false;
int counter = 0;
while (counter < waitCounter) {
result = webDriver.getPageSource().contains(text);
if (result) {
break;
}
waitTime(waitInMillis);
counter++;
}
if (!result) {
String message = "The specified text \"" + text + "\" could not be found!";
LOGGER.error(message);
throw new StopTestException(message);
}
return result;
}
/**
* Searches for a given text in the HTML source and returns true if found.
*
* FitNesse usage..: |text|arg1|is visible| <br />
* FitNesse example: |text|Login successful|is visible| <br />
* <br />
*
* @param text
* to be searched for
* @return true if the String-Value of <code>text</code> is present, false
* otherwise
*/
public boolean textIsVisible(String text) {
boolean result = webDriver.getPageSource().contains(text);
if (!result) {
String message = "The specified text \"" + text + "\" could not be found!";
LOGGER.error(message);
}
return result;
}
/**
* Searches for a given text in the HTML source and returns true if found.
*
* FitNesse usage..: |text|arg1|is visible| <br />
* FitNesse example: |text|Login successful|is visible| <br />
* <br />
*
* @param text
* to be searched for
* @param elementListKey
* key to find the technical locator
* @param replaceArgs
* values to replace the place holders in the element list entry
* with
* @return true if the String-Value of <code>text</code> is present, false
* otherwise
*/
public boolean textIsVisibleInField(String text, String elementListKey, String... replaceArgs) {
String result = privateReadAttributeFromField("innertext", elementListKey, replaceArgs);
return result.equalsIgnoreCase(text);
}
/**
* Switches to another frame (e.g. iFrame).
*
* @param elementListKey
* key to find the technical locator
* @return true if switch successed
*/
public boolean switchToFrame(String elementListKey) {
WebElement webElement = findWebelement(elementListKey);
webDriver.switchTo().frame(webElement);
return true;
}
/**
* Searches for a given text in the HTML source and returns true if not
* found.
*
* FitNesse usage..: |text|arg1|is unvisible| <br />
* FitNesse example: |text|Login successful|is unvisible| <br />
* <br />
*
* @param text
* to be searched for
* @return true if the String-Value of <code>text</code> isn't present,
* false otherwise
*/
public boolean textIsUnvisible(String text) {
boolean result = !webDriver.getPageSource().contains(text);
if (!result) {
String message = "The specified text \"" + text + "\" could be found!";
LOGGER.error(message);
}
return result;
}
/**
* Close the browser instance.
*
* FitNesse usage..: |close browser| <br />
* FitNesse example: |close browser| <br />
* <br />
*
* @return always true to show inside FitNesse a positive result
*/
public boolean closeBrowser() {
// checks if Browser is Chrome because Chromedriver does not function
// with Close-Method of WebDriver
if (webDriver instanceof ChromeDriver) {
webDriver.quit();
} else {
webDriver.close();
// necessary wait, at least for FF portable
waitTime(500);
// best effort
try {
webDriver.quit();
// CHECKSTYLE:OFF
} catch (Throwable t) { // disable checkstyle for empty block
// CHECKSTYLE:ON
// NFA - at least Firefox portable is down after close()
}
}
return true;
}
/**
* Simulates a MouseOver on a Menu. Moves to the given Gui-Element.
*
* FitNesse usage..: |move to element;|arg1|[arg2, arg3, ...]| <br />
* FitNesse example: |move to element;|IconInRow{0}Col{1}|[5, 3]| <br />
* <br />
*
* @param elementListKey
* the Gui-Element where to move.
* @param replaceArgs
* values to replace the place holders in the element list entry
* with
* @return true if WebElement is found and Mouse moved to this Element to
* perform an Action.
*/
public boolean moveToElement(String elementListKey, String... replaceArgs) {
boolean result = false;
WebElement element = findWebelement(elementListKey, replaceArgs);
if (element != null && element.isDisplayed()) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("element found ready for Action (moveToElement)");
}
Actions actions = new Actions(webDriver);
actions.moveToElement(element).build().perform();
result = true;
}
return result;
}
/**
* Move to element and click menu.
*
* @param elementListKey
* key of element in elementList.conf.
* @param menuEntryKey
* key of menu.
* @return true if element is found and menu is activated.
*/
public boolean moveToElementAndClickMenu(String elementListKey, String menuEntryKey) {
boolean result = false;
WebElement element = findWebelement(elementListKey, new String[] {});
if (element != null && element.isDisplayed()) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("element found ready for Action (moveToElement)");
}
Actions actions = new Actions(webDriver);
actions.moveToElement(element).build().perform();
result = true;
}
result = result && click(menuEntryKey);
return result;
}
/**
* Works just like <code>moveToElement(elementListKey, replaceArgs)</code>
* except the argument <code>replaceArgs</code> is always an empty array.
*
* @param elementListKey
* the Gui-Element where to move.
* @return true if WebElement is found and Mouse moved to this Element to
* perform an Action.
*/
public boolean moveToElement(String elementListKey) {
return moveToElement(elementListKey, new String[] {});
}
/**
* This Method finds WebElements with a given Key as XPATH expression or
* id-value.
*
* @param elementListKey
* key in the ElementList
* @param replaceArgs
* values to replace the place holders in the element list entry
* with
* @return the webElement if element is not found, then return null
*/
protected WebElement findWebelement(String elementListKey, String... replaceArgs) {
return findWebelement(elementListKey, true, replaceArgs);
}
/**
* This Method finds WebElements with a given Key as XPATH expression or
* id-value.
*
* @param elementListKey
* key in the ElementList
* @param handleTimeout
* specifies if a TimeoutException should be handled by this
* method (default: true!) or in special cases (e.g.
* assertElementNotFound) should be handled by the calling method
* @param replaceArgs
* values to replace the place holders in the element list entry
* with
* @return the webElement if element is not found, then return null
*/
protected WebElement findWebelement(String elementListKey, boolean handleTimeout, String... replaceArgs) {
WebElement element = null;
try {
element = waitForElement(createByFromElementList(elementListKey, replaceArgs));
} catch (TimeoutException e) {
if (handleTimeout) {
LOGGER.error(elementListKey);
LOGGER.error(e.getMessage());
ExceptionUtils.handleNoSuchElementException(elementListKey, e);
} else {
// Don't handle the exception here. Just pass it on to the
// caller. For instance, when the caller expects that finding a
// certain element will fail.
throw e;
}
}
return element;
}
/**
* Wait for a element with a given Key as XPATH expression or id-value.
*
* @param elementListKey
* key in the ElementList
* @return true if WebElement is found and displayed
*/
public boolean waitForElement(String elementListKey) {
boolean result = false;
WebElement element = findWebelement(elementListKey);
if (element != null && element.isDisplayed()) {
result = true;
}
return result;
}
/**
* This Method finds WebElements with a given {@link By}. If the given
* {@link By} is an XPath expression and matches multiple elements, this
* method will return the first visible element (as determined by selenium's
* {@link isDisplayed} method) that matches.
*
* @param context
* the search context or subtree to query. Argument
* <code>context</code> may be <code>null</code> to search the
* whole document.
* @param by
* Mechanism used to locate elements within a document
* @return the webElement
* @throws TimeoutException
* if element is not found
*/
protected WebElement waitForElement(final WebElement context, final By by) throws TimeoutException {
List<WebElement> elements = null;
WebElement result = null;
int counter = 0;
while (elements == null) {
if (counter >= waitCounter) {
break;
}
try {
if (context == null) {
elements = webDriver.findElements(by);
} else {
elements = context.findElements(by);
}
} catch (Exception e) {
elements = null;
}
if (elements != null) {
result = getFirstDisplayed(elements);
if (result != null) {
break;
}
}
elements = null;
waitTime(waitInMillis);
counter++;
}
if (result == null || !result.isDisplayed()) {
throw new TimeoutException("Timeout: no element was found");
}
return result;
}
/**
* Iterates over a list of web elements and returns the first that is
* visible (as determined by selenium's {@link isDisplayed} method).
*
* @param elements
* the element list to search
* @return the first visible element from the supplied list; null if the
* list is empty or not web element is visible
*/
private WebElement getFirstDisplayed(List<WebElement> elements) {
WebElement result = null;
if (elements != null) {
for (WebElement element : elements) {
if (element.isDisplayed()) {
result = element;
break;
}
}
}
return result;
}
/**
* This Method finds WebElements with a given {@link By}.
*
* @param by
* Mechanism used to locate elements within a document
* @return the webElement
* @throws TimeoutException
* if element is not found
*/
protected WebElement waitForElement(final By by) throws TimeoutException {
return waitForElement(null, by);
}
/**
* Returns the locator for a given key.
*
* @param elementListKey
* key in the ElementList
* @return locator as String
*/
protected String getLocatorFromElementList(String elementListKey) {
try {
return elementListService.getValue(elementListKey);
} catch (ElementKeyNotFoundException e) {
return defaultHandelKeyNotFoundException(elementListKey, e);
}
}
/**
*
* @param elementListKey
* key in the ElementList, that isn't found.
* @param e
* ElementKeyNotFoundException always thrown
*/
protected String defaultHandelKeyNotFoundException(String elementListKey, ElementKeyNotFoundException e) {
ExceptionUtils.handleElementKeyNotFoundException(elementListKey, e);
return "";
}
/**
* This Method create a By instance with a given Key as XPATH expression or
* id-value.
*
* @param elementListKey
* key (e.g. inputUsername)
* @param replaceArgs
* values to replace the place holders in the element list entry
* with
* @return By
*/
protected By createByFromElementList(String elementListKey, String... replaceArgs) {
String locator = getLocatorFromElementList(elementListKey);
// Apostrophes in X-Paths must not be wiped out - hence escape
if (locator.contains("%")) {
LOGGER.info("contains % " + locator);
locator = createXPathFromLocator(locator);
LOGGER.info("replaced % " + locator);
}
if (locator != null) {
locator = locator.replace("'", "''");
}
Object[] args;
if (replaceArgs != null) {
args = replaceArgs;
} else {
args = new Object[] {};
}
locator = MessageFormat.format(locator, args);
By by;
if (hasElementPrefix(locator)) {
by = getByFromLacatorWithPraefix(locator);
} else if (StringUtils.isXPath(locator)) {
by = By.xpath(locator);
} else {
by = By.id(locator);
}
LOGGER.info(by);
return by;
}
/**
*
*
* @param locator
* as a String
* @return true if the locator starts with an ElementPrefix
*/
protected boolean hasElementPrefix(String locator) {
return locator.startsWith(ElementPrefix.CLASSNAME.getName())
|| locator.startsWith(ElementPrefix.CSSSELECTOR.getName())
|| locator.startsWith(ElementPrefix.ID.getName())
|| locator.startsWith(ElementPrefix.LINKTEXT.getName())
|| locator.startsWith(ElementPrefix.NAME.getName())
|| locator.startsWith(ElementPrefix.PARTIAL.getName())
|| locator.startsWith(ElementPrefix.TAGNAME.getName())
|| locator.startsWith(ElementPrefix.XPATH.getName());
}
/**
*
* @param locator
* identified by an element of the {@link ElementPrefix}
* @return By
*/
private By getByFromLacatorWithPraefix(String locator) {
if (locator.startsWith(ElementPrefix.CLASSNAME.getName())) {
locator = locator.substring(ElementPrefix.CLASSNAME.getName().length());
return By.className(locator);
} else if (locator.startsWith(ElementPrefix.CSSSELECTOR.getName())) {
locator = locator.substring(ElementPrefix.CSSSELECTOR.getName().length());
return By.cssSelector(locator);
} else if (locator.startsWith(ElementPrefix.ID.getName())) {
locator = locator.substring(ElementPrefix.ID.getName().length());
return By.id(locator);
} else if (locator.startsWith(ElementPrefix.LINKTEXT.getName())) {
locator = locator.substring(ElementPrefix.LINKTEXT.getName().length());
return By.linkText(locator);
} else if (locator.startsWith(ElementPrefix.NAME.getName())) {
locator = locator.substring(ElementPrefix.NAME.getName().length());
return By.name(locator);
} else if (locator.startsWith(ElementPrefix.PARTIAL.getName())) {
locator = locator.substring(ElementPrefix.PARTIAL.getName().length());
return By.partialLinkText(locator);
} else if (locator.startsWith(ElementPrefix.TAGNAME.getName())) {
locator = locator.substring(ElementPrefix.TAGNAME.getName().length());
return By.tagName(locator);
} else if (locator.startsWith(ElementPrefix.XPATH.getName())) {
locator = locator.substring(ElementPrefix.XPATH.getName().length());
return By.xpath(locator);
}
return By.id(locator);
}
/**
*
* @param locator
* the locator including '%'
* @return the xpath with contains the locator.
*/
protected String createXPathFromLocator(String locator) {
String tempLocator = locator.replaceAll("%", "");
LOGGER.info(tempLocator);
/**
* Invalid JavaDoc: Sets the implicit wait timeout in seconds for each test
* step.<br />
*
* FitNesse usage..: |set timeout|arg1| <br />
* FitNesse example: |set timeout|1| <br />
* <br />
*
* @param timeout
* timeout in seconds
*/
public void setTimeout(String timeout) {
this.timeout = Integer.valueOf(timeout);
if (LOGGER.isTraceEnabled()) {
LOGGER.trace(">>>> Set timeout to: " + this.timeout + " seconds. <<<<<");
}
}
/**
* Checks if value is visible and if not stops the test.
*
* @param value
* Value to be found on website
* @return result True if value was found
*/
public boolean checkTextAndTearDown(String value) {
boolean result = webDriver.getPageSource().contains(value);
if (!result) {
String message = "The specified text \"" + value + "\" could not be found!";
result = true;
throw new StopTestException(message, new Throwable());
}
return result;
}
@Override
public boolean tearDown() {
return closeBrowser();
}
}
|
package org.tibennetwork.iamame.mame;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Software used with a Machine
*/
@XmlRootElement
public class Software {
@XmlRootElement
static class Part {
static class DiskArea {
static class Disk {
@XmlAttribute(name="name")
private String name;
public String getName () {
return this.name;
}
}
@XmlElement(name="disk")
private Disk disk;
public Disk getDisk () {
return this.disk;
}
}
@XmlAttribute(name="name")
private String name;
@XmlAttribute(name="interface")
private String deviceInterface;
@XmlElement
private DiskArea diskarea;
public String getName() {
return name;
}
public String getDeviceInterface() {
return deviceInterface;
}
public DiskArea getDiskarea () {
return diskarea;
}
}
@XmlAttribute(name="name")
private String name;
@XmlElement(name="description")
private String description;
@XmlElement(name="year")
private String year;
@XmlElement(name="publisher")
private String publisher;
@XmlElement(name="part")
private List<Part> parts = new ArrayList<>();
private Machine machine;
private MediaDevice mediaDevice;
private SoftwareList softwareList;
private String regularFileName;
public Software () {}
/**
* constructor for non softwarelist files.
*/
public Software (Machine m, MediaDevice md, String name) {
this.machine = m;
this.mediaDevice = md;
this.regularFileName = name;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public String getYear() {
return year;
}
public String getPublisher() {
return publisher;
}
public List<Part> getParts() {
return parts;
}
public Machine getMachine() {
return machine;
}
public void setMachine(Machine machine) {
this.machine = machine;
}
public MediaDevice getMediaDevice() {
return mediaDevice;
}
public SoftwareList getSoftwareList() {
return softwareList;
}
public void setSoftwareList(SoftwareList softwareList) {
this.softwareList = softwareList;
}
public boolean isRegularFile () {
return this.regularFileName != null;
}
public String getMediaInterface () {
if (this.isRegularFile()) {
return this.mediaDevice.getMediaInterface();
}
for (Part p : this.parts) {
return p.getDeviceInterface();
}
return null;
}
/**
* Determines whether the files of this software
* are available on the given romPath
*/
public boolean isAvailable (List<File> romsPaths) {
String rfp = this.getRelativeFilePath();
for (File rp: romsPaths) {
File softwareFile = new File(rp + File.separator + rfp);
if(softwareFile.exists()) {
System.out.println(softwareFile);
return true;
}
}
return false;
}
public String toString() {
return this.isRegularFile()
? String.format("Software [device: %s, file: %s]",
this.getMediaInterface(),
this.regularFileName)
: String.format(
"Software: [device: %s, name: %s (%s), publisher: %s, "
+ "machine: %s]",
this.getMediaInterface(),
this.description,
this.name,
this.publisher,
this.machine.getDescription());
}
/**
* Return the partial file path relative to the
* rompath.
*/
public String getRelativeFilePath() {
// Its a CDROM ? so its a CHD
if (this.parts.get(0).getName().equals("cdrom")) {
return this.softwareList.getName()
+ File.separator
+ this.name
+ File.separator
+ this.getChdName()
+ ".chd";
} else {
return this.softwareList.getName()
+ File.separator
+ this.name
+ ".zip";
}
}
public String getChdName () {
return this.parts.get(0).getDiskarea().getDisk().getName();
}
}
|
package org.webbitserver.netty;
import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
import org.jboss.netty.handler.codec.http.HttpChunkAggregator;
import org.jboss.netty.handler.codec.http.HttpRequestDecoder;
import org.jboss.netty.handler.codec.http.HttpResponseEncoder;
import org.webbitserver.EventSourceHandler;
import org.webbitserver.HttpHandler;
import org.webbitserver.WebServer;
import org.webbitserver.WebSocketHandler;
import org.webbitserver.handler.HttpToEventSourceHandler;
import org.webbitserver.handler.HttpToWebSocketHandler;
import org.webbitserver.handler.PathMatchHandler;
import org.webbitserver.handler.ServerHeaderHandler;
import org.webbitserver.handler.exceptions.PrintStackTraceExceptionHandler;
import org.webbitserver.handler.exceptions.SilentExceptionHandler;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import static org.jboss.netty.channel.Channels.pipeline;
public class NettyWebServer implements WebServer {
private final ServerBootstrap bootstrap;
private final SocketAddress socketAddress;
private final URI publicUri;
private final List<HttpHandler> handlers = new ArrayList<HttpHandler>();
private final Executor executor;
private Channel channel;
protected long nextId = 1;
private Thread.UncaughtExceptionHandler exceptionHandler;
private Thread.UncaughtExceptionHandler ioExceptionHandler;
public NettyWebServer(int port) {
this(Executors.newSingleThreadScheduledExecutor(), port);
}
public NettyWebServer(final Executor executor, int port) {
this(executor, new InetSocketAddress(port), localUri(port));
}
public NettyWebServer(final Executor executor, SocketAddress socketAddress, URI publicUri) {
this.executor = executor;
this.socketAddress = socketAddress;
this.publicUri = publicUri;
// Uncaught exceptions from handlers get dumped to console by default.
// To change, call uncaughtExceptionHandler()
uncaughtExceptionHandler(new PrintStackTraceExceptionHandler());
// Default behavior is to silently discard any exceptions caused
// when reading/writing to the client. The Internet is flaky - it happens.
connectionExceptionHandler(new SilentExceptionHandler());
// Configure the server.
bootstrap = new ServerBootstrap();
// Set up the event pipeline factory.
bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
@Override
public ChannelPipeline getPipeline() throws Exception {
long timestamp = timestamp();
Object id = nextId();
ChannelPipeline pipeline = pipeline();
pipeline.addLast("decoder", new HttpRequestDecoder());
pipeline.addLast("aggregator", new HttpChunkAggregator(65536));
pipeline.addLast("encoder", new HttpResponseEncoder());
pipeline.addLast("handler", new NettyHttpChannelHandler(
executor, handlers, id, timestamp, exceptionHandler, ioExceptionHandler));
return pipeline;
}
});
setupDefaultHandlers();
}
protected void setupDefaultHandlers() {
add(new ServerHeaderHandler("Webbit"));
}
@Override
public URI getUri() {
return publicUri;
}
@Override
public Executor getExecutor() {
return executor;
}
@Override
public NettyWebServer add(HttpHandler handler) {
handlers.add(handler);
return this;
}
@Override
public NettyWebServer add(String path, HttpHandler handler) {
return add(new PathMatchHandler(path, handler));
}
@Override
public NettyWebServer add(String path, WebSocketHandler handler) {
return add(path, new HttpToWebSocketHandler(handler));
}
@Override
public WebServer add(String path, EventSourceHandler handler) {
return add(path, new HttpToEventSourceHandler(handler));
}
@Override
public synchronized NettyWebServer start() {
bootstrap.setFactory(new NioServerSocketChannelFactory(
Executors.newSingleThreadExecutor(),
Executors.newSingleThreadExecutor(), 1));
channel = bootstrap.bind(socketAddress);
return this;
}
@Override
public synchronized NettyWebServer stop() throws IOException {
if (channel != null) {
channel.close();
}
if (bootstrap != null) {
bootstrap.releaseExternalResources();
}
return this;
}
@Override
public synchronized NettyWebServer join() throws InterruptedException {
if (channel != null) {
channel.getCloseFuture().await();
}
return this;
}
@Override
public WebServer uncaughtExceptionHandler(Thread.UncaughtExceptionHandler exceptionHandler) {
this.exceptionHandler = exceptionHandler;
return this;
}
@Override
public WebServer connectionExceptionHandler(Thread.UncaughtExceptionHandler ioExceptionHandler) {
this.ioExceptionHandler = ioExceptionHandler;
return this;
}
private static URI localUri(int port) {
try {
return URI.create("http://" + InetAddress.getLocalHost().getHostName() + (port == 80 ? "" : (":" + port)) + "/");
} catch (UnknownHostException e) {
return null;
}
}
protected long timestamp() {
return System.currentTimeMillis();
}
protected Object nextId() {
return nextId++;
}
}
|
package puck.parser.gen;
import com.nativelibs4java.opencl.CLContext;
import puck.package$;
import puck.parser.*;
import java.util.*;
/**
* TODO
*
* @author dlwh
*/
public abstract class SimpleGenRuleMultiply<C, L> extends JavaFriendlyGenRuleMultiply<C, L> {
public static final int WARP_SIZE = 32;
public static final int NUM_WARPS = 90;
public static final int NUM_SM = 15;
public RuleStructure<C, L> structure;
private boolean writeDirectToChart;
private RuleSemiring semiring;
public SimpleGenRuleMultiply(RuleStructure<C, L> structure, boolean writeDirectToChart, RuleSemiring semiring) {
super(structure, writeDirectToChart);
this.structure = structure;
this.writeDirectToChart = writeDirectToChart;
this.semiring = semiring;
}
public abstract List<IndexedUnaryRule<C, L>>[] segmentUnaries(List<IndexedUnaryRule<C, L>> indexedUnaryRules);
public abstract List<IndexedBinaryRule<C, L>>[][] segmentBinaries(List<IndexedBinaryRule<C, L>> indexedBinaryRules);
public CLBinaryRuleUpdater javaBinaryRuleApplication(List<IndexedBinaryRule<C, L>> indexedBinaryRules, String name, CLContext context) {
ArrayList<String> kernelTexts = new ArrayList<String>();
List<IndexedBinaryRule<C, L>>[][] segments = segmentBinaries(indexedBinaryRules);
boolean supportsExtendedAtomics = supportsExtendedAtomics(context);
for (int s=0; s<segments.length; s++) {
kernelTexts.add(binaryKernelText(name+s, segments[s], supportsExtendedAtomics));
}
List<RuleKernel> kernels = compileKernels(context, this.<IndexedBinaryRule<C, L>>flatten(segments), kernelTexts);
int[] globalSize = {WARP_SIZE * NUM_WARPS, NUM_SM, 1};
int[] wgSize = {WARP_SIZE, 1, 1};
return new CLBinaryRuleUpdater(kernels, globalSize, wgSize, writeDirectToChart);
}
private String binaryKernelText(String name, List<IndexedBinaryRule<C, L>>[] subsegments, boolean supportsExtendedAtomics) {
StringBuilder sb = new StringBuilder();
// determine duplicate parents
Set<Integer> allParents = new HashSet<Integer>();
Set<Integer> dupParents = new HashSet<Integer>();
for(int m = 0; m < NUM_SM; ++m) {
for(SymId<C, L> sym: getParents(subsegments[m])) {
if(allParents.contains(sym.gpu())) {
dupParents.add(sym.gpu());
} else {
allParents.add(sym.gpu());
}
}
}
if(!dupParents.isEmpty() && supportsExtendedAtomics) {
sb.append("#pragma OPENCL EXTENSION cl_khr_global_int32_extended_atomics : enable\n");
}
appendAddition(sb);
sb.append(WRITE_PARENT_ATOMIC);
sb.append(CLMaskKernels.maskHeader(structure));
sb.append("\n\n");
// Sort so that LHS priority, then RHS
for(List<IndexedBinaryRule<C, L>> rules : subsegments) {
Collections.sort(rules, new Comparator<IndexedBinaryRule<C, L>>() {
@Override
public int compare(IndexedBinaryRule<C, L> o1, IndexedBinaryRule<C, L> o2) {
int parent = Integer.compare(o1.rule().parent().gpu(), o2.rule().parent().gpu());
if(parent != 0) return parent;
int lhs = Integer.compare(o1.rule().left().gpu(), o2.rule().left().gpu());
if(lhs != 0) return lhs;
int rhs = Integer.compare(o1.rule().right().gpu(), o2.rule().right().gpu());
return rhs;
}
});
}
for (int m=0; m<NUM_SM; ++m) {
sb.append("static void subpart"+m+"(const mask_t mask, __global volatile float* parents, __global int* parentIndex, int row, __global float* left, __global float* right, float scale, int numRows) {\n");
// if (!subsegments[m].isEmpty()) sb.append(String.format("if (%s) return;\n", CLMaskKernels.genCheckIfMaskIsEmpty(structure, "mask", getParents(subsegments[m]))));
Map<Integer,String> declaredParents = new HashMap<Integer, String>();
Map<Integer,String> declaredLeft = new HashMap<Integer, String>();
Map<Integer,String> declaredRight = new HashMap<Integer, String>();
if(writeDirectToChart)
sb.append("int pi = parentIndex[row];");
Map<Integer,Integer> parentCounts = new HashMap<Integer,Integer>();
for(IndexedBinaryRule<C, L> rule : subsegments[m]) {
int parentIndex = rule.rule().parent().gpu();
Integer count = parentCounts.get(parentIndex);
if (count == null) {
count = 0;
}
count++;
parentCounts.put(parentIndex, count);
}
int cellSize = package$.MODULE$.roundUpToMultipleOf(Math.max(structure.numNonTerms(), structure.numTerms()), 32);
for(IndexedBinaryRule<C, L> rule : subsegments[m]) {
int parentIndex = rule.rule().parent().gpu();
String parent = declaredParents.get(parentIndex);
if(parent == null) {
parent = "parent_" + parentIndex;
sb.append(String.format("float parent_%d = %s;\n", parentIndex, floatToString(semiring.zero())));
declaredParents.put(parentIndex, parent);
}
int leftIndex = rule.rule().left().gpu();
String left = declaredLeft.get(leftIndex);
if(left == null) {
left = "left_" + leftIndex;
sb.append(String.format("float left_%d = left[%d * numRows + row];\n", leftIndex, leftIndex));
declaredLeft.put(leftIndex, left);
}
int rightIndex = rule.rule().right().gpu();
String right = declaredRight.get(rightIndex);
if(right == null) {
right = "right_" + rightIndex;
sb.append(String.format("float right_%d = right[%d * numRows + row];\n", rightIndex, rightIndex));
declaredRight.put(rightIndex, right);
}
sb.append(String.format("%s = semiring_mad(%s, %s, %ff);\n", parent, parent, semiring.times(left, right),structure.scores()[rule.ruleId()]));
// if(writeDirectToChart && semiring.needsScaling() && name.startsWith("inside_tn"))
// sb.append(String.format("if(pi == 5 && %s >= 1.0f) printf(\"%d %%e %%e %%e\\n\", %s, %s, %s);\n", parent, parentIndex, parent,left, right));
parentCounts.put(parentIndex, parentCounts.get(parentIndex)-1);
if (parentCounts.get(parentIndex) == 0) {
if(writeDirectToChart) {
if(semiring.needsScaling()) {
sb.append(parent + " *= scale;");
}
String dest = String.format("parents[pi * "+cellSize+" + %d]", parentIndex);
String src = parent;
sb.append(genWriteSymbol(dest, src, false, supportsExtendedAtomics));
// force no atomics
// sb.append(genWriteSymbol(dest, src, true, supportsExtendedAtomics));
} else {
String dest = String.format("parents[%d * numRows + row]", parentIndex);
String src = parent;
sb.append(genWriteSymbol(dest, src, !dupParents.contains(parentIndex), supportsExtendedAtomics));
// force no atomics
// sb.append(genWriteSymbol(dest, src, true, supportsExtendedAtomics));
}
}
}
// sb.append("// write out\n");
// for(Map.Entry<Integer, String> e: declaredParents.entrySet()) {
// sb.append(String.format("parents[%d * numRows + row] = %s;\n", e.getKey(), e.getValue()));
// String dest = String.format("parents[%d * numRows + row]", e.getKey());
// String src = e.getValue();
// sb.append(genWriteSymbol(dest, src, !dupParents.contains(e.getKey()), supportsExtendedAtomics));
sb.append("}\n\n");
}
sb.append(String.format(
" __kernel void %s(__global volatile float* parents," +
"__global const float* parentScale," +
" __global int* parentIndex, " + // cell offset into parents column if writeDirect, and always parentScale
" __global float* left," +
" __global const float* leftScale," +
" __global int* _leftIndex, int leftOff, " +
" __global float* right," +
" __global const float* rightScale," +
" __global int* _rightIndex, int rightOff," +
" __global const mask_t* masks, int numRows, int cellsToDo) {\n" +
" int numWorkers = get_global_size(0);\n" +
" int grammarSubPartition = get_group_id(1);\n" +
" __global int* leftIndex = _leftIndex + leftOff;\n" +
" __global int* rightIndex = _rightIndex + rightOff;\n" +
" for (int row = get_global_id(0); row < cellsToDo; row += numWorkers) {\n" +
" const mask_t mask = masks[parentIndex[row]];\n", name));
sb.append("\n\n");
if(semiring.needsScaling()) {
sb.append("float scale = native_exp(-parentScale[parentIndex[row]] + rightScale[rightIndex[row]] + leftScale[leftIndex[row]] );");
} else {
sb.append("float scale = 1.0f;");
}
sb.append("switch (grammarSubPartition) {\n");
for (int m=0; m<NUM_SM; ++m) {
sb.append("case "+m+": subpart"+m+"(mask, parents, parentIndex, row, left, right, scale, numRows); continue;\n");
}
sb.append("default: continue;\n");
sb.append("}\n");
sb.append("}\n");
sb.append("}\n");
return sb.toString();
}
protected String floatToString(float zero) {
if(zero == Float.NEGATIVE_INFINITY) return "-INFINITY";
else return zero +"f";
}
private void appendAddition(StringBuilder sb) {
sb.append(semiring.includes());
}
private boolean semiringIsViterbi() {
return semiring instanceof ViterbiRuleSemiring$;
}
public CLUnaryRuleUpdater javaUnaryRuleApplication(List<IndexedUnaryRule<C, L>> indexedUnaryRules, String name, CLContext context) {
ArrayList<String> kernelTexts = new ArrayList<String>();
List<IndexedUnaryRule<C, L>>[] segments = segmentUnaries(indexedUnaryRules);
for (int s=0; s<segments.length; s++) {
kernelTexts.add(unaryKernelText(name+s, segments[s]));
}
List<RuleKernel> kernels = compileKernels(context, Arrays.asList(segments), kernelTexts);
return new CLUnaryRuleUpdater(kernels);
}
private String unaryKernelText(String name, List<IndexedUnaryRule<C, L>> segment) {
StringBuilder sb = new StringBuilder();
appendAddition(sb);
sb.append("\n\n\n");
sb.append(String.format(
" __kernel void %s(__global volatile float* parents," +
"__global const float* parentScale," +
" __global int* parentIndex, " + // cell offset into parents column if writeDirect, and always parentScale
" __global float* child, " +
"__global const float* childScale," +
" __global int* _childIndex, " + // cell offset into childs column if writeDirect, and always childScale
" int childOff, " +
"int numRows, int cellsToDo) {\n" +
" int numWorkers = get_global_size(0);\n" +
" int grammarSubPartition = get_group_id(1);\n" +
" for (int row = get_global_id(0); row < cellsToDo; row += numWorkers) {\n", name));
sb.append("\n\n");
Map<Integer,String> declaredParents = new HashMap<Integer, String>(),
declaredLeft = new HashMap<Integer, String>();
if(semiring.needsScaling()) {
sb.append("__global int* childIndex = _childIndex + childOff;");
sb.append("float scale = native_exp(-parentScale[parentIndex[row]] + childScale[childIndex[row]]);");
} else {
sb.append("float scale = 1.0f;");
}
// todo: reorder to sensible groupings
for(IndexedUnaryRule<C, L> rule : segment) {
int parentIndex = rule.rule().parent().gpu();
String parent = declaredParents.get(parentIndex);
if(parent == null) {
parent = "parent_" + parentIndex;
sb.append(String.format("float parent_%d = %s;\n", parentIndex, floatToString(semiring.zero())));
// sb.append(String.format("float parent_%d = parents[%d * numRows + row];\n", parentIndex, parentIndex));
declaredParents.put(parentIndex, parent);
}
int childIndex = rule.rule().child().gpu();
String child = declaredLeft.get(childIndex);
if(child == null) {
child = "child_" + childIndex;
sb.append(String.format("float child_%d = child[%d * numRows + row];\n", childIndex, childIndex));
declaredLeft.put(childIndex, child);
}
sb.append(String.format("%s = semiring_mad(%s, %s, %ff);\n", parent, parent, child, structure.scores()[rule.ruleId()]));
}
sb.append("// write out\n");
for(Map.Entry<Integer, String> e: declaredParents.entrySet()) {
if(semiring.needsScaling()) {
sb.append(String.format("parents[%d * numRows + row] += %s * scale;\n", e.getKey(), e.getValue()));
} else {
sb.append(String.format("parents[%d * numRows + row] = %s;\n", e.getKey(), e.getValue()));
}
}
sb.append("}\n");
sb.append("}\n");
return sb.toString();
}
public static boolean GRAMMAR_IS_GENERATIVE = true;
public static boolean NVIDIA_IS_STILL_STUPID = true;
public String genWriteSymbol(String dest, String src, boolean symIsUniqueToSubsegmentation, boolean supportsExtendedAtomics) {
// return String.format("write_parent_atomic_nvidia_gen(&%s, %s);\n", dest, src);
if(symIsUniqueToSubsegmentation) {
return String.format("%s = semiring_add(%s, %s);\n", dest, dest, src);
} else if(semiringIsViterbi() && GRAMMAR_IS_GENERATIVE && supportsExtendedAtomics && NVIDIA_IS_STILL_STUPID) {
return String.format("write_parent_atomic_nvidia_gen(&%s, %s);\n", dest, src);
} else if(semiringIsViterbi() & GRAMMAR_IS_GENERATIVE && supportsExtendedAtomics) {
return String.format("write_parent_gen_atomic(&%s, %s);\n", dest, src);
} else {
return String.format("write_parent_atomic(&%s, %s);\n", dest, src);
}
}
// floats < 0 are well ordered such that if max(float1, float2) = float1, then min(*(int*)&float1,*(int*)&float2) = *(int*)&float1
// note inversion of min and max
// this is for write_atomic_min (because all floats are same sign)
// there's a problem if one float is 0.0, but eh.
private static final String WRITE_PARENT_ATOMIC = "" +
" typedef union { int old; float oldf; } intbox;\n" +
" \n" +
" inline void write_parent_gen_atomic(volatile __global float* loc, float value) {\n" +
" atomic_min((volatile __global int*)loc, *(int*)&value);\n" +
" }\n"+
" #ifdef NVIDIA \n" +
" inline void write_parent_atomic_nvidia_gen(volatile __global float* loc, float value) {\n" +
" volatile __global int* d_ptr = (volatile __global int*)loc;\n" +
" int z = *(int*)&value;\n" +
" asm volatile(\"atom.global.min.s32 %0, [%1], %2;\" : \"=r\"(z), \"+l\"(d_ptr): \"r\"(z));\n" +
" }\n"+
" \n" +
" #endif \n" +
" inline void write_parent_atomic(volatile __global float* loc, const float value) {\n" +
" intbox old;\n" +
" old.oldf = *loc;\n" +
" float z = semiring_add(old.oldf, value);\n" +
" \n" +
" while((old.old = atomic_cmpxchg((volatile __global int*)loc, old.old, *(int*)&z)) != *(int*)&z) z = semiring_add(old.oldf, value);\n" +
" }\n\n\n";
}
|
package reborncore.common.util;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.io.IOUtils;
import reborncore.common.IModInfo;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
public class VersionChecker {
public static final String apiAddress = "http://modmuss50.me/api/v1/version.php";
public String projectName;
public IModInfo modInfo;
ArrayList<ModifacationVersionInfo> versions;
public boolean isChecking;
public VersionChecker(String projectName, IModInfo modInfo) {
this.projectName = projectName;
this.modInfo = modInfo;
}
public void checkVersion() throws IOException {
isChecking = true;
URL url = new URL(apiAddress + "?project=" + projectName);
URLConnection con = url.openConnection();
InputStream in = con.getInputStream();
String encoding = con.getContentEncoding();
encoding = encoding == null ? "UTF-8" : encoding;
String body = IOUtils.toString(in, encoding).replaceAll("<br />", "");
Gson gson = new Gson();
versions = gson.fromJson(body, new TypeToken<ArrayList<ModifacationVersionInfo>>() {
}.getType());
isChecking = false;
}
public void checkVersionThreaded() {
new Thread(new Runnable() {
public void run() {
try {
checkVersion();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
public boolean isLatestVersion() {
if (versions == null || versions.isEmpty()) {
return true;
}
return versions.get(0).version.equals(modInfo.MOD_VERSION());
}
public ModifacationVersionInfo getLatestVersion() {
if (versions == null || versions.isEmpty()) {
return null;
}
return versions.get(0);
}
public ArrayList<String> getChangeLogSinceCurrentVersion() {
ArrayList<String> log = new ArrayList<String>();
if (!isLatestVersion()) {
for (ModifacationVersionInfo version : versions) {
if (version.version.equals(modInfo.MOD_VERSION())) {
break;
}
log.addAll(version.changeLog);
}
}
return log;
}
static class ModifacationVersionInfo {
public String version;
public String minecraftVersion;
public ArrayList<String> changeLog;
public String releaseDate;
public boolean recommended;
public ModifacationVersionInfo(String version, String minecraftVersion, ArrayList<String> changeLog, String releaseDate, boolean recommended) {
this.version = version;
this.minecraftVersion = minecraftVersion;
this.changeLog = changeLog;
this.releaseDate = releaseDate;
this.recommended = recommended;
}
public ModifacationVersionInfo() {
}
}
//use this to make an example json file
public static void main(String[] args) throws IOException {
System.out.println("Generating example json file");
ArrayList<ModifacationVersionInfo> infos = new ArrayList<ModifacationVersionInfo>();
ArrayList<String> changelog = new ArrayList<String>();
changelog.add("A change");
changelog.add("Another change");
infos.add(new ModifacationVersionInfo("1.1.1", "1.7.10", changelog, "12th July", true));
infos.add(new ModifacationVersionInfo("1.2.0", "1.7.10", changelog, "28th July", true));
Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(infos);
try {
FileWriter writer = new FileWriter(new File("master.json"));
writer.write(json);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
package se.kth.bbc.security.audit;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import se.kth.bbc.activity.Activity;
import se.kth.bbc.activity.ActivityFacade;
import se.kth.bbc.lims.MessagesController;
import se.kth.bbc.security.audit.model.AccountAudit;
import se.kth.bbc.security.audit.model.RolesAudit;
import se.kth.bbc.security.audit.model.Userlogins;
import se.kth.bbc.security.ua.UserManager;
import se.kth.hopsworks.user.model.Users;
@ManagedBean
@ViewScoped
public class AuditTrails implements Serializable {
private static final long serialVersionUID = 1L;
@EJB
private UserManager userManager;
@EJB
private AuditManager auditManager;
@EJB
private ActivityFacade activityController;
private String username;
private Date from;
private Date to;
private AccountsAuditActions selectedAccountsAuditAction;
private RolesAuditActions selectdeRolesAuditAction;
private StudyAuditActions selectedStudyAuditAction;
private UserAuditActions selectedLoginsAuditAction;
private List<Userlogins> userLogins;
private List<RolesAudit> roleAudit;
private List<AccountAudit> accountAudit;
private List<Activity> ad;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getFrom() {
return from;
}
public void setFrom(Date from) {
this.from = from;
}
public Date getTo() {
return to;
}
public void setTo(Date to) {
this.to = to;
}
public RolesAuditActions[] getAuditActions() {
return RolesAuditActions.values();
}
public List<Userlogins> getUserLogins() {
return userLogins;
}
public void setUserLogins(List<Userlogins> userLogins) {
this.userLogins = userLogins;
}
public List<RolesAudit> getRoleAudit() {
return roleAudit;
}
public void setRoleAudit(List<RolesAudit> roleAudit) {
this.roleAudit = roleAudit;
}
public List<AccountAudit> getAccountAudit() {
return accountAudit;
}
public void setAccountAudit(List<AccountAudit> accountAudit) {
this.accountAudit = accountAudit;
}
public AccountsAuditActions[] getAccountsAuditActions() {
return AccountsAuditActions.values();
}
public RolesAuditActions[] getRolesAuditActions() {
return RolesAuditActions.values();
}
public UserAuditActions[] getLoginsAuditActions() {
return UserAuditActions.values();
}
public StudyAuditActions[] getStudyAuditActions() {
return StudyAuditActions.values();
}
public AccountsAuditActions getSelectedAccountsAuditAction() {
return selectedAccountsAuditAction;
}
public void setSelectedAccountsAuditAction(
AccountsAuditActions selectedAccountsAuditAction) {
this.selectedAccountsAuditAction = selectedAccountsAuditAction;
}
public RolesAuditActions getSelectdeRolesAuditAction() {
return selectdeRolesAuditAction;
}
public void setSelectdeRolesAuditAction(
RolesAuditActions selectdeRolesAuditAction) {
this.selectdeRolesAuditAction = selectdeRolesAuditAction;
}
public StudyAuditActions getSelectedStudyAuditAction() {
return selectedStudyAuditAction;
}
public void setSelectedStudyAuditAction(
StudyAuditActions selectedStudyAuditAction) {
this.selectedStudyAuditAction = selectedStudyAuditAction;
}
public UserAuditActions getSelectedLoginsAuditAction() {
return selectedLoginsAuditAction;
}
public void setSelectedLoginsAuditAction(
UserAuditActions selectedLoginsAuditAction) {
this.selectedLoginsAuditAction = selectedLoginsAuditAction;
}
public List<Activity> getAd() {
return ad;
}
public void setAd(List<Activity> ad) {
this.ad = ad;
}
/**
* Generate audit report for account modifications.
* <p>
* @param username
* @param from
* @param to
* @param action
* @return
*/
public List<AccountAudit> getAccoutnAudit(String username, Date from, Date to,
String action) {
Users u = userManager.getUserByEmail(username);
if (u == null) {
return auditManager.getAccountAudit(convertTosqlDate(from),
convertTosqlDate(to), action);
} else {
return auditManager.getAccountAudit(u.getUid(), convertTosqlDate(from),
convertTosqlDate(to), action);
}
}
/**
* Generate audit report for role entitlement.
* <p>
* @param username
* @param from
* @param to
* @param action
* @return
*/
public List<RolesAudit> getRoleAudit(String username, Date from, Date to,
String action) {
Users u = userManager.getUserByEmail(username);
if (u == null) {
return auditManager.getRoletAudit(convertTosqlDate(from),
convertTosqlDate(to), action);
} else {
return auditManager.getRoletAudit(u.getUid(), convertTosqlDate(from),
convertTosqlDate(to), action);
}
}
/**
*
* @param username
* @param from
* @param to
* @param action
* @return
*/
public List<Userlogins> getUserLogins(String username, Date from, Date to,
String action) {
Users u = userManager.getUserByEmail(username);
if (u == null) {
return auditManager.getUsersLoginsFromTo(convertTosqlDate(from),
convertTosqlDate(to), action);
} else if ( action.equals(UserAuditActions.SUCCESS.name()) || action.equals(UserAuditActions.FAILED.name())
|| action.equals(UserAuditActions.ABORTED.name())){
return auditManager.getUserLoginsOutcome(u.getUid(), convertTosqlDate(from),
convertTosqlDate(to), action);
} else {
return auditManager.
getUserLoginsFromTo(u.getUid(), convertTosqlDate(from),
convertTosqlDate(to), action);
}
}
/**
* Dispatch the audit events and get the relevant audit trails.
* <p>
* @param action
*/
public void processLoginAuditRequest(UserAuditActions action) {
if (action.getValue().equals(UserAuditActions.REGISTRATION.getValue())) {
userLogins = getUserLogins(username, from, to, action.getValue());
} else if (action.getValue().equals(UserAuditActions.LOGIN.
getValue()) || action.getValue().equals(UserAuditActions.LOGOUT.
getValue())) {
userLogins = getUserLogins(username, from, to, action.getValue());
} else if (action.getValue().equals(UserAuditActions.SUCCESS.
getValue()) || action.getValue().equals(UserAuditActions.FAILED.getValue())
|| action.getValue().equals(UserAuditActions.ABORTED.
getValue())) {
userLogins = getUserLogins(username, from, to, action.getValue());
} else if (action.getValue().equals(UserAuditActions.QRCODE.
getValue()) || action.getValue().equals(UserAuditActions.RECOVERY.
getValue())) {
userLogins = getUserLogins(username, from, to, action.getValue());
} else if(action.getValue().equals(UserAuditActions.ALL.getValue())){
userLogins = getUserLogins(username, from, to, action.getValue());
} else {
MessagesController.addSecurityErrorMessage("Audit action not supported.");
}
}
/**
* Dispatch the audit events and get the relevant audit trails.
* <p>
* @param action
*/
public void processAccountAuditRequest(AccountsAuditActions action) {
if (action.getValue().equals(AccountsAuditActions.PASSWORDCHANGE.getValue())) {
accountAudit = getAccoutnAudit(username, from, to, action.getValue());
} else if (action.getValue().equals(AccountsAuditActions.LOSTDEVICE.
getValue())) {
accountAudit = getAccoutnAudit(username, from, to, action.getValue());
} else if (action.getValue().equals(AccountsAuditActions.PROFILEUPDATE.
getValue())) {
accountAudit = getAccoutnAudit(username, from, to, action.getValue());
} else if (action.getValue().equals(AccountsAuditActions.SECQUESTIONCHANGE.
getValue())) {
accountAudit = getAccoutnAudit(username, from, to, action.getValue());
} else if (action.getValue().equals(AccountsAuditActions.PROFILEUPDATE.
getValue())) {
accountAudit = getAccoutnAudit(username, from, to, action.getValue());
} else if (action.getValue().equals(AccountsAuditActions.USERMANAGEMENT.
getValue())) {
accountAudit = getAccoutnAudit(username, from, to, action.getValue());
} else if (action.getValue().equals(AccountsAuditActions.USERMANAGEMENT.
getValue())) {
accountAudit = getAccoutnAudit(username, from, to, action.getValue());
} else if (action.getValue().equals(AccountsAuditActions.ALL.
getValue())) {
accountAudit = getAccoutnAudit(username, from, to, action.getValue());
}else {
MessagesController.addSecurityErrorMessage("Audit action not supported.");
}
}
/**
* Generate audit report for role entitlement.
* <p>
* @param action
*/
public void processRoleAuditRequest(RolesAuditActions action) {
if (action.getValue().equals(RolesAuditActions.ADDROLE.getValue())) {
roleAudit = getRoleAudit(username, from, to, action.getValue());
} else if (action.getValue().equals(RolesAuditActions.REMOVEROLE.getValue())) {
roleAudit = getRoleAudit(username, from, to, action.getValue());
} else if (action.getValue().equals(RolesAuditActions.ALLROLEASSIGNMENTS.
getValue())) {
roleAudit = getRoleAudit(username, from, to, action.getValue());
}else if (action.getValue().equals(RolesAuditActions.SUCCESS) || action.getValue().equals(RolesAuditActions.FAILED)) {
roleAudit = getRoleAudit(username, from, to, action.getValue());
} else {
MessagesController.addSecurityErrorMessage("Audit action not supported.");
}
}
/**
* Generate audit report for studies.
* <p>
* @param action
*/
public void processStudyAuditRequest(StudyAuditActions action) {
if (action.getValue().equals(StudyAuditActions.AUDITTRAILS.getValue())) {
ad = activityController.activityDetailOnStudyAudit(username,
convertTosqlDate(from), convertTosqlDate(to));
} else {
MessagesController.addSecurityErrorMessage("Audit action not supported.");
}
}
/**
* Convert the GUI date to SQL format.
* <p>
* @param calendarDate
* @return
*/
public java.sql.Date convertTosqlDate(java.util.Date calendarDate) {
return new java.sql.Date(calendarDate.getTime());
}
}
|
package seedu.address.logic.parser;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeFormatterBuilder;
import java.time.format.DateTimeParseException;
import java.time.format.ResolverStyle;
import java.time.temporal.ChronoField;
import java.util.Optional;
import seedu.address.commons.util.SubstringRange;
/**
* A parser for dates in day/month/year format.
*/
public class DateParser implements Parser<LocalDate> {
private final LocalDate referenceDate;
private final DateTimeFormatter dateFormatter;
public DateParser(LocalDate referenceDate) {
this.referenceDate = referenceDate;
dateFormatter = new DateTimeFormatterBuilder()
.appendPattern("d[/M[/uuuu]]")
.parseDefaulting(ChronoField.MONTH_OF_YEAR, this.referenceDate.getMonthValue())
.parseDefaulting(ChronoField.YEAR, this.referenceDate.getYear())
.toFormatter()
.withResolverStyle(ResolverStyle.STRICT);
}
public DateParser() {
this(LocalDate.now());
}
public LocalDate getReferenceDate() {
return referenceDate;
}
@Override
public LocalDate parse(String str) throws ParseException {
final Optional<LocalDate> nameDate = parseAsName(str.trim());
if (nameDate.isPresent()) {
return nameDate.get();
}
try {
return LocalDate.parse(str.trim(), dateFormatter);
} catch (DateTimeParseException e) {
throw new ParseException(e.toString(), e, SubstringRange.of(str));
}
}
private Optional<LocalDate> parseAsName(String name) {
switch (name) {
case "tdy": // today
return Optional.of(referenceDate);
case "tmr": // tomorrow
return Optional.of(referenceDate.plusDays(1));
case "yst": // yesterday
return Optional.of(referenceDate.minusDays(1));
default:
return Optional.empty();
}
}
}
|
package seedu.address.model.tag;
import static java.util.Objects.requireNonNull;
import static seedu.address.commons.util.CollectionUtil.requireAllNonNull;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import seedu.address.commons.core.UnmodifiableObservableList;
import seedu.address.commons.exceptions.DuplicateDataException;
import seedu.address.commons.util.CollectionUtil;
/**
* A list of tags that enforces no nulls and uniqueness between its elements.
*
* Supports minimal set of list operations for the app's features.
*
* @see Tag#equals(Object)
*/
public class UniqueTagList implements Iterable<Tag> {
private final ObservableList<Tag> internalList = FXCollections.observableArrayList();
/**
* Constructs empty TagList.
*/
public UniqueTagList() {}
/**
* Creates a UniqueTagList using given tags.
* Enforces no nulls.
*/
public UniqueTagList(Set<Tag> tags) {
requireAllNonNull(tags);
internalList.addAll(tags);
assert CollectionUtil.elementsAreUnique(internalList);
}
/**
* Returns all tags in this list as a Set.
* This set is mutable and change-insulated against the internal list.
*/
public Set<Tag> toSet() {
assert CollectionUtil.elementsAreUnique(internalList);
return new HashSet<>(internalList);
}
/**
* Replaces the Tags in this list with those in the argument tag list.
*/
public void setTags(Set<Tag> tags) {
requireAllNonNull(tags);
internalList.setAll(tags);
assert CollectionUtil.elementsAreUnique(internalList);
}
/**
* Ensures every tag in the argument list exists in this object.
*/
public void mergeFrom(UniqueTagList from) {
final Set<Tag> alreadyInside = this.toSet();
from.internalList.stream()
.filter(tag -> !alreadyInside.contains(tag))
.forEach(internalList::add);
assert CollectionUtil.elementsAreUnique(internalList);
}
/**
* Returns true if the list contains an equivalent Tag as the given argument.
*/
public boolean contains(Tag toCheck) {
requireNonNull(toCheck);
return internalList.contains(toCheck);
}
/**
* Adds a Tag to the list.
*
* @throws DuplicateTagException if the Tag to add is a duplicate of an existing Tag in the list.
*/
public void add(Tag toAdd) throws DuplicateTagException {
requireNonNull(toAdd);
if (contains(toAdd)) {
throw new DuplicateTagException();
}
internalList.add(toAdd);
assert CollectionUtil.elementsAreUnique(internalList);
}
@Override
public Iterator<Tag> iterator() {
assert CollectionUtil.elementsAreUnique(internalList);
return internalList.iterator();
}
public UnmodifiableObservableList<Tag> asObservableList() {
assert CollectionUtil.elementsAreUnique(internalList);
return new UnmodifiableObservableList<>(internalList);
}
@Override
public boolean equals(Object other) {
assert CollectionUtil.elementsAreUnique(internalList);
return other == this // short circuit if same object
|| (other instanceof UniqueTagList // instanceof handles nulls
&& this.internalList.equals(((UniqueTagList) other).internalList));
}
public boolean equalsOrderInsensitive(UniqueTagList other) {
assert CollectionUtil.elementsAreUnique(internalList);
assert CollectionUtil.elementsAreUnique(other.internalList);
return this == other || new HashSet<>(this.internalList).equals(new HashSet<>(other.internalList));
}
@Override
public int hashCode() {
assert CollectionUtil.elementsAreUnique(internalList);
return internalList.hashCode();
}
/**
* Signals that an operation would have violated the 'no duplicates' property of the list.
*/
public static class DuplicateTagException extends DuplicateDataException {
protected DuplicateTagException() {
super("Operation would result in duplicate tags");
}
}
}
|
package seedu.ezdo.logic.commands;
import java.util.List;
import java.util.Optional;
import seedu.ezdo.commons.core.Messages;
import seedu.ezdo.commons.util.CollectionUtil;
import seedu.ezdo.logic.commands.exceptions.CommandException;
import seedu.ezdo.model.tag.UniqueTagList;
import seedu.ezdo.model.todo.DueDate;
import seedu.ezdo.model.todo.Name;
import seedu.ezdo.model.todo.Priority;
import seedu.ezdo.model.todo.ReadOnlyTask;
import seedu.ezdo.model.todo.StartDate;
import seedu.ezdo.model.todo.Task;
import seedu.ezdo.model.todo.UniqueTaskList;
/**
* Edits the details of an existing task in ezDo.
*/
public class EditCommand extends Command {
public static final String COMMAND_WORD = "edit";
public static final String MESSAGE_USAGE = COMMAND_WORD + ": Edits the details of the task identified "
+ "by the index number used in the last task listing. "
+ "Existing values will be overwritten by the input values.\n"
+ "Parameters: INDEX (must be a positive integer) "
+ "[NAME] [p/PRIORITY] [s/START_DATE] [d/DUE_DATE] [t/TAG]...\n"
+ "Example: " + COMMAND_WORD + " 1 p/2 s/10/12/2017";
public static final String MESSAGE_EDIT_TASK_SUCCESS = "Edited Task: %1$s";
public static final String MESSAGE_NOT_EDITED = "At least one field to edit must be provided.";
public static final String MESSAGE_DUPLICATE_TASK = "This task already exists in ezDo.";
private final int filteredTaskListIndex;
private final EditTaskDescriptor editTaskDescriptor;
/**
* @param filteredTaskListIndex the index of the task in the filtered task list to edit
* @param editTaskDescriptor details to edit the task with
*/
public EditCommand(int filteredTaskListIndex, EditTaskDescriptor editTaskDescriptor) {
assert filteredTaskListIndex > 0;
assert editTaskDescriptor != null;
// converts filteredTaskListIndex from one-based to zero-based.
this.filteredTaskListIndex = filteredTaskListIndex - 1;
this.editTaskDescriptor = new EditTaskDescriptor(editTaskDescriptor);
}
@Override
public CommandResult execute() throws CommandException {
List<ReadOnlyTask> lastShownList = model.getFilteredTaskList();
if (filteredTaskListIndex >= lastShownList.size()) {
throw new CommandException(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
}
ReadOnlyTask taskToEdit = lastShownList.get(filteredTaskListIndex);
Task editedTask = createEditedTask(taskToEdit, editTaskDescriptor);
try {
model.updateTask(filteredTaskListIndex, editedTask);
} catch (UniqueTaskList.DuplicateTaskException dte) {
throw new CommandException(MESSAGE_DUPLICATE_TASK);
}
model.updateFilteredListToShowAll();
return new CommandResult(String.format(MESSAGE_EDIT_TASK_SUCCESS, taskToEdit));
}
/**
* Creates and returns a {@code Task} with the details of {@code taskToEdit}
* edited with {@code editTaskDescriptor}.
*/
private static Task createEditedTask(ReadOnlyTask taskToEdit,
EditTaskDescriptor editTaskDescriptor) {
assert taskToEdit != null;
Name updatedName = editTaskDescriptor.getName().orElseGet(taskToEdit::getName);
Priority updatedPriority = editTaskDescriptor.getPriority().orElseGet(taskToEdit::getPriority);
StartDate updatedStartDate = editTaskDescriptor.getStartDate().orElseGet(taskToEdit::getStartDate);
DueDate updatedDueDate = editTaskDescriptor.getDueDate().orElseGet(taskToEdit::getDueDate);
UniqueTagList updatedTags = editTaskDescriptor.getTags().orElseGet(taskToEdit::getTags);
return new Task(updatedName, updatedPriority, updatedStartDate, updatedDueDate, updatedTags);
}
/**
* Stores the details to edit the task with. Each non-empty field value will replace the
* corresponding field value of the task.
*/
public static class EditTaskDescriptor {
private Optional<Name> name = Optional.empty();
private Optional<Priority> priority = Optional.empty();
private Optional<StartDate> startDate = Optional.empty();
private Optional<DueDate> dueDate = Optional.empty();
private Optional<UniqueTagList> tags = Optional.empty();
public EditTaskDescriptor() {}
public EditTaskDescriptor(EditTaskDescriptor toCopy) {
this.name = toCopy.getName();
this.priority = toCopy.getPriority();
this.startDate = toCopy.getStartDate();
this.dueDate = toCopy.getDueDate();
this.tags = toCopy.getTags();
}
/**
* Returns true if at least one field is edited.
*/
public boolean isAnyFieldEdited() {
return CollectionUtil.isAnyPresent(this.name, this.priority,
this.startDate, this.tags);
}
public void setName(Optional<Name> name) {
assert name != null;
this.name = name;
}
public Optional<Name> getName() {
return name;
}
public void setPriority(Optional<Priority> priority) {
assert priority != null;
this.priority = priority;
}
public Optional<Priority> getPriority() {
return priority;
}
public void setStartDate(Optional<StartDate> startDate) {
assert startDate != null;
this.startDate = startDate;
}
public Optional<StartDate> getStartDate() {
return startDate;
}
public void setDueDate(Optional<DueDate> dueDate) {
assert dueDate != null;
this.dueDate = dueDate;
}
public Optional<DueDate> getDueDate() {
return dueDate;
}
public void setTags(Optional<UniqueTagList> tags) {
assert tags != null;
this.tags = tags;
}
public Optional<UniqueTagList> getTags() {
return tags;
}
}
}
|
package techreborn.items.tools;
import me.modmuss50.jsonDestroyer.api.IHandHeld;
import me.modmuss50.jsonDestroyer.api.ITexturedItem;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.item.Item;
import net.minecraft.item.ItemPickaxe;
import net.minecraft.item.ItemStack;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import reborncore.RebornCore;
import reborncore.api.power.IEnergyItemInfo;
import reborncore.common.powerSystem.PoweredItem;
import reborncore.common.util.TorchHelper;
import techreborn.client.TechRebornCreativeTab;
import techreborn.lib.ModInfo;
import techreborn.utils.OreDictUtils;
import java.util.List;
import java.util.Random;
import net.minecraft.item.Item.ToolMaterial;
public class ItemJackhammer extends ItemPickaxe implements IEnergyItemInfo, ITexturedItem , IHandHeld
{
public static int tier = 1;
public int maxCharge = 1;
public int cost = 250;
public double transferLimit = 100;
public ItemJackhammer(ToolMaterial material, String unlocalizedName, int energyCapacity, int tier)
{
super(material);
efficiencyOnProperMaterial = 20F;
setCreativeTab(TechRebornCreativeTab.instance);
setMaxStackSize(1);
setMaxDamage(240);
setUnlocalizedName(unlocalizedName);
RebornCore.jsonDestroyer.registerObject(this);
this.maxCharge = energyCapacity;
this.tier = tier;
}
@Override public boolean onBlockDestroyed(ItemStack stack, World worldIn, IBlockState blockIn, BlockPos pos,
EntityLivingBase entityLiving)
{
Random rand = new Random();
if (rand.nextInt(EnchantmentHelper.getEnchantmentLevel(Enchantment.getEnchantmentByID(34), stack) + 1) == 0)
{
PoweredItem.useEnergy(cost, stack);
}
return true;
}
@Override
public boolean canHarvestBlock(IBlockState state)
{
// TODO needs // FIXME: 13/03/2016
return OreDictUtils.isOre(state, "stone") && PoweredItem.canUseEnergy(cost, null);
}
@Override
public float getStrVsBlock(ItemStack stack, IBlockState state) {
if ((OreDictUtils.isOre(state, "stone") || state.getBlock() == Blocks.STONE) && PoweredItem.canUseEnergy(cost, stack)) {
return efficiencyOnProperMaterial;
} else {
return 0.5F;
}
}
@Override
public boolean hitEntity(ItemStack itemstack, EntityLivingBase entityliving, EntityLivingBase entityliving1)
{
return true;
}
@Override
public EnumActionResult onItemUse(ItemStack stack, EntityPlayer playerIn, World worldIn, BlockPos pos,
EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ)
{
return TorchHelper.placeTorch(stack, playerIn, worldIn, pos, facing, hitX, hitY, hitZ, hand);
}
@Override
public boolean isRepairable()
{
return false;
}
@Override
public double getMaxPower(ItemStack stack)
{
return maxCharge;
}
@Override
public boolean canAcceptEnergy(ItemStack stack)
{
return true;
}
@Override
public boolean canProvideEnergy(ItemStack stack)
{
return false;
}
@Override
public double getMaxTransfer(ItemStack stack)
{
return transferLimit;
}
@Override
public int getStackTier(ItemStack stack)
{
return tier;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
@SideOnly(Side.CLIENT)
public void getSubItems(Item item, CreativeTabs par2CreativeTabs, List itemList)
{
ItemStack itemStack = new ItemStack(this, 1);
itemList.add(itemStack);
ItemStack charged = new ItemStack(this, 1);
PoweredItem.setEnergy(getMaxPower(charged), charged);
itemList.add(charged);
}
@Override
public double getDurabilityForDisplay(ItemStack stack)
{
if (PoweredItem.getEnergy(stack) > getMaxPower(stack))
{
return 0;
}
double charge = (PoweredItem.getEnergy(stack) / getMaxPower(stack));
return 1 - charge;
}
@Override
public boolean showDurabilityBar(ItemStack stack)
{
return true;
}
@Override
public String getTextureName(int damage)
{
return "techreborn:items/tool/nullJackhammer";
}
@Override
public int getMaxMeta()
{
return 1;
}
@Override
@SideOnly(Side.CLIENT)
public ModelResourceLocation getModel(ItemStack stack, EntityPlayer player, int useRemaining)
{
return new ModelResourceLocation(ModInfo.MOD_ID + ":" + getUnlocalizedName(stack).substring(5), "inventory");
}
}
|
package tk.allele.duckshop.items;
import info.somethingodd.bukkit.OddItem.OddItem;
import org.bukkit.Material;
import org.bukkit.inventory.ItemStack;
import tk.allele.duckshop.errors.InvalidSyntaxException;
import java.lang.reflect.Field;
import java.util.Map;
import java.util.NavigableSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Represents a tangible item, rather than money.
*/
public class TangibleItem extends Item {
/**
* The format for a tangible item: the amount as an integer, then a
* space, then the item name, then an optional durability value.
*/
private static final Pattern tangibleItemPattern = Pattern.compile("(\\d+)\\s+([A-Za-z_]+|\\d+)\\s*(\\d*)");
private static final int NAME_LENGTH = 10;
private final int itemId;
private final int amount;
private final short damage;
/**
* Create a new TangibleItem instance.
* <p>
* The item string is not parsed; it is simply kept so it can be
* later retrieved by {@link #getOriginalString()}.
*/
public TangibleItem(final int itemId, final int amount, final short damage, final String itemString) {
super(itemString);
this.itemId = itemId;
this.amount = amount;
this.damage = damage;
}
/**
* Create a new TangibleItem.
*/
public TangibleItem(final int itemId, final int amount, final short damage) {
super();
this.itemId = itemId;
this.amount = amount;
this.damage = damage;
}
/**
* Parse a TangibleItem from a String.
*
* @throws InvalidSyntaxException if the item cannot be parsed.
*/
public static TangibleItem fromString(final String itemString)
throws InvalidSyntaxException {
Matcher matcher = tangibleItemPattern.matcher(itemString);
if(matcher.matches()) {
// Group 1 is definitely an integer, since it was matched with "\d+"
int amount = Integer.parseInt(matcher.group(1));
String itemName = matcher.group(2);
int itemId;
short damage = 0;
// Try parsing it as an item ID first
try {
itemId = Integer.parseInt(itemName);
} catch(NumberFormatException ex) {
// If it isn't an integer, treat it as an item name
ItemStack itemDfn;
try {
itemDfn = OddItem.getItemStack(itemName);
} catch(IllegalArgumentException ex2) {
throw new InvalidSyntaxException();
}
itemId = itemDfn.getTypeId();
damage = itemDfn.getDurability();
}
// If there's another number after that, it's a damage value
try {
damage = Short.parseShort(matcher.group(3));
} catch(NumberFormatException ex) {
// Do nothing -- keep the damage value from the code above
}
// Check if it's actually a real item
if(Material.getMaterial(itemId) == null) {
throw new InvalidSyntaxException();
}
// Create the object!
return new TangibleItem(itemId, amount, damage, itemString);
} else {
throw new InvalidSyntaxException();
}
}
/**
* Get the item ID, or the data value.
*/
public int getItemId() {
return itemId;
}
/**
* Get the number of items.
*/
public int getAmount() {
return amount;
}
/**
* Get the damage value of this object.
*/
public short getDamage() {
return damage;
}
/**
* Create a single ItemStack corresponding to this object.
*/
public ItemStack toItemStack() {
return new ItemStack(itemId, amount, damage);
}
/**
* Create an array of ItemStacks with the same data as this object,
* but grouped into stacks.
*/
public ItemStack[] toItemStackArray() {
int maxStackSize = Material.getMaterial(itemId).getMaxStackSize();
ItemStack[] stacks;
int quotient = amount / maxStackSize;
if(amount % maxStackSize == 0) {
stacks = new ItemStack[quotient];
} else {
// If it cannot be divided evenly, the last cell will
// contain the part left over
stacks = new ItemStack[quotient+1];
stacks[quotient] = new ItemStack(itemId, amount % maxStackSize, damage);
}
for(int i = 0; i < quotient; ++i) {
stacks[i] = new ItemStack(itemId, maxStackSize, damage);
}
return stacks;
}
@Override
public boolean equals(Object thatObj) {
if(thatObj instanceof TangibleItem) {
TangibleItem that = (TangibleItem) thatObj;
return (this.itemId == that.itemId && this.damage == that.damage);
} else if(thatObj instanceof ItemStack) {
ItemStack that = (ItemStack) thatObj;
return (this.itemId == that.getTypeId() && this.damage == that.getDurability());
} else {
return false;
}
}
@Override
public int hashCode() {
int hash = itemId - 199;
hash = hash * 887 + damage;
hash = hash * 887 + amount;
return hash;
}
@SuppressWarnings("unchecked")
private static NavigableSet<String> getAliasesById(int itemId, short damage) {
Field itemsField;
try {
itemsField = OddItem.class.getDeclaredField("items");
} catch (NoSuchFieldException e) {
throw new RuntimeException(e);
}
itemsField.setAccessible(true);
Map<String, NavigableSet<String>> items;
try {
items = (Map<String, NavigableSet<String>>) itemsField.get(null);
} catch(IllegalAccessException e) {
throw new RuntimeException(e);
}
NavigableSet<String> result;
if((result = items.get(itemId + ";" + damage)) != null) {
return result;
} else if(damage == 0 && (result = items.get(Integer.toString(itemId))) != null) {
return result;
} else {
return null;
}
}
private static String getBestName(NavigableSet<String> aliases) {
String currentName = null;
for(String name : aliases) {
if(name.length() <= NAME_LENGTH) {
if(currentName != null && currentName.length() == NAME_LENGTH) {
break;
} else {
currentName = name;
}
}
}
return currentName;
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder(15);
buffer.append(Integer.toString(amount));
buffer.append(" ");
NavigableSet<String> aliases = getAliasesById(itemId, damage);
if(aliases != null) {
// If there is a specific name for this, use it
buffer.append(getBestName(aliases));
} else {
// Otherwise, use the generic name + damage value
aliases = getAliasesById(itemId, (short) 0);
if(aliases != null) {
buffer.append(getBestName(aliases));
buffer.append(Short.toString(damage));
} else {
// If there isn't even a generic name, just use the ID
buffer.append(Integer.toString(itemId));
if(damage != 0) {
buffer.append(" ");
buffer.append(Short.toString(damage));
}
}
}
return buffer.toString();
}
}
|
package org.intermine.web;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.struts.action.ActionForward;
/**
* Utility wrapper class for programatically adding parameters to ActionForward paths.
* The <code>redirect</code> property of the new ActionForward returned by forward()
* will be equal to the redirect setting of the original ActionForward.
*
* @author tom
*/
public class ForwardParameters
{
/** Original ActionForward. */
protected ActionForward af;
/** Map from parameter name to parameter value. */
protected Map params = new LinkedHashMap();
/** Anchor name. */
protected String anchor;
/**
* Creates a new instance of ForwardParameters.
*
* @param af the ActionForward to append parameters to
*/
public ForwardParameters(ActionForward af) {
this.af = af;
}
/**
* Add a parameter to the path.
*
* @param name the name of the parameter
* @param value the value of the parameter
* @return this ForwardParameters object
*/
public ForwardParameters addParameter(String name, String value) {
params.put(name, value);
return this;
}
/**
* Add an anchor to the path.
*
* @param anchor anchor name
* @return this ForwardParameters object
*/
public ForwardParameters addAnchor(String anchor) {
this.anchor = anchor;
return this;
}
/**
* Construct the resulting ActionForward.
*
* @return ActionForward with parameters in path
*/
public ActionForward forward() {
String path = "";
Iterator iter = params.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
if (path.length() > 0) {
path += "&";
}
path += entry.getKey() + "=" + entry.getValue();
}
if (path.length() > 0) {
path = "?" + path;
}
if (anchor != null) {
path += "#" + anchor;
}
return new ActionForward(af.getPath() + path, af.getRedirect());
}
}
|
package com.jukta.maven;
import com.jukta.jtahoe.gen.GenContext;
import com.jukta.jtahoe.gen.NodeProcessor;
import com.jukta.jtahoe.gen.xml.XthBlockModelProvider;
import com.jukta.jtahoe.resource.*;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.logging.Log;
import org.apache.maven.project.MavenProject;
import javax.tools.JavaFileObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import org.apache.maven.model.Resource;
import org.codehaus.plexus.util.FileUtils;
/**
* @since 1.0
*/
public class JarBuilder {
private String blocksDir;
private String resourceSrcDir;
private File resourceDestDir;
private File targetDir;
private MavenProject mavenProject;
private MavenSession mavenSession;
protected String id;
private Log log;
public JarBuilder(String blocksDir, String resourceSrcDir, File targetDir, MavenProject mavenProject, MavenSession mavenSession, Log log) {
this.blocksDir = blocksDir;
this.resourceSrcDir = resourceSrcDir;
this.targetDir = targetDir;
this.mavenProject = mavenProject;
this.mavenSession = mavenSession;
id = UUID.randomUUID().toString();
this.log = log;
}
public void generateSources(ResourceResolver resolver) throws IOException {
XthBlockModelProvider provider = new XthBlockModelProvider(resolver);
NodeProcessor nodeProcessor = new NodeProcessor();
// Map<String, List<JavaFileObject>> javaFileObjects = ;
File compileDir = new File(targetDir, "java");
log.info("Generating source files");
for (GenContext.Package aPackage : nodeProcessor.process(provider).values()) {
for (JavaFileObject f : aPackage.getJavaFileObjects()) {
log.info(f.getName());
BufferedReader reader = new BufferedReader(f.openReader(false));
File file = new File(compileDir, f.getName());
file.getParentFile().mkdirs();
FileWriter w = new FileWriter(file);
String line;
while ((line = reader.readLine()) != null) {
w.append(line);
}
w.close();
reader.close();
}
}
mavenProject.addCompileSourceRoot(compileDir.getAbsolutePath());
}
private void generateResourceFile(ResourceResolver resources, ResourceType type) throws IOException {
List<com.jukta.jtahoe.resource.Resource> files = new ArrayList<>();
files.addAll(resources.getResources(type));
StringBuilder stringBuilder = ResourceAppender.append(files);
File file = new File(resourceDestDir, id + "." + type.getExtension());
log.info("Generated resource file: " + file.getName());
FileWriter w = new FileWriter(file);
w.append(stringBuilder.toString());
w.close();
}
private void copyResources() throws IOException {
File resDir = new File(resourceDestDir, id);
resDir.mkdirs();
log.info("Creating resource dir: " + resDir.getName());
FileUtils.copyDirectoryStructure(new File(resourceSrcDir), resDir);
}
protected void generateProps() throws IOException {
File file = new File(resourceDestDir, "jtahoe.properties");
FileWriter w = new FileWriter(file);
w.append("lib.name=" + mavenProject.getArtifactId() + "\n");
w.append("lib.version=" + mavenProject.getVersion() + "\n");
w.append("lib.id=" + id + "\n");
w.close();
}
public void generate() throws IOException {
resourceDestDir = new File(targetDir, "resources");
resourceDestDir.mkdirs();
Resource resource = new Resource();
resource.setDirectory(resourceDestDir.getAbsolutePath());
mavenProject.addResource(resource);
ResourceResolver resolver = new FileSystemResources(blocksDir);
generateSources(resolver);
generateResourceFile(resolver, ResourceType.CSS);
generateResourceFile(resolver, ResourceType.JS);
copyResources();
generateProps();
}
}
|
package org.jboss.as.jmx;
import java.io.IOException;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.MalformedURLException;
import java.net.ServerSocket;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.RMIServerSocketFactory;
import java.rmi.server.UnicastRemoteObject;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.HashMap;
import javax.management.MBeanServer;
import javax.management.remote.JMXServiceURL;
import javax.management.remote.rmi.RMIConnectorServer;
import javax.management.remote.rmi.RMIJRMPServerImpl;
import org.jboss.as.server.services.net.SocketBinding;
import org.jboss.logging.Logger;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceName;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
/**
* Set up JSR-160 connector
*
* @author <a href="kabir.khan@jboss.com">Kabir Khan</a>
* @author Jason T. Greene
*/
public class JMXConnectorService implements Service<Void> {
public static final ServiceName SERVICE_NAME = ServiceName.JBOSS.append("mbean", "connector");
private static final String SERVER_HOSTNAME = "java.rmi.server.hostname";
private static final String RMI_BIND_NAME = "jmxrmi";
private static final int BACKLOG = 50;
private final Logger log = Logger.getLogger(JMXConnectorService.class);
private final InjectedValue<MBeanServer> injectedMBeanServer = new InjectedValue<MBeanServer>();
private final InjectedValue<SocketBinding> registryPortBinding = new InjectedValue<SocketBinding>();
private final InjectedValue<SocketBinding> serverPortBinding = new InjectedValue<SocketBinding>();
private RMIConnectorServer adapter;
private RMIJRMPServerImpl rmiServer;
private Registry registry;
public static void addService(final ServiceTarget target, final String serverBinding, final String registryBinding) {
JMXConnectorService jmxConnectorService = new JMXConnectorService();
target.addService(JMXConnectorService.SERVICE_NAME, jmxConnectorService)
.addDependency(MBeanServerService.SERVICE_NAME, MBeanServer.class, jmxConnectorService.getMBeanServerServiceInjector())
.addDependency(SocketBinding.JBOSS_BINDING_NAME.append(registryBinding), SocketBinding.class, jmxConnectorService.getRegistryPortBinding())
.addDependency(SocketBinding.JBOSS_BINDING_NAME.append(serverBinding), SocketBinding.class, jmxConnectorService.getServerPortBinding())
.setInitialMode(ServiceController.Mode.ACTIVE)
.install();
}
@Override
public void start(StartContext context) throws StartException {
log.info("Starting remote JMX connector");
setRmiServerProperty(serverPortBinding.getValue().getAddress().getHostAddress());
try {
SocketBinding registryBinding = registryPortBinding.getValue();
RMIServerSocketFactory registrySocketFactory = new JMXServerSocketFactory(registryBinding);
SocketBinding rmiServerBinding = serverPortBinding.getValue();
RMIServerSocketFactory serverSocketFactory = new JMXServerSocketFactory(rmiServerBinding);
registry = LocateRegistry.createRegistry(getRmiRegistryPort(), null, registrySocketFactory);
HashMap<String, Object> env = new HashMap<String, Object>();
rmiServer = new RMIJRMPServerImpl(getRmiServerPort(), null, serverSocketFactory, env);
JMXServiceURL url = buildJMXServiceURL();
adapter = new RMIConnectorServer(url, env, rmiServer, injectedMBeanServer.getValue());
adapter.start();
registry.rebind(RMI_BIND_NAME, rmiServer.toStub());
} catch (Exception e) {
throw new StartException(e);
}
}
public void stop(StopContext context) {
try {
registry.unbind(RMI_BIND_NAME);
} catch (Exception e) {
log.error("Could not unbind jmx connector from registry", e);
} finally {
try {
adapter.stop();
} catch (Exception e) {
log.error("Could not stop connector server", e);
} finally {
try {
UnicastRemoteObject.unexportObject(registry, true);
} catch (Exception e) {
log.error("Could not shutdown rmi registry");
}
}
}
log.info("JMX remote connector stopped");
}
private JMXServiceURL buildJMXServiceURL() throws MalformedURLException {
String host = getRmiRegistryAddressString();
if (host.indexOf(':') != -1) { // is this a IPV6 literal address? if yes, surround with square brackets
// as per rfc2732.
// IPV6 literal addresses have one or more colons
// IPV4 addresses/hostnames have no colons
host = "[" + host + "]";
}
JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://" + host);
return url;
}
@Override
public Void getValue() throws IllegalStateException {
return null;
}
public InjectedValue<MBeanServer> getMBeanServerServiceInjector() {
return injectedMBeanServer;
}
public InjectedValue<SocketBinding> getRegistryPortBinding() {
return registryPortBinding;
}
public InjectedValue<SocketBinding> getServerPortBinding() {
return serverPortBinding;
}
private int getRmiRegistryPort() {
return registryPortBinding.getValue().getSocketAddress().getPort();
}
private int getRmiServerPort() {
return serverPortBinding.getValue().getSocketAddress().getPort();
}
private InetAddress getRmiRegistryAddress() {
return registryPortBinding.getValue().getSocketAddress().getAddress();
}
private String getRmiRegistryAddressString() {
return registryPortBinding.getValue().getSocketAddress().getAddress().getHostAddress();
}
private static class JMXServerSocketFactory implements RMIServerSocketFactory, Serializable {
private static final long serialVersionUID = 1564081885379700777L;
private final SocketBinding socketBinding;
public JMXServerSocketFactory(final SocketBinding socketBinding) {
this.socketBinding = socketBinding;
}
@Override
public ServerSocket createServerSocket(int port) throws IOException {
int fixed = socketBinding.isFixedPort() ? 0 : 1;
int configuredPort = socketBinding.getPort() + (socketBinding.getSocketBindings().getPortOffset() * fixed);
if (port != configuredPort) {
throw new IllegalStateException(String.format("Received request for server socket %s on port [%d] but am configured for port [%d]",
socketBinding.getName(), port, configuredPort));
}
return socketBinding.createServerSocket(BACKLOG);
}
}
private void setRmiServerProperty(final String address) {
SecurityManager sm = System.getSecurityManager();
if(sm != null) {
AccessController.doPrivileged(new PrivilegedAction<Void>() {
public Void run() {
System.setProperty(SERVER_HOSTNAME, address);
return null;
}
});
} else {
System.setProperty(SERVER_HOSTNAME, address);
}
}
}
|
// -*- indent-tabs-mode:nil; c-basic-offset:4; -*-
package ca.patricklam.judodb.client;
import java.util.Collection;
import java.util.List;
import java.util.LinkedList;
import java.util.Date;
import java.util.Collections;
import java.util.HashMap;
import java.util.Objects;
import com.google.gwt.core.client.JsonUtils;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.datepicker.client.CalendarUtil;
public class CostCalculator {
// constants for Prix
public final static String JUDO_QC = null;
public final static String ALL_DIVISIONS = "*";
public final static String ALL_COURS = "-1";
static int remainingWeeks(ServiceData sd, SessionSummary ss, Date dateInscription, List<SessionSummary> sessionSummaries) {
try {
if (ss == null) return 0;
Date sessionEnd = Constants.DB_DATE_FORMAT.parse(ss.getLastClassDate());
double remainingWeeks = (CalendarUtil.getDaysBetween(dateInscription, sessionEnd) + 6) / 7.0;
if (sd.getSessionCount() == 2) {
for (SessionSummary ssp : sessionSummaries) {
if (ssp.getSeqno().equals(ss.getLinkedSeqno())) {
remainingWeeks += totalWeeks(ssp);
}
}
}
return (int)(remainingWeeks+0.5);
}
catch (NullPointerException e) { return 1; }
catch (IllegalArgumentException e) { return 1; }
}
static int totalWeeks(SessionSummary ss) {
try {
if (ss == null) return 1;
Date sessionStart = Constants.DB_DATE_FORMAT.parse(ss.getFirstClassDate());
Date sessionEnd = Constants.DB_DATE_FORMAT.parse(ss.getLastClassDate());
double totalWeeks = (CalendarUtil.getDaysBetween(sessionStart, sessionEnd) + 6) / 7.0;
return (int)(totalWeeks+0.5);
}
catch (NullPointerException e) { return 1; }
catch (IllegalArgumentException e) { return 1; }
}
static int totalWeeksBothSessions(ServiceData sd, SessionSummary ss, List<SessionSummary> sessionSummaries) {
int totalWeeks = totalWeeks(ss);
if (ss != null && sd.getSessionCount() == 2) {
for (SessionSummary ssp : sessionSummaries) {
if (ssp.getSeqno().equals(ss.getLinkedSeqno())) {
totalWeeks += totalWeeks(ssp);
}
}
}
return totalWeeks;
}
static double fraisCours(ClientData cd, ServiceData sd, ClubSummary cs, List<SessionSummary> sessionSummaries, List<CoursSummary> coursSummaries, List<Prix> prixSummaries) {
Constants.Division d = null;
String[] sessionsByName = sd.getSessions().split(" ");
StringBuilder sessions = new StringBuilder();
for (String s : sessionsByName) {
for (SessionSummary ss : sessionSummaries) {
if (ss.getAbbrev().equals(s)) {
d = cd.getDivision(ss.getYear());
break;
}
}
}
if (d == null) return -1.0;
return Double.parseDouble(getFrais(prixSummaries, cs,
JudoDB.sessionSeqnosFromAbbrevs(sd.getSessions(), sessionSummaries),
d.abbrev,
sd.getCours()));
}
static double proratedFraisCours(ClientData cd, ServiceData sd, ClubSummary cs, SessionSummary ss, List<SessionSummary> sessionSummaries, List<CoursSummary> coursSummaries, List<Prix> prixSummaries) {
double baseCost = fraisCours(cd, sd, cs, sessionSummaries, coursSummaries, prixSummaries);
if (sd == null || sd.getDateInscription() == null || sd.getDateInscription() == Constants.DB_DUMMY_DATE)
return baseCost;
Date dateInscription = null;
try { dateInscription = Constants.DB_DATE_FORMAT.parse(sd.getDateInscription()); } catch (Exception e) { return baseCost; }
// calculate number of weeks between start of session and dateInscription
// calculate total number of weeks
// divide, then add Constants.PRORATA_PENALITE
// but only use the prorated frais if ew < tw - 4
int rw = remainingWeeks(sd, ss, dateInscription, sessionSummaries);
int tw = totalWeeksBothSessions(sd, ss, sessionSummaries);
double supplement_prorata = 0;
if (cs.getSupplementProrata() != null && !cs.getSupplementProrata().equals(""))
supplement_prorata = Double.parseDouble(cs.getSupplementProrata());
double prorataCost = baseCost * ((double)rw / (double)tw) + supplement_prorata;
if (rw < tw - 4)
return Math.min(baseCost, prorataCost);
else
return baseCost;
}
private static final double getFraisJudoQC(SessionSummary ss, Constants.Division c, List<SessionSummary> sessionSummaries, List<Prix> prixSummaries) {
// xxx fix ss.getSeqno().
StringBuilder seqnoPair = new StringBuilder();
if (ss.isPrimary()) {
seqnoPair.append(ss.getSeqno());
SessionSummary linked = JudoDB.getLinkedSession(ss, sessionSummaries);
if (ss != linked) {
seqnoPair.append(" ");
seqnoPair.append(linked.getSeqno());
}
} else {
SessionSummary linked = JudoDB.getLinkedSession(ss, sessionSummaries);
seqnoPair.append(linked.getSeqno());
if (ss != linked) {
seqnoPair.append(" ");
seqnoPair.append(ss.getSeqno());
}
}
return Double.parseDouble(getFrais(prixSummaries, null,
seqnoPair.toString(), c.abbrev,
ALL_COURS));
}
static double affiliationFrais(ClientData cd, ServiceData sd, SessionSummary ss, List<SessionSummary> sessionSummaries, List<Prix> prixSummaries) {
if (sd == null) return 0.0;
boolean sans_affiliation = sd.getSansAffiliation();
boolean affiliation_initiation = sd.getAffiliationInitiation();
boolean affiliation_ecole = sd.getAffiliationEcole();
boolean affiliation_parascolaire = sd.getAffiliationParascolaire();
Constants.Division c = cd.getDivision(ss.getYear());
double dAffiliationFrais = 0.0;
if (!sans_affiliation) {
if (affiliation_initiation)
dAffiliationFrais = Constants.COUT_JUDOQC_INITIATION;
else if (affiliation_ecole)
dAffiliationFrais = Constants.COUT_JUDOQC_ECOLE;
else if (affiliation_parascolaire)
dAffiliationFrais = Constants.COUT_JUDOQC_PARASCOLAIRE;
else
dAffiliationFrais = getFraisJudoQC(ss, c, sessionSummaries, prixSummaries);
}
return dAffiliationFrais;
}
static double suppFrais(ServiceData sd, ClubSummary cs, Collection<ProduitSummary> ps, double fraisSoFar) {
if (sd == null) return 0.0;
double judogiFrais = 0.0;
for (ProduitSummary p : ps) {
try { judogiFrais += Double.parseDouble(p.getMontant()); } catch (Exception e) {}
}
boolean resident = sd.getResident();
boolean paypal = sd.getPaypal();
double dSuppFrais = judogiFrais;
if (resident)
dSuppFrais -= Double.parseDouble(cs.getEscompteResident());
if (paypal)
dSuppFrais += Constants.PAYPAL_PCT / 100.0 * (dSuppFrais + fraisSoFar);
return dSuppFrais;
}
static boolean isCasSpecial(ServiceData sd, EscompteSummary es) {
return es != null && es.getAmountPercent().equals("-1");
}
static EscompteSummary getApplicableEscompte(ServiceData sd,
List<EscompteSummary> escompteSummaries) {
EscompteSummary es = null;
for (EscompteSummary e : escompteSummaries) {
if (e.getId().equals(sd.getEscompteId())) {
es = e; break;
}
}
return es;
}
static Collection<ProduitSummary> getApplicableProduits(ServiceData sd,
List<ProduitSummary> produitSummaries) {
Collection<ProduitSummary> ps = new java.util.ArrayList<ProduitSummary>();
if (sd.getJudogi() == null) return ps;
List<String> produits = java.util.Arrays.asList(sd.getJudogi().split(";"));
for (ProduitSummary p : produitSummaries) {
if (produits.contains(p.getId()))
ps.add(p);
}
return ps;
}
static double escompteFrais(ServiceData sd, double dCategorieFrais,
List<EscompteSummary> escompteSummaries) {
if (sd == null) return 0.0;
EscompteSummary es = getApplicableEscompte(sd, escompteSummaries);
if (es == null) return 0.0;
double escomptePct = 0.0;
boolean emptyPct = false;
if (isCasSpecial(sd, es)) {
// cas special, use amount stored in sd
return Double.parseDouble(sd.getEscompteFrais());
} else {
if (es.getAmountPercent().equals(""))
emptyPct = true;
else
escomptePct = Double.parseDouble(es.getAmountPercent());
}
if (emptyPct)
return es.getAmountAbsolute().equals("") ? 0.0 : -Double.parseDouble(es.getAmountAbsolute());
return -dCategorieFrais * (escomptePct / 100.0);
}
static String getWeeksSummary(ServiceData sd, SessionSummary ss, Date dateInscription, List<SessionSummary> sessionSummaries) {
int rw = remainingWeeks(sd, ss, dateInscription, sessionSummaries);
int tw = totalWeeksBothSessions(sd, ss, sessionSummaries);
if (rw < tw)
return " ("+rw+"/"+tw+")";
else
return "";
}
public static String getFrais(List<Prix> applicablePrix, ClubSummary cs, String session_seqno, String division_abbrev, String cours_id) {
String club_id = (cs == null) ? JUDO_QC : cs.getId();
if (cs != null && !cs.getAjustableCours())
cours_id = ALL_COURS;
if (cs != null && !cs.getAjustableDivision())
division_abbrev = ALL_DIVISIONS;
for (Prix p : applicablePrix) {
if (p.getClubId().equals(club_id) &&
p.getSessionSeqno().equals(session_seqno) &&
p.getDivisionAbbrev().equals(division_abbrev) &&
p.getCoursId().equals(cours_id))
return p.getFrais();
}
return "0";
}
// extract data from Prix objects and lists thereof...
public static List<Prix> getPrixForClubSessionCours(List<Prix> applicablePrix, String club_id, String session_seqno, String cours_id, boolean isUnidivision) {
if (isUnidivision) {
for (Prix p : applicablePrix) {
if (p.getClubId().equals(club_id) &&
p.getSessionSeqno().equals(session_seqno) &&
p.getCoursId().equals(cours_id) &&
p.getDivisionAbbrev().equals(ALL_DIVISIONS))
return Collections.singletonList(p);
}
Prix np = JsonUtils.<Prix>safeEval
("{\"id\":\"0\", \"club_id\":\""+club_id+"\", \"session_seqno\":\""+session_seqno+"\","+
"\"division_abbrev\":\""+ALL_DIVISIONS+"\",\"cours_id\":\""+cours_id+"\",\"frais\":\"0\"}");
return Collections.singletonList(np);
}
HashMap<Constants.Division, Prix> rv = new HashMap<>();
for (Prix p : applicablePrix) {
if (Objects.equals(p.getClubId(), club_id) &&
Objects.equals(p.getSessionSeqno(), session_seqno) &&
Objects.equals(p.getCoursId(), cours_id))
rv.put(Constants.getDivisionByAbbrev(p.getDivisionAbbrev()), p);
}
List<Prix> rvSorted = new LinkedList<>();
for (Constants.Division d : Constants.DIVISIONS) {
if (rv.containsKey(d))
rvSorted.add(rv.get(d));
else {
Prix np = JsonUtils.<Prix>safeEval
("{\"id\":\"0\", \"club_id\":\""+club_id+"\", \"session_seqno\":\""+session_seqno+"\","+
"\"division_abbrev\":\""+d.abbrev+"\",\"cours_id\":\""+cours_id+"\",\"frais\":\"0\"}");
rvSorted.add(np);
}
}
return rvSorted;
}
/** Model-level method to recompute costs. */
public static void recompute(SessionSummary ss, ClientData cd, ServiceData sd, ClubSummary cs, List<SessionSummary> sessionSummaries, List<CoursSummary> coursSummaries, Collection<ProduitSummary> ps, boolean prorataOverride, List<Prix> prixSummaries, List<EscompteSummary> escompteSummaries) {
if (prixSummaries == null) return;
if (ss == null) return;
double dCategorieFrais = proratedFraisCours(cd, sd, cs, ss, sessionSummaries, coursSummaries, prixSummaries);
if (!prorataOverride) dCategorieFrais = fraisCours(cd, sd, cs, sessionSummaries, coursSummaries, prixSummaries);
double dEscompteFrais = escompteFrais(sd, dCategorieFrais, escompteSummaries);
double dAffiliationFrais = affiliationFrais(cd, sd, ss, sessionSummaries, prixSummaries);
double dSuppFrais = suppFrais(sd, cs, ps, dCategorieFrais + dEscompteFrais + dAffiliationFrais);
if (sd != null) {
sd.setCategorieFrais(Double.toString(dCategorieFrais));
sd.setEscompteFrais(Double.toString(dEscompteFrais));
sd.setAffiliationFrais(Double.toString(dAffiliationFrais));
sd.setSuppFrais(Double.toString(dSuppFrais));
sd.setFrais(Double.toString(dCategorieFrais + dAffiliationFrais + dEscompteFrais + dSuppFrais));
}
}
}
|
package com.bitsofproof.supernode.core;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.bouncycastle.util.encoders.Hex;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;
import com.bitsofproof.supernode.messages.AddrMessage;
import com.bitsofproof.supernode.messages.AlertMessage;
import com.bitsofproof.supernode.messages.BitcoinMessageListener;
import com.bitsofproof.supernode.messages.BlockMessage;
import com.bitsofproof.supernode.messages.GetBlocksMessage;
import com.bitsofproof.supernode.messages.GetDataMessage;
import com.bitsofproof.supernode.messages.InvMessage;
import com.bitsofproof.supernode.messages.VersionMessage;
public class BitcoinPeer extends P2P.Peer
{
private static final Logger log = LoggerFactory.getLogger (BitcoinPeer.class);
private final TransactionTemplate transactionTemplate;
private BitcoinNetwork network;
private String agent;
private long height;
private long peerVersion;
private long peerServices;
private static final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool (1);
private static final long CONNECTIONTIMEOUT = 30;
public class Message implements P2P.Message
{
private final String command;
private long version;
public Message (String command)
{
this.command = command;
version = peerVersion;
}
public long getVersion ()
{
return version;
}
public void setVersion (long version)
{
this.version = version;
}
public String getCommand ()
{
return command;
}
@Override
public byte[] toByteArray () throws NoSuchAlgorithmException
{
ByteArrayOutputStream out = new ByteArrayOutputStream ();
WireFormat.Writer writer = new WireFormat.Writer (out);
writer.writeUint32 (network.getChain ().getMagic ());
writer.writeZeroDelimitedString (getCommand (), 12);
WireFormat.Writer payload = new WireFormat.Writer ();
toWire (payload);
byte[] data = payload.toByteArray ();
writer.writeUint32 (data.length);
byte[] checksum = new byte[4];
MessageDigest sha;
sha = MessageDigest.getInstance ("SHA-256");
System.arraycopy (sha.digest (sha.digest (data)), 0, checksum, 0, 4);
writer.writeBytes (checksum);
writer.writeBytes (data);
return writer.toByteArray ();
}
@Override
public String dump ()
{
try
{
return new String (Hex.encode (toByteArray ()), "UTF-8");
}
catch ( UnsupportedEncodingException e )
{
}
catch ( NoSuchAlgorithmException e )
{
}
return null;
}
public void validate () throws ValidationException
{
}
public void toWire (WireFormat.Writer writer)
{
};
public void fromWire (WireFormat.Reader reader)
{
};
}
public Message createMessage (String command)
{
if ( command.equals ("version") )
{
return new VersionMessage (this);
}
else if ( command.equals ("inv") )
{
return new InvMessage (this);
}
else if ( command.equals ("addr") )
{
return new AddrMessage (this);
}
else if ( command.equals ("getdata") )
{
return new GetDataMessage (this);
}
else if ( command.equals ("getblocks") )
{
return new GetBlocksMessage (this);
}
else if ( command.equals ("block") )
{
return new BlockMessage (this);
}
else if ( command.equals ("alert") )
{
return new AlertMessage (this, this.getNetwork ().getChain ().getAlertKey ());
}
return new Message (command);
}
public Map<String, ArrayList<BitcoinMessageListener>> listener = Collections.synchronizedMap (new HashMap<String, ArrayList<BitcoinMessageListener>> ());
public BitcoinPeer (P2P p2p, TransactionTemplate transactionTemplate, InetSocketAddress address)
{
p2p.super (address);
network = (BitcoinNetwork) p2p;
this.transactionTemplate = transactionTemplate;
// this will be overwritten by the first version message we get
peerVersion = network.getChain ().getVersion ();
addListener ("version", new BitcoinMessageListener ()
{
@Override
public void process (BitcoinPeer.Message m, BitcoinPeer peer) throws Exception
{
VersionMessage v = (VersionMessage) m;
agent = v.getAgent ();
height = v.getHeight ();
peerVersion = Math.min (peerVersion, v.getVersion ());
peerServices = v.getServices ();
peer.send (peer.createMessage ("verack"));
}
});
addListener ("verack", new BitcoinMessageListener ()
{
@Override
public void process (BitcoinPeer.Message m, BitcoinPeer peer)
{
log.info ("Connection to '" + getAgent () + "' at " + getAddress () + " Open connections: " + getNetwork ().getNumberOfConnections ());
network.addPeer (peer);
network.notifyPeerAdded (peer);
}
});
}
public BitcoinNetwork getNetwork ()
{
return network;
}
public void setNetwork (BitcoinNetwork network)
{
this.network = network;
}
public long getVersion ()
{
return peerVersion;
}
public long getServices ()
{
return peerServices;
}
public long getHeight ()
{
return height;
}
public String getAgent ()
{
return agent;
}
@Override
public void onDisconnect ()
{
network.notifyPeerRemoved (this);
log.info ("Disconnected '" + getAgent () + "' at " + getAddress () + ". Open connections: " + getNetwork ().getNumberOfConnections ());
}
public static final int MAX_BLOCK_SIZE = 1000000;
@Override
public Message parse (InputStream readIn) throws IOException
{
try
{
byte[] head = new byte[24];
if ( readIn.read (head) != head.length )
{
throw new ValidationException ("Read timeout for " + getAddress ());
}
WireFormat.Reader reader = new WireFormat.Reader (head);
long mag = reader.readUint32 ();
if ( mag != network.getChain ().getMagic () )
{
throw new ValidationException ("Wrong magic for this chain " + getAddress ());
}
String command = reader.readZeroDelimitedString (12);
Message m = createMessage (command);
long length = reader.readUint32 ();
byte[] checksum = reader.readBytes (4);
if ( length < 0 || length >= MAX_BLOCK_SIZE )
{
throw new ValidationException ("Block size limit exceeded " + getAddress ());
}
else
{
byte[] buf = new byte[(int) length];
if ( readIn.read (buf) != buf.length )
{
throw new ValidationException ("Package length mismatch " + getAddress ());
}
byte[] cs = new byte[4];
MessageDigest sha;
try
{
sha = MessageDigest.getInstance ("SHA-256");
System.arraycopy (sha.digest (sha.digest (buf)), 0, cs, 0, 4);
}
catch ( NoSuchAlgorithmException e )
{
throw new ValidationException ("SHA-256 implementation missing " + getAddress ());
}
if ( !Arrays.equals (cs, checksum) )
{
throw new ValidationException ("Checksum mismatch " + getAddress ());
}
if ( m != null )
{
m.fromWire (new WireFormat.Reader (buf));
if ( m instanceof AlertMessage )
{
m.validate ();
log.warn (((AlertMessage) m).getPayload ());
}
}
}
return m;
}
catch ( ValidationException e )
{
throw new IOException (e);
}
}
@Override
public void onConnect ()
{
try
{
VersionMessage m = (VersionMessage) createMessage ("version");
m.setHeight (network.getChainHeight ());
m.setPeer (getAddress ().getAddress ());
m.setRemotePort (getAddress ().getPort ());
send (m);
final BitcoinPeer peer = this;
scheduler.schedule (new Runnable ()
{
@Override
public void run ()
{
if ( !network.isConnected (peer) )
{
peer.disconnect ();
}
}
}, CONNECTIONTIMEOUT, TimeUnit.SECONDS);
}
catch ( Exception e )
{
log.error ("Can not connect peer " + getAddress (), e);
}
}
@Override
public void receive (P2P.Message m)
{
final BitcoinPeer self = this;
final Message bm = (Message) m;
transactionTemplate.execute (new TransactionCallbackWithoutResult ()
{
@Override
protected void doInTransactionWithoutResult (TransactionStatus arg0)
{
try
{
bm.validate ();
List<BitcoinMessageListener> classListener = listener.get (bm.getCommand ());
if ( classListener != null )
{
for ( BitcoinMessageListener l : classListener )
{
l.process (bm, self);
}
}
}
catch ( Exception e )
{
arg0.setRollbackOnly ();
log.error ("Failed to process " + bm.getCommand (), e);
disconnect ();
}
}
});
}
public void addListener (String type, BitcoinMessageListener l)
{
ArrayList<BitcoinMessageListener> ll = listener.get (type);
if ( ll == null )
{
ll = new ArrayList<BitcoinMessageListener> ();
listener.put (type, ll);
}
if ( !ll.contains (l) )
{
ll.add (l);
}
}
public void removeListener (String type, BitcoinMessageListener l)
{
ArrayList<BitcoinMessageListener> ll = listener.get (type);
if ( ll != null )
{
ll.remove (l);
}
}
}
|
package com.chariotsolutions.nfc.plugin;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentFilter.MalformedMimeTypeException;
import android.nfc.*;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.nfc.tech.NfcA;
import android.os.Parcelable;
import android.util.Log;
import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
import com.phonegap.api.PluginResult.Status;
import com.sun.corba.se.spi.logging.LogWrapperBase;
import org.json.JSONArray;
import org.json.JSONException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class NdefPlugin extends Plugin {
private static final String REGISTER_MIME_TYPE = "registerMimeType";
private static final String REGISTER_NDEF = "registerNdef";
private static final String REGISTER_NDEF_FORMATTABLE = "registerNdefFormattable";
private static final String WRITE_TAG = "writeTag";
private static final String SHARE_TAG = "shareTag";
private static final String UNSHARE_TAG = "unshareTag";
private static final String NDEF = "ndef";
private static final String NDEF_MIME = "ndef-mime";
private static final String NDEF_UNFORMATTED = "ndef-unformatted";
private NdefMessage p2pMessage = null;
private static String TAG = "NdefPlugin";
private PendingIntent pendingIntent = null;
private List<IntentFilter> intentFilters = new ArrayList<IntentFilter>();
private ArrayList<String[]> techLists = new ArrayList<String[]>();
@Override
public PluginResult execute(String action, JSONArray data, String callbackId) {
createPendingIntent();
if (action.equalsIgnoreCase(REGISTER_MIME_TYPE)) {
try {
String mimeType = data.getString(0);
intentFilters.add(createIntentFilter(mimeType));
} catch (MalformedMimeTypeException e) {
return new PluginResult(Status.ERROR, "Invalid MIME Type");
} catch (JSONException e) {
return new PluginResult(Status.JSON_EXCEPTION, "Invalid MIME Type");
}
startNfc();
parseMessage();
return new PluginResult(Status.OK);
} else if (action.equalsIgnoreCase(REGISTER_NDEF)) {
addTechList(new String[]{Ndef.class.getName()});
startNfc();
parseMessage();
return new PluginResult(Status.OK);
} else if (action.equalsIgnoreCase(REGISTER_NDEF_FORMATTABLE)) {
addTechList(new String[]{NdefFormatable.class.getName()});
startNfc();
parseMessage();
return new PluginResult(Status.OK);
} else if (action.equalsIgnoreCase(WRITE_TAG)) {
if (ctx.getIntent() == null) {
return new PluginResult(Status.ERROR, "Failed to write tag, received null intent");
}
try {
Tag tag = ctx.getIntent().getParcelableExtra(NfcAdapter.EXTRA_TAG);
NdefRecord[] records = Util.jsonToNdefRecords(data.getString(0));
writeTag(new NdefMessage(records), tag);
} catch (JSONException e) {
return new PluginResult(Status.JSON_EXCEPTION, "Error reading NDEF message from JSON");
} catch (Exception e) {
return new PluginResult(Status.ERROR, e.getMessage());
}
return new PluginResult(Status.OK);
} else if (action.equalsIgnoreCase(SHARE_TAG)) {
try {
NdefRecord[] records = Util.jsonToNdefRecords(data.getString(0));
this.p2pMessage = new NdefMessage(records);
startNdefPush();
} catch (JSONException e) {
return new PluginResult(Status.JSON_EXCEPTION, "Error reading NDEF message from JSON");
}
return new PluginResult(Status.OK);
} else if (action.equalsIgnoreCase(UNSHARE_TAG)) {
p2pMessage = null;
stopNdefPush();
return new PluginResult(Status.OK);
}
Log.w(TAG, "No plugin action for " + action);
return new PluginResult(Status.ERROR, "No plugin action for " + action);
}
private void createPendingIntent() {
if (pendingIntent == null) {
Intent intent = new Intent(ctx, ctx.getClass());
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
pendingIntent = PendingIntent.getActivity(ctx, 0, intent, 0);
}
}
private void addTechList(String[] list) {
this.addTechFilter();
this.addToTechList(list);
}
private void addTechFilter() {
intentFilters.add(new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED));
}
private void startNfc() {
this.ctx.runOnUiThread(new Runnable() {
public void run() {
NfcAdapter.getDefaultAdapter(ctx).enableForegroundDispatch(
ctx, getPendingIntent(), getIntentFilters(), getTechLists());
if (p2pMessage != null) {
NfcAdapter.getDefaultAdapter(ctx).enableForegroundNdefPush(ctx, p2pMessage);
}
}
});
}
private void stopNfc() {
this.ctx.runOnUiThread(new Runnable() {
public void run() {
NfcAdapter.getDefaultAdapter(ctx).disableForegroundDispatch(ctx);
NfcAdapter.getDefaultAdapter(ctx).disableForegroundNdefPush(ctx);
}
});
}
private void startNdefPush() {
this.ctx.runOnUiThread(new Runnable() {
public void run() {
NfcAdapter.getDefaultAdapter(ctx).enableForegroundNdefPush(ctx, p2pMessage);
}
});
}
private void stopNdefPush() {
this.ctx.runOnUiThread(new Runnable() {
public void run() {
NfcAdapter.getDefaultAdapter(ctx).disableForegroundNdefPush(ctx);
}
});
}
private void addToTechList(String[] techs) {
techLists.add(techs);
}
private IntentFilter createIntentFilter(String mimeType) throws MalformedMimeTypeException {
IntentFilter intentFilter = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
intentFilter.addDataType(mimeType);
return intentFilter;
}
private PendingIntent getPendingIntent() {
return pendingIntent;
}
private IntentFilter[] getIntentFilters() {
return intentFilters.toArray(new IntentFilter[intentFilters.size()]);
}
private String[][] getTechLists() {
//noinspection ToArrayCallWithZeroLengthArrayArgument
return techLists.toArray(new String[0][0]);
}
private void parseMessage() {
Intent intent = ctx.getIntent();
String action = intent.getAction();
if (action.equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) {
Parcelable[] rawData = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
for (Parcelable message : rawData) {
fireNdefEvent(NDEF_MIME, message);
}
} else if (action.equals(NfcAdapter.ACTION_TECH_DISCOVERED)) {
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
for (String tagTech : tag.getTechList()) {
if (tagTech.equalsIgnoreCase(NdefFormatable.class.getName())) {
fireNdefEvent(NDEF_UNFORMATTED);
} else if (tagTech.equalsIgnoreCase(Ndef.class.getName())) {
Parcelable[] messages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (messages.length == 0) { // empty formatted tag
fireNdefEvent(NDEF);
} else {
for (Parcelable message : messages) {
fireNdefEvent(NDEF, message);
}
}
}
}
}
}
private void fireNdefEvent(String type) {
JSONArray jsonData = new JSONArray();
fireNdefEvent(type, jsonData);
}
private void fireNdefEvent(String type, Parcelable parcelable) {
JSONArray jsonData = Util.messageToJSON((NdefMessage) parcelable);
fireNdefEvent(type, jsonData);
}
private void fireNdefEvent(String type, JSONArray ndefMessage) {
String command = "navigator.nfc.fireEvent('" + type + "', " + ndefMessage + ")";
this.sendJavascript(command);
}
private void writeTag(NdefMessage message, Tag tag) throws TagWriteException, IOException, FormatException {
Ndef ndef = Ndef.get(tag);
if (ndef != null) {
ndef.connect();
if (!ndef.isWritable()) {
throw new TagWriteException("Tag is read only");
}
int size = message.toByteArray().length;
if (ndef.getMaxSize() < size) {
String errorMessage = "Tag capacity is " + ndef.getMaxSize() + " bytes, message is " + size + " bytes.";
throw new TagWriteException(errorMessage);
}
ndef.writeNdefMessage(message);
} else {
NdefFormatable formatable = NdefFormatable.get(tag);
if (formatable != null) {
formatable.connect();
formatable.format(message);
} else {
throw new TagWriteException("Tag doesn't support NDEF");
}
}
}
@Override
public void onPause(boolean multitasking) {
super.onPause(multitasking);
stopNfc();
}
@Override
public void onResume(boolean multitasking) {
super.onResume(multitasking);
startNfc();
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equalsIgnoreCase(ctx.getIntent().getAction())) {
parseMessage();
ctx.setIntent(new Intent());
}
}
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
ctx.setIntent(intent);
// parseMessage();
}
}
|
package com.codemelon.graph.vertex.types;
import java.util.IdentityHashMap;
import java.util.Set;
import com.codemelon.graph.common.Color;
import com.codemelon.graph.common.EdgeType;
import com.codemelon.graph.edge.EdgeConstants;
import com.codemelon.graph.graph.types.DiGraph;
import com.codemelon.graph.vertex.common.VertexConstants;
import com.codemelon.graph.vertex.interfaces.ChildVertex;
import com.codemelon.graph.vertex.interfaces.ColoredVertex;
import com.codemelon.graph.vertex.interfaces.EdgeTypeVertex;
import com.codemelon.graph.vertex.interfaces.Vertex;
import com.codemelon.graph.vertex.interfaces.VisitedVertex;
/**
* @author Marshall Farrier
* @version Dec 7, 2012
*/
public class DfsVertex implements Vertex, ColoredVertex, ChildVertex,
VisitedVertex, EdgeTypeVertex {
private DiGraph<? extends Vertex> graph;
private IdentityHashMap<Vertex, EdgeType> adjacencies;
private ChildVertex parent;
private Color color;
private int discoveryTime;
private int finishTime;
public DfsVertex() {
graph = null;
adjacencies = new IdentityHashMap<Vertex, EdgeType>();
parent = null;
color = Color.WHITE;
discoveryTime = VertexConstants.INITIAL_DISCOVERY_TIME;
finishTime = VertexConstants.INITIAL_FINISH_TIME;
}
/* (non-Javadoc)
* @see com.codemelon.graph.vertex.interfaces.EdgeTypeVertex#setEdgeType(com.codemelon.graph.vertex.interfaces.EdgeTypeVertex, com.codemelon.graph.common.EdgeType)
*/
@Override
public void setEdgeType(EdgeTypeVertex to, EdgeType edgeType) {
if (!adjacencies.containsKey(to)) {
throw new IllegalArgumentException("Edge does not exist!");
}
adjacencies.put(to, edgeType);
}
/* (non-Javadoc)
* @see com.codemelon.graph.vertex.interfaces.EdgeTypeVertex#getEdgeType(com.codemelon.graph.vertex.interfaces.EdgeTypeVertex)
*/
@Override
public EdgeType getEdgeType(EdgeTypeVertex to) {
return adjacencies.get(to);
}
/* (non-Javadoc)
* @see com.codemelon.graph.vertex.interfaces.VisitedVertex#setDiscoveryTime(int)
*/
@Override
public void setDiscoveryTime(int discoveryTime) {
this.discoveryTime = discoveryTime;
}
/* (non-Javadoc)
* @see com.codemelon.graph.vertex.interfaces.VisitedVertex#setFinishTime(int)
*/
@Override
public void setFinishTime(int finishTime) {
this.finishTime = finishTime;
}
/* (non-Javadoc)
* @see com.codemelon.graph.vertex.interfaces.VisitedVertex#getDiscoveryTime()
*/
@Override
public int getDiscoveryTime() {
return discoveryTime;
}
/* (non-Javadoc)
* @see com.codemelon.graph.vertex.interfaces.VisitedVertex#getFinishTime()
*/
@Override
public int getFinishTime() {
return finishTime;
}
/* (non-Javadoc)
* @see com.codemelon.graph.vertex.interfaces.ChildVertex#setParent(com.codemelon.graph.vertex.interfaces.ChildVertex)
*/
@Override
public void setParent(ChildVertex parent) {
if (parent == null) {
this.parent = parent;
return;
}
if (graph == null) {
throw new IllegalArgumentException("Vertex must belong to a graph to have a parent!");
}
if (parent.getGraph() != graph) {
throw new IllegalArgumentException("Parent must belong to the same graph!");
}
this.parent = parent;
}
/* (non-Javadoc)
* @see com.codemelon.graph.vertex.interfaces.ChildVertex#getParent()
*/
@Override
public ChildVertex getParent() {
return parent;
}
/* (non-Javadoc)
* @see com.codemelon.graph.vertex.interfaces.ColoredVertex#setColor(com.codemelon.graph.common.Color)
*/
@Override
public void setColor(Color color) {
this.color = color;
}
/* (non-Javadoc)
* @see com.codemelon.graph.vertex.interfaces.ColoredVertex#getColor()
*/
@Override
public Color getColor() {
return color;
}
/* (non-Javadoc)
* @see com.codemelon.graph.vertex.interfaces.Vertex#setGraph(com.codemelon.graph.graph.DiGraph)
*/
@Override
public void setGraph(DiGraph<? extends Vertex> diGraph) {
this.graph = diGraph;
}
/* (non-Javadoc)
* @see com.codemelon.graph.vertex.interfaces.Vertex#getGraph()
*/
@Override
public DiGraph<? extends Vertex> getGraph() {
return graph;
}
/* (non-Javadoc)
* @see com.codemelon.graph.vertex.interfaces.Vertex#addAdjacency(com.codemelon.graph.vertex.interfaces.Vertex)
*/
@Override
public boolean addAdjacency(Vertex to) {
if (this.graph == null || this.graph != to.getGraph()) {
throw new IllegalArgumentException("Adjacency must belong to the same graph!");
}
if (adjacencies.containsKey(to)) { return false; }
adjacencies.put(to, EdgeConstants.DEFAULT_EDGE_TYPE);
return true;
}
/* (non-Javadoc)
* @see com.codemelon.graph.vertex.interfaces.Vertex#removeAdjacency(com.codemelon.graph.vertex.interfaces.Vertex)
*/
@Override
public boolean removeAdjacency(Vertex to) {
if (adjacencies.containsKey(to)) {
adjacencies.remove(to);
return true;
}
return false;
}
/* (non-Javadoc)
* @see com.codemelon.graph.vertex.interfaces.Vertex#clearAdjacencies()
*/
@Override
public void clearAdjacencies() {
adjacencies.clear();
}
/* (non-Javadoc)
* @see com.codemelon.graph.vertex.interfaces.Vertex#containsAdjacency(com.codemelon.graph.vertex.interfaces.Vertex)
*/
@Override
public boolean containsAdjacency(Vertex to) {
return adjacencies.containsKey(to);
}
/* (non-Javadoc)
* @see com.codemelon.graph.vertex.interfaces.Vertex#adjacencyCount()
*/
@Override
public int adjacencyCount() {
return adjacencies.size();
}
/* (non-Javadoc)
* @see com.codemelon.graph.vertex.interfaces.Vertex#getAdjacencies()
*/
@Override
public Set<Vertex> getAdjacencies() {
return adjacencies.keySet();
}
/* (non-Javadoc)
* @see com.codemelon.graph.vertex.interfaces.Vertex#hasAdjacencies()
*/
@Override
public boolean hasAdjacencies() {
return !adjacencies.isEmpty();
}
}
|
package com.dmdirc.ui.messages;
import com.dmdirc.DMDircMBassador;
import com.dmdirc.config.ConfigBinding;
import com.dmdirc.events.BaseChannelTextEvent;
import com.dmdirc.events.BaseQueryTextEvent;
import com.dmdirc.events.ChannelHighlightEvent;
import com.dmdirc.events.DisplayProperty;
import com.dmdirc.events.DisplayableEvent;
import com.dmdirc.events.QueryHighlightEvent;
import com.dmdirc.events.UnreadStatusChangedEvent;
import com.dmdirc.interfaces.WindowModel;
import com.dmdirc.util.colours.Colour;
import java.util.Optional;
import net.engio.mbassy.listener.Handler;
/**
* Tracks unread messages and other notifications.
*/
public class UnreadStatusManager {
private final DMDircMBassador eventBus;
private final WindowModel container;
private final ColourManager colourManager;
private int unreadLines;
private Optional<Colour> notificationColour = Optional.empty();
private Optional<Colour> miscellaneousColour = Optional.of(Colour.GREEN);
private Optional<Colour> messageColour = Optional.of(Colour.BLUE);
private Optional<Colour> highlightColour = Optional.of(Colour.RED);
public UnreadStatusManager(final WindowModel container) {
this.container = container;
this.eventBus = container.getEventBus();
this.colourManager = new ColourManager(container.getConfigManager());
}
@Handler
public void handleDisplayableEvent(final DisplayableEvent event) {
if (includeEvent(event)) {
updateStatus(miscellaneousColour, unreadLines + 1);
}
}
@Handler
public void handleChannelTextEvent(final BaseChannelTextEvent event) {
if (includeEvent(event)) {
updateStatus(messageColour);
}
}
@Handler
public void handleQueryTextEvent(final BaseQueryTextEvent event) {
if (includeEvent(event)) {
updateStatus(messageColour);
}
}
@Handler
public void handleChannelHighlightEvent(final ChannelHighlightEvent event) {
if (includeEvent(event)) {
updateStatus(highlightColour);
}
}
@Handler
public void handleQueryHighlightEvent(final QueryHighlightEvent event) {
if (includeEvent(event)) {
updateStatus(highlightColour);
}
}
private boolean includeEvent(final DisplayableEvent event) {
return event.getSource().equals(container)
&& !event.getDisplayProperty(DisplayProperty.DO_NOT_DISPLAY).orElse(false);
}
public int getUnreadLines() {
return unreadLines;
}
public Optional<Colour> getNotificationColour() {
return notificationColour;
}
public void clearStatus() {
updateStatus(Optional.empty(), 0);
}
private void updateStatus(final Optional<Colour> desiredColour) {
updateStatus(desiredColour, unreadLines);
}
private void updateStatus(final Optional<Colour> desiredColour, final int newUnreadCount) {
final Optional<Colour> newColour = getBestColour(desiredColour, notificationColour);
final boolean updated = !newColour.equals(notificationColour)
|| newUnreadCount != unreadLines;
notificationColour = newColour;
unreadLines = newUnreadCount;
if (updated) {
publishChangedEvent();
}
}
private Optional<Colour> getBestColour(
final Optional<Colour> desiredColour,
final Optional<Colour> existingColour) {
if (!desiredColour.isPresent()) {
// If we're trying to explicitly reset, go with the empty one.
return desiredColour;
}
if (desiredColour.equals(highlightColour)
|| !existingColour.isPresent()
|| existingColour.equals(miscellaneousColour)) {
return desiredColour;
} else {
return existingColour;
}
}
@ConfigBinding(domain = "ui", key = "miscellaneousNotificationColour")
void handleMiscellaneousColour(final String colour) {
final Optional<Colour> newColour = Optional.ofNullable(
colourManager.getColourFromString(colour, Colour.GREEN));
if (notificationColour.equals(miscellaneousColour)) {
notificationColour = newColour;
publishChangedEvent();
}
miscellaneousColour = newColour;
}
@ConfigBinding(domain = "ui", key = "messageNotificationColour")
void handleMessageColour(final String colour) {
final Optional<Colour> newColour = Optional.ofNullable(
colourManager.getColourFromString(colour, Colour.BLUE));
if (notificationColour.equals(messageColour)) {
notificationColour = newColour;
publishChangedEvent();
}
messageColour = newColour;
}
@ConfigBinding(domain = "ui", key = "highlightNotificationColour")
void handleHighlightColour(final String colour) {
final Optional<Colour> newColour = Optional.ofNullable(
colourManager.getColourFromString(colour, Colour.RED));
if (notificationColour.equals(highlightColour)) {
notificationColour = newColour;
publishChangedEvent();
}
highlightColour = newColour;
}
private void publishChangedEvent() {
eventBus.publishAsync(new UnreadStatusChangedEvent(container, this, notificationColour,
unreadLines));
}
}
|
package com.ecyrd.jspwiki.render;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
import org.jdom.JDOMException;
import org.jdom.Text;
import org.jdom.xpath.XPath;
import com.ecyrd.jspwiki.WikiContext;
import com.ecyrd.jspwiki.parser.WikiDocument;
/**
* A simple renderer that just renders all the text() nodes
* from the DOM tree. This is very useful for cleaning away
* all of the XHTML.
*
* @author Janne Jalkanen
* @since 2.4
*/
public class CleanTextRenderer
extends WikiRenderer
{
protected static Logger log = Logger.getLogger( CleanTextRenderer.class );
public CleanTextRenderer( WikiContext context, WikiDocument doc )
{
super( context, doc );
}
public String getString()
throws IOException
{
StringBuffer sb = new StringBuffer();
try
{
XPath xp = XPath.newInstance("//text()");
List nodes = xp.selectNodes(m_document.getDocument());
for( Iterator i = nodes.iterator(); i.hasNext(); )
{
Object el = i.next();
if( el instanceof Text )
{
sb.append( ((Text)el).getValue() );
}
}
}
catch( JDOMException e )
{
log.error("Could not parse XPATH expression");
throw new IOException( e.getMessage() );
}
return sb.toString();
}
}
|
package com.premnirmal.Magnet;
import android.content.Context;
import android.graphics.PixelFormat;
import android.os.Build;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.widget.ImageView;
public class RemoveView {
protected View layout;
protected View button;
protected View shadow;
protected ImageView buttonImage;
protected WindowManager windowManager;
protected SimpleAnimator showAnim;
protected SimpleAnimator hideAnim;
protected SimpleAnimator shadowFadeOut;
protected SimpleAnimator shadowFadeIn;
protected final int buttonBottomPadding;
protected boolean shouldBeResponsive = true;
protected boolean isShowing;
protected RemoveView(Context context) {
layout = LayoutInflater.from(context).inflate(R.layout.x_button_holder, null);
button = layout.findViewById(R.id.xButton);
buttonImage = (ImageView) layout.findViewById(R.id.xButtonImg);
buttonImage.setImageResource(R.drawable.ic_close);
buttonBottomPadding = button.getPaddingBottom();
shadow = layout.findViewById(R.id.shadow);
windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
showAnim = new SimpleAnimator(button, R.anim.slide_up);
hideAnim = new SimpleAnimator(button, R.anim.slide_down);
shadowFadeIn = new SimpleAnimator(shadow, android.R.anim.fade_in);
shadowFadeOut = new SimpleAnimator(shadow, android.R.anim.fade_out);
}
protected void setIconResId(int id) {
buttonImage.setImageResource(id);
}
protected void setShadowBG(int shadowBG) {
shadow.setBackgroundResource(shadowBG);
}
protected void show() {
if (layout != null && layout.getParent() == null) {
addToWindow(layout);
}
shadowFadeIn.startAnimation();
showAnim.startAnimation(new Animation.AnimationListener() {
@Override public void onAnimationStart(Animation animation) {
isShowing = true;
}
@Override public void onAnimationEnd(Animation animation) {
}
@Override public void onAnimationRepeat(Animation animation) {
}
});
}
protected boolean isShowing() {
return isShowing;
}
protected void hide() {
shadowFadeOut.startAnimation();
hideAnim.startAnimation(new Animation.AnimationListener() {
@Override public void onAnimationStart(Animation animation) {
}
@Override public void onAnimationEnd(Animation animation) {
if (layout != null && layout.getParent() != null) {
isShowing = false;
layout.post(new Runnable() {
@Override
public void run() {
windowManager.removeView(layout);
}
});
}
}
@Override public void onAnimationRepeat(Animation animation) {
}
});
}
protected void onMove(final float x, final float y) {
if (shouldBeResponsive) {
final int midpoint = button.getContext().getResources().getDisplayMetrics().widthPixels / 2;
final float xDelta = x - midpoint;
final int xTransformed = (int) Math.abs(xDelta * 100 / midpoint);
final int bottomPadding = buttonBottomPadding - (xTransformed / 5);
if (xDelta < 0) {
button.setPadding(0, 0, xTransformed, bottomPadding);
} else {
button.setPadding(xTransformed, 0, 0, bottomPadding);
}
}
}
protected void destroy() {
if (layout != null && layout.getParent() != null) {
windowManager.removeView(layout);
}
layout = null;
windowManager = null;
}
private void addToWindow(View layout) {
int overlayFlag;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
overlayFlag = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
} else {
overlayFlag = WindowManager.LayoutParams.TYPE_PHONE;
}
WindowManager.LayoutParams params =
new WindowManager.LayoutParams(WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT, overlayFlag,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
| WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN, PixelFormat.TRANSLUCENT);
windowManager.addView(layout, params);
}
}
|
package com.sbar.smsnenado.activities;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.ActionBar;
import android.app.FragmentTransaction;
import android.app.Activity;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Intent.ShortcutIconResource;
import android.content.pm.ApplicationInfo;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.util.Patterns;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SearchView.OnQueryTextListener;
import android.widget.TextView;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.sbar.smsnenado.activities.ActivityClass;
import com.sbar.smsnenado.activities.EditUserPhoneNumbersActivity;
import com.sbar.smsnenado.activities.ReportSpamActivity;
import com.sbar.smsnenado.activities.SettingsActivity;
import com.sbar.smsnenado.BootService;
import com.sbar.smsnenado.BuildEnv;
import com.sbar.smsnenado.Common;
import com.sbar.smsnenado.DatabaseConnector;
import com.sbar.smsnenado.dialogs.AboutProgramDialogFragment;
import com.sbar.smsnenado.dialogs.InThisVersionDialogFragment;
import com.sbar.smsnenado.dialogs.NeedDataDialogFragment;
import com.sbar.smsnenado.dialogs.SmsInfoDialogFragment;
import com.sbar.smsnenado.R;
import com.sbar.smsnenado.SmsItem;
import com.sbar.smsnenado.SmsItemAdapter;
import com.sbar.smsnenado.SmsLoader;
import static com.sbar.smsnenado.Common.LOGE;
import static com.sbar.smsnenado.Common.LOGI;
import static com.sbar.smsnenado.Common.LOGW;
import java.lang.CharSequence;
import java.util.ArrayList;
import java.util.regex.Pattern;
import java.util.Set;
public class MainActivity extends BaseActivity {
private static MainActivity sInstance = null;
public static final int ITEMS_PER_PAGE = 10;
private ListView mSmsListView = null;
private SearchView mSearchView = null;
private SmsItemAdapter mSmsItemAdapter = null;
private AdView mBanner = null;
private boolean mRemovedMode = false;
private static SmsItem sSelectedSmsItem = null;
private boolean mReachedEndSmsList = false;
private String mLastRequestedFilter = "";
private int mLastRequestedPage = -1;
private boolean mLastRequestedRemovedMode = false;
private UpdaterAsyncTask mUpdaterAsyncTask = null;
private int mSearchTestTimer = 0;
private Messenger mService = null;
private boolean mPhoneHasMessages = false;
private SmsLoader mSmsLoader = new SmsLoader(this) {
@Override
protected void onSmsListLoaded(ArrayList<SmsItem> list,
int from,
String filter,
boolean removed) {
String actualFilter = getSearchFilter();
if (!equalFilters(filter, actualFilter) ||
removed != mRemovedMode) {
return;
}
if (list != null) {
if (list.isEmpty()) {
mReachedEndSmsList = true;
} else {
mPhoneHasMessages = true;
}
mSmsItemAdapter.addAll(list);
mSmsItemAdapter.setLoadingVisible(false);
mSearchTestTimer = 0;
}
int emptyTextId = -1;
if (mSmsItemAdapter.getCount() == 0 && list.isEmpty()) {
if (actualFilter.isEmpty()) {
emptyTextId = R.string.no_messages;
} else {
emptyTextId = R.string.not_found;
}
} else {
emptyTextId = R.string.loading;
}
updateEmptyListText(emptyTextId);
}
};
private void updateEmptyListText(int emptyTextId) {
View smsListEmptyLinearLayout = (View)
findViewById(R.id.smsListEmpty_LinearLayout);
TextView smsListEmptyTextView = (TextView) findViewById(
R.id.smsListEmpty_TextView);
smsListEmptyTextView.setText(getString(emptyTextId));
mSmsListView.setEmptyView(smsListEmptyLinearLayout);
}
public static MainActivity getInstance() {
return sInstance;
}
public void sendToBootService(int what, Object object) {
if (mService != null) {
try {
LOGI("sendToBootService " + what);
Message msg = Message.obtain(null, what, object);
//msg.replyTo = mMessenger;
mService.send(msg);
} catch (RemoteException e) {
LOGE("sendToBootService: " + e.getMessage());
e.printStackTrace();
}
}
}
private void createTabs() {
final ActionBar actionBar = getActionBar();
final String LAST_MESSAGES = "last_messages";
final String REMOVED_MESSAGES = "removed_messages";
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
@Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction ft) {
String tabId = tab.getContentDescription().toString();
boolean lastMode = mRemovedMode;
if (tabId.equals(LAST_MESSAGES)) {
mRemovedMode = false;
} else if (tabId.equals(REMOVED_MESSAGES)) {
mRemovedMode = true;
}
if (lastMode != mRemovedMode) {
mPhoneHasMessages = false;
refreshSmsItemAdapter();
}
}
@Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction ft) {
}
@Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction ft) {
}
};
actionBar.addTab(
actionBar.newTab()
.setText(getString(R.string.last_messages))
.setContentDescription(LAST_MESSAGES)
.setTabListener(tabListener));
actionBar.addTab(
actionBar.newTab()
.setText(getString(R.string.removed_messages))
.setContentDescription(REMOVED_MESSAGES)
.setTabListener(tabListener));
}
@Override
public void onCreate(Bundle s) {
super.onCreate(s);
setContentView(R.layout.main);
createTabs();
if (BuildEnv.TEST_API) {
setTitle("TEST_API=true");
LOGI("TEST_API=true");
}
if (Common.isFirstRun(this)) {
addShortcut();
}
updateSettings();
sInstance = this;
if (Common.isAppVersionChanged(this)) {
LOGI("! VERSION CHANGED");
DialogFragment df = new InThisVersionDialogFragment();
df.show(getFragmentManager(), "");
}
BootService.maybeRunService(this);
mSmsListView = (ListView) findViewById(R.id.sms_ListView);
mSmsListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View v,
int position, long id) {
sSelectedSmsItem = mSmsItemAdapter.getItem(position);
DatabaseConnector dc = DatabaseConnector.getInstance(
MainActivity.this);
int messageStatus = dc.getMessageStatus(sSelectedSmsItem.mId);
LOGI("onItemClick messageStatus=" + messageStatus +
" id=" + sSelectedSmsItem.mId);
if (messageStatus == SmsItem.STATUS_NONE ||
messageStatus == SmsItem.STATUS_UNKNOWN)
{
Intent intent = new Intent(MainActivity.this,
ReportSpamActivity.class);
startActivity(intent);
} else {
int textId = 0;
boolean mNotSpamButton = true;
switch (messageStatus) {
case SmsItem.STATUS_SPAM:
textId = R.string.this_sms_spam_wont_be_received;
//mNotSpamButton = false;
break;
case SmsItem.STATUS_IN_INTERNAL_QUEUE:
if (Common.isNetworkAvailable(MainActivity.this)) {
textId = R.string.sms_in_internal_queue;
BootService service = BootService.getInstance();
if (service != null) {
service.updateInternalQueue();
}
} else {
textId = R.string.sms_in_internal_queue_need_net;
}
break;
case SmsItem.STATUS_IN_INTERNAL_QUEUE_SENDING_REPORT:
case SmsItem.STATUS_IN_INTERNAL_QUEUE_WAITING_CONFIRMATION:
if (Common.isNetworkAvailable(MainActivity.this)) {
textId = R.string.sms_in_internal_queue;
} else {
textId = R.string.sms_in_internal_queue_need_net;
}
case SmsItem.STATUS_IN_INTERNAL_QUEUE_SENDING_CONFIRMATION:
if (Common.isNetworkAvailable(MainActivity.this)) {
textId = R.string.sms_in_internal_queue;
} else {
textId = R.string.sms_in_internal_queue_need_net;
}
mNotSpamButton = false;
break;
case SmsItem.STATUS_IN_QUEUE:
textId = R.string.sms_in_queue;
mNotSpamButton = false;
break;
case SmsItem.STATUS_UNSUBSCRIBED:
textId = R.string.sms_unsubscribed;
mNotSpamButton = false;
break;
case SmsItem.STATUS_FAS_GUIDE_SENT:
textId = R.string.sms_fas_guide_sent;
mNotSpamButton = false;
break;
case SmsItem.STATUS_GUIDE_SENT:
textId = R.string.sms_guide_sent;
mNotSpamButton = false;
break;
case SmsItem.STATUS_FAS_SENT:
textId = R.string.sms_sent_to_fas;
mNotSpamButton = false;
break;
default:
LOGE(
"mSmsListView.OnItemClick: unknown status " +
messageStatus);
break;
}
DialogFragment df = SmsInfoDialogFragment
.newInstance(textId, mNotSpamButton, messageStatus);
df.show(getFragmentManager(), "");
}
}
});
mSmsListView.setOnScrollListener(new EndlessScrollListener());
refreshSmsItemAdapter();
mBanner = (AdView) findViewById(R.id.banner_AdView);
mBanner.setAdListener(new AdListener() {
public void onAdClosed() {
super.onAdClosed();
LOGI("onAdClosed");
}
public void onAdFailedToLoad(int errorCode) {
super.onAdFailedToLoad(errorCode);
LOGI("onAdFailedToLoad " + errorCode);
}
// Called when an ad leaves the application (e.g., go to browser)
public void onAdLeftApplication() {
super.onAdLeftApplication();
LOGI("onAdLeftApplication");
}
public void onAdLoaded() {
super.onAdLoaded();
LOGI("onAdLoaded");
}
public void onAdOpened() {
super.onAdOpened();
LOGI("onAdOpened");
}
});
requestBanner();
}
public void requestBanner() {
if (mBanner != null && Common.isNetworkAvailable(this)) {
LOGI("requestBanner");
AdRequest adRequest = (new AdRequest.Builder()).build();
mBanner.loadAd(adRequest);
}
}
@Override
public void onResume() {
super.onResume();
LOGI("MainActivity.onResume");
if (mUpdaterAsyncTask == null) {
mUpdaterAsyncTask = new UpdaterAsyncTask();
mUpdaterAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
try {
if (mBanner != null) {
mBanner.resume();
requestBanner();
}
} catch (Exception e) {
LOGE("AdView: " + e.getMessage());
}
}
@Override
public void onPause() {
super.onPause();
LOGI("MainActivity.onPause");
if (mUpdaterAsyncTask.getStatus() == AsyncTask.Status.RUNNING) {
mUpdaterAsyncTask.cancel(false);
mUpdaterAsyncTask = null;
System.gc();
}
try {
if (mBanner != null) {
mBanner.pause();
}
} catch (Exception e) {
LOGE("AdView: " + e.getMessage());
}
}
@Override
public void onDestroy() {
LOGI("MainActivity.onDestroy");
if (mUpdaterAsyncTask != null &&
mUpdaterAsyncTask.getStatus() == AsyncTask.Status.RUNNING) {
mUpdaterAsyncTask.cancel(false);
mUpdaterAsyncTask = null;
System.gc();
}
sInstance = null;
if (mService != null) {
unbindService(mServiceConnection);
mService = null;
}
try {
if (mBanner != null) {
mBanner.destroy();
}
} catch (Exception e) {
LOGE("AdView: " + e.getMessage());
}
super.onDestroy();
}
@Override
public void onStart() {
super.onStart();
Intent intent = new Intent(this, BootService.class);
//bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
bindService(intent, mServiceConnection, Context.BIND_ABOVE_CLIENT);
BootService service = BootService.getInstance();
if (service != null) {
service.updateInternalQueue();
}
}
@Override
public void onStop() {
super.onStop();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
mSearchView = (SearchView)
menu.findItem(R.id.search_MenuItem).getActionView();
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
public boolean onQueryTextChange(String newText) {
LOGI("onQueryTextChange newText='" + newText + "'" +
" filter='" + getSearchFilter() + "'");
if (!equalFilters(mLastRequestedFilter, getSearchFilter())) {
refreshSmsItemAdapter();
}
return true;
}
public boolean onQueryTextSubmit(String query) {
LOGI("onQueryTextSubmit query='" + query + "'" +
" filter='" + getSearchFilter() + "'");
if (!equalFilters(mLastRequestedFilter, getSearchFilter())) {
refreshSmsItemAdapter();
}
return true;
}
});
updateOptionsMenu(menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.settings_MenuItem: {
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
return true;
}
case R.id.about_MenuItem: {
DialogFragment df = new AboutProgramDialogFragment();
df.show(getFragmentManager(), "");
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
public boolean isSearchViewUpdatedToEmpty() {
String filter = getSearchFilter();
if (filter.isEmpty() && mPhoneHasMessages &&
mSmsItemAdapter.getCount() == 0) {
return true;
}
return false;
}
public void refreshSmsItemAdapter() {
clearSmsItemAdapter();
updateSmsItemAdapter();
}
public void updateSettings() {
PreferenceManager.setDefaultValues(
this, R.xml.preferences, false);
SharedPreferences sharedPref = PreferenceManager
.getDefaultSharedPreferences(this);
updateUserEmail(sharedPref);
updateUserPhoneNumber(sharedPref);
}
private void updateUserEmail(SharedPreferences sharedPref) {
String userEmail = sharedPref
.getString(SettingsActivity.KEY_STRING_USER_EMAIL, "");
if (userEmail.isEmpty()) {
Pattern emailPattern = Patterns.EMAIL_ADDRESS;
Account[] accounts = AccountManager.get(this).getAccounts();
boolean foundEmail = false;
for (Account account : accounts) {
if (emailPattern.matcher(account.name).matches()) {
userEmail = account.name;
foundEmail = true;
break;
}
}
if (foundEmail) {
SharedPreferences.Editor prefEditor = sharedPref.edit();
prefEditor.putString(SettingsActivity.KEY_STRING_USER_EMAIL,
userEmail);
prefEditor.commit();
String notification = String.format(
(String) getText(R.string.updated_email_automatically),
userEmail);
Common.showToast(this, notification);
} else {
String text = (String) (
getText(R.string.cannot_detect_email) + " " +
getText(R.string.you_need_to_set_email));
DialogFragment df = NeedDataDialogFragment.newInstance(
text, ActivityClass.SETTINGS);
df.show(getFragmentManager(), "");
}
}
}
private void updateUserPhoneNumber(SharedPreferences sharedPref) {
String phoneNumber = Common.getPhoneNumber(this);
LOGI("phoneNumber is '" + phoneNumber + "'");
if (phoneNumber.isEmpty() ||
!EditUserPhoneNumbersActivity.saveUserPhoneNumber(
phoneNumber, this)) {
Set<String> userPhoneNumbers =
SettingsActivity.getUserPhoneNumbers(this);
if (userPhoneNumbers.size() == 0) {
LOGI("need to set phoneNumber");
String text = (String) getText(R.string.cannot_detect_phone_number);
text += " ";
text += (String) getText(R.string.you_need_to_set_phone_number);
DialogFragment df = NeedDataDialogFragment.newInstance(
text, ActivityClass.EDIT_USER_PHONE_NUMBERS);
df.show(getFragmentManager(), "");
} else {
LOGI("userPhoneNumbers size=" + userPhoneNumbers.size());
}
}
}
public void updateSmsItemAdapter() {
LOGI("updateSmsItemAdapter");
if (mSmsItemAdapter == null) {
return;
}
String filter = getSearchFilter();
if (mSmsItemAdapter.getCount() == 0) {
if (mReachedEndSmsList) { // no messages at all
return;
}
mSmsLoader.loadSmsListAsync(0, ITEMS_PER_PAGE, filter, mRemovedMode);
mLastRequestedPage = 0;
mLastRequestedFilter = filter;
mLastRequestedRemovedMode = mRemovedMode;
mSmsItemAdapter.setLoadingVisible(true);
} else if (!mReachedEndSmsList) {
int page = mSmsItemAdapter.getCount() / ITEMS_PER_PAGE;
if (mSmsItemAdapter.getLoadingVisible() &&
page == mLastRequestedPage &&
equalFilters(mLastRequestedFilter, filter) &&
mLastRequestedRemovedMode == mRemovedMode) {
return;
}
mLastRequestedPage = page;
mLastRequestedFilter = filter;
mLastRequestedRemovedMode = mRemovedMode;
mSmsLoader.loadSmsListAsync(
page * ITEMS_PER_PAGE, ITEMS_PER_PAGE, filter, mRemovedMode);
mSmsItemAdapter.setLoadingVisible(true);
}
}
public void clearSmsItemAdapter() {
mSmsLoader.clearLoadedIdCache();
mReachedEndSmsList = false;
mSmsItemAdapter = new SmsItemAdapter(this, new ArrayList<SmsItem>());
mSmsListView.setAdapter(mSmsItemAdapter);
System.gc();
}
public static SmsItem getSelectedSmsItem() {
return sSelectedSmsItem;
}
public void unsetSpamForSelectedItem() {
boolean result = true;
SmsItem selectedSmsItem = getSelectedSmsItem();
if (selectedSmsItem == null) {
return;
}
DatabaseConnector dc = DatabaseConnector
.getInstance(this);
if (!dc.unsetSpamMessages(selectedSmsItem.mAddress)) {
LOGE("Failed to cancel spam messages");
result = false;
}
if (!result) {
return;
}
Common.showToast(this, getString(R.string.canceled_spam));
// refresh all sms items with this address
updateItemStatus(selectedSmsItem.mId, SmsItem.STATUS_NONE);
}
public void addToWhiteListSelectedItem() {
boolean result = true;
SmsItem selectedSmsItem = getSelectedSmsItem();
DatabaseConnector dc = DatabaseConnector
.getInstance(this);
if (!dc.addToWhiteList(selectedSmsItem.mAddress)) {
LOGE("Failed to add address '" + selectedSmsItem.mAddress +
"' to white list");
result = false;
}
if (!result) {
return;
}
String addedToWhiteList = String.format(
(String) getText(R.string.added_to_white_list),
selectedSmsItem.mAddress);
Common.showToast(this, addedToWhiteList);
refreshSmsItemAdapter();
}
public void updateItemStatus(String msgId, int status) {
mSmsItemAdapter.updateStatus(msgId, status);
switch (status) {
case SmsItem.STATUS_IN_INTERNAL_QUEUE: {
// if we selected an item to be sent as spam than mark all
// items of the same address with NONE status by SPAM
SmsItem item = mSmsItemAdapter.getSmsItemFromId(msgId);
if (item != null) {
mSmsItemAdapter.updateStatusesIf(
item.mAddress,
SmsItem.STATUS_NONE,
SmsItem.STATUS_SPAM);
} else {
LOGE("(1) item == null");
}
break;
}
case SmsItem.STATUS_NONE: {
// we pressed "it ain't a spam". it means all messages with
// this address are not spam
SmsItem item = mSmsItemAdapter.getSmsItemFromId(msgId);
if (item != null) {
mSmsItemAdapter.updateStatusesIf(
item.mAddress,
SmsItem.STATUS_SPAM,
SmsItem.STATUS_NONE);
mSmsItemAdapter.updateStatusesIf(
item.mAddress,
SmsItem.STATUS_IN_INTERNAL_QUEUE,
SmsItem.STATUS_NONE);
} else {
LOGE("(2) item == null");
}
break;
}
}
mSmsItemAdapter.notifyDataSetChanged();
}
private String getSearchFilter() {
String actualFilter = "";
if (mSearchView != null) {
actualFilter = mSearchView.getQuery().toString().trim();
}
return actualFilter;
}
private boolean equalFilters(String f0, String f1) {
return (f0 == null && f1 == null) ||
(f0 != null && f0.equals(f1));
}
private void addShortcut() {
Intent shortcutIntent = new Intent(getApplicationContext(),
MainActivity.class);
shortcutIntent.setAction(Intent.ACTION_MAIN);
Intent addIntent = new Intent();
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
getText(R.string.app_name));
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(getApplicationContext(),
R.drawable.ic_launcher));
addIntent.putExtra("duplicate", false);
addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
getApplicationContext().sendBroadcast(addIntent);
}
/*private void removeShortcut() {
Intent shortcutIntent = new Intent(getApplicationContext(),
MainActivity.class);
shortcutIntent.setAction(Intent.ACTION_MAIN);
Intent addIntent = new Intent();
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME,
getText(R.string.app_name));
addIntent.setAction("com.android.launcher.action.UNINSTALL_SHORTCUT");
getApplicationContext().sendBroadcast(addIntent);
}*/
private class UpdaterAsyncTask extends AsyncTask<Void, Void, Void> {
public static final int UPDATER_TIMEOUT = 500;
public static final int SEARCH_TEST_TIMEOUT = 2000;
@Override
protected Void doInBackground(Void... params) {
LOGI("MainActivity UpdaterAsyncTask ThreadID=" +
Thread.currentThread().getId());
while (true) {
if (isCancelled()) {
LOGI("isCancelled UpdaterAsyncTask");
break;
}
Common.runOnMainThread(new Runnable() {
public void run() {
// HACK: onTextChanged doesn't handle backspace properly
if (MainActivity.this == null) {
return;
}
if (isSearchViewUpdatedToEmpty()) {
LOGI("need to update listview (case 1)...");
updateEmptyListText(R.string.loading);
refreshSmsItemAdapter();
}
}
});
Common.runOnMainThread(new Runnable() {
public void run() {
if (MainActivity.this == null) {
mSearchTestTimer = 0;
return;
}
// HACK: by unknown reason sometimes we don't receive
// a correct list
/*if (mSmsItemAdapter != null &&
mSmsItemAdapter.getLoadingVisible()) {
mSearchTestTimer += UPDATER_TIMEOUT;
if (mSearchTestTimer >= SEARCH_TEST_TIMEOUT) {
mSearchTestTimer = 0;
LOGI("need to update listview (case 2)...");
refreshSmsItemAdapter();
}
} else {
mSearchTestTimer = 0;
}*/
}
});
try {
Thread.sleep(UPDATER_TIMEOUT);
} catch (Throwable t) {
}
}
LOGI("MainActivity EXITING UpdaterAsyncTask ThreadID=" +
Thread.currentThread().getId());
return null;
}
}
private class EndlessScrollListener implements OnScrollListener {
public EndlessScrollListener() {
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (firstVisibleItem + visibleItemCount >= totalItemCount) {
updateSmsItemAdapter();
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
}
private ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName className,
IBinder service) {
mService = new Messenger(service);
LOGI("onServiceConnected mService=" + mService);
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
mService = null;
LOGI("onServiceDisconnected mService=" + mService);
}
};
}
|
package com.simsilica.lemur.component;
import java.util.*;
import com.jme3.math.Vector3f;
import com.jme3.scene.Node;
import com.simsilica.lemur.core.GuiControl;
import com.simsilica.lemur.core.GuiLayout;
/**
* A layout that manages children similar to Swing's BorderLayout where
* children can be placed in any of Position enum values (Position.Center,
* Position.North, etc.) Currently this layout operates only in the x/y
* axes.
*
* @author Paul Speed
*/
public class BorderLayout extends AbstractGuiComponent
implements GuiLayout, Cloneable {
public enum Position { North, South, East, West, Center };
private GuiControl parent;
private Map<Position,Node> children = new EnumMap<Position, Node>(Position.class);
private Vector3f lastPreferredSize = new Vector3f();
public BorderLayout() {
}
@Override
public BorderLayout clone() {
// Easier and better to just instantiate with the proper
// settings
BorderLayout result = new BorderLayout();
return result;
}
@Override
protected void invalidate() {
if( parent != null ) {
parent.invalidate();
}
}
protected Vector3f getPreferredSize( Position pos ) {
Node child = children.get(pos);
if( child == null )
return Vector3f.ZERO;
return child.getControl(GuiControl.class).getPreferredSize();
}
public void calculatePreferredSize( Vector3f size ) {
// Layout looks something like:
// | North |
// | W | | E |
// | e | | a |
// | s | Center | s |
// | t | | t |
// | South |
Vector3f pref;
// The center affects both axes
pref = getPreferredSize(Position.Center);
size.addLocal(pref);
// North and south only affect y
pref = getPreferredSize(Position.North);
size.y += pref.y;
size.x = Math.max( size.x, pref.x );
pref = getPreferredSize(Position.South);
size.y += pref.y;
size.x = Math.max(size.x, pref.x);
// East and west only affect x
pref = getPreferredSize(Position.East);
size.y = Math.max(size.y, pref.y);
size.x += pref.x;
pref = getPreferredSize(Position.West);
size.y = Math.max(size.y, pref.y);
size.x += pref.x;
}
public void reshape(Vector3f pos, Vector3f size) {
// Note: we use the pos and size for scratch because we
// are a layout and we should therefore always be last.
// Make sure the preferred size book-keeping is up to date.
// Some children don't like being asked to resize without
// having been asked to calculate their preferred size first.
calculatePreferredSize(new Vector3f());
Vector3f pref;
Node child;
// First the north component takes up the entire upper
// border.
child = children.get(Position.North);
if( child != null ) {
pref = getPreferredSize(Position.North);
child.setLocalTranslation(pos);
pos.y -= pref.y;
size.y -= pref.y;
child.getControl(GuiControl.class).setSize(new Vector3f(size.x, pref.y, size.z));
}
// And the south component takes up the entire lower border
child = children.get(Position.South);
if( child != null ) {
pref = getPreferredSize(Position.South);
child.setLocalTranslation(pos.x, pos.y - size.y + pref.y, pos.z);
size.y -= pref.y;
child.getControl(GuiControl.class).setSize(new Vector3f(size.x, pref.y, size.z));
}
// Now the east and west to hem in the left/right borders
child = children.get(Position.West);
if( child != null ) {
pref = getPreferredSize(Position.West);
child.setLocalTranslation(pos);
pos.x += pref.x;
size.x -= pref.x;
child.getControl(GuiControl.class).setSize(new Vector3f(pref.x, size.y, size.z));
}
child = children.get(Position.East);
if( child != null ) {
pref = getPreferredSize(Position.East);
child.setLocalTranslation(pos.x + size.x - pref.x, pos.y, pos.z);
size.x -= pref.x;
child.getControl(GuiControl.class).setSize(new Vector3f(pref.x, size.y, size.z));
}
// And what's left goes to the center component and it needs to
// be resized appropriately.
child = children.get(Position.Center);
if( child != null ) {
child.setLocalTranslation( pos );
child.getControl(GuiControl.class).setSize(size);
}
}
public <T extends Node> T addChild( Position pos, T n ) {
if( n.getControl(GuiControl.class) == null )
throw new IllegalArgumentException( "Child is not GUI element." );
// See if there is already a child there
Node existing = children.remove(pos);
if( existing != null && parent != null ) {
parent.getNode().detachChild(existing);
}
children.put(pos, n);
if( parent != null ) {
parent.getNode().attachChild(n);
}
invalidate();
return n;
}
public <T extends Node> T addChild( T n, Object... constraints ) {
Position p = Position.Center;
for( Object o : constraints ) {
if( o instanceof Position ) {
p = (Position)o;
} else {
throw new IllegalArgumentException( "Unknown border layout constraint:" + o );
}
}
// Determine the next natural location
addChild(p, n);
return n;
}
public void removeChild( Node n ) {
if( !children.values().remove(n) )
throw new RuntimeException( "Node is not a child of this layout." );
if( parent != null ) {
parent.getNode().detachChild(n);
}
invalidate();
}
public Collection<Node> getChildren() {
return Collections.unmodifiableCollection(children.values());
}
public void clearChildren() {
if( parent != null ) {
// Need to detach any children
for( Node n : children.values() ) {
// Detaching from the parent we know prevents
// accidentally detaching a node that has been
// reparented without our knowledge
parent.getNode().detachChild(n);
}
}
children.clear();
invalidate();
}
@Override
public void attach( GuiControl parent ) {
this.parent = parent;
Node self = parent.getNode();
for( Node child : children.values() ) {
self.attachChild(child);
}
}
@Override
public void detach( GuiControl parent ) {
this.parent = null;
for( Node child : children.values() ) {
child.removeFromParent();
}
}
}
|
package com.tellmas.android.redditor;
import java.util.concurrent.TimeUnit;
import android.app.Application;
import android.content.Context;
/**
* Global constants for this app.
*/
public final class GlobalDefines extends Application {
/**
* the "tag" for android.util.Log
*/
public static final String LOG_TAG = "REDDITOR";
public static final String USER_AGENT = "fetchit/0.5 by tellmas";
public static final String REDDIT_URI_API = "http://api.reddit.com/";
public static final String REDDIT_API_LISTING_DATAYPE_JSON = ".json";
public static final String REDDIT_API_LISTING_DATAYPE_XML = ".xml";
public static final String REDDIT_API_LISTING_DATAYPE_DEFAULT = REDDIT_API_LISTING_DATAYPE_JSON;
public static final String REDDIT_API_LISTING_DEFAULT = "hot.json";
public static final String BUNDLE_KEY_LIST_OF_LINKS = "bundlekeylistoflinks";
public static final String BUNDLE_KEY_FOR_URL = "bundlekeyforurl";
public static final String SUBREDDIT_URI_PREFIX = "/r/";
public static final int EXIT_STATUS_ERROR = 1;
public static final double SCROLL_DURATION_FACTOR = 2; // multiple of slower
public static final int PROGRESS_LOADING_SHOW_THRESHOLD = 10;
public static final String DEFAULT_LISTING = "";
public static final String DEFAULT_SORT = "hot";
public static final String STRING_REPLACEMENT = "{value}";
public enum RedditorTimeUnit {SECONDS, MINUTES, HOURS, DAYS};
/**
*
* @param seconds TODO
* @return TODO
*/
public static RedditorTime convertToAppropriateTimeUnits(final RedditorTime seconds) {
final RedditorTime time = seconds;
final long timeValue = seconds.getTimeValue();
if (TimeUnit.SECONDS.toDays(timeValue) > 0) {
time.setTimeValue(TimeUnit.SECONDS.toDays(timeValue));
time.setTimeUnit(RedditorTimeUnit.DAYS);
} else if (TimeUnit.SECONDS.toHours(timeValue) > 0) {
time.setTimeValue(TimeUnit.SECONDS.toHours(timeValue));
time.setTimeUnit(RedditorTimeUnit.HOURS);
} else if (TimeUnit.SECONDS.toMinutes(timeValue) > 0) {
time.setTimeValue(TimeUnit.SECONDS.toMinutes(timeValue));
time.setTimeUnit(RedditorTimeUnit.MINUTES);
}
return time;
}
/**
* TODO
*/
public static String submissionTimeStringBuilder(String submissionTime, Context context) throws NumberFormatException {
return submissionTimeStringBuilder(Long.parseLong(submissionTime), context);
}
/**
* TODO
*/
public static String submissionTimeStringBuilder(long submissionTime, Context context) {
final StringBuilder submissionTimeSB = new StringBuilder();
RedditorTime timeAgo = new RedditorTime(
System.currentTimeMillis() / 1000 - submissionTime
,RedditorTimeUnit.SECONDS
);
timeAgo = GlobalDefines.convertToAppropriateTimeUnits(timeAgo);
submissionTimeSB.append(Long.toString(timeAgo.getTimeValue()));
submissionTimeSB.append(" ");
boolean isSingularValue = false;
if (timeAgo.getTimeValue() == 1) {
isSingularValue = true;
}
int timeUnitId = 0;
switch(timeAgo.getTimeUnit()) {
case SECONDS:
if (isSingularValue) {
timeUnitId = R.string.second;
} else {
timeUnitId = R.string.seconds;
}
break;
case MINUTES:
if (isSingularValue) {
timeUnitId = R.string.minute;
} else {
timeUnitId = R.string.minutes;
}
break;
case HOURS:
if (isSingularValue) {
timeUnitId = R.string.hour;
} else {
timeUnitId = R.string.hours;
}
break;
case DAYS:
if (isSingularValue) {
timeUnitId = R.string.day;
} else {
timeUnitId = R.string.days;
}
break;
default:
timeUnitId = R.string.empty;
break;
}
submissionTimeSB.append(context.getResources().getString(timeUnitId));
submissionTimeSB.append(" ");
submissionTimeSB.append(context.getResources().getString(R.string.ago));
return submissionTimeSB.toString();
}
private static GlobalDefines singleton;
public static GlobalDefines getInstance() {
return singleton;
}
@Override
public void onCreate() {
super.onCreate();
singleton = this;
}
}
|
package org.apache.lucene.util.automaton;
import org.apache.lucene.util.ArrayUtil;
import org.apache.lucene.util.RamUsageEstimator;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import java.util.Iterator;
/**
* <tt>Automaton</tt> state.
*
* @lucene.experimental
*/
public class State implements Serializable, Comparable<State> {
boolean accept;
public Transition[] transitionsArray;
public int numTransitions;
int number;
int id;
static int next_id;
/**
* Constructs a new state. Initially, the new state is a reject state.
*/
public State() {
resetTransitions();
id = next_id++;
}
/**
* Resets transition set.
*/
final void resetTransitions() {
transitionsArray = new Transition[0];
numTransitions = 0;
}
private class TransitionsIterable implements Iterable<Transition> {
public Iterator<Transition> iterator() {
return new Iterator<Transition>() {
int upto;
public boolean hasNext() {
return upto < numTransitions;
}
public Transition next() {
return transitionsArray[upto++];
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
}
/**
* Returns the set of outgoing transitions. Subsequent changes are reflected
* in the automaton.
*
* @return transition set
*/
public Iterable<Transition> getTransitions() {
return new TransitionsIterable();
}
public int numTransitions() {
return numTransitions;
}
public void setTransitions(Transition[] transitions) {
this.numTransitions = transitions.length;
this.transitionsArray = transitions;
}
/**
* Adds an outgoing transition.
*
* @param t transition
*/
public void addTransition(Transition t) {
if (numTransitions == transitionsArray.length) {
final Transition[] newArray = new Transition[ArrayUtil.oversize(1+numTransitions, RamUsageEstimator.NUM_BYTES_OBJ_REF)];
System.arraycopy(transitionsArray, 0, newArray, 0, numTransitions);
transitionsArray = newArray;
}
transitionsArray[numTransitions++] = t;
}
/**
* Sets acceptance for this state.
*
* @param accept if true, this state is an accept state
*/
public void setAccept(boolean accept) {
this.accept = accept;
}
/**
* Returns acceptance status.
*
* @return true is this is an accept state
*/
public boolean isAccept() {
return accept;
}
/**
* Performs lookup in transitions, assuming determinism.
*
* @param c codepoint to look up
* @return destination state, null if no matching outgoing transition
* @see #step(int, Collection)
*/
public State step(int c) {
assert c >= 0;
for (int i=0;i<numTransitions;i++) {
final Transition t = transitionsArray[i];
if (t.min <= c && c <= t.max) return t.to;
}
return null;
}
/**
* Performs lookup in transitions, allowing nondeterminism.
*
* @param c codepoint to look up
* @param dest collection where destination states are stored
* @see #step(int)
*/
public void step(int c, Collection<State> dest) {
for (int i=0;i<numTransitions;i++) {
final Transition t = transitionsArray[i];
if (t.min <= c && c <= t.max) dest.add(t.to);
}
}
void addEpsilon(State to) {
if (to.accept) accept = true;
for (Transition t : to.getTransitions())
addTransition(t);
}
/** Downsizes transitionArray to numTransitions */
public void trimTransitionsArray() {
if (numTransitions < transitionsArray.length) {
final Transition[] newArray = new Transition[numTransitions];
System.arraycopy(transitionsArray, 0, newArray, 0, numTransitions);
transitionsArray = newArray;
}
}
/**
* Reduces this state. A state is "reduced" by combining overlapping
* and adjacent edge intervals with same destination.
*/
public void reduce() {
if (numTransitions <= 1) {
return;
}
sortTransitions(Transition.CompareByDestThenMinMax);
State p = null;
int min = -1, max = -1;
int upto = 0;
for (int i=0;i<numTransitions;i++) {
final Transition t = transitionsArray[i];
if (p == t.to) {
if (t.min <= max + 1) {
if (t.max > max) max = t.max;
} else {
if (p != null) {
transitionsArray[upto++] = new Transition(min, max, p);
}
min = t.min;
max = t.max;
}
} else {
if (p != null) {
transitionsArray[upto++] = new Transition(min, max, p);
}
p = t.to;
min = t.min;
max = t.max;
}
}
if (p != null) {
transitionsArray[upto++] = new Transition(min, max, p);
}
numTransitions = upto;
}
/**
* Returns sorted list of outgoing transitions.
*
* @param to_first if true, order by (to, min, reverse max); otherwise (min,
* reverse max, to)
* @return transition list
*/
/** Sorts transitions array in-place. */
public void sortTransitions(Comparator<Transition> comparator) {
if (numTransitions > 1)
Arrays.sort(transitionsArray, 0, numTransitions, comparator);
}
/**
* Return this state's number.
* <p>
* Expert: Will be useless unless {@link Automaton#getNumberedStates}
* has been called first to number the states.
* @return the number
*/
public int getNumber() {
return number;
}
/**
* Returns string describing this state. Normally invoked via
* {@link Automaton#toString()}.
*/
@Override
public String toString() {
StringBuilder b = new StringBuilder();
b.append("state ").append(number);
if (accept) b.append(" [accept]");
else b.append(" [reject]");
b.append(":\n");
for (Transition t : getTransitions())
b.append(" ").append(t.toString()).append("\n");
return b.toString();
}
/**
* Compares this object with the specified object for order. States are
* ordered by the time of construction.
*/
public int compareTo(State s) {
return s.id - id;
}
@Override
public int hashCode() {
return id;
}
}
|
package cgeo.geocaching.unifiedmap;
import cgeo.geocaching.CgeoApplication;
import cgeo.geocaching.R;
import cgeo.geocaching.activity.AbstractBottomNavigationActivity;
import cgeo.geocaching.activity.ActivityMixin;
import cgeo.geocaching.downloader.DownloaderUtils;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.location.Geopoint;
import cgeo.geocaching.location.Viewport;
import cgeo.geocaching.maps.MapMode;
import cgeo.geocaching.maps.MapUtils;
import cgeo.geocaching.maps.RouteTrackUtils;
import cgeo.geocaching.maps.Tracks;
import cgeo.geocaching.maps.routing.Routing;
import cgeo.geocaching.models.Geocache;
import cgeo.geocaching.models.IndividualRoute;
import cgeo.geocaching.models.Route;
import cgeo.geocaching.permission.PermissionHandler;
import cgeo.geocaching.permission.PermissionRequestContext;
import cgeo.geocaching.permission.RestartLocationPermissionGrantedCallback;
import cgeo.geocaching.sensors.GeoData;
import cgeo.geocaching.sensors.GeoDirHandler;
import cgeo.geocaching.sensors.Sensors;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.storage.DataStore;
import cgeo.geocaching.ui.ViewUtils;
import cgeo.geocaching.unifiedmap.tileproviders.AbstractTileProvider;
import cgeo.geocaching.unifiedmap.tileproviders.TileProviderFactory;
import cgeo.geocaching.utils.AngleUtils;
import cgeo.geocaching.utils.CompactIconModeUtils;
import cgeo.geocaching.utils.HistoryTrackUtils;
import cgeo.geocaching.utils.ImageUtils;
import cgeo.geocaching.utils.Log;
import static cgeo.geocaching.settings.Settings.MAPROTATION_AUTO;
import static cgeo.geocaching.settings.Settings.MAPROTATION_MANUAL;
import static cgeo.geocaching.settings.Settings.MAPROTATION_OFF;
import static cgeo.geocaching.unifiedmap.UnifiedMapType.BUNDLE_MAPTYPE;
import static cgeo.geocaching.unifiedmap.UnifiedMapType.UnifiedMapTypeType.UMTT_TargetCoords;
import static cgeo.geocaching.unifiedmap.UnifiedMapType.UnifiedMapTypeType.UMTT_TargetGeocode;
import static cgeo.geocaching.unifiedmap.tileproviders.TileProviderFactory.MAP_LANGUAGE_DEFAULT_ID;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.location.Location;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import androidx.annotation.NonNull;
import androidx.appcompat.widget.PopupMenu;
import androidx.core.content.res.ResourcesCompat;
import java.lang.ref.WeakReference;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import org.oscim.core.BoundingBox;
import org.oscim.core.GeoPoint;
public class UnifiedMapActivity extends AbstractBottomNavigationActivity {
private static final String STATE_ROUTETRACKUTILS = "routetrackutils";
private static final String BUNDLE_ROUTE = "route";
private static final String BUNDLE_OVERRIDEPOSITIONANDZOOM = "overridePositionAndZoom";
private static final String ROUTING_SERVICE_KEY = "UnifiedMap";
private AbstractTileProvider tileProvider = null;
private AbstractGeoitemLayer geoitemLayer = null;
private final UpdateLoc geoDirUpdate = new UpdateLoc(this);
private final CompositeDisposable resumeDisposables = new CompositeDisposable();
private static boolean followMyLocation = Settings.isLiveMap();
private MenuItem followMyLocationItem = null;
private RouteTrackUtils routeTrackUtils = null;
private IndividualRoute individualRoute = null;
private Tracks tracks = null;
private UnifiedMapPosition currentMapPosition = new UnifiedMapPosition();
private UnifiedMapType mapType = null;
private MapMode compatibilityMapMode = MapMode.LIVE;
private boolean overridePositionAndZoom = false; // to preserve those on config changes in favour to mapType defaults
// rotation indicator
protected Bitmap rotationIndicator = ImageUtils.convertToBitmap(ResourcesCompat.getDrawable(CgeoApplication.getInstance().getResources(), R.drawable.bearing_indicator, null));
protected int rotationWidth = rotationIndicator.getWidth();
protected int rotationHeight = rotationIndicator.getHeight();
// class: update location
private static class UpdateLoc extends GeoDirHandler {
// use the following constants for fine tuning - find good compromise between smooth updates and as less updates as possible
// minimum time in milliseconds between position overlay updates
private static final long MIN_UPDATE_INTERVAL = 500;
private long timeLastPositionOverlayCalculation = 0;
// minimum change of heading in grad for position overlay update
private static final float MIN_HEADING_DELTA = 15f;
// minimum change of location in fraction of map width/height (whatever is smaller) for position overlay update
private static final float MIN_LOCATION_DELTA = 0.01f;
@NonNull
Location currentLocation = Sensors.getInstance().currentGeo();
float currentHeading;
/**
* weak reference to the outer class
*/
@NonNull
private final WeakReference<UnifiedMapActivity> mapActivityRef;
UpdateLoc(@NonNull final UnifiedMapActivity mapActivity) {
mapActivityRef = new WeakReference<>(mapActivity);
}
@Override
public void updateGeoDir(@NonNull final GeoData geo, final float dir) {
currentLocation = geo;
currentHeading = AngleUtils.getDirectionNow(dir);
repaintPositionOverlay();
}
@NonNull
public Location getCurrentLocation() {
return currentLocation;
}
/**
* Repaint position overlay but only with a max frequency and if position or heading changes sufficiently.
*/
void repaintPositionOverlay() {
final long currentTimeMillis = System.currentTimeMillis();
if (currentTimeMillis > (timeLastPositionOverlayCalculation + MIN_UPDATE_INTERVAL)) {
timeLastPositionOverlayCalculation = currentTimeMillis;
try {
final UnifiedMapActivity mapActivity = mapActivityRef.get();
if (mapActivity != null) {
final boolean needsRepaintForDistanceOrAccuracy = needsRepaintForDistanceOrAccuracy();
final boolean needsRepaintForHeading = needsRepaintForHeading();
if (needsRepaintForDistanceOrAccuracy && followMyLocation) {
mapActivity.tileProvider.getMap().setCenter(new Geopoint(currentLocation));
mapActivity.currentMapPosition.resetFollowMyLocation = false;
}
if (needsRepaintForDistanceOrAccuracy || needsRepaintForHeading) {
if (mapActivity.tileProvider.getMap().positionLayer != null) {
mapActivity.tileProvider.getMap().positionLayer.setCurrentPositionAndHeading(currentLocation, currentHeading);
}
// @todo: check if proximity notification needs an update
}
}
} catch (final RuntimeException e) {
Log.w("Failed to update location", e);
}
}
}
boolean needsRepaintForHeading() {
final UnifiedMapActivity mapActivity = mapActivityRef.get();
if (mapActivity == null) {
return false;
}
return Math.abs(AngleUtils.difference(currentHeading, mapActivity.tileProvider.getMap().getHeading())) > MIN_HEADING_DELTA;
}
boolean needsRepaintForDistanceOrAccuracy() {
final UnifiedMapActivity map = mapActivityRef.get();
if (map == null) {
return false;
}
final Location lastLocation = map.getLocation();
if (lastLocation.getAccuracy() != currentLocation.getAccuracy()) {
return true;
}
// @todo: NewMap uses a more sophisticated calculation taking map dimensions into account - check if this is still needed
return currentLocation.distanceTo(lastLocation) > MIN_LOCATION_DELTA;
}
}
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// get data from intent
final Bundle extras = getIntent().getExtras();
if (extras != null) {
mapType = extras.getParcelable(BUNDLE_MAPTYPE);
}
setMapModeFromMapType();
// Get fresh map information from the bundle if any
if (savedInstanceState != null) {
if (savedInstanceState.containsKey(BUNDLE_MAPTYPE)) {
mapType = savedInstanceState.getParcelable(BUNDLE_MAPTYPE);
}
overridePositionAndZoom = savedInstanceState.getBoolean(BUNDLE_OVERRIDEPOSITIONANDZOOM, false);
// proximityNotification = savedInstanceState.getParcelable(BUNDLE_PROXIMITY_NOTIFICATION);
individualRoute = savedInstanceState.getParcelable(BUNDLE_ROUTE);
// followMyLocation = mapOptions.mapState.followsMyLocation();
} else {
// if (mapOptions.mapState != null) {
// followMyLocation = mapOptions.mapState.followsMyLocation();
// } else {
// followMyLocation = followMyLocation && mapOptions.mapMode == MapMode.LIVE;
individualRoute = null;
// proximityNotification = Settings.isGeneralProximityNotificationActive() ? new ProximityNotification(true, false) : null;
}
// make sure we have a defined mapType
if (mapType == null || mapType.type == UnifiedMapType.UnifiedMapTypeType.UMTT_Undefined) {
mapType = new UnifiedMapType();
}
changeMapSource(Settings.getTileProvider());
Routing.connect(ROUTING_SERVICE_KEY, () -> resumeRoute(true));
CompactIconModeUtils.setCompactIconModeThreshold(getResources());
// MapUtils.showMapOneTimeMessages(this, mapMode);
}
private void setMapModeFromMapType() {
if (mapType == null) {
return;
}
if (mapType.type == UMTT_TargetGeocode) {
compatibilityMapMode = MapMode.SINGLE;
} else if (mapType.type == UMTT_TargetCoords) {
compatibilityMapMode = MapMode.COORDS;
} else {
compatibilityMapMode = MapMode.LIVE;
}
}
private void changeMapSource(final AbstractTileProvider newSource) {
final AbstractTileProvider oldProvider = tileProvider;
if (oldProvider != null) {
oldProvider.getMap().prepareForTileSourceChange();
}
tileProvider = newSource;
if (tileProvider != oldProvider) {
if (oldProvider != null) {
tileProvider.getMap().init(this, oldProvider.getMap().getCurrentZoom(), oldProvider.getMap().getCenter(), () -> onMapReadyTasks(newSource, true));
} else {
tileProvider.getMap().init(this, Settings.getMapZoom(compatibilityMapMode), null, () -> onMapReadyTasks(newSource, true));
}
configMapChangeListener(true);
} else {
onMapReadyTasks(newSource, false);
}
}
private void onMapReadyTasks(final AbstractTileProvider newSource, final boolean mapChanged) {
TileProviderFactory.resetLanguages();
tileProvider.getMap().setTileSource(newSource);
Settings.setTileProvider(newSource);
tileProvider.getMap().setDelayedZoomTo();
tileProvider.getMap().setDelayedCenterTo();
final View spinner = findViewById(R.id.map_progressbar);
if (spinner != null) {
spinner.setVisibility(View.GONE);
}
if (mapChanged) {
routeTrackUtils = new RouteTrackUtils(this, null /* @todo: savedInstanceState == null ? null : savedInstanceState.getBundle(STATE_ROUTETRACKUTILS) */, this::centerMap, this::clearIndividualRoute, this::reloadIndividualRoute, this::setTrack, this::isTargetSet);
tracks = new Tracks(routeTrackUtils, this::setTrack);
// map settings popup
// findViewById(R.id.map_settings_popup).setOnClickListener(v -> MapSettingsUtils.showSettingsPopup(this, individualRoute, this::refreshMapData, this::routingModeChanged, this::compactIconModeChanged, mapOptions.filterContext));
// routes / tracks popup
findViewById(R.id.map_individualroute_popup).setOnClickListener(v -> routeTrackUtils.showPopup(individualRoute, this::setTarget));
// create geoitem layers
geoitemLayer = tileProvider.getMap().createGeoitemLayers(tileProvider);
// react to mapType
setMapModeFromMapType();
switch (mapType.type) {
case UMTT_PlainMap:
// restore last saved position and zoom
tileProvider.getMap().setZoom(Settings.getMapZoom(compatibilityMapMode));
tileProvider.getMap().setCenter(Settings.getUMMapCenter());
break;
case UMTT_TargetGeocode:
final Geocache cache = DataStore.loadCache(mapType.target, LoadFlags.LOAD_CACHE_OR_DB);
if (cache != null && cache.getCoords() != null) {
geoitemLayer.add(cache);
tileProvider.getMap().zoomToBounds(DataStore.getBounds(mapType.target, Settings.getZoomIncludingWaypoints()));
setTarget(cache.getCoords(), cache.getName());
}
break;
case UMTT_TargetCoords:
tileProvider.getMap().setCenter(mapType.coords);
break;
default:
// nothing to do
break;
}
if (overridePositionAndZoom) {
tileProvider.getMap().setZoom(Settings.getMapZoom(compatibilityMapMode));
tileProvider.getMap().setCenter(Settings.getUMMapCenter());
overridePositionAndZoom = false;
}
// @todo for testing purposes only
/*
if (geoitemLayer != null) {
geoitemLayer.add("GC9C8G5");
geoitemLayer.add("GC9RZT2");
geoitemLayer.add("GC37RRG");
geoitemLayer.add("GC360D1");
geoitemLayer.add("GC8902H");
}
*/
}
// refresh options menu and routes/tracks display
invalidateOptionsMenu();
onResume();
}
private void configMapChangeListener(final boolean enabled) {
if (enabled) {
tileProvider.getMap().setActivityMapChangeListener(unifiedMapPosition -> {
final UnifiedMapPosition old = currentMapPosition;
currentMapPosition = (UnifiedMapPosition) unifiedMapPosition;
if (currentMapPosition.zoomLevel != old.zoomLevel) {
Log.e("zoom level changed from " + old.zoomLevel + " to " + currentMapPosition.zoomLevel);
}
if (currentMapPosition.latitude != old.latitude || currentMapPosition.longitude != old.longitude) {
Log.e("position change from [" + old.latitude + "/" + old.longitude + "] to [" + currentMapPosition.latitude + "/" + currentMapPosition.longitude + "]");
if (old.resetFollowMyLocation) {
followMyLocation = false;
initFollowMyLocationButton();
}
}
if (currentMapPosition.bearing != old.bearing) {
repaintRotationIndicator(currentMapPosition.bearing);
Log.e("bearing change from " + old.bearing + " to " + currentMapPosition.bearing);
}
});
tileProvider.getMap().setResetFollowMyLocationListener(() -> {
followMyLocation = false;
initFollowMyLocationButton();
});
} else {
tileProvider.getMap().setActivityMapChangeListener(null);
tileProvider.getMap().setResetFollowMyLocationListener(null);
}
}
/**
* centers map on coords given + resets "followMyLocation" state
**/
private void centerMap(final Geopoint geopoint) {
followMyLocation = false;
initFollowMyLocationButton();
tileProvider.getMap().setCenter(geopoint);
}
private Location getLocation() {
final Geopoint center = tileProvider.getMap().getCenter();
final Location loc = new Location("UnifiedMap");
loc.setLatitude(center.getLatitude());
loc.setLongitude(center.getLongitude());
return loc;
}
private void initFollowMyLocationButton() {
if (followMyLocationItem != null) {
followMyLocationItem.setIcon(followMyLocation ? R.drawable.ic_menu_mylocation : R.drawable.ic_menu_mylocation_off);
}
}
protected void repaintRotationIndicator(final float bearing) {
if (!tileProvider.getMap().usesOwnBearingIndicator) {
final ImageView compassrose = findViewById(R.id.bearingIndicator);
if (bearing == 0.0f) {
compassrose.setImageBitmap(null);
} else {
final Matrix matrix = new Matrix();
matrix.setRotate(bearing, rotationWidth / 2.0f, rotationHeight / 2.0f);
compassrose.setImageBitmap(Bitmap.createBitmap(rotationIndicator, 0, 0, rotationWidth, rotationHeight, matrix, true));
compassrose.setOnClickListener(v -> {
tileProvider.getMap().setBearing(0.0f);
repaintRotationIndicator(0.0f);
});
}
}
}
// Routes, tracks and targets handling
private void setTarget(final Geopoint geopoint, final String s) {
if (tileProvider.getMap().positionLayer != null) {
tileProvider.getMap().positionLayer.setDestination(new GeoPoint(geopoint.getLatitude(), geopoint.getLongitude()));
}
// @todo
/*
lastNavTarget = coords;
if (StringUtils.isNotBlank(geocode)) {
targetGeocode = geocode;
final Geocache target = getCurrentTargetCache();
targetView.setTarget(targetGeocode, target != null ? target.getName() : StringUtils.EMPTY);
if (lastNavTarget == null && target != null) {
lastNavTarget = target.getCoords();
}
} else {
targetGeocode = null;
targetView.setTarget(null, null);
}
if (navigationLayer != null) {
navigationLayer.setDestination(lastNavTarget);
navigationLayer.requestRedraw();
}
if (distanceView != null) {
distanceView.setDestination(lastNavTarget);
distanceView.setCoordinates(geoDirUpdate.getCurrentLocation());
}
ActivityMixin.invalidateOptionsMenu(this);
*/
}
// glue method for old map
// can be removed when removing CGeoMap and NewMap, routeTrackUtils need to be adapted then
@SuppressWarnings("unused")
private void centerMap(final double latitude, final double longitude, final Viewport viewport) {
centerMap(new Geopoint(latitude, longitude));
}
private Boolean isTargetSet() {
// return StringUtils.isNotBlank(targetGeocode) && null != lastNavTarget;
return false; // @todo
}
private void setTrack(final String key, final Route route) {
tracks.setRoute(key, route);
resumeTrack(key, null == route);
}
private void reloadIndividualRoute() {
individualRoute.reloadRoute((route) -> {
if (tileProvider.getMap().positionLayer != null) {
tileProvider.getMap().positionLayer.updateIndividualRoute(route);
}
});
}
private void clearIndividualRoute() {
individualRoute.clearRoute((route) -> tileProvider.getMap().positionLayer.updateIndividualRoute(route));
// ActivityMixin.invalidateOptionsMenu(this); // @todo still needed since introduction of route popup?
showToast(res.getString(R.string.map_individual_route_cleared));
}
// Bottom navigation methods
@Override
public int getSelectedBottomItemId() {
return MENU_MAP;
}
// Menu handling
@Override
public boolean onPrepareOptionsMenu(final Menu menu) {
final boolean result = super.onPrepareOptionsMenu(menu);
TileProviderFactory.addMapViewLanguageMenuItems(menu);
this.routeTrackUtils.onPrepareOptionsMenu(menu, findViewById(R.id.container_individualroute), individualRoute, tracks);
ViewUtils.extendMenuActionBarDisplayItemCount(this, menu);
// map rotation state
menu.findItem(R.id.menu_map_rotation).setVisible(true); // @todo: can be visible always when CGeoMap/NewMap is removed
final int mapRotation = Settings.getMapRotation();
switch (mapRotation) {
case MAPROTATION_OFF:
menu.findItem(R.id.menu_map_rotation_off).setChecked(true);
break;
case MAPROTATION_MANUAL:
menu.findItem(R.id.menu_map_rotation_manual).setChecked(true);
break;
case MAPROTATION_AUTO:
menu.findItem(R.id.menu_map_rotation_auto).setChecked(true);
break;
default:
break;
}
// theming options
menu.findItem(R.id.menu_theme_mode).setVisible(tileProvider.supportsThemes());
menu.findItem(R.id.menu_theme_options).setVisible(tileProvider.supportsThemes());
//@todo menu.findItem(R.id.menu_theme_legend).setVisible(tileProvider.supportsThemes() && RenderThemeLegend.supportsLegend());
return result;
}
@Override
public boolean onCreateOptionsMenu(@NonNull final Menu menu) {
final boolean result = super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.map_activity, menu);
followMyLocationItem = menu.findItem(R.id.menu_toggle_mypos);
initFollowMyLocationButton();
return result;
}
@Override
public boolean onOptionsItemSelected(@NonNull final MenuItem item) {
final int id = item.getItemId();
/* yet missing:
- live mode
- all cache related menu entries
- all target related menu entries
- filter related menu entries
*/
if (id == R.id.menu_toggle_mypos) {
followMyLocation = !followMyLocation;
Settings.setLiveMap(followMyLocation);
if (followMyLocation) {
final Location currentLocation = geoDirUpdate.getCurrentLocation();
tileProvider.getMap().setCenter(new Geopoint(currentLocation.getLatitude(), currentLocation.getLongitude()));
currentMapPosition.resetFollowMyLocation = false;
}
initFollowMyLocationButton();
} else if (id == R.id.menu_map_rotation_off) {
setMapRotation(item, MAPROTATION_OFF);
} else if (id == R.id.menu_map_rotation_manual) {
setMapRotation(item, MAPROTATION_MANUAL);
} else if (id == R.id.menu_map_rotation_auto) {
setMapRotation(item, MAPROTATION_AUTO);
} else if (id == R.id.menu_check_routingdata) {
final BoundingBox bb = tileProvider.getMap().getBoundingBox();
MapUtils.checkRoutingData(this, bb.getMinLatitude(), bb.getMinLongitude(), bb.getMaxLatitude(), bb.getMaxLongitude());
} else if (HistoryTrackUtils.onOptionsItemSelected(this, id, () -> tileProvider.getMap().positionLayer.repaintHistory(), () -> tileProvider.getMap().positionLayer.clearHistory())
|| DownloaderUtils.onOptionsItemSelected(this, id, true)) {
return true;
} else if (id == R.id.menu_theme_mode) {
tileProvider.getMap().selectTheme(this);
} else if (id == R.id.menu_theme_options) {
tileProvider.getMap().selectThemeOptions(this);
} else if (id == R.id.menu_theme_legend) {
// @todo
// RenderThemeLegend.showLegend(this, this.renderThemeHelper, mapView.getModel().displayModel);
} else if (id == R.id.menu_routetrack) {
routeTrackUtils.showPopup(individualRoute, this::setTarget);
} else if (id == R.id.menu_select_mapview) {
// dynamically create submenu to reflect possible changes in map sources
final View v = findViewById(R.id.menu_select_mapview);
if (v != null) {
final PopupMenu menu = new PopupMenu(this, v, Gravity.TOP);
menu.inflate(R.menu.map_downloader);
TileProviderFactory.addMapviewMenuItems(this, menu);
menu.setOnMenuItemClickListener(this::onOptionsItemSelected);
menu.show();
}
} else {
final String language = TileProviderFactory.getLanguage(id);
if (language != null || id == MAP_LANGUAGE_DEFAULT_ID) {
item.setChecked(true);
Settings.setMapLanguage(language);
tileProvider.getMap().setPreferredLanguage(language);
return true;
}
final AbstractTileProvider tileProvider = TileProviderFactory.getTileProvider(id);
if (tileProvider != null) {
item.setChecked(true);
changeMapSource(tileProvider);
return true;
}
// @todo: remove this if-block after having completed implementation of UnifiedMap
if (item.getItemId() != android.R.id.home) {
ActivityMixin.showShortToast(this, "menu item '" + item.getTitle() + "' not yet implemented for UnifiedMap");
}
return super.onOptionsItemSelected(item);
}
return true;
}
private void setMapRotation(final MenuItem item, final int mapRotation) {
Settings.setMapRotation(mapRotation);
tileProvider.getMap().setMapRotation(mapRotation);
item.setChecked(true);
}
@Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
super.onActivityResult(requestCode, resultCode, data);
this.routeTrackUtils.onActivityResult(requestCode, resultCode, data);
}
// Lifecycle methods
@Override
protected void onSaveInstanceState(@NonNull final Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBundle(STATE_ROUTETRACKUTILS, routeTrackUtils.getState());
// final MapState state = prepareMapState();
outState.putParcelable(BUNDLE_MAPTYPE, mapType);
// if (proximityNotification != null) {
// outState.putParcelable(BUNDLE_PROXIMITY_NOTIFICATION, proximityNotification);
if (individualRoute != null) {
outState.putParcelable(BUNDLE_ROUTE, individualRoute);
}
outState.putBoolean(BUNDLE_OVERRIDEPOSITIONANDZOOM, true);
}
@Override
protected void onStart() {
super.onStart();
// resume location access
PermissionHandler.executeIfLocationPermissionGranted(this,
new RestartLocationPermissionGrantedCallback(PermissionRequestContext.NewMap) {
@Override
public void executeAfter() {
resumeDisposables.add(geoDirUpdate.start(GeoDirHandler.UPDATE_GEODIR));
}
});
}
@Override
protected void onStop() {
this.resumeDisposables.clear();
super.onStop();
}
@Override
public void onPause() {
tileProvider.getMap().onPause();
configMapChangeListener(false);
Settings.setMapZoom(compatibilityMapMode, tileProvider.getMap().getCurrentZoom());
Settings.setMapCenter(tileProvider.getMap().getCenter());
super.onPause();
}
@Override
protected void onResume() {
super.onResume();
tileProvider.getMap().onResume();
configMapChangeListener(true);
resumeRoute(false);
if (tracks != null) {
tracks.resumeAllTracks(this::resumeTrack);
}
// MapUtils.updateFilterBar(this, mapOptions.filterContext);
}
private void resumeRoute(final boolean force) {
if (null == individualRoute || force) {
individualRoute = new IndividualRoute(this::setTarget);
reloadIndividualRoute();
} else if (tileProvider.getMap().positionLayer != null) {
individualRoute.updateRoute((route) -> tileProvider.getMap().positionLayer.updateIndividualRoute(route));
}
}
private void resumeTrack(final String key, final boolean preventReloading) {
if (null == tracks && !preventReloading) {
this.tracks = new Tracks(this.routeTrackUtils, this::setTrack);
} else if (null != tracks) {
tileProvider.getMap().positionLayer.updateTrack(key, tracks.getRoute(key));
}
}
@Override
protected void onDestroy() {
tileProvider.getMap().onDestroy();
super.onDestroy();
}
}
|
package io.mangoo.core;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.Charset;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RegExUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.quartz.CronExpression;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.Trigger;
import com.google.common.io.Resources;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.Stage;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import io.github.classgraph.ClassGraph;
import io.github.classgraph.ScanResult;
import io.mangoo.admin.AdminController;
import io.mangoo.annotations.Schedule;
import io.mangoo.cache.CacheProvider;
import io.mangoo.enums.CacheName;
import io.mangoo.enums.Default;
import io.mangoo.enums.Key;
import io.mangoo.enums.Mode;
import io.mangoo.enums.Required;
import io.mangoo.exceptions.MangooSchedulerException;
import io.mangoo.interfaces.MangooBootstrap;
import io.mangoo.routing.Bind;
import io.mangoo.routing.On;
import io.mangoo.routing.Router;
import io.mangoo.routing.handlers.DispatcherHandler;
import io.mangoo.routing.handlers.ExceptionHandler;
import io.mangoo.routing.handlers.FallbackHandler;
import io.mangoo.routing.handlers.MetricsHandler;
import io.mangoo.routing.handlers.ServerSentEventHandler;
import io.mangoo.routing.handlers.WebSocketHandler;
import io.mangoo.routing.routes.FileRoute;
import io.mangoo.routing.routes.PathRoute;
import io.mangoo.routing.routes.RequestRoute;
import io.mangoo.routing.routes.ServerSentEventRoute;
import io.mangoo.routing.routes.WebSocketRoute;
import io.mangoo.scheduler.Scheduler;
import io.mangoo.utils.ByteUtils;
import io.mangoo.utils.MangooUtils;
import io.mangoo.utils.SchedulerUtils;
import io.undertow.Handlers;
import io.undertow.Undertow;
import io.undertow.Undertow.Builder;
import io.undertow.UndertowOptions;
import io.undertow.server.HttpHandler;
import io.undertow.server.RoutingHandler;
import io.undertow.server.handlers.PathHandler;
import io.undertow.server.handlers.resource.ClassPathResourceManager;
import io.undertow.server.handlers.resource.ResourceHandler;
import io.undertow.util.Methods;
/**
* Main class that starts all components of a mangoo I/O application
*
* @author svenkubiak
*
*/
public final class Application {
private static final Logger LOG = LogManager.getLogger(Application.class);
private static final int KEY_MIN_BIT_LENGTH = 512;
private static final int BUFFERSIZE = 255;
private static String httpHost;
private static String ajpHost;
private static Undertow undertow;
private static Mode mode;
private static Injector injector;
private static LocalDateTime start = LocalDateTime.now();
private static PathHandler pathHandler;
private static boolean started;
private static int httpPort;
private static int ajpPort;
private Application() {
}
public static void main(String... args) {
start(Mode.PROD);
}
public static void start(Mode mode) {
Objects.requireNonNull(mode, Required.MODE.toString());
if (!started) {
userCheck();
prepareMode(mode);
prepareInjector();
applicationInitialized();
prepareConfig();
prepareRoutes();
createRoutes();
prepareScheduler();
prepareUndertow();
sanityChecks();
showLogo();
applicationStarted();
Runtime.getRuntime().addShutdownHook(getInstance(Shutdown.class));
started = true;
}
}
/**
* Checks if application is run as root
* There is no need to run as root
*/
private static void userCheck() {
String osName = System.getProperty("os.name");
if (StringUtils.isNotBlank(osName) && !osName.startsWith("Windows")) {
Process exec;
try {
exec = Runtime.getRuntime().exec("id -u");
BufferedReader input = new BufferedReader(new InputStreamReader(exec.getInputStream(), Charset.forName("UTF-8")));
String output = input.lines().collect(Collectors.joining(System.lineSeparator()));
input.close();
if (("0").equals(output) && inProdMode()) {
LOG.error("Can not run application as root");
failsafe();
}
} catch (IOException e) {
LOG.error("Failed to check user running application", e);
}
}
}
/**
* Checks if the application is running in dev mode
*
* @return True if the application is running in dev mode, false otherwise
*/
public static boolean inDevMode() {
return Mode.DEV == mode;
}
/**
* Checks if the application is running in prod mode
*
* @return True if the application is running in prod mode, false otherwise
*/
public static boolean inProdMode() {
return Mode.PROD == mode;
}
/**
* Checks if the application is running in test mode
*
* @return True if the application is running in test mode, false otherwise
*/
public static boolean inTestMode() {
return Mode.TEST == mode;
}
/**
* Returns the current mode the application is running in
*
* @return Enum Mode
*/
public static Mode getMode() {
return mode;
}
/**
* Returns the Google Guice Injector
*
* @return Google Guice injector instance
*/
public static Injector getInjector() {
return injector;
}
/**
* @return True if the application started successfully, false otherwise
*/
public static boolean isStarted() {
return started;
}
/**
* @return The LocalDateTime of the application start
*/
public static LocalDateTime getStart() {
return start;
}
/**
* @return The duration of the application uptime
*/
public static Duration getUptime() {
Objects.requireNonNull(start, Required.START.toString());
return Duration.between(start, LocalDateTime.now());
}
/**
* Short form for getting an Goolge Guice injected class by
* calling getInstance(...)
*
* @param clazz The class to retrieve from the injector
* @param <T> JavaDoc requires this (just ignore it)
*
* @return An instance of the requested class
*/
public static <T> T getInstance(Class<T> clazz) {
Objects.requireNonNull(clazz, Required.CLASS.toString());
return injector.getInstance(clazz);
}
/**
* Stops the underlying undertow server
*/
public static void stopUndertow() {
undertow.stop();
}
/**
* Sets the mode the application is running in
*
* @param providedMode A given mode or null
*/
private static void prepareMode(Mode providedMode) {
final String applicationMode = System.getProperty(Key.APPLICATION_MODE.toString());
if (StringUtils.isNotBlank(applicationMode)) {
switch (applicationMode.toLowerCase(Locale.ENGLISH)) {
case "dev" : mode = Mode.DEV;
break;
case "test" : mode = Mode.TEST;
break;
default : mode = Mode.PROD;
break;
}
} else {
mode = providedMode;
}
}
/**
* Sets the injector wrapped through netflix Governator
*/
private static void prepareInjector() {
injector = Guice.createInjector(Stage.PRODUCTION, getModules());
}
/**
* Callback to MangooLifecycle applicationInitialized
*/
private static void applicationInitialized() {
getInstance(MangooBootstrap.class).applicationInitialized();
}
/**
* Checks for config failures that prevent the application from starting
*/
private static void prepareConfig() {
Config config = getInstance(Config.class);
int bitLength = getBitLength(config.getApplicationSecret());
if (bitLength < KEY_MIN_BIT_LENGTH) {
LOG.error("Application requires a 512 bit application secret. The current property for application.secret has currently only {} bit.", bitLength);
failsafe();
}
bitLength = getBitLength(config.getAuthenticationCookieEncryptionKey());
if (bitLength < KEY_MIN_BIT_LENGTH) {
LOG.error("Authentication cookie requires a 512 bit encryption key. The current property for authentication.cookie.encryptionkey has only {} bit.", bitLength);
failsafe();
}
bitLength = getBitLength(config.getAuthenticationCookieSignKey());
if (bitLength < KEY_MIN_BIT_LENGTH) {
LOG.error("Authentication cookie requires a 512 bit sign key. The current property for authentication.cookie.signkey has only {} bit.", bitLength);
failsafe();
}
bitLength = getBitLength(config.getSessionCookieEncryptionKey());
if (bitLength < KEY_MIN_BIT_LENGTH) {
LOG.error("Session cookie requires a 512 bit encryption key. The current property for session.cookie.encryptionkey has only {} bit.", bitLength);
failsafe();
}
bitLength = getBitLength(config.getSessionCookieSignKey());
if (bitLength < KEY_MIN_BIT_LENGTH) {
LOG.error("Session cookie requires a 512 bit sign key. The current property for session.cookie.signkey has only {} bit.", bitLength);
failsafe();
}
bitLength = getBitLength(config.getFlashCookieSignKey());
if (bitLength < KEY_MIN_BIT_LENGTH) {
LOG.error("Flash cookie requires a 512 bit sign key. The current property for flash.cookie.signkey has only {} bit.", bitLength);
failsafe();
}
bitLength = getBitLength(config.getFlashCookieEncryptionKey());
if (bitLength < KEY_MIN_BIT_LENGTH) {
LOG.error("Flash cookie requires a 512 bit encryption key. The current property for flash.cookie.encryptionkey has only {} bit.", bitLength);
failsafe();
}
if (!config.isDecrypted()) {
LOG.error("Found encrypted config values in config.props but decryption was not successful!");
failsafe();
}
}
/**
* Do sanity checks on the configuration an warn about it in the log
*/
private static void sanityChecks() {
Config config = getInstance(Config.class);
List<String> warnings = new ArrayList<>();
if (!config.isAuthenticationCookieSecure()) {
String warning = "Authentication cookie has secure flag set to false. It is highly recommended to set authentication.cookie.secure to true in an production environment.";
warnings.add(warning);
LOG.warn(warning);
}
if (config.getAuthenticationCookieName().equals(Default.AUTHENTICATION_COOKIE_NAME.toString())) {
String warning = "Authentication cookie name has default value. Consider changing authentication.cookie.name to an application specific value.";
warnings.add(warning);
LOG.warn(warning);
}
if (config.getAuthenticationCookieSignKey().equals(config.getApplicationSecret())) {
String warning = "Authentication cookie sign key is using application secret. It is highly recommended to set a dedicated value to authentication.cookie.signkey.";
warnings.add(warning);
LOG.warn(warning);
}
if (config.getAuthenticationCookieEncryptionKey().equals(config.getApplicationSecret())) {
String warning = "Authentication cookie encryption is using application secret. It is highly recommended to set a dedicated value to authentication.cookie.encryptionkey.";
warnings.add(warning);
LOG.warn(warning);
}
if (!config.isSessionCookieSecure()) {
String warning = "Session cookie has secure flag set to false. It is highly recommended to set session.cookie.secure to true in an production environment.";
warnings.add(warning);
LOG.warn(warning);
}
if (config.getSessionCookieName().equals(Default.SESSION_COOKIE_NAME.toString())) {
String warning = "Session cookie name has default value. Consider changing session.cookie.name to an application specific value.";
warnings.add(warning);
LOG.warn(warning);
}
if (config.getSessionCookieSignKey().equals(config.getApplicationSecret())) {
String warning = "Session cookie sign key is using application secret. It is highly recommended to set a dedicated value to session.cookie.signkey.";
warnings.add(warning);
LOG.warn(warning);
}
if (config.getSessionCookieEncryptionKey().equals(config.getApplicationSecret())) {
String warning = "Session cookie encryption is using application secret. It is highly recommended to set a dedicated value to session.cookie.encryptionkey.";
warnings.add(warning);
LOG.warn(warning);
}
if (config.getFlashCookieName().equals(Default.FLASH_COOKIE_NAME.toString())) {
String warning = "Flash cookie name has default value. Consider changing flash.cookie.name to an application specific value.";
warnings.add(warning);
LOG.warn(warning);
}
if (config.getFlashCookieSignKey().equals(config.getApplicationSecret())) {
String warning = "Flash cookie sign key is using application secret. It is highly recommended to set a dedicated value to flash.cookie.signkey.";
warnings.add(warning);
LOG.warn(warning);
}
if (config.getFlashCookieEncryptionKey().equals(config.getApplicationSecret())) {
String warning = "Flash cookie encryption key is using application secret. It is highly recommended to set a dedicated value to flash.cookie.encryptionkey.";
warnings.add(warning);
LOG.warn(warning);
}
getInstance(CacheProvider.class).getCache(CacheName.APPLICATION).put(Key.MANGOOIO_WARNINGS.toString(), warnings);
}
/**
* Validate if the routes that are defined in the router are valid
*/
private static void prepareRoutes() {
injector.getInstance(MangooBootstrap.class).initializeRoutes();
Router.getRequestRoutes().forEach((RequestRoute requestRoute) -> {
if (!methodExists(requestRoute.getControllerMethod(), requestRoute.getControllerClass())) {
LOG.error("Could not find controller method '{}' in controller class '{}'", requestRoute.getControllerMethod(), requestRoute.getControllerClass());
failsafe();
}
if (requestRoute.hasAuthorization() && (!MangooUtils.resourceExists(Default.MODEL_CONF.toString()) || !MangooUtils.resourceExists(Default.POLICY_CSV.toString()))) {
LOG.error("Route on method '{}' in controller class '{}' requires authorization, but either model.conf or policy.csv is missing", requestRoute.getControllerMethod(), requestRoute.getControllerClass());
failsafe();
}
});
}
/**
* Checks if a given method exists in a given class
* @param controllerMethod The method to check
* @param controllerClass The class to check
*
* @return True if the method exists, false otherwise
*/
private static boolean methodExists(String controllerMethod, Class<?> controllerClass) {
Objects.requireNonNull(controllerMethod, Required.CONTROLLER_METHOD.toString());
Objects.requireNonNull(controllerClass, Required.CONTROLLER_CLASS.toString());
return Arrays.stream(controllerClass.getMethods()).anyMatch(method -> method.getName().equals(controllerMethod));
}
/**
* Create routes for WebSockets ServerSentEvent and Resource files
*/
private static void createRoutes() {
pathHandler = new PathHandler(getRoutingHandler());
Router.getWebSocketRoutes().forEach((WebSocketRoute webSocketRoute) ->
pathHandler.addExactPath(webSocketRoute.getUrl(),
Handlers.websocket(getInstance(WebSocketHandler.class)
.withControllerClass(webSocketRoute.getControllerClass())
.withAuthentication(webSocketRoute.hasAuthentication())))
);
Router.getServerSentEventRoutes().forEach((ServerSentEventRoute serverSentEventRoute) ->
pathHandler.addExactPath(serverSentEventRoute.getUrl(),
Handlers.serverSentEvents(getInstance(ServerSentEventHandler.class)
.withAuthentication(serverSentEventRoute.hasAuthentication())))
);
Router.getPathRoutes().forEach((PathRoute pathRoute) ->
pathHandler.addPrefixPath(pathRoute.getUrl(),
new ResourceHandler(new ClassPathResourceManager(Thread.currentThread().getContextClassLoader(), Default.FILES_FOLDER.toString() + pathRoute.getUrl())))
);
Config config = getInstance(Config.class);
if (config.isApplicationAdminEnable()) {
pathHandler.addPrefixPath("/@admin/assets/", new ResourceHandler(new ClassPathResourceManager(Thread.currentThread().getContextClassLoader(), "templates/@admin/assets/")));
}
}
private static RoutingHandler getRoutingHandler() {
final RoutingHandler routingHandler = Handlers.routing();
routingHandler.setFallbackHandler(Application.getInstance(FallbackHandler.class));
Config config = getInstance(Config.class);
if (config.isApplicationAdminEnable()) {
Bind.controller(AdminController.class)
.withBasicAuthentication(config.getApplicationAdminUsername(), config.getApplicationAdminPassword(), config.getApplicationAdminSecret())
.withRoutes(
On.get().to("/@admin").respondeWith("index"),
On.get().to("/@admin/scheduler").respondeWith("scheduler"),
On.get().to("/@admin/logger").respondeWith("logger"),
On.post().to("/@admin/logger/ajax").respondeWith("loggerajax"),
On.get().to("/@admin/routes").respondeWith("routes"),
On.get().to("/@admin/metrics").respondeWith("metrics"),
On.get().to("/@admin/metrics/reset").respondeWith("resetMetrics"),
On.get().to("/@admin/tools").respondeWith("tools"),
On.post().to("/@admin/tools/ajax").respondeWith("toolsajax"),
On.get().to("/@admin/scheduler/execute/{name}").respondeWith("execute"),
On.get().to("/@admin/scheduler/state/{name}").respondeWith("state")
);
Bind.controller(AdminController.class)
.withBasicAuthentication(config.getApplicationAdminUsername(), config.getApplicationAdminPassword())
.withRoutes(
On.get().to("/@admin/health").respondeWith("health")
);
}
Router.getRequestRoutes().forEach((RequestRoute requestRoute) -> {
DispatcherHandler dispatcherHandler = Application.getInstance(DispatcherHandler.class)
.dispatch(requestRoute.getControllerClass(), requestRoute.getControllerMethod())
.isBlocking(requestRoute.isBlocking())
.withBasicAuthentication(requestRoute.getUsername(), requestRoute.getPassword(), requestRoute.getSecret())
.withAuthentication(requestRoute.hasAuthentication())
.withAuthorization(requestRoute.hasAuthorization())
.withLimit(requestRoute.getLimit());
routingHandler.add(requestRoute.getMethod().toString(), requestRoute.getUrl(), dispatcherHandler);
});
ResourceHandler resourceHandler = Handlers.resource(new ClassPathResourceManager(
Thread.currentThread().getContextClassLoader(),
Default.FILES_FOLDER.toString() + '/'));
Router.getFileRoutes().forEach((FileRoute fileRoute) -> routingHandler.add(Methods.GET, fileRoute.getUrl(), resourceHandler));
return routingHandler;
}
private static void prepareUndertow() {
Config config = getInstance(Config.class);
HttpHandler httpHandler;
if (config.isMetricsEnable()) {
httpHandler = MetricsHandler.HANDLER_WRAPPER.wrap(Handlers.exceptionHandler(pathHandler)
.addExceptionHandler(Throwable.class, Application.getInstance(ExceptionHandler.class)));
} else {
httpHandler = Handlers.exceptionHandler(pathHandler)
.addExceptionHandler(Throwable.class, Application.getInstance(ExceptionHandler.class));
}
Builder builder = Undertow.builder()
.setServerOption(UndertowOptions.MAX_ENTITY_SIZE, config.getUndertowMaxEntitySize())
.setHandler(httpHandler);
httpHost = config.getConnectorHttpHost();
httpPort = config.getConnectorHttpPort();
ajpHost = config.getConnectorAjpHost();
ajpPort = config.getConnectorAjpPort();
boolean hasConnector = false;
if (httpPort > 0 && StringUtils.isNotBlank(httpHost)) {
builder.addHttpListener(httpPort, httpHost);
hasConnector = true;
}
if (ajpPort > 0 && StringUtils.isNotBlank(ajpHost)) {
builder.addAjpListener(ajpPort, ajpHost);
hasConnector = true;
}
if (hasConnector) {
undertow = builder.build();
undertow.start();
} else {
LOG.error("No connector found! Please configure a HTTP and/or AJP connector in your config.props");
failsafe();
}
}
@SuppressFBWarnings(justification = "Buffer only used locally, without user input", value = "CRLF_INJECTION_LOGS")
private static void showLogo() {
final StringBuilder buffer = new StringBuilder(BUFFERSIZE);
buffer.append('\n')
.append(getLogo())
.append("\n\nhttps://github.com/svenkubiak/mangooio | @mangoo_io | ")
.append(MangooUtils.getVersion())
.append('\n');
String logo = buffer.toString();
LOG.info(logo);
if (httpPort > 0 && StringUtils.isNotBlank(httpHost)) {
LOG.info("HTTP connector listening @{}:{}", httpHost, httpPort);
}
if (ajpPort > 0 && StringUtils.isNotBlank(ajpHost)) {
LOG.info("AJP connector listening @{}:{}", ajpHost, ajpPort);
}
String startup = "mangoo I/O application started in " + ChronoUnit.MILLIS.between(start, LocalDateTime.now()) + " ms in " + mode.toString() + " mode. Enjoy.";
LOG.info(startup);
}
/**
* Retrieves the logo from the logo file and returns the string
*
* @return The mangoo I/O logo string
*/
@SuppressFBWarnings(justification = "Intenionally used to access the file system", value = "URLCONNECTION_SSRF_FD")
public static String getLogo() {
String logo = "";
try (InputStream inputStream = Resources.getResource(Default.LOGO_FILE.toString()).openStream()) {
logo = IOUtils.toString(inputStream, Default.ENCODING.toString());
} catch (final IOException e) {
LOG.error("Failed to get application logo", e);
}
return logo;
}
private static int getBitLength(String secret) {
Objects.requireNonNull(secret, Required.SECRET.toString());
return ByteUtils.bitLength(RegExUtils.replaceAll(secret, "[^\\x00-\\x7F]", ""));
}
private static List<Module> getModules() {
final List<Module> modules = new ArrayList<>();
try {
modules.add(new io.mangoo.core.Module());
modules.add((AbstractModule) Class.forName(Default.MODULE_CLASS.toString()).getConstructor().newInstance());
} catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
| NoSuchMethodException | SecurityException | ClassNotFoundException e) {
LOG.error("Failed to load modules. Check that app/Module.java exists in your application", e);
failsafe();
}
return modules;
}
private static void applicationStarted() {
getInstance(MangooBootstrap.class).applicationStarted();
}
private static void prepareScheduler() {
Config config = getInstance(Config.class);
if (config.isSchedulerEnabled()) {
List<Class<?>> jobs = new ArrayList<>();
try (ScanResult scanResult =
new ClassGraph()
.enableAnnotationInfo()
.enableClassInfo()
.whitelistPackages(config.getSchedulerPackage())
.scan()) {
scanResult.getClassesWithAnnotation(Default.SCHEDULER_ANNOTATION.toString()).forEach(c -> jobs.add(c.loadClass()));
}
if (!jobs.isEmpty() && config.isSchedulerAutostart()) {
final Scheduler mangooScheduler = getInstance(Scheduler.class);
mangooScheduler.initialize();
for (Class<?> clazz : jobs) {
final Schedule schedule = clazz.getDeclaredAnnotation(Schedule.class);
String scheduled = schedule.cron();
Trigger trigger = null;
final JobDetail jobDetail = SchedulerUtils.createJobDetail(clazz.getName(), Default.SCHEDULER_JOB_GROUP.toString(), clazz.asSubclass(Job.class));
if (scheduled != null) {
scheduled = scheduled.toLowerCase(Locale.ENGLISH).trim();
if (scheduled.contains("every")) {
scheduled = scheduled.replace("every", "").trim();
String timespan = scheduled.substring(0, scheduled.length() - 1);
String duration = scheduled.substring(scheduled.length() - 1);
String triggerName = clazz.getName() + "-trigger";
String description = schedule.description();
String triggerGroup = Default.SCHEDULER_TRIGGER_GROUP.toString();
int time = Integer.parseInt(timespan);
switch(duration) {
case "s":
trigger = SchedulerUtils.createTrigger(triggerName, triggerGroup, description, time, TimeUnit.SECONDS);
break;
case "m":
trigger = SchedulerUtils.createTrigger(triggerName, triggerGroup, description, time, TimeUnit.MINUTES);
break;
case "h":
trigger = SchedulerUtils.createTrigger(triggerName, triggerGroup, description, time, TimeUnit.HOURS);
break;
case "d":
trigger = SchedulerUtils.createTrigger(triggerName, triggerGroup, description, time, TimeUnit.DAYS);
break;
default:
break;
}
} else {
if (CronExpression.isValidExpression(schedule.cron())) {
trigger = SchedulerUtils.createTrigger(clazz.getName() + "-trigger", Default.SCHEDULER_TRIGGER_GROUP.toString(), schedule.description(), schedule.cron());
} else {
LOG.error("Invalid or missing cron expression for job: {}", clazz.getName());
failsafe();
}
}
try {
mangooScheduler.schedule(jobDetail, trigger);
LOG.info("Successfully scheduled job {} with cron {} ", clazz.getName(), schedule.cron());
} catch (MangooSchedulerException e) {
LOG.error("Failed to add a job to the scheduler", e);
}
}
}
try {
mangooScheduler.start();
} catch (MangooSchedulerException e) {
LOG.error("Failed to start the scheduler", e);
failsafe();
}
}
}
}
/**
* Failsafe exit of application startup
*/
private static void failsafe() {
System.out.print("Failed to start mangoo I/O application"); //NOSONAR Intentionally as we want to exit the application at this point
System.exit(1); //NOSONAR Intentionally as we want to exit the application at this point
}
}
|
package com.xruby.compiler.codegen;
import com.xruby.runtime.lang.*;
import com.xruby.runtime.value.ObjectFactory;
import com.xruby.runtime.value.RubyFixnum;
import com.xruby.runtime.value.RubyString;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.Label;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.commons.GeneratorAdapter;
import org.objectweb.asm.commons.Method;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.List;
class MethodGenerator extends GeneratorAdapter {
private SymbolTable symbol_table_;
private IntegerTable integer_table_ = new IntegerTable();
private ArrayList<Class> current_types_on_stack_ = new ArrayList<Class>();
private ArrayList<Integer> saved_vars_ = new ArrayList<Integer>();//may be have same length of current_types_on_stack_
private final boolean is_singleton_;
public MethodGenerator(final int arg0, final Method arg1, final ClassVisitor cv, RubyBinding binding, SymbolTable st, boolean is_singleton) {
super(arg0, arg1, null, null, cv);
if (null == st) {
symbol_table_ = new SymbolTable(null == binding ? null : binding.getVariableNames());
} else {
symbol_table_ = new SymbolTableForBlock(null == binding ? null : binding.getVariableNames(), st);
}
is_singleton_ = is_singleton;
visitCode();
}
public boolean isSingleton() {
return is_singleton_;
}
public void saveCurrentVariablesOnStack() {
Collections.reverse(current_types_on_stack_);
for (Class c : current_types_on_stack_) {
int v = newLocal(Type.getType(c));
saved_vars_.add(v);
storeLocal(v);
}
Collections.reverse(current_types_on_stack_);
}
public void restoreCurrentVariablesOnStack() {
if (saved_vars_.isEmpty()) {
return;
}
int i = newLocal(Type.getType(RubyValue.class));
storeLocal(i);
Collections.reverse(saved_vars_);
for (Integer v : saved_vars_) {
loadLocal(v);
}
saved_vars_.clear();
loadLocal(i);
}
//Use this method if you are going to stack depth > 1 and exception may throw in the middle
public void addCurrentVariablesOnStack(Class c) {
current_types_on_stack_.add(c);
}
public void removeCurrentVariablesOnStack() {
current_types_on_stack_.remove(current_types_on_stack_.size() - 1);
}
public SymbolTable getSymbolTable() {
return symbol_table_;
}
public void pushNull() {
visitInsn(Opcodes.ACONST_NULL);
}
public void loadRubyLocalVariable(String name) {
loadLocal(getSymbolTable().getLocalVariable(name));
}
public void storeRubyLocalVariable(String name) {
storeLocal(getSymbolTable().getLocalVariable(name));
}
public void storeNewLocalVariable(String name) {
int i = newLocal(Types.RUBY_VALUE_TYPE);
getSymbolTable().addLocalVariable(name, i);
storeLocal(i);
}
public void storeBlockForFutureRestoreAndCheckReturned() {
dup();
int i = symbol_table_.getInternalBlockVar();
if (i < 0) {
i = newLocal(Types.RUBY_BLOCK_TYPE);
symbol_table_.setInternalBlockVar(i);
}
storeLocal(i);
}
public void returnIfBlockReturned() {
dup();
invokeVirtual(Types.RUBY_VALUE_TYPE,
Method.getMethod("boolean returnedInBlock()"));
Label after_return = new Label();
ifZCmp(GeneratorAdapter.EQ, after_return);
returnValue();//TODO more error checking, may not in the method context
mark(after_return);
/*TODO if it is going to return any way, should not not check.
Right now the code may look like:
if(!rubyvalue5.returnedInBlock()) goto _L2; else goto _L1
_L1:
return;
_L2:
return;
*/
}
public void store_asterisk_parameter_(Class c) {
loadThis();
swap();
putField(Type.getType(c), "asterisk_parameter_", Types.RUBY_VALUE_TYPE);
}
public void store_block_parameter_(Class c) {
loadThis();
swap();
putField(Type.getType(c), "block_parameter_", Types.RUBY_VALUE_TYPE);
}
public void load_asterisk_parameter_(Class c) {
loadThis();
getField(Type.getType(c), "asterisk_parameter_", Types.RUBY_VALUE_TYPE);
}
public void load_block_parameter_(Class c) {
loadThis();
getField(Type.getType(c), "block_parameter_", Types.RUBY_VALUE_TYPE);
}
public void loadBlock(boolean is_in_block) {
if (is_in_block) {
RubyBlock_blockOfCurrentMethod_();
} else {
loadCurrentBlock();
}
}
public void loadMethodPrameterLength() {
//This is only called for methods with default args
loadArg(1);
invokeVirtual(Types.RUBY_ARRAY_TYPE,
Method.getMethod("int size()"));
}
public void loadCurrentScope(boolean is_in_class_builder, boolean is_in_singleton_method, boolean is_in_global_scope, boolean is_in_block) {
if (is_in_class_builder) {
loadCurrentClass();
} else if (is_in_global_scope) {
loadArg(3);
} else {
loadThis();
MethodBlockBase_getScope();
}
}
public void loadCurrentClass() {
loadArg(3);
}
public void loadMethodArg() {
loadArg(1);
}
public int saveRubyArrayAsLocalVariable() {
int var = newLocal(Types.RUBY_ARRAY_TYPE);
storeLocal(var);
return var;
}
public int saveRubyValueAsLocalVariable() {
int var = newLocal(Types.RUBY_VALUE_TYPE);
storeLocal(var);
return var;
}
public void catchRubyException(Label start, Label end) {
catchException(start,
end,
Type.getType(RubyException.class));
}
public void RubyBlock_argOfCurrentMethod_() {
loadThis();
getField(Types.RUBY_BLOCK_TYPE, "argOfCurrentMethod_", Types.RUBY_VALUE_TYPE);
}
public void RubyBlock_argsOfCurrentMethod_() {
loadThis();
getField(Types.RUBY_BLOCK_TYPE, "argsOfCurrentMethod_", Types.RUBY_ARRAY_TYPE);
}
private void RubyBlock_blockOfCurrentMethod_() {
loadThis();
getField(Types.RUBY_BLOCK_TYPE, "blockOfCurrentMethod_", Types.RUBY_BLOCK_TYPE);
}
private void RubyBlock_selfOfCurrentMethod_() {
loadThis();
getField(Types.RUBY_BLOCK_TYPE, "selfOfCurrentMethod_", Types.RUBY_VALUE_TYPE);
}
public void RubyBlock__break__() {
loadThis();
push(true);
putField(Types.RUBY_BLOCK_TYPE, "__break__", Type.getType(boolean.class));
returnValue();
}
public void RubyBlock__return__() {
loadThis();
push(true);
putField(Types.RUBY_BLOCK_TYPE, "__return__", Type.getType(boolean.class));
returnValue();
}
public void RubyBlock__redo__() {
loadThis();
push(true);
putField(Types.RUBY_BLOCK_TYPE, "__redo__", Type.getType(boolean.class));
returnValue();
}
public void loadSelf(boolean is_in_block) {
if (is_in_block) {
RubyBlock_selfOfCurrentMethod_();
} else {
loadArg(0);
}
}
public void new_MethodClass(String methodName) {
Type methodNameType = Type.getType("L" + methodName + ";");
newInstance(methodNameType);
dup();
invokeConstructor(methodNameType,
Method.getMethod("void <init> ()"));
}
void loadCurrentBlock() {
loadArg(2);
}
public void new_BlockClass(ClassGenerator cg, String methodName, String[] commons, boolean is_in_class_builder, boolean is_in_singleton_method, boolean is_in_global_scope, boolean is_in_block) {
Type methodNameType = Type.getType("L" + methodName + ";");
newInstance(methodNameType);
dup();
loadSelf(is_in_block);
cg.loadArgOfMethodForBlock();
if (is_in_global_scope) {
pushNull();
} else {
loadBlock(is_in_block);
}
loadCurrentScope(is_in_class_builder, is_in_singleton_method, is_in_global_scope, is_in_block);
if (is_in_block) {
push(true);
} else {
push(false);
}
for (String name : commons) {
cg.loadVariable(name);
}
invokeConstructor(methodNameType,
Method.getMethod(ClassGeneratorForRubyBlock.buildContructorSignature(commons.length)));
}
public void RubyArray_add(boolean is_method_call) {
if (is_method_call) {
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue expandArrayIfThereIsZeroOrOneValue(com.xruby.runtime.lang.RubyValue)"));
}
invokeVirtual(Types.RUBY_ARRAY_TYPE,
Method.getMethod("com.xruby.runtime.value.RubyArray add(com.xruby.runtime.lang.RubyValue)"));
}
public void RubyArray_expand(boolean is_method_call) {
if (is_method_call) {
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue expandArrayIfThereIsZeroOrOneValue(com.xruby.runtime.lang.RubyValue)"));
}
invokeVirtual(Types.RUBY_ARRAY_TYPE,
Method.getMethod("com.xruby.runtime.value.RubyArray expand(com.xruby.runtime.lang.RubyValue)"));
}
public void RubyArray_get(int index) {
push(index);
invokeVirtual(Types.RUBY_ARRAY_TYPE,
Method.getMethod("com.xruby.runtime.lang.RubyValue get(int)"));
}
public void RubyArray_collect(int index) {
push(index);
invokeVirtual(Types.RUBY_ARRAY_TYPE,
Method.getMethod("com.xruby.runtime.lang.RubyValue collect(int)"));
}
public void RubyString_append(String value) {
push(value);
invokeVirtual(Type.getType(RubyString.class),
Method.getMethod("com.xruby.runtime.value.RubyString appendString(String)"));
}
public void RubyString_append() {
invokeVirtual(Type.getType(RubyString.class),
Method.getMethod("com.xruby.runtime.value.RubyString appendString(com.xruby.runtime.lang.RubyValue)"));
}
public void RubyHash_addValue() {
invokeVirtual(Types.RUBY_HASH_TYPE,
Method.getMethod("com.xruby.runtime.value.RubyHash add(com.xruby.runtime.lang.RubyValue, com.xruby.runtime.lang.RubyValue)"));
}
public boolean RubyRuntime_getBuiltinClass(String className) {
if (Types.isBuiltinClass(className)) {
getStatic(Type.getType(RubyRuntime.class),
className + "Class",
Types.RUBY_CLASS_TYPE);
return true;
} else {
return false;
}
}
public boolean RubyRuntime_getBuiltinModule(String name) {
if (Types.isBuiltinModule(name)) {
getStatic(Type.getType(RubyRuntime.class),
name + "Module",
Types.RUBY_MODULE_TYPE);
return true;
} else {
return false;
}
}
public void createFrequentlyUsedInteger(int value) {
if (value >= 0 && value <= 10) {
return;
}
Integer i = integer_table_.getInteger(value);
if (null != i) {
return;
}
ObjectFactory_createFixnum(value);
int var = newLocal(Types.RUBY_VALUE_TYPE);
storeLocal(var);
integer_table_.addInteger(value, var);
}
public void ObjectFactory_createFixnum(int value) {
if (value >= 0 && value <= 10) {
getStatic(Type.getType(ObjectFactory.class),
"FIXNUM" + value,
Type.getType(RubyFixnum.class));
return;
}
Integer i = integer_table_.getInteger(value);
if (null != i) {
loadLocal(i);
return;
}
push(value);
invokeStatic(Type.getType(ObjectFactory.class),
Method.getMethod("com.xruby.runtime.value.RubyFixnum createFixnum(int)"));
}
public void ObjectFactory_createFloat(double value) {
push(value);
invokeStatic(Type.getType(ObjectFactory.class),
Method.getMethod("com.xruby.runtime.value.RubyFloat createFloat(double)"));
}
public void ObjectFactory_createBignum(BigInteger value) {
push(value.toString());
invokeStatic(Type.getType(ObjectFactory.class),
Method.getMethod("com.xruby.runtime.value.RubyBignum createBignum(String)"));
}
public void ObjectFactory_createString(String value) {
push(value);
invokeStatic(Type.getType(ObjectFactory.class),
Method.getMethod("com.xruby.runtime.value.RubyString createString(String)"));
}
public void ObjectFactory_createString() {
invokeStatic(Type.getType(ObjectFactory.class),
Method.getMethod("com.xruby.runtime.value.RubyString createString()"));
}
public void ObjectFactory_createRegexp(String value) {
push(value);
invokeStatic(Type.getType(ObjectFactory.class),
Method.getMethod("com.xruby.runtime.value.RubyRegexp createRegexp(String)"));
}
public void ObjectFactory_createRegexp() {
invokeVirtual(Type.getType(RubyString.class),
Method.getMethod("String toString()"));
invokeStatic(Type.getType(ObjectFactory.class),
Method.getMethod("com.xruby.runtime.value.RubyRegexp createRegexp(String)"));
}
public void ObjectFactory_createSymbol(String value) {
push(value);
invokeStatic(Type.getType(ObjectFactory.class),
Method.getMethod("com.xruby.runtime.lang.RubySymbol createSymbol(String)"));
}
public void ObjectFactory_nilValue() {
getStatic(Type.getType(ObjectFactory.class),
"NIL_VALUE",
Types.RUBY_VALUE_TYPE);
}
public void ObjectFactory_trueValue() {
getStatic(Type.getType(ObjectFactory.class),
"TRUE_VALUE",
Types.RUBY_VALUE_TYPE);
}
public void ObjectFactory_falseValue() {
getStatic(Type.getType(ObjectFactory.class),
"FALSE_VALUE",
Types.RUBY_VALUE_TYPE);
}
public void ObjectFactory_createArray(int size, int rhs_size, boolean has_single_asterisk) {
push(size);
push(rhs_size);
push(has_single_asterisk);
invokeStatic(Type.getType(ObjectFactory.class),
Method.getMethod("com.xruby.runtime.value.RubyArray createArray(int, int, boolean)"));
}
public void ObjectFactory_createHash() {
invokeStatic(Type.getType(ObjectFactory.class),
Method.getMethod("com.xruby.runtime.value.RubyHash createHash()"));
}
public void ObjectFactory_createRange() {
invokeStatic(Type.getType(ObjectFactory.class),
Method.getMethod("com.xruby.runtime.value.RubyRange createRange(com.xruby.runtime.lang.RubyValue, com.xruby.runtime.lang.RubyValue, boolean)"));
}
public void GlobalVatiables_set(String var) {
if (GlobalVariables.isReadOnly(var)) {
push(var);
invokeStatic(Type.getType(GlobalVariables.class),
Method.getMethod("void throwNameError(String)"));
return;
}
push(var);
invokeStatic(Type.getType(GlobalVariables.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue set(com.xruby.runtime.lang.RubyValue, String)"));
}
public void GlobalVatiables_get(String var) {
push(var);
invokeStatic(Type.getType(GlobalVariables.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue get(String)"));
}
public void GlobalVariables_alias(String newName, String oldName) {
push(newName);
push(oldName);
invokeStatic(Type.getType(GlobalVariables.class),
Method.getMethod("void alias(String, String)"));
}
public void RubyRuntime_GlobalScope() {
getStatic(Type.getType(RubyRuntime.class),
"ObjectClass",
Type.getType(RubyClass.class));
}
public void RubyAPI_testTrueFalse() {
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("boolean testTrueFalse(com.xruby.runtime.lang.RubyValue)"));
}
private void loadRubyID(String s) {
RubyIDClassGenerator.getField(this, s);
}
public void RubyAPI_callPublicMethod(String methodName) {
loadRubyID(methodName);
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue callPublicMethod(com.xruby.runtime.lang.RubyValue, com.xruby.runtime.value.RubyArray, com.xruby.runtime.lang.RubyBlock, com.xruby.runtime.lang.RubyID)"));
}
public void RubyAPI_callPublicNoArgMethod(String methodName) {
loadRubyID(methodName);
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue callPublicNoArgMethod(com.xruby.runtime.lang.RubyValue, com.xruby.runtime.lang.RubyBlock, com.xruby.runtime.lang.RubyID)"));
}
public void RubyAPI_callPublicOneArgMethod(String methodName) {
loadRubyID(methodName);
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue callPublicOneArgMethod(com.xruby.runtime.lang.RubyValue, com.xruby.runtime.lang.RubyValue, com.xruby.runtime.lang.RubyBlock, com.xruby.runtime.lang.RubyID)"));
}
public void RubyAPI_callMethod(String methodName) {
loadRubyID(methodName);
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue callMethod(com.xruby.runtime.lang.RubyValue, com.xruby.runtime.value.RubyArray, com.xruby.runtime.lang.RubyBlock, com.xruby.runtime.lang.RubyID)"));
}
public void RubyAPI_callNoArgMethod(String methodName) {
loadRubyID(methodName);
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue callNoArgMethod(com.xruby.runtime.lang.RubyValue, com.xruby.runtime.lang.RubyBlock, com.xruby.runtime.lang.RubyID)"));
}
public void RubyAPI_callOneArgMethod(String methodName) {
loadRubyID(methodName);
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue callOneArgMethod(com.xruby.runtime.lang.RubyValue, com.xruby.runtime.lang.RubyValue, com.xruby.runtime.lang.RubyBlock, com.xruby.runtime.lang.RubyID)"));
}
public void RubyAPI_callSuperMethod(String methodName) {
loadRubyID(methodName);
loadThis();
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue callSuperMethod(com.xruby.runtime.lang.RubyValue, com.xruby.runtime.value.RubyArray, com.xruby.runtime.lang.RubyBlock, com.xruby.runtime.lang.RubyID, com.xruby.runtime.lang.MethodBlockBase)"));
}
public void RubyAPI_callSuperNoArgMethod(String methodName) {
loadRubyID(methodName);
loadThis();
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue callSuperNoArgMethod(com.xruby.runtime.lang.RubyValue, com.xruby.runtime.lang.RubyBlock, com.xruby.runtime.lang.RubyID, com.xruby.runtime.lang.MethodBlockBase)"));
}
public void RubyAPI_callSuperOneArgMethod(String methodName) {
loadRubyID(methodName);
loadThis();
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue callSuperOneArgMethod(com.xruby.runtime.lang.RubyValue, com.xruby.runtime.lang.RubyValue, com.xruby.runtime.lang.RubyBlock, com.xruby.runtime.lang.RubyID, com.xruby.runtime.lang.MethodBlockBase)"));
}
public void RubyAPI_operatorNot() {
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue operatorNot(com.xruby.runtime.lang.RubyValue)"));
}
public void RubyAPI_runCommandAndCaptureOutput(String command) {
push(command);
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue runCommandAndCaptureOutput(String)"));
}
public void RubyAPI_runCommandAndCaptureOutput() {
invokeVirtual(Type.getType(RubyString.class),
Method.getMethod("String toString()"));
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue runCommandAndCaptureOutput(String)"));
}
public void RubyAPI_testCaseEqual() {
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("boolean testCaseEqual(com.xruby.runtime.lang.RubyValue, com.xruby.runtime.lang.RubyValue)"));
}
public void RubyAPI_testExceptionType() {
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("boolean testExceptionType(com.xruby.runtime.value.RubyArray, com.xruby.runtime.lang.RubyException)"));
}
public void RubyAPI_getSingleValue() {
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue getSingleValue(com.xruby.runtime.lang.RubyValue)"));
}
public void RubyAPI_expandArrayIfThereIsZeroOrOneValue() {
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue expandArrayIfThereIsZeroOrOneValue(com.xruby.runtime.lang.RubyValue)"));
}
public void RubyAPI_expandArrayIfThereIsZeroOrOneValue2() {
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue expandArrayIfThereIsZeroOrOneValue(com.xruby.runtime.value.RubyArray)"));
}
public void RubyAPI_expandArrayIfThereIsOnlyOneRubyArray() {
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.value.RubyArray expandArrayIfThereIsOnlyOneRubyArray(com.xruby.runtime.value.RubyArray)"));
}
public void RubyAPI_expandArrayIfThereIsOnlyOneRubyArray2() {
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue expandArrayIfThereIsOnlyOneRubyArray(com.xruby.runtime.lang.RubyValue)"));
}
public void RubyAPI_convertToArrayIfNotYet() {
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.value.RubyArray convertToArrayIfNotYet(com.xruby.runtime.lang.RubyValue)"));
}
public void RubyAPI_convertRubyValue2RubyBlock() {
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyBlock convertRubyValue2RubyBlock(com.xruby.runtime.lang.RubyValue)"));
}
public void RubyAPI_convertRubyException2RubyValue() {
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue convertRubyException2RubyValue(com.xruby.runtime.lang.RubyException)"));
}
public void RubyAPI_isDefinedPublicMethod(String name) {
push(name);
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue isDefinedPublicMethod(com.xruby.runtime.lang.RubyValue, com.xruby.runtime.lang.RubyModule, String)"));
}
public void RubyAPI_isDefinedMethod(String name) {
push(name);
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue isDefinedMethod(com.xruby.runtime.lang.RubyValue, String)"));
}
public void RubyAPI_isDefinedCurrentNamespaceConstant(String name) {
push(name);
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue isDefinedCurrentNamespaceConstant(com.xruby.runtime.lang.RubyValue, String)"));
}
public void RubyAPI_isDefinedSuperMethod(String name) {
push(name);
loadThis();
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue isDefinedSuperMethod(com.xruby.runtime.lang.RubyValue, String, com.xruby.runtime.lang.RubyMethod)"));
}
public void RubyAPI_isDefinedYield() {
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue isDefinedYield(com.xruby.runtime.lang.RubyBlock)"));
}
public void RubyAPI_setTopLevelConstant(String name) {
push(name);
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue setTopLevelConstant(com.xruby.runtime.lang.RubyValue, String)"));
}
public void RubyAPI_getCurrentNamespaceConstant(String name) {
push(name);
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue getCurrentNamespaceConstant(com.xruby.runtime.lang.RubyModule, String)"));
}
public void RubyAPI_getConstant(String name) {
push(name);
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue getConstant(com.xruby.runtime.lang.RubyValue, String)"));
}
public void RubyAPI_setConstant(String name) {
push(name);
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue setConstant(com.xruby.runtime.lang.RubyValue, com.xruby.runtime.lang.RubyValue, String)"));
}
public void RubyAPI_callArraySet() {
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("void callArraySet(com.xruby.runtime.lang.RubyValue, com.xruby.runtime.lang.RubyValue, com.xruby.runtime.lang.RubyValue)"));
}
public void RubyAPI_defineClass() {
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyClass defineClass(String, com.xruby.runtime.lang.RubyValue)"));
}
public void RubyModule_defineClass() {
invokeVirtual(Type.getType(RubyModule.class),
Method.getMethod("com.xruby.runtime.lang.RubyClass defineClass(String, com.xruby.runtime.lang.RubyValue)"));
}
public void RubyAPI_defineModule(String name) {
push(name);
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyModule defineModule(String)"));
}
public void RubyAPI_initializeAsteriskParameter(int argc) {
loadArg(1);
push(argc);
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue initializeAsteriskParameter(com.xruby.runtime.value.RubyArray, int)"));
}
public void RubyAPI_initializeBlockParameter() {
this.loadCurrentBlock();
invokeStatic(Type.getType(RubyAPI.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue initializeBlockParameter(com.xruby.runtime.lang.RubyBlock)"));
}
public void RubyModule_defineModule(String name) {
push(name);
invokeVirtual(Type.getType(RubyModule.class),
Method.getMethod("com.xruby.runtime.lang.RubyModule defineModule(String)"));
}
public void RubyModule_getClassVariable(String name) {
push(name);
invokeVirtual(Type.getType(RubyModule.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue getClassVariable(String)"));
}
public void RubyModule_setClassVariable(String name) {
push(name);
invokeVirtual(Type.getType(RubyModule.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue setClassVariable(com.xruby.runtime.lang.RubyValue, String)"));
}
public void RubyModule_aliasMethod(String newName, String oldName) {
loadCurrentClass();
push(newName);
push(oldName);
invokeVirtual(Type.getType(RubyModule.class),
Method.getMethod("void aliasMethod(String, String)"));
}
public void RubyModule_undefMethod(String name) {
loadCurrentClass();
push(name);
invokeVirtual(Type.getType(RubyModule.class),
Method.getMethod("void undefMethod(String)"));
}
public void RubyModule_defineMethod(String methodName, String uniqueMethodName) {
push(methodName);
new_MethodClass(uniqueMethodName);
invokeVirtual(Type.getType(RubyModule.class),
Method.getMethod("com.xruby.runtime.lang.RubyValue defineMethod(String, com.xruby.runtime.lang.RubyMethod)"));
}
public void RubyBlock_invokeNoArg(boolean is_in_block) {
invokeVirtual(Types.RUBY_BLOCK_TYPE,
Method.getMethod("com.xruby.runtime.lang.RubyValue invoke(com.xruby.runtime.lang.RubyValue)"));
}
public void RubyBlock_invokeOneArg(boolean is_in_block) {
invokeVirtual(Types.RUBY_BLOCK_TYPE,
Method.getMethod("com.xruby.runtime.lang.RubyValue invoke(com.xruby.runtime.lang.RubyValue, com.xruby.runtime.lang.RubyValue)"));
}
public void RubyBlock_invoke(boolean is_in_block) {
invokeVirtual(Types.RUBY_BLOCK_TYPE,
Method.getMethod("com.xruby.runtime.lang.RubyValue invoke(com.xruby.runtime.lang.RubyValue, com.xruby.runtime.value.RubyArray)"));
}
public void checkBreakedOrReturned(boolean is_in_block) {
int value = newLocal(Types.RUBY_VALUE_TYPE);
storeLocal(value);
invokeVirtual(Types.RUBY_BLOCK_TYPE,
Method.getMethod("boolean breakedOrReturned()"));
Label after_return = new Label();
ifZCmp(GeneratorAdapter.EQ, after_return);
if (is_in_block) {
loadThis();
push(true);
putField(Types.RUBY_BLOCK_TYPE, "__break__", Type.getType(boolean.class));
}
loadLocal(value);
returnValue();//TODO more error checking, may not in the method context
mark(after_return);
loadLocal(value);
}
public void RubyValue_getRubyClass() {
invokeVirtual(Types.RUBY_VALUE_TYPE,
Method.getMethod("com.xruby.runtime.lang.RubyClass getRubyClass()"));
}
public void RubyValue_getSingletonClass() {
invokeVirtual(Types.RUBY_VALUE_TYPE,
Method.getMethod("com.xruby.runtime.lang.RubyClass getSingletonClass()"));
}
public void RubyValue_getInstanceVariable(String name) {
//push(name);
RubyIDClassGenerator.getField(this, name);
invokeVirtual(Types.RUBY_VALUE_TYPE,
Method.getMethod("com.xruby.runtime.lang.RubyValue getInstanceVariable(com.xruby.runtime.lang.RubyID)"));
}
public void RubyValue_setInstanceVariable(String name) {
RubyIDClassGenerator.getField(this, name);
//push(name);
invokeVirtual(Types.RUBY_VALUE_TYPE,
Method.getMethod("com.xruby.runtime.lang.RubyValue setInstanceVariable(com.xruby.runtime.lang.RubyValue, com.xruby.runtime.lang.RubyID)"));
}
private void MethodBlockBase_getScope() {
invokeVirtual(Types.METHOD_BLOCK_BASE_TYPE,
Method.getMethod("com.xruby.runtime.lang.RubyModule getScope()"));
}
public void RubyProc_isDefinedInAnotherBlock() {
invokeVirtual(Types.RUBY_PROC_TYPE,
Method.getMethod("boolean isDefinedInAnotherBlock()"));
}
// For debug function
/**
* Write the local varirable info.
*
*/
public void writeLocalVariableInfo() {
Label endLabel = mark();
SymbolTable table = getSymbolTable();
Map<String,Label> varRanges = table.getLocalVariableRange();
List<String> sequence = table.getDeclarationSeq();
for(String var: sequence) {
Label startLabel = varRanges.get(var);
if(startLabel != null) {
int index = table.getLocalVariable(var);
this.visitLocalVariable(var, "Lcom/xruby/runtime/lang/RubyValue;", null, startLabel, endLabel, index);
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.