answer stringlengths 17 10.2M |
|---|
package me.coley.recaf.ui;
import com.github.javaparser.utils.StringEscapeUtils;
import me.coley.recaf.bytecode.*;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.*;
import static org.objectweb.asm.Opcodes.*;
import java.lang.annotation.Annotation;
import java.util.Collection;
import java.util.List;
import org.objectweb.asm.Handle;
import javafx.scene.Node;
import javafx.scene.control.Label;
import javafx.scene.layout.VBox;
import me.coley.recaf.Logging;
import me.coley.recaf.bytecode.insn.ParameterValInsnNode;
import me.coley.recaf.config.impl.ConfDisplay;
import me.coley.recaf.ui.component.InsnHBox;
import me.coley.recaf.ui.component.TextHBox;
import me.coley.recaf.ui.component.constructor.TypeAnnotationNodeConstructor.RefType;
/**
* Text formatting.
*
* @author Matt
*/
public class FormatFactory {
/**
* Max length of LDC string constant. Larger strings cut off and end
* replaced with "..."
*/
private static final int MAX_LDC_LENGTH = 100;
/**
* @param text
* Raw text.
* @return Text node of raw text.
*/
public static Node raw(String text) {
TextHBox t = new TextHBox();
addRaw(t, text);
return t;
}
/**
* @param name
* Name.
* @return Text node of name.
*/
public static TextHBox name(String name) {
TextHBox t = new TextHBox();
addName(t, name);
return t;
}
/**
* @param type
* ASM Type descriptor. Does not allow method types.
* @return Text node of type.
*/
public static TextHBox type(Type type) {
TextHBox t = new TextHBox();
addType(t, type);
return t;
}
/**
* @param type
* ASM Type descriptor. Only allows method types.
* @return Text node of type.
*/
public static TextHBox typeMethod(Type type) {
TextHBox t = new TextHBox();
addMethodType(t, type);
return t;
}
/**
* @param types
* Array of ASM Type descriptor.
* @return Text node of array.
*/
public static TextHBox typeArray(Type[] types) {
TextHBox t = new TextHBox();
addArray(t, types);
return t;
}
/**
* @param node
* Try-catch node.
* @param method
* Method containing try-catch.
* @return Text of try-catch block.
*/
public static TextHBox exception(TryCatchBlockNode node, MethodNode method) {
TextHBox t = new TextHBox();
String type = node.type;
if (type == null) {
addRaw(t, "*");
} else {
addType(t, Type.getObjectType(node.type));
}
addRaw(t, " - [");
add(t, insnNode(node.start, method));
addRaw(t, " - ");
add(t, insnNode(node.end, method));
addRaw(t, "
add(t, insnNode(node.handler, method));
addRaw(t, "]");
return t;
}
/**
* @param item
* Annotation.
* @return Text of annotation.
*/
public static TextHBox annotation(AnnotationNode item) {
TextHBox t = new TextHBox();
annotation(t, item);
return t;
}
private static void annotation(TextHBox t, AnnotationNode item) {
if (item.desc != null) {
addRaw(t, "@");
addType(t, Type.getType(item.desc));
}
if (item instanceof TypeAnnotationNode) {
TypeAnnotationNode itemType = (TypeAnnotationNode) item;
addRaw(t, " Path:");
addRaw(t, itemType.typePath.toString());
addRaw(t, " Ref:");
addRaw(t, RefType.fromSort(itemType.typeRef).name());
addRaw(t, " ");
}
int max = item.values == null ? 0 : item.values.size();
if (max > 0) {
addRaw(t, "(");
for (int i = 0; i < max; i += 2) {
String name = (String) item.values.get(i);
Object value = item.values.get(i + 1);
if (max > 2 || !"value".equals(name)) {
addName(t, name);
addRaw(t, "=");
}
if (value instanceof String) {
addString(t, "\"" + value.toString() + "\"");
} else if (value instanceof Type) {
Type type = (Type) value;
if (TypeUtil.isInternal(type)) {
addName(t, type.getInternalName());
} else if (TypeUtil.isStandard(type.toString())) {
addType(t, type);
} else {
Logging.warn("Unknown annotation type format in value: @" + (i + 1) + " type: " + value.toString());
addRaw(t, type.getDescriptor());
}
} else if (value instanceof Number) {
addValue(t, value.toString());
} else if (value instanceof List) {
List<?> l = (List<?>) value;
if (l.isEmpty()) {
addRaw(t, "[]");
} else {
addRaw(t, "[");
Object first = l.get(0);
Type type;
if (first instanceof String[]) {
type = Type.getType(Enum.class);
} else if (first instanceof Type) {
type = Type.getType(Class.class);
} else if (first instanceof AnnotationNode) {
type = Type.getType(Annotation.class);
} else {
type = Type.getType(first.getClass());
}
addType(t, type);
addRaw(t, "...]");
}
} else if (value instanceof String[]) { // enum
String[] str = (String[]) value;
Type enumType = Type.getType(str[0]);
addType(t, enumType);
addRaw(t, ".");
addName(t, str[1]);
} else if (value instanceof AnnotationNode) {
annotation(t, (AnnotationNode) value);
} else {
Logging.fine("Unknown annotation data-type: @" + i + " type: " + value.getClass());
}
if (i + 2 < max) {
addRaw(t, ", ");
}
}
addRaw(t, ")");
}
}
/**
* Text representation of a local variable.
*
* @param node
* Local variable.
* @param method
* Method containing the variable.
* @return
*/
public static TextHBox variable(LocalVariableNode node, MethodNode method) {
TextHBox t = new TextHBox();
addName(t, node.name);
addRaw(t, " - ");
addType(t, Type.getType(node.desc));
return t;
}
/**
* Text representation of an instruction.
*
* @param ain
* Instruction.
* @param method
* Method containing the instruction.
* @return Text representation of an instruction.
*/
public static InsnHBox insnNode(AbstractInsnNode ain, MethodNode method) {
if (ain == null)
throw new IllegalStateException("Attempted to display null instruction");
InsnHBox t = new InsnHBox(ain);
try {
style(t, "opcode-wrapper");
addInsn(t, ain, method);
} catch (Exception e) {
String type = ain.getClass().getSimpleName();
String meth = method == null ? "<ISOLATED>" : method.name + method.desc;
int index = InsnUtil.index(ain, method);
Logging.error("Invalid instruction: " + type + "@" + meth + "@" + index, true);
Logging.error(e, false);
}
return t;
}
/**
* VBox wrapper for multiple instructions populated via
* {@link #insnNode(AbstractInsnNode, MethodNode)}.
*
* @param insns
* Collection of instructions.
* @param method
* Method containing the instructions.
* @return Wrapper for the instructions.
*/
public static Node insnsNode(Collection<AbstractInsnNode> insns, MethodNode method) {
VBox box = new VBox();
for (AbstractInsnNode ain : insns) {
box.getChildren().add(insnNode(ain, method));
}
return box;
}
/**
* String representation for multiple instruction populated via
* {@link #insnNode(AbstractInsnNode, MethodNode)}.
*
* @param insns
* Collection of instructions.
* @param method
* Method containing the instructions.
* @return String of the instructions representation.
*/
public static String insnsString(Collection<AbstractInsnNode> insns, MethodNode method) {
StringBuilder sb = new StringBuilder();
for (AbstractInsnNode ain : insns) {
sb.append(insnNode(ain, method).getText() + "\n");
}
return sb.toString().trim();
}
private static void addName(TextHBox text, String name) {
text.append(name);
Node t = text(name);
style(t, "op-name");
add(text, t);
}
private static void addType(TextHBox text, Type type) {
String content = TypeUtil.filter(type);
text.append(content);
Node t = text(content);
style(t, "op-type");
add(text, t);
}
private static void addMethodType(TextHBox text, Type type) {
addRaw(text, "(");
int len = type.getArgumentTypes().length;
for (int i = 0; i < len; i++) {
Type param = type.getArgumentTypes()[i];
addType(text, param);
if (i != len - 1) {
addRaw(text, ", ");
}
}
addRaw(text, ")");
addType(text, type.getReturnType());
}
private static void addArray(TextHBox text, Type[] types) {
int len = types.length;
for (int i = 0; i < len; i++) {
addType(text, types[i]);
// Add separator between types
if (i != len - 1) {
addRaw(text, ", ");
}
}
}
private static void addInsn(InsnHBox text, AbstractInsnNode ain, MethodNode method) {
addInsn(text, ain, method, true);
}
private static void addInsn(InsnHBox text, AbstractInsnNode ain, MethodNode method, boolean includeIndex) {
if (includeIndex && !InsnUtil.isolated(ain)) {
// digit spaces
int spaces = String.valueOf(method == null ? InsnUtil.getSize(ain) : method.instructions.size()).length();
// index of instruction
String index = pad(String.valueOf(InsnUtil.index(ain, method)), spaces);
addRaw(text, index);
addRaw(text, ": ");
}
// add instruction name (opcode)
String opName = OpcodeUtil.opcodeToName(ain.getOpcode());
if (ain.getType() == AbstractInsnNode.LINE) {
// F_NEW is the opcode for LineInsn's, so make an exception here.
opName = "LINE";
} else if (ain.getType() == AbstractInsnNode.LABEL) {
opName = "LABEL";
}
text.append(opName);
Label op = text(opName);
style(op, "op-opcode");
add(text, op);
// add space for following content
if (ain.getType() != AbstractInsnNode.INSN) {
addRaw(text, " ");
}
// add instruction-type specific content. {} for scoped variable names.
switch (ain.getType()) {
case AbstractInsnNode.FIELD_INSN: {
FieldInsnNode fin = (FieldInsnNode) ain;
addType(text, Type.getObjectType(fin.owner));
addRaw(text, ".");
addName(text, fin.name);
addRaw(text, " ");
addType(text, Type.getType(fin.desc));
break;
}
case AbstractInsnNode.METHOD_INSN: {
MethodInsnNode min = (MethodInsnNode) ain;
addType(text, Type.getObjectType(min.owner));
addRaw(text, ".");
addName(text, min.name);
addMethodType(text, Type.getType(min.desc));
break;
}
case AbstractInsnNode.TYPE_INSN: {
TypeInsnNode tin = (TypeInsnNode) ain;
String desc = tin.desc;
addType(text, Type.getObjectType(desc));
if (ain.getOpcode() == Opcodes.ANEWARRAY) {
addRaw(text, "[]");
}
break;
}
case AbstractInsnNode.INT_INSN: {
IntInsnNode iin = (IntInsnNode) ain;
addValue(text, String.valueOf(iin.operand));
break;
}
case AbstractInsnNode.LDC_INSN: {
LdcInsnNode ldc = (LdcInsnNode) ain;
if (ldc.cst instanceof String) {
String value = StringEscapeUtils.escapeJava(String.valueOf(ldc.cst));
if (value.length() > MAX_LDC_LENGTH) {
value = value.substring(0, MAX_LDC_LENGTH) + "...";
}
addString(text, "\"" + value + "\"");
} else if (ldc.cst instanceof Type) {
addType(text, TypeUtil.parse(ldc.cst.toString()));
} else {
addValue(text, String.valueOf(ldc.cst));
}
break;
}
case AbstractInsnNode.LINE: {
LineNumberNode line = (LineNumberNode) ain;
addValue(text, String.valueOf(line.line));
if (line.start != null) {
addRaw(text, ":");
addInsn(text, line.start, method, false);
}
break;
}
case AbstractInsnNode.JUMP_INSN: {
JumpInsnNode jin = (JumpInsnNode) ain;
addInsn(text, jin.label, method, false);
if (ConfDisplay.instance().jumpHelp) {
//@formatter:off
String help = " ";
switch (ain.getOpcode()) {
case IFEQ : help += "[$0 == 0 -> offset]"; break;
case IFNE : help += "[$0 != 0 -> offset]"; break;
case IFLE : help += "[$0 <= 0 -> offset]"; break;
case IFLT : help += "[$0 < 0 -> offset]"; break;
case IFGE : help += "[$0 >= 0 -> offset]"; break;
case IFGT : help += "[$0 > 0 -> offset]"; break;
case IF_ACMPNE: help += "[$1 != $0 -> offset]"; break;
case IF_ACMPEQ: help += "[$1 == $0 -> offset]"; break;
case IF_ICMPEQ: help += "[$1 == $0 -> offset]"; break;
case IF_ICMPNE: help += "[$1 != $0 -> offset]"; break;
case IF_ICMPLE: help += "[$1 <= $0 -> offset]"; break;
case IF_ICMPLT: help += "[$0 < $0 -> offset]"; break;
case IF_ICMPGE: help += "[$0 >= $0 -> offset]"; break;
case IF_ICMPGT: help += "[$0 > $0 -> offset]"; break;
case GOTO : help += "[-> offset]"; break;
case JSR : help += "[-> offset, +address]"; break;
case IFNULL : help += "[$0 == null -> offset]";break;
case IFNONNULL: help += "[$0 != null -> offset]";break;
}
addNote(text, help);
//@formatter:on
}
break;
}
case AbstractInsnNode.IINC_INSN: {
IincInsnNode iinc = (IincInsnNode) ain;
LocalVariableNode lvn = InsnUtil.getLocal(method, iinc.var);
if (lvn != null) {
addValue(text, "$" + iinc.var);
addRaw(text, ":");
addName(text, lvn.name);
} else {
addValue(text, "$" + iinc.var);
}
if (iinc.incr > 0) {
addRaw(text, " + ");
} else {
addRaw(text, " - ");
}
addValue(text, String.valueOf(Math.abs(iinc.incr)));
break;
}
case AbstractInsnNode.VAR_INSN: {
VarInsnNode vin = (VarInsnNode) ain;
addValue(text, String.valueOf(vin.var));
LocalVariableNode lvn = InsnUtil.getLocal(method, vin.var);
if (lvn != null) {
String type = TypeUtil.filter(Type.getType(lvn.desc));
StringBuilder sb = new StringBuilder(" [");
sb.append(lvn.name);
sb.append(":");
sb.append(type);
sb.append("]");
addNote(text, sb.toString());
}
break;
}
case AbstractInsnNode.TABLESWITCH_INSN: {
TableSwitchInsnNode tsin = (TableSwitchInsnNode) ain;
StringBuilder lbls = new StringBuilder();
for (LabelNode label : tsin.labels) {
String offset = InsnUtil.labelName(label);
lbls.append(offset).append(", ");
}
if (lbls.toString().endsWith(", ")) {
lbls = new StringBuilder(lbls.substring(0, lbls.length() - 2));
}
String dfltOff = InsnUtil.labelName(tsin.dflt);
addNote(text, " range[" + tsin.min + "-" + tsin.max + "]");
addNote(text, " offsets[" + lbls + "]");
addNote(text, " default:" + dfltOff);
break;
}
case AbstractInsnNode.LOOKUPSWITCH_INSN: {
LookupSwitchInsnNode lsin = (LookupSwitchInsnNode) ain;
String lbls = "";
int cap = Math.min(lsin.keys.size(), lsin.labels.size());
for (int i = 0; i < cap; i++) {
String offset = InsnUtil.labelName(lsin.labels.get(i));
lbls += lsin.keys.get(i) + "=" + offset + ", ";
}
if (lbls.endsWith(", ")) {
lbls = lbls.substring(0, lbls.length() - 2);
}
addNote(text, " mapping[" + lbls + "]");
if (lsin.dflt != null) {
String offset = InsnUtil.labelName(lsin.dflt);
addNote(text, " default:" + offset);
}
break;
}
case AbstractInsnNode.MULTIANEWARRAY_INSN: {
MultiANewArrayInsnNode manain = (MultiANewArrayInsnNode) ain;
addType(text, Type.getType(manain.desc));
StringBuilder dims = new StringBuilder();
for (int i = 0; i < manain.dims; i++)
dims.append("[]");
addRaw(text, dims.toString());
break;
}
case AbstractInsnNode.INVOKE_DYNAMIC_INSN: {
InvokeDynamicInsnNode insnIndy = (InvokeDynamicInsnNode) ain;
if (insnIndy.bsmArgs.length >= 2 && insnIndy.bsmArgs[1] instanceof Handle) {
Handle handle = (Handle) insnIndy.bsmArgs[1];
Type typeIndyOwner = Type.getObjectType(handle.getOwner());
Type typeIndyDesc = Type.getMethodType(handle.getDesc());
addType(text, typeIndyDesc.getReturnType());
addRaw(text, " ");
addType(text, typeIndyOwner);
addRaw(text, ".");
addName(text, handle.getName());
addRaw(text, "(");
Type[] args = typeIndyDesc.getArgumentTypes();
for (int i = 0; i < args.length; i++) {
Type t = args[i];
addType(text, t);
if (i < args.length - 1) {
addRaw(text, ", ");
}
}
addRaw(text, ")");
} else {
addNote(text, " (unknown indy format)");
}
break;
}
case AbstractInsnNode.LABEL: {
addRaw(text, InsnUtil.labelName(ain));
break;
}
case AbstractInsnNode.FRAME: {
// FrameNode frame = (FrameNode) ain;
break;
}
case OpcodeUtil.CUSTOM: {
// custom opcodes
if (ain.getOpcode() == ParameterValInsnNode.PARAM_VAL) {
ParameterValInsnNode param = (ParameterValInsnNode) ain;
addValue(text, String.valueOf(param.getIndex()));
addRaw(text, " ");
// Attempt to get variable name
if (param.getParameter() != null) {
addRaw(text, "(");
addName(text, param.getParameter().name);
addRaw(text, ":");
addType(text, param.getValueType());
addRaw(text, ") ");
} else {
LocalVariableNode lvn = InsnUtil.getLocal(method, param.getIndex());
if (lvn != null) {
addRaw(text, "(");
addName(text, lvn.name);
addRaw(text, ":");
addType(text, param.getValueType());
addRaw(text, ") ");
} else {
addType(text, param.getValueType());
}
}
}
break;
}
}
}
private static Label addValue(TextHBox text, String content) {
text.append(content);
Label lbl = text(content);
style(lbl, "op-value");
add(text, lbl);
return lbl;
}
private static Label addString(TextHBox text, String content) {
text.append(content);
Label lbl = text(content);
style(lbl, "op-value-string");
add(text, lbl);
return lbl;
}
private static Label addRaw(TextHBox text, String content) {
text.append(content);
Label lbl = text(content);
style(lbl, "op-raw");
add(text, lbl);
return lbl;
}
private static Label addNote(TextHBox text, String content) {
text.append(content);
Label lbl = text(content);
style(lbl, "op-note");
add(text, lbl);
return lbl;
}
/**
* Add {@code Node} to {@code HTextBox}.
*
* @param text
* @param node
*/
private static void add(TextHBox text, Node node) {
text.getChildren().add(node);
}
/**
* Adds a css class to the given text.
*
* @param text
* @param clazz
*/
private static void style(Node text, String clazz) {
text.getStyleClass().add(clazz);
}
/**
* Create label from string.
*
* @param value
* String value.
* @return Label of string.
*/
private static Label text(String value) {
Label text = new Label(value);
text.getStyleClass().add("code-fmt");
return text;
}
/**
* Pad to the right.
*
* @param text
* @param padding
* @return
*/
private static String pad(String text, int padding) {
return String.format("%-" + padding + "s", text);
}
} |
package com.garlicg.sample.cutin;
import java.util.Timer;
import java.util.TimerTask;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.PorterDuff.Mode;
import android.graphics.Rect;
import android.view.LayoutInflater;
import android.view.SurfaceView;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import com.garlicg.cutinlib.CutinService;
import com.garlicg.sample.cutin.util.Logger;
public class GarlinParade extends CutinService {
private ParadeView mView;
@Override
protected View create() {
RelativeLayout layout = (RelativeLayout)LayoutInflater.from(this).inflate(R.layout.garlin_parade, null);
mView = new ParadeView(this);
@SuppressWarnings("deprecation")
RelativeLayout.LayoutParams p = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
layout.addView(mView, 0, p);
return layout;
}
@Override
protected void start() {
mView.setOnParadeEndListener(new OnAnimationEndListener() {
@Override
public void endAnimation() {
finishCutin();
}
});
mView.startParade();
}
@Override
protected void destroy() {
mView.onDestroy();
}
private interface OnAnimationEndListener{
void endAnimation();
}
private class ParadeView extends SurfaceView{
private class Garlin{
private Rect src;
private Rect dest;
public Garlin(){
}
}
private Bitmap mBitmap;
private Timer mTimer;
private OnAnimationEndListener mListener;
private long RATE = 1000/25;
private float mScreenWidth;
private float mScreenDx;
private float mFinishDx;
private float mScreenHeight;
private int mGarlinWidth;
private int mGarlinRectX;
private int mGarlinRectY;
private Garlin[][] mGarlins;
private static final int MAX_TATE = 5;
private static final int MAX_YOKO = 15;
public ParadeView(Context context) {
super(context);
Logger.v("PradaView");
mTimer = new Timer(true);
getHolder().setFormat(PixelFormat.TRANSPARENT);
mBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.garlin);
}
@Override
protected void onLayout(boolean changed, int left, int top, int right,
int bottom) {
super.onLayout(changed, left, top, right, bottom);
Logger.v("onLayout");
mScreenWidth = right -left;
mScreenHeight = bottom - top;
mGarlinWidth = (int)(mScreenHeight / MAX_TATE);
mGarlinRectX = mGarlinWidth/2;
mGarlinRectY = mGarlinWidth;
}
private void onDestroy(){
mTimer.purge();
mBitmap.recycle();
}
protected void draw() {
if(!mBitmap.isRecycled()){
Canvas canvas = getHolder().lockCanvas();
if(canvas != null){
try {
canvas.translate(mScreenDx, 0);
canvas.drawColor(Color.TRANSPARENT, Mode.CLEAR);
int size1 = mGarlins.length;
for(int i = 0 ; i < size1 ; i++){
int size2 = mGarlins[i].length;
for(int s = 0 ; s < size2 ; s++){
Garlin garin = mGarlins[i][s];
canvas.save();
canvas.rotate((float)(Math.random()*20)-10 , garin.dest.left,garin.dest.top);
canvas.drawBitmap(mBitmap, garin.src, garin.dest, null);
canvas.restore();
}
}
} catch (RuntimeException e) {
Logger.e("GarlinParado" ,e.toString());
}
finally{
getHolder().unlockCanvasAndPost(canvas);
}
}
}
}
private void startParade(){
Logger.v("startParade");
mGarlins = new Garlin[MAX_TATE][MAX_YOKO];
for(int i = 0 ; i < MAX_TATE ; i++){
for(int s = 0 ; s< MAX_YOKO ; s++){
Garlin garlin = new Garlin();
garlin.src = new Rect(0, 0, mBitmap.getWidth(), mBitmap.getHeight());
garlin.dest = new Rect(
mGarlinRectX*s,
mGarlinRectY*i,
mGarlinRectX*s+(int)(mGarlinWidth*1.5),
mGarlinRectY*i+(int)(mGarlinWidth*1.5));
mGarlins[i][s] = garlin;
}
}
mScreenDx = -(mScreenWidth + (mGarlinRectX * MAX_YOKO));
mFinishDx = mScreenWidth + (mGarlinRectX * (MAX_YOKO-1)*2/3);
final int xdiff = dpToPx(getResources(), 30);
// invalidater
mTimer.schedule(new TimerTask() {
@Override
public void run() {
if(mScreenDx > mFinishDx){
mTimer.cancel();
mListener.endAnimation();
}
else{
draw();
}
mScreenDx += xdiff;
}
}, 0,RATE);
}
private void setOnParadeEndListener(OnAnimationEndListener listener){
mListener = listener;
}
private int dpToPx(Resources res , int dp){
return (int)(res.getDisplayMetrics().density * dp + 0.5f);
}
}
} |
package me.nallar.modpatcher;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import me.nallar.javapatcher.patcher.Patcher;
import net.minecraft.launchwrapper.LaunchClassLoader;
import net.minecraftforge.fml.relauncher.ReflectionHelper;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.io.*;
import java.lang.reflect.*;
import java.net.*;
import java.nio.file.FileSystem;
import java.nio.file.*;
import java.util.*;
import java.util.concurrent.*;
/**
* ModPatcher API
*
* This class is the public facing API of ModPatcher
*
* It automatically downloads ModPatcher if the file is missing from the libs folder, or a coremod depends on
* a newer version of modpatcher than the installed version
*
* This behaviour can be disabled by creating the file "libs/modpatcher/NEVER_UPDATE.txt"
*/
public class ModPatcher {
private static final int API_VERSION = 1;
private static final Logger log = LogManager.getLogger("ModPatcher");
private static final String mcVersion = "@MC_VERSION@";
private static final Path neverUpdatePath = realPath("mods/ModPatcher_NEVER_UPDATE.txt");
private static final Path modPatcherPath = realPath("mods/ModPatcher.jlib");
private static final Future<Boolean> defaultUpdateRequired = CompletableFuture.completedFuture(!Files.exists(modPatcherPath));
private static final String DOWNLOAD_URL_PROPERTY = "modpatcher.downloadUrl";
private static final String REQUIRED_VERSION_PROPERTY = "modpatcher.requiredVersion";
private static final String RELEASE_PROPERTY = "modpatcher.release";
private static final String VERSION_URL_PROPERTY = "modpatcher.versionUrl";
private static final String NEVER_UPDATE_PROPERTY = "modpatcher.neverUpdate";
private static final String DEFAULT_RELEASE = "stable";
private static final String MODPATCHER_PACKAGE = "me.nallar.modpatcher";
private static String modPatcherRelease;
private static Future<Boolean> updateRequired = defaultUpdateRequired;
private static Version requiredVersion;
private static Version lastVersion;
private static boolean checked = false;
static {
requireVersionInternal(null, null);
}
/**
* Gets the name of the setup class to use in your IFMLLoadingPlugin
*
* @return Name of the ModPatcher setup class
*/
public static String getSetupClass() {
return "me.nallar.modpatcher.ModPatcherSetup";
}
/**
* Requests the given ModPatcher version
*
* @param versionString Minimum version of ModPatcher required. Special value "latest" always uses latest version
*/
public static void requireVersion(String versionString) {
requireVersion(versionString, null);
}
/**
* Requests the given ModPatcher version
*
* @param versionString Minimum version of ModPatcher required. Special value "latest" always uses latest version
* @param release Release stream to use. null by default
*/
public static void requireVersion(String versionString, String release) {
requireVersionInternal(versionString, release);
}
/**
* Load JavaPatcher patches
*
* @param inputStream stream to load patches from
*/
public static void loadPatches(InputStream inputStream) {
getPatcher().loadPatches(inputStream);
}
/**
* Load JavaPatcher patches
*
* @param patches String to load patches from
*/
public static void loadPatches(String patches) {
getPatcher().loadPatches(patches);
}
/**
* Gets the JavaPatcher Patcher instance
*
* @return the Patcher
* @deprecated Use specific methods such as loadPatches(InputStream)
*/
@Deprecated
public static Patcher getPatcher() {
checkClassLoading();
return ModPatcherTransformer.getPatcher();
}
/**
* Loads mixins from the given package.
* The package must have a package-info.java with @Mixin annotation
*
* @param mixinPackage Package to load mixins from
*/
public static void loadMixins(String mixinPackage) {
checkClassLoading();
ModPatcherTransformer.getMixinApplicator().addSource(mixinPackage);
}
/**
* Loads all mixins from the given path, regardless of package
*
* @param path Path to load mixins from
*/
public static void loadMixins(Path path) {
checkClassLoading();
ModPatcherTransformer.getMixinApplicator().addSource(path);
}
/**
* Loads all mixins from the given path, if they match the given package
*
* @param path Path to load mixins from
*/
public static void loadMixins(Path path, String packageName) {
checkClassLoading();
ModPatcherTransformer.getMixinApplicator().addSource(path, packageName);
}
/**
* Gets the default patches directory. Any patches in this directory are loaded by ModPatcher on startup.
*
* @return default patches directory
*/
public static String getDefaultPatchesDirectory() {
checkClassLoading();
return ModPatcherTransformer.getDefaultPatchesDirectory();
}
static void initialiseClassLoader(LaunchClassLoader classLoader) {
checkClassLoading();
ModPatcherTransformer.initialiseClassLoader(classLoader);
}
private static Path realPath(String s) {
Path absolute = Paths.get(s).toAbsolutePath();
try {
return absolute.toRealPath();
} catch (IOException e) {
return absolute;
}
}
private static void requireVersionInternal(String versionString, String release) {
if (updateRequired == null)
throw new Error("Modpatcher has already been loaded, it is too late to call getSetupClass");
versionString = System.getProperty(REQUIRED_VERSION_PROPERTY, versionString);
release = System.getProperty(RELEASE_PROPERTY, release);
if (release != null && versionString == null)
throw new IllegalArgumentException("versionString must be non-null if release is non-null");
boolean startCheck = false;
if (release != null) {
if (modPatcherRelease == null) {
modPatcherRelease = release;
startCheck = true;
} else {
log.warn("Conflicting ModPatcher release requests. Set to " + modPatcherRelease + ", requested: " + release);
}
}
if (versionString != null) {
Version requested = Version.of(versionString);
if (requested.compareTo(requiredVersion) > 0) {
requiredVersion = requested;
startCheck = true;
}
}
if (startCheck)
startVersionCheck();
}
private static void loadModPatcher() {
download();
updateRequired = null;
addToCurrentClassLoader();
checkClassLoading(false);
}
private static String getModPatcherRelease() {
return mcVersion + '-' + (modPatcherRelease == null ? DEFAULT_RELEASE : modPatcherRelease);
}
@SuppressWarnings("unchecked")
private static void addToCurrentClassLoader() {
ClassLoader cl = ModPatcher.class.getClassLoader();
try {
final URL url = modPatcherPath.toUri().toURL();
log.trace("Adding " + url + " to classloader");
if (cl instanceof LaunchClassLoader) {
LaunchClassLoader lcl = (LaunchClassLoader) cl;
lcl.addTransformerExclusion(MODPATCHER_PACKAGE);
lcl.addURL(url);
Set<String> invalidClasses = ReflectionHelper.<Set<String>, LaunchClassLoader>getPrivateValue(LaunchClassLoader.class, lcl, "invalidClasses");
Set<String> negativeResources = ReflectionHelper.<Set<String>, LaunchClassLoader>getPrivateValue(LaunchClassLoader.class, lcl, "negativeResourceCache");
invalidClasses.removeIf(ModPatcher::removeModPatcherEntries);
negativeResources.removeIf(ModPatcher::removeModPatcherEntries);
log.trace("Loaded class: " + Class.forName(MODPATCHER_PACKAGE + ".ModPatcherLoadHook"));
} else {
Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
method.setAccessible(true);
method.invoke(cl, url);
}
} catch (Exception e) {
throw new Error(e);
}
}
private static boolean removeModPatcherEntries(String entry) {
return entry.replace('/', '.').startsWith(MODPATCHER_PACKAGE);
}
static boolean neverUpdate() {
return "true".equals(System.getProperty(NEVER_UPDATE_PROPERTY)) || Files.exists(neverUpdatePath);
}
private static boolean isDownloadNeeded() {
if (neverUpdate())
return false;
try {
return updateRequired.get();
} catch (InterruptedException | ExecutionException e) {
log.warn("Failed to check if updates are required", e);
}
return false;
}
private static void download() {
if (!isDownloadNeeded())
return;
try (InputStream in = new URL(System.getProperty(DOWNLOAD_URL_PROPERTY, "https://modpatcher.nallar.me/" + getModPatcherRelease() + "/ModPatcher-lib.jar")).openConnection().getInputStream()) {
Files.deleteIfExists(modPatcherPath);
Files.createDirectories(modPatcherPath.getParent());
Files.copy(in, modPatcherPath);
} catch (IOException e) {
log.error("Failed to download ModPatcher", e);
}
}
private static void checkClassLoading() {
checkClassLoading(true);
}
private static void checkClassLoading(boolean load) {
if (checked)
return;
try {
Class.forName(MODPATCHER_PACKAGE + ".ModPatcherLoadHook");
ModPatcherLoadHook.loadHook(requiredVersion, getModPatcherRelease(), API_VERSION);
checked = true;
} catch (ClassNotFoundException | NoClassDefFoundError e) {
if (!load)
throw new Error(e);
loadModPatcher();
}
}
private static void startVersionCheck() {
if (neverUpdate() || requiredVersion == null)
return;
updateRequired.cancel(true);
try {
if (!updateRequired.isDone() || updateRequired.isCancelled() || !updateRequired.get()) {
FutureTask<Boolean> task;
updateRequired = task = new FutureTask<>(() -> {
Version current;
try {
current = getLastVersion();
} catch (Exception e) {
current = Version.NONE;
log.warn("Failed to determine current ModPatcher version, assuming it is outdated", e);
}
if (requiredVersion.newerThan(current)) {
try {
Version online = new Version(Resources.toString(new URL(System.getProperty(VERSION_URL_PROPERTY, "https://modpatcher.nallar.me/" + getModPatcherRelease() + "/version.txt")), Charsets.UTF_8).trim());
return online.compareTo(current) > 0;
} catch (InterruptedIOException ignored) {
} catch (Throwable t) {
log.warn("Failed to check for update", t);
}
}
return false;
});
task.run();
}
} catch (InterruptedException | ExecutionException e) {
log.warn("Interrupted when checking done/not cancelled future", e);
}
}
static Version getLastVersion() {
if (lastVersion != null)
return lastVersion;
if (!Files.exists(modPatcherPath))
return Version.NONE;
try (FileSystem fs = FileSystems.newFileSystem(modPatcherPath, null)) {
return lastVersion = new Version(Files.readAllLines(fs.getPath("modpatcher.version"), Charsets.UTF_8).get(0));
} catch (IOException e) {
throw new IOError(e);
}
}
static class Version implements Comparable<Version> {
public static final Version LATEST = new Version(String.valueOf(Integer.MAX_VALUE));
public static final Version NONE = new Version("0");
private String version;
private Version(String version) {
if (version == null)
throw new IllegalArgumentException("Version can not be null");
version = version.trim();
if (!version.matches("[0-9]+(\\.[0-9]+)*"))
throw new IllegalArgumentException("Invalid version format. Should consist entirely of digits and dots. Got '" + version + "'");
this.version = version;
}
static Version of(String s) {
if (s.equalsIgnoreCase("latest")) {
return LATEST;
}
return new Version(s);
}
public final String get() {
return this.version;
}
@Override
public int compareTo(Version that) {
if (that == null)
return 1;
if (this == that || version.equals(that.version))
return 0;
String[] thisParts = this.get().split("\\.");
String[] thatParts = that.get().split("\\.");
int length = Math.max(thisParts.length, thatParts.length);
for (int i = 0; i < length; i++) {
int thisPart = i < thisParts.length ?
Integer.parseInt(thisParts[i]) : 0;
int thatPart = i < thatParts.length ?
Integer.parseInt(thatParts[i]) : 0;
if (thisPart < thatPart)
return -1;
if (thisPart > thatPart)
return 1;
}
return 0;
}
@Override
public String toString() {
return version;
}
@Override
public int hashCode() {
return version.hashCode();
}
@Override
public boolean equals(Object that) {
return this == that || that != null && this.getClass() == that.getClass() && this.compareTo((Version) that) == 0;
}
public boolean newerThan(Version other) {
return compareTo(other) > 0;
}
}
} |
package com.growthbeat.analytics;
import java.util.UUID;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {
private SharedPreferences sharedPreferences = null;
private static final String applicationId = "OyVa3zboPjHVjsDC";
private static final String credentialId = "3EKydeJ0imxJ5WqS22FJfdVamFLgu7XA";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GrowthAnalytics.getInstance().initialize(getApplicationContext(), applicationId, credentialId);
sharedPreferences = getSharedPreferences("GrowthAnalyticsSample", Context.MODE_PRIVATE);
findViewById(R.id.tag).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String product = "item";
GrowthAnalytics.getInstance().tag(String.format("Tag:%s:Custom:Click", applicationId), product);
GrowthAnalytics.getInstance().purchase(100, "item", product);
}
});
}
@Override
public void onStart() {
super.onStart();
GrowthAnalytics.getInstance().open();
GrowthAnalytics.getInstance().setBasicTags();
String userId = sharedPreferences.getString("userId", UUID.randomUUID().toString());
sharedPreferences.edit().putString("userId", userId).commit();
GrowthAnalytics.getInstance().setUserId(userId);
GrowthAnalytics.getInstance().setAdvertisingId();
GrowthAnalytics.getInstance().setRandom();
}
@Override
public void onStop() {
super.onStop();
GrowthAnalytics.getInstance().close();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
} |
package moba.server.datatypes.base;
import java.io.IOException;
import moba.server.json.JSONException;
import moba.server.json.JSONToStringI;
public class Time implements JSONToStringI {
protected int time;
public Time() {
}
public Time(int time)
throws IllegalArgumentException {
setTime(time);
}
public Time(int hour, int minute)
throws IllegalArgumentException {
if(hour < 0 || hour > 24 || minute < 0 || minute > 59) {
throw new IllegalArgumentException();
}
time = hour * 60 * 60;
time += minute * 60;
}
public Time(String time)
throws IllegalArgumentException {
setTime(time);
}
public final void setTime(int time)
throws IllegalArgumentException {
if(time < 0 || time > ((60 * 60 * 24) - 1)) {
throw new IllegalArgumentException();
}
this.time = time;
}
public final void setTime(String time)
throws IllegalArgumentException {
String[] tokens = time.split(":");
this.time = Integer.parseInt(tokens[0]) * 60 * 60;
this.time += Integer.parseInt(tokens[1]) * 60;
}
public final boolean appendTime(int time)
throws IllegalArgumentException {
if(time < 1) {
throw new IllegalArgumentException("invalid time diff given");
}
this.time = (this.time + time) % (60 * 60 * 24);
if(this.time < time) {
return true;
}
return false;
}
public int getTime() {
return time;
}
public boolean isFullHour() {
long f = time / 60;
return (f % 60 == 0);
}
@Override
public String toString() {
long t = time / 60;
long m = t % 60;
t /= 60;
long h = t % 24;
StringBuilder sb = new StringBuilder();
if(h < 10) {
sb.append("0");
}
sb.append(h);
sb.append(":");
if(m < 10) {
sb.append("0");
}
sb.append(m);
return sb.toString();
}
@Override
public String toJsonString(boolean formated, int indent)
throws JSONException, IOException {
StringBuilder b = new StringBuilder();
b.append('"');
b.append(toString());
b.append('"');
return b.toString();
}
} |
package io.branch.indexing;
import android.app.Activity;
import android.content.Context;
import android.os.Parcel;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import io.branch.referral.Branch;
import io.branch.referral.BranchError;
import io.branch.referral.BranchShortLinkBuilder;
import io.branch.referral.Defines;
import io.branch.referral.util.LinkProperties;
import io.branch.referral.util.ShareSheetStyle;
/**
* <p>Class represents a single piece of content within your app, as well as any associated metadata.
* It provides convenient methods for sharing, deep linking, and tracking how often that content is viewed. This information is then used to provide you with powerful content analytics
* and deep linking.
* </p>
*/
public class BranchUniversalObject implements Parcelable {
/* Canonical identifier for the content referred. Normally the canonical path for your content in the app or web */
private String canonicalIdentifier_;
/* Title for the content referred by BranchUniversalObject */
private String title_;
/* Description for the content referred */
private String description_;
/* An image url associated with the content referred */
private String imageUrl_;
/* Meta data provided for the content. This meta data is used as the link parameters for links created from this object */
private final HashMap<String, String> metadata_;
/* Mime type for the content referred */
private String type_;
/* Content index mode */
private CONTENT_INDEX_MODE indexMode_;
/* Any keyword associated with the content. Used for indexing */
private final ArrayList<String> keywords_;
/* Expiry date for the content and any associated links. Represented as epoch milli second */
private long expirationInMilliSec_;
/**
* Defines the Content indexing modes
* PUBLIC | PRIVATE
*/
public enum CONTENT_INDEX_MODE {
PUBLIC, /* Referred contents are publically indexable */
// PUBLIC_IN_APP, /* Referred contents are publically available to the any app user */
PRIVATE/* Referred contents are not publically indexable */
}
/**
* <p>
* Create a BranchUniversalObject with the given content.
* </p>
*/
public BranchUniversalObject() {
metadata_ = new HashMap<>();
keywords_ = new ArrayList<>();
canonicalIdentifier_ = "";
title_ = "";
description_ = "";
type_ = "";
indexMode_ = CONTENT_INDEX_MODE.PUBLIC; // Default content indexing mode is public
expirationInMilliSec_ = 0L;
}
/**
* <p>
* Set the canonical identifier for this BranchUniversalObject. Canonical identifier is normally the canonical path for your content in the application or web
* </p>
*
* @param canonicalIdentifier A {@link String} with value for the canonical identifier
* @return This instance to allow for chaining of calls to set methods
*/
public BranchUniversalObject setCanonicalIdentifier(@NonNull String canonicalIdentifier) {
this.canonicalIdentifier_ = canonicalIdentifier;
return this;
}
/**
* <p>
* Set a title for the content referred by this object
* </p>
*
* @param title A {@link String} with value of for the content title
* @return This instance to allow for chaining of calls to set methods
*/
public BranchUniversalObject setTitle(@NonNull String title) {
this.title_ = title;
return this;
}
/**
* <p/>
* Set description for the content for the content referred by this object
* <p/>
*
* @param description A {@link String} with value for the description of the content referred by this object
* @return This instance to allow for chaining of calls to set methods
*/
public BranchUniversalObject setContentDescription(String description) {
this.description_ = description;
return this;
}
/**
* <p/>
* Set the url to any image associated with this content.
* <p/>
*
* @param imageUrl A {@link String} specifying a url to an image associated with content referred by this object
* @return This instance to allow for chaining of calls to set methods
*/
public BranchUniversalObject setContentImageUrl(@NonNull String imageUrl) {
this.imageUrl_ = imageUrl;
return this;
}
/**
* <p>
* Adds the the given set of key value pairs to the metadata associated with this content. These key values are passed to another user on deep linking.
* </p>
*
* @param metadata A {@link HashMap} with {@link String} key value pairs
* @return This instance to allow for chaining of calls to set methods
*/
@SuppressWarnings("unused")
public BranchUniversalObject addContentMetadata(HashMap<String, String> metadata) {
this.metadata_.putAll(metadata);
return this;
}
/**
* <p>
* Adds the the given set of key value pair to the metadata associated with this content. These key value is passed to another user on deep linking.
* </p>
*
* @param key A {@link String} value for metadata key
* @param value A {@link String} value for metadata value
* @return This instance to allow for chaining of calls to set methods
*/
public BranchUniversalObject addContentMetadata(String key, String value) {
this.metadata_.put(key, value);
return this;
}
/**
* <p>
* Sets the content type for this Object
* </p>
*
* @param type {@link String} with value for the mime type of the content referred
* @return This instance to allow for chaining of calls to set methods
*/
public BranchUniversalObject setContentType(String type) {
this.type_ = type;
return this;
}
/**
* <p>
* Set the indexing mode for the content referred in this object
* </p>
*
* @param indexMode {@link BranchUniversalObject.CONTENT_INDEX_MODE} value for the content referred
* @return This instance to allow for chaining of calls to set methods
*/
public BranchUniversalObject setContentIndexingMode(CONTENT_INDEX_MODE indexMode) {
this.indexMode_ = indexMode;
return this;
}
/**
* <p>
* Adds any keywords associated with the content referred
* </p>
*
* @param keywords An {@link ArrayList} of {@link String} values
* @return This instance to allow for chaining of calls to set methods
*/
@SuppressWarnings("unused")
public BranchUniversalObject addKeyWords(ArrayList<String> keywords) {
this.keywords_.addAll(keywords);
return this;
}
/**
* <p>
* Add a keyword associated with the content referred
* </p>
*
* @param keyword A{@link String} with value for keyword
* @return This instance to allow for chaining of calls to set methods
*/
public BranchUniversalObject addKeyWord(String keyword) {
this.keywords_.add(keyword);
return this;
}
/**
* <p>
* Set the content expiration time.
* </p>
*
* @param expirationDate A {@link Date} value representing the expiration date.
* @return This instance to allow for chaining of calls to set methods
*/
public BranchUniversalObject setContentExpiration(Date expirationDate) {
this.expirationInMilliSec_ = expirationDate.getTime();
return this;
}
/**
* <p>
* Specifies whether the contents referred by this object is publically indexable
* </p>
*
* @return A {@link Boolean} whose value is set to true if index mode is public
*/
public boolean isPublicallyIndexable() {
return indexMode_ == CONTENT_INDEX_MODE.PUBLIC;
}
/**
* <p>
* Get the meta data provided for the content referred bt this object
* </p>
*
* @return A {@link HashMap} containing metadata for the provided for this {@link BranchUniversalObject}
*/
public HashMap<String, String> getMetadata() {
return metadata_;
}
/**
* <p>
* Get expiry date for the content and any associated links. Represented as epoch milli second
* </p>
*
* @return A {@link Long} with content expiration time in epoch milliseconds
*/
public long getExpirationTime() {
return expirationInMilliSec_;
}
/**
* <p>
* Get the canonical identifier for this BranchUniversalObject
* </p>
*
* @return A {@link String} with value for the canonical identifier
*/
public String getCanonicalIdentifier() {
return canonicalIdentifier_;
}
/**
* <p/>
* Get description for the content for the content referred by this object
* <p/>
*
* @return A {@link String} with value for the description of the content referred by this object
*/
public String getDescription() {
return description_;
}
/**
* <p/>
* Get the url to any image associated with this content.
* <p/>
*
* @return A {@link String} specifying a url to an image associated with content referred by this object
*/
public String getImageUrl() {
return imageUrl_;
}
/**
* <p>
* Get a title for the content referred by this object
* </p>
*
* @return A {@link String} with value of for the content title
*/
public String getTitle() {
return title_;
}
/**
* <p>
* Get a title for the content referred by this object
* </p>
*
* @return A {@link String} with value of for the content title
*/
public String getType() {
return type_;
}
/**
* Get the keywords associated with this {@link BranchUniversalObject}
*
* @return A {@link JSONArray} with keywords associated with this {@link BranchUniversalObject}
*/
public JSONArray getKeywordsJsonArray() {
JSONArray keywordArray = new JSONArray();
for (String keyword : keywords_) {
keywordArray.put(keyword);
}
return keywordArray;
}
/**
* Get the keywords associated with this {@link BranchUniversalObject}
*
* @return A {@link ArrayList} with keywords associated with this {@link BranchUniversalObject}
*/
@SuppressWarnings("unused")
public ArrayList<String> getKeywords() {
return keywords_;
}
/**
* Mark the content referred by this object as viewed. This increment the view count of the contents referred by this object.
*/
public void registerView() {
registerView(null);
}
/**
* Mark the content referred by this object as viewed. This increment the view count of the contents referred by this object.
*
* @param callback An instance of {@link RegisterViewStatusListener} to listen to results of the operation
*/
public void registerView(@Nullable RegisterViewStatusListener callback) {
if (Branch.getInstance() != null) {
Branch.getInstance().registerView(this, callback);
} else {
if (callback != null) {
callback.onRegisterViewFinished(false, new BranchError("Register view error", BranchError.ERR_BRANCH_NOT_INSTANTIATED));
}
}
}
/**
* <p>
* Callback interface for listening register content view status
* </p>
*/
public interface RegisterViewStatusListener {
/**
* Called on finishing the the register view process
*
* @param registered A {@link Boolean} which is set to true if register content view succeeded
* @param error An instance of {@link BranchError} to notify any error occurred during registering a content view event.
* A null value is set if the registering content view succeeds
*/
void onRegisterViewFinished(boolean registered, BranchError error);
}
public String getShortUrl(@NonNull Context context, @NonNull LinkProperties linkProperties) {
return getLinkBuilder(context, linkProperties).getShortUrl();
}
public void generateShortUrl(@NonNull Context context, @NonNull LinkProperties linkProperties, @Nullable Branch.BranchLinkCreateListener callback) {
getLinkBuilder(context, linkProperties).generateShortUrl(callback);
}
public void showShareSheet(@NonNull Activity activity, @NonNull LinkProperties linkProperties, @NonNull ShareSheetStyle style, @Nullable Branch.BranchLinkShareListener callback) {
if (Branch.getInstance() == null) { //if in case Branch instance is not created. In case of user missing create instance or BranchApp in manifest
if (callback != null) {
callback.onLinkShareResponse(null, null, new BranchError("Trouble sharing link. ", BranchError.ERR_BRANCH_NOT_INSTANTIATED));
} else {
Log.e("BranchSDK", "Sharing error. Branch instance is not created yet. Make sure you have initialised Branch.");
}
} else {
JSONObject params = new JSONObject();
try {
for (String key : metadata_.keySet()) {
params.put(key, metadata_.get(key));
}
HashMap<String, String> controlParams = linkProperties.getControlParams();
for (String key : controlParams.keySet()) {
params.put(key, controlParams.get(key));
}
} catch (JSONException ignore) {
}
Branch.ShareLinkBuilder shareLinkBuilder = new Branch.ShareLinkBuilder(activity, getLinkBuilder(activity, linkProperties))
.setCallback(callback)
.setSubject(style.getMessageTitle())
.setMessage(style.getMessageBody());
if (style.getCopyUrlIcon() != null) {
shareLinkBuilder.setCopyUrlStyle(style.getCopyUrlIcon(), style.getCopyURlText(), style.getUrlCopiedMessage());
}
if (style.getMoreOptionIcon() != null) {
shareLinkBuilder.setMoreOptionStyle(style.getMoreOptionIcon(), style.getMoreOptionText());
}
if (style.getDefaultURL() != null) {
shareLinkBuilder.setDefaultURL(style.getDefaultURL());
}
if (style.getPreferredOptions().size() > 0) {
shareLinkBuilder.addPreferredSharingOptions(style.getPreferredOptions());
}
shareLinkBuilder.shareLink();
}
}
private BranchShortLinkBuilder getLinkBuilder(@NonNull Context context, @NonNull LinkProperties linkProperties) {
BranchShortLinkBuilder shortLinkBuilder = new BranchShortLinkBuilder(context);
if (linkProperties.getTags() != null) {
shortLinkBuilder.addTags(linkProperties.getTags());
}
if (linkProperties.getFeature() != null) {
shortLinkBuilder.setFeature(linkProperties.getFeature());
}
if (linkProperties.getAlias() != null) {
shortLinkBuilder.setAlias(linkProperties.getAlias());
}
if (linkProperties.getChannel() != null) {
shortLinkBuilder.setChannel(linkProperties.getChannel());
}
if (linkProperties.getStage() != null) {
shortLinkBuilder.setStage(linkProperties.getStage());
}
if (linkProperties.getMatchDuration() > 0) {
shortLinkBuilder.setDuration(linkProperties.getMatchDuration());
}
shortLinkBuilder.addParameters(Defines.Jsonkey.ContentTitle.getKey(), title_);
shortLinkBuilder.addParameters(Defines.Jsonkey.CanonicalIdentifier.getKey(), canonicalIdentifier_);
shortLinkBuilder.addParameters(Defines.Jsonkey.ContentKeyWords.getKey(), getKeywordsJsonArray());
shortLinkBuilder.addParameters(Defines.Jsonkey.ContentDesc.getKey(), description_);
shortLinkBuilder.addParameters(Defines.Jsonkey.ContentImgUrl.getKey(), imageUrl_);
shortLinkBuilder.addParameters(Defines.Jsonkey.ContentType.getKey(), type_);
shortLinkBuilder.addParameters(Defines.Jsonkey.ContentExpiryTime.getKey(), "" + expirationInMilliSec_);
for (String key : metadata_.keySet()) {
shortLinkBuilder.addParameters(key, metadata_.get(key));
}
HashMap<String, String> controlParam = linkProperties.getControlParams();
for (String key : controlParam.keySet()) {
shortLinkBuilder.addParameters(key, controlParam.get(key));
}
return shortLinkBuilder;
}
/**
* Get the {@link BranchUniversalObject} associated with the latest deep linking. This should retrieve the
* exact object used for creating the deep link. This should be called only after initialising Branch Session.
*
* @return A {@link BranchUniversalObject} used to create the deep link that started the this app session.
* Null is returned if this session is not started by Branch link click
*/
public static BranchUniversalObject getReferredBranchUniversalObject() {
BranchUniversalObject branchUniversalObject = null;
Branch branchInstance = Branch.getInstance();
if (branchInstance != null && branchInstance.getLatestReferringParams() != null) {
JSONObject latestParam = branchInstance.getLatestReferringParams();
try {
if (latestParam.has("+clicked_branch_link") && latestParam.getBoolean("+clicked_branch_link")) {
branchUniversalObject = new BranchUniversalObject();
if (latestParam.has(Defines.Jsonkey.ContentTitle.getKey())) {
branchUniversalObject.title_ = latestParam.getString(Defines.Jsonkey.ContentTitle.getKey());
}
if (latestParam.has(Defines.Jsonkey.CanonicalIdentifier.getKey())) {
branchUniversalObject.canonicalIdentifier_ = latestParam.getString(Defines.Jsonkey.CanonicalIdentifier.getKey());
}
if (latestParam.has(Defines.Jsonkey.ContentKeyWords.getKey())) {
JSONArray keywordJsonArray = latestParam.getJSONArray(Defines.Jsonkey.ContentKeyWords.getKey());
for (int i = 0; i < keywordJsonArray.length(); i++) {
branchUniversalObject.keywords_.add((String) keywordJsonArray.get(i));
}
}
if (latestParam.has(Defines.Jsonkey.ContentDesc.getKey())) {
branchUniversalObject.description_ = latestParam.getString(Defines.Jsonkey.ContentDesc.getKey());
}
if (latestParam.has(Defines.Jsonkey.ContentImgUrl.getKey())) {
branchUniversalObject.imageUrl_ = latestParam.getString(Defines.Jsonkey.ContentImgUrl.getKey());
}
if (latestParam.has(Defines.Jsonkey.ContentType.getKey())) {
branchUniversalObject.type_ = latestParam.getString(Defines.Jsonkey.ContentType.getKey());
}
if (latestParam.has(Defines.Jsonkey.ContentExpiryTime.getKey())) {
branchUniversalObject.expirationInMilliSec_ = latestParam.getLong(Defines.Jsonkey.ContentExpiryTime.getKey());
}
Iterator<String> keys = latestParam.keys();
while (keys.hasNext()) {
String key = keys.next();
branchUniversalObject.addContentMetadata(key, latestParam.getString(key));
}
}
} catch (Exception ignore) {
}
}
return branchUniversalObject;
}
@Override
public int describeContents() {
return 0;
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public BranchUniversalObject createFromParcel(Parcel in) {
return new BranchUniversalObject(in);
}
public BranchUniversalObject[] newArray(int size) {
return new BranchUniversalObject[size];
}
};
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(canonicalIdentifier_);
dest.writeString(title_);
dest.writeString(description_);
dest.writeString(imageUrl_);
dest.writeString(type_);
dest.writeLong(expirationInMilliSec_);
dest.writeInt(indexMode_.ordinal());
dest.writeSerializable(keywords_);
int metaDataSize = metadata_.size();
dest.writeInt(metaDataSize);
for (HashMap.Entry<String, String> entry : metadata_.entrySet()) {
dest.writeString(entry.getKey());
dest.writeString(entry.getValue());
}
}
private BranchUniversalObject(Parcel in) {
this();
canonicalIdentifier_ = in.readString();
title_ = in.readString();
description_ = in.readString();
imageUrl_ = in.readString();
type_ = in.readString();
expirationInMilliSec_ = in.readLong();
indexMode_ = CONTENT_INDEX_MODE.values()[in.readInt()];
@SuppressWarnings("unchecked")
ArrayList<String> keywordsTemp = (ArrayList<String>) in.readSerializable();
keywords_.addAll(keywordsTemp);
int metadataSize = in.readInt();
for (int i = 0; i < metadataSize; i++) {
metadata_.put(in.readString(), in.readString());
}
}
} |
package morphology;
import zemberek.core.turkish.PrimaryPos;
import zemberek.core.turkish.RootAttribute;
import zemberek.core.turkish.SecondaryPos;
import zemberek.morphology.lexicon.DictionaryItem;
import zemberek.morphology.parser.MorphParse;
import zemberek.morphology.parser.tr.TurkishWordParserGenerator;
import java.io.IOException;
import java.util.List;
public class AddNewDictionaryItem {
TurkishWordParserGenerator parserGenerator;
public AddNewDictionaryItem(TurkishWordParserGenerator parserGenerator) {
this.parserGenerator = parserGenerator;
}
void addNewDictionaryItemTest(String input, DictionaryItem newItem) throws IOException {
List<MorphParse> before = parserGenerator.parse(input);
System.out.println("Parses for " + input + " before adding lemma :");
printResults(before);
// This must be called. So that parser forgets the old results. Due to a small bug,
// parserGenerator.invalidateCache(input); does not work for proper nouns.
parserGenerator.invalidateAllCache();
parserGenerator.getGraph().addDictionaryItem(newItem);
List<MorphParse> after = parserGenerator.parse(input);
System.out.println("Parses for " + input + " after adding lemma :");
printResults(after);
}
private void printResults(List<MorphParse> before) {
int i = 1;
for (MorphParse morphParse : before) {
String str = morphParse.formatLong();
if (morphParse.dictionaryItem.attributes.contains(RootAttribute.Runtime)) {
str = str + " (Generated by UnidentifiedTokenParser)";
}
System.out.println(i + " - " + str);
i++;
}
}
public static void main(String[] args) throws IOException {
AddNewDictionaryItem app = new AddNewDictionaryItem(TurkishWordParserGenerator.createWithDefaults());
System.out.println("Proper Noun Test - 1 :");
app.addNewDictionaryItemTest("Meydan'a",
new DictionaryItem("Meydan", "meydan", "meydan", PrimaryPos.Noun, SecondaryPos.ProperNoun));
System.out.println();
System.out.println("Proper Noun Test - 2 :");
app.addNewDictionaryItemTest("Meeeydan'a",
new DictionaryItem("Meeeydan", "meeeydan", "meeeydan", PrimaryPos.Noun, SecondaryPos.ProperNoun));
System.out.println();
System.out.println("Verb Test : ");
app.addNewDictionaryItemTest("tweetleyeyazdım",
new DictionaryItem("tweetlemek", "tweetle", "tivitle", PrimaryPos.Verb, SecondaryPos.None));
}
} |
package net.ilexiconn.magister;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import net.ilexiconn.magister.adapter.*;
import net.ilexiconn.magister.container.*;
import net.ilexiconn.magister.container.sub.Privilege;
import net.ilexiconn.magister.exeption.PrivilegeException;
import net.ilexiconn.magister.util.AndroidUtil;
import net.ilexiconn.magister.util.HttpUtil;
import net.ilexiconn.magister.util.LogUtil;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.security.InvalidParameterException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
public class Magister {
public static final String VERSION = "0.1.0-develop";
public Gson gson = new GsonBuilder()
.registerTypeAdapter(Profile.class, new ProfileAdapter())
.registerTypeAdapter(Study[].class, new StudyAdapter())
.registerTypeAdapter(Contact[].class, new ContactAdapter())
.registerTypeAdapter(Appointment[].class, new AppointmentAdapter())
.registerTypeAdapter(Grade[].class, new GradeAdapter())
.registerTypeAdapter(MessageFolder[].class, new MessageFolderAdapter())
.registerTypeAdapter(Message[].class, new MessageAdapter())
.registerTypeAdapter(SingleMessage[].class, new SingleMessageAdapter())
.create();
public School school;
public Version version;
public Session session;
public Profile profile;
public Study[] studies;
public Study currentStudy;
public static Magister login(School school, String username, String password) throws Exception {
Magister magister = new Magister();
AndroidUtil.isRunningOnAndroid();
magister.school = school;
magister.version = magister.gson.fromJson(HttpUtil.httpGet(school.url + "/api/versie"), Version.class);
HttpUtil.httpDelete(school.url + "/api/sessies/huidige");
HashMap<String, String> nameValuePairMap = new HashMap<String, String>();
nameValuePairMap.put("Gebruikersnaam", username);
nameValuePairMap.put("Wachtwoord", password);
magister.session = magister.gson.fromJson(HttpUtil.httpPost(school.url + "/api/sessies", nameValuePairMap), Session.class);
if (!magister.session.state.equals("active")) {
LogUtil.printError("Invalid credentials", new InvalidParameterException());
return null;
}
magister.profile = magister.gson.fromJson(HttpUtil.httpGet(school.url + "/api/account"), Profile.class);
magister.studies = magister.gson.fromJson(HttpUtil.httpGet(school.url + "/api/personen/" + magister.profile.id + "/aanmeldingen"), Study[].class);
DateFormat format = new SimpleDateFormat("y-m-d", Locale.ENGLISH);
Date now = new Date();
for (Study study : magister.studies) {
if (format.parse(study.endDate.substring(0, 10)).after(now)) {
magister.currentStudy = study;
}
}
return magister;
}
public Contact[] getPupilInfo(String name) throws IOException, PrivilegeException {
return getContactInfo(name, "Leerling");
}
public Contact[] getTeacherInfo(String name) throws IOException, PrivilegeException {
return getContactInfo(name, "Personeel");
}
public Contact[] getContactInfo(String name, String type) throws IOException, PrivilegeException {
if (!hasPrivilege("Contactpersonen")) {
throw new PrivilegeException();
}
return gson.fromJson(HttpUtil.httpGet(school.url + "/api/personen/" + profile.id + "/contactpersonen?contactPersoonType=" + type + "&q=" + name), Contact[].class);
}
public Appointment[] getAppointments(Date from, Date until) throws IOException, PrivilegeException {
if (!hasPrivilege("Afspraken")) {
throw new PrivilegeException();
}
DateFormat format = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
String dateNow = format.format(from);
String dateFrom = format.format(until);
return gson.fromJson(HttpUtil.httpGet(school.url + "/api/personen/" + profile.id + "/afspraken?status=0&van=" + dateNow + "&tot=" + dateFrom), Appointment[].class);
}
public Appointment[] getAppointmentsOfToday() throws IOException, PrivilegeException {
Date now = new Date();
return getAppointments(now, now);
}
public Grade[] getGrades(boolean onlyAverage, boolean onlyPTA, boolean onlyActiveStudy) throws IOException, PrivilegeException {
if (!hasPrivilege("Cijfers")) {
throw new PrivilegeException();
}
return gson.fromJson(HttpUtil.httpGet(school.url + "/api/personen/" + profile.id + "/aanmeldingen/" + currentStudy.id + "/cijfers/cijferoverzichtvooraanmelding?alleenBerekendeKolommen=" + onlyAverage + "&alleenPTAKolommen=" + onlyPTA + "&actievePerioden=" + onlyActiveStudy), Grade[].class);
}
public Grade[] getAllGrades() throws IOException, PrivilegeException {
return getGrades(false, false, false);
}
public MessageFolder[] getMessageFolders() throws IOException, PrivilegeException {
if (!hasPrivilege("Berichten")) {
throw new PrivilegeException();
}
return gson.fromJson(HttpUtil.httpGet(school.url + "/api/personen/" + profile.id + "/berichten/mappen"), MessageFolder[].class);
}
public Message[] getMessagesPerFolder(int folderID) throws IOException, PrivilegeException {
if (!hasPrivilege("Berichten")) {
throw new PrivilegeException();
}
return gson.fromJson(HttpUtil.httpGet(school.url + "/api/personen/" + profile.id + "/berichten?mapId=" + folderID + "&orderby=soort+DESC&skip=0&top=25"), Message[].class);
}
public SingleMessage[] getSingleMessage(int messageID) throws IOException, PrivilegeException {
if (!hasPrivilege("Berichten")) {
throw new PrivilegeException();
}
return gson.fromJson(HttpUtil.httpGet(school.url + "/api/personen/" + profile.id + "/berichten/" + messageID + "?berichtSoort=Bericht"), SingleMessage[].class);
}
public boolean hasPrivilege(String privilege) {
for (Privilege p : profile.privileges) {
if (p.name.equals(privilege)) {
return true;
}
}
return false;
}
public BufferedImage getImage() throws IOException {
return getImage(42, 64, false);
}
public BufferedImage getImage(int width, int height, boolean crop) throws IOException {
HttpGet get = new HttpGet(school.name + "/api/personen/" + profile.id + "/foto" + (width != 42 || height != 64 || crop ? "?width=" + width + "&height=" + height + "&crop=" + crop : ""));
CloseableHttpResponse responseGet = HttpUtil.getHttpClient().execute(get);
return ImageIO.read(responseGet.getEntity().getContent());
}
// public SingleMessage[] postSingleMessage() throws IOException {
// TODO: Implement post
// return SingleMessage;
} |
// This file is part of OpenTSDB.
// This program is free software: you can redistribute it and/or modify it
// option) any later version. This program is distributed in the hope that it
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
package net.opentsdb.tsd;
import java.util.Map;
import net.opentsdb.core.Const;
import net.opentsdb.core.Internal;
import net.opentsdb.core.TSDB;
import net.opentsdb.meta.Annotation;
import net.opentsdb.stats.StatsCollector;
import com.stumbleupon.async.Deferred;
/**
* Real Time publisher plugin interface that is used to emit data from a TSD
* as data comes in. Initially it supports publishing data points immediately
* after they are queued for storage. In the future we may support publishing
* meta data or other types of information as changes are made.
* <p>
* <b>Note:</b> Implementations must have a parameterless constructor. The
* {@link #initialize()} method will be called immediately after the plugin is
* instantiated and before any other methods are called.
* <p>
* <b>Warning:</b> All processing should be performed asynchronously and return
* a Deferred as quickly as possible.
* @since 2.0
*/
public abstract class RTPublisher {
public abstract void initialize(final TSDB tsdb);
/**
* Called to gracefully shutdown the plugin. Implementations should close
* any IO they have open
* @return A deferred object that indicates the completion of the request.
* The {@link Object} has not special meaning and can be {@code null}
* (think of it as {@code Deferred<Void>}).
*/
public abstract Deferred<Object> shutdown();
/**
* Should return the version of this plugin in the format:
* MAJOR.MINOR.MAINT, e.g. 2.0.1. The MAJOR version should match the major
* version of OpenTSDB the plugin is meant to work with.
* @return A version string used to log the loaded version
*/
public abstract String version();
/**
* Called by the TSD when a request for statistics collection has come in. The
* implementation may provide one or more statistics. If no statistics are
* available for the implementation, simply stub the method.
* @param collector The collector used for emitting statistics
*/
public abstract void collectStats(final StatsCollector collector);
/**
* Called by the TSD when a new, raw data point is published. Because this
* is called after a data point is queued, the value has been converted to a
* byte array so we need to convert it back to an integer or floating point
* value. Instead of requiring every implementation to perform the calculation
* we perform it here and let the implementer deal with the integer or float.
* @param metric The name of the metric associated with the data point
* @param timestamp Timestamp as a Unix epoch in seconds or milliseconds
* (depending on the TSD's configuration)
* @param value The value as a byte array
* @param tags Tagk/v pairs
* @param tsuid Time series UID for the value
* @param flags Indicates if the byte array is an integer or floating point
* value
* @return A deferred without special meaning to wait on if necessary. The
* value may be null but a Deferred must be returned.
*/
public final Deferred<Object> sinkDataPoint(final String metric,
final long timestamp, final byte[] value, final Map<String, String> tags,
final byte[] tsuid, final short flags) {
if ((flags & Const.FLAG_FLOAT) == 0x0) {
return publishDataPoint(metric, timestamp,
Internal.extractFloatingPointValue(value, 0, (byte) flags),
tags, tsuid);
} else {
return publishDataPoint(metric, timestamp,
Internal.extractIntegerValue(value, 0, (byte) flags), tags, tsuid);
}
}
/**
* Called any time a new data point is published
* @param metric The name of the metric associated with the data point
* @param timestamp Timestamp as a Unix epoch in seconds or milliseconds
* (depending on the TSD's configuration)
* @param value Value for the data point
* @param tags Tagk/v pairs
* @param tsuid Time series UID for the value
* @return A deferred without special meaning to wait on if necessary. The
* value may be null but a Deferred must be returned.
*/
public abstract Deferred<Object> publishDataPoint(final String metric,
final long timestamp, final long value, final Map<String, String> tags,
final byte[] tsuid);
/**
* Called any time a new data point is published
* @param metric The name of the metric associated with the data point
* @param timestamp Timestamp as a Unix epoch in seconds or milliseconds
* (depending on the TSD's configuration)
* @param value Value for the data point
* @param tags Tagk/v pairs
* @param tsuid Time series UID for the value
* @return A deferred without special meaning to wait on if necessary. The
* value may be null but a Deferred must be returned.
*/
public abstract Deferred<Object> publishDataPoint(final String metric,
final long timestamp, final double value, final Map<String, String> tags,
final byte[] tsuid);
/**
* Called any time a new annotation is published
* @param annotation The published annotation
* @return A deferred without special meaning to wait on if necessary. The
* value may be null but a Deferred must be returned.
*/
public abstract Deferred<Object> publishAnnotation(Annotation annotation);
} |
package net.imagej.ops;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import org.scijava.command.CommandInfo;
import org.scijava.command.CommandService;
import org.scijava.log.LogService;
import org.scijava.module.Module;
import org.scijava.module.ModuleInfo;
import org.scijava.module.ModuleItem;
import org.scijava.module.ModuleService;
import org.scijava.plugin.AbstractPTService;
import org.scijava.plugin.Parameter;
import org.scijava.plugin.Plugin;
import org.scijava.service.Service;
/**
* Default service for managing and executing {@link Op}s.
*
* @author Curtis Rueden
*/
@Plugin(type = Service.class)
public class DefaultOpService extends AbstractPTService<Op> implements
OpService
{
@Parameter
private ModuleService moduleService;
@Parameter
private CommandService commandService;
@Parameter
private OpMatchingService matcher;
@Parameter
private LogService log;
// -- OpService methods --
@Override
public Object run(final String name, final Object... args) {
final Module module = module(name, args);
return run(module);
}
@Override
public Object run(final Class<? extends Op> type, final Object... args) {
final Module module = module(type, args);
return run(module);
}
@Override
public Object run(final Op op, final Object... args) {
return run(module(op, args));
}
@Override
public Op op(final String name, final Object... args) {
final Module module = module(name, args);
if (module == null) return null;
return (Op) module.getDelegateObject();
}
@Override
public <OP extends Op> OP op(final Class<OP> type, final Object... args) {
final Module module = module(type, args);
if (module == null) return null;
@SuppressWarnings("unchecked")
final OP op = (OP) module.getDelegateObject();
return op;
}
@Override
public Module module(final String name, final Object... args) {
return matcher.findModule(name, null, args);
}
@Override
public Module module(final Class<? extends Op> type, final Object... args) {
return matcher.findModule(null, type, args);
}
@Override
public Module module(final Op op, final Object... args) {
final Module module = info(op).createModule(op);
getContext().inject(module.getDelegateObject());
return matcher.assignInputs(module, args);
}
@Override
public CommandInfo info(final Op op) {
return commandService.getCommand(op.getClass());
}
@Override
public Collection<String> ops() {
// collect list of unique operation names
final HashSet<String> operations = new HashSet<String>();
for (final CommandInfo info : matcher.getOps()) {
final String name = info.getName();
if (name != null && !name.isEmpty()) operations.add(info.getName());
}
// convert the set into a sorted list
final ArrayList<String> sorted = new ArrayList<String>(operations);
Collections.sort(sorted);
return sorted;
}
@Override
public String help(final String name) {
return help(matcher.findCandidates(name, null));
}
@Override
public String help(final Class<? extends Op> type) {
return help(matcher.findCandidates(null, type));
}
@Override
public String help(final Op op) {
return help(Collections.singleton(info(op)));
}
private String help(final Collection<? extends ModuleInfo> infos) {
if (infos.size() == 0) {
return "No such operation.";
}
final StringBuilder sb = new StringBuilder("Available operations:");
for (final ModuleInfo info : infos) {
sb.append("\n\t" + matcher.getOpString(info));
}
if (infos.size() == 1) {
final ModuleInfo info = infos.iterator().next();
final String description = info.getDescription();
if (description != null && !description.isEmpty()) {
sb.append("\n\n" + description);
}
}
return sb.toString();
}
// -- Operation shortcuts --
@Override
public Object add(final Object... args) {
return run(Ops.Add.NAME, args);
}
@Override
public Object ascii(Object... args) {
return run(Ops.ASCII.NAME, args);
}
@Override
public Object chunker(Object... args) {
return run(Ops.Chunker.NAME, args);
}
@Override
public Object convert(Object... args) {
return run(Ops.Convert.NAME, args);
}
@Override
public Object convolve(Object... args) {
return run(Ops.Convolve.NAME, args);
}
@Override
public Object createimg(Object... args) {
return run(Ops.CreateImg.NAME, args);
}
@Override
public Object crop(Object... args) {
return run(Ops.Crop.NAME, args);
}
@Override
public Object divide(Object... args) {
return run(Ops.Divide.NAME, args);
}
@Override
public Object equation(Object... args) {
return run(Ops.Equation.NAME, args);
}
@Override
public Object gauss(Object... args) {
return run(Ops.Gauss.NAME, args);
}
@Override
public Object histogram(Object... args) {
return run(Ops.Histogram.NAME, args);
}
@Override
public Object identity(Object... args) {
return run(Ops.Identity.NAME, args);
}
@Override
public Object invert(Object... args) {
return run(Ops.Invert.NAME, args);
}
@Override
public Object join(Object... args) {
return run(Ops.Join.NAME, args);
}
@Override
public Object lookup(Object... args) {
return run(Ops.Lookup.NAME, args);
}
@Override
public Object loop(Object... args) {
return run(Ops.Loop.NAME, args);
}
@Override
public Object map(Object... args) {
return run(Ops.Map.NAME, args);
}
@Override
public Object max(Object... args) {
return run(Ops.Max.NAME, args);
}
@Override
public Object mean(Object... args) {
return run(Ops.Mean.NAME, args);
}
@Override
public Object median(Object... args) {
return run(Ops.Median.NAME, args);
}
@Override
public Object min(Object... args) {
return run(Ops.Min.NAME, args);
}
@Override
public Object minmax(Object... args) {
return run(Ops.MinMax.NAME, args);
}
@Override
public Object multiply(Object... args) {
return run(Ops.Multiply.NAME, args);
}
@Override
public Object normalize(Object... args) {
return run(Ops.Normalize.NAME, args);
}
@Override
public Object project(Object... args) {
return run(Ops.Project.NAME, args);
}
@Override
public Object quantile(Object... args) {
return run(Ops.Quantile.NAME, args);
}
@Override
public Object scale(Object... args) {
return run(Ops.Scale.NAME, args);
}
@Override
public Object size(Object... args) {
return run(Ops.Size.NAME, args);
}
@Override
public Object slicewise(Object... args) {
return run(Ops.Slicewise.NAME, args);
}
@Override
public Object stddev(Object... args) {
return run(Ops.StdDeviation.NAME, args);
}
@Override
public Object subtract(Object... args) {
return run(Ops.Subtract.NAME, args);
}
@Override
public Object sum(Object... args) {
return run(Ops.Sum.NAME, args);
}
@Override
public Object threshold(Object... args) {
return run(Ops.Threshold.NAME, args);
}
@Override
public Object variance(Object... args) {
return run(Ops.Variance.NAME, args);
}
// -- SingletonService methods --
@Override
public Class<Op> getPluginType() {
return Op.class;
}
// -- Helper methods --
private Object run(final Module module) {
module.run();
return result(module);
}
private Object result(final Module module) {
final List<Object> outputs = new ArrayList<Object>();
for (final ModuleItem<?> output : module.getInfo().outputs()) {
final Object value = output.getValue(module);
outputs.add(value);
}
return outputs.size() == 1 ? outputs.get(0) : outputs;
}
// -- Deprecated methods --
@Deprecated
@Override
public Object create(Object... args) {
return createimg(args);
}
} |
package net.imagej.util;
import java.io.IOException;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import javax.xml.parsers.ParserConfigurationException;
import org.scijava.util.XML;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
* A minimal MediaWiki API client for interacting with the ImageJ Wiki.
*
* @author Johannes Schindelin
*/
public class MediaWikiClient {
private static final String IMAGEJ_WIKI_URL = "http://wiki.imagej.net/";
private final String baseURL;
private final Set<String> postActions = new HashSet<String>(Arrays.asList("login", "changeuploadpassword"));
private String currentUser;
private Map<String, String> cookies = new LinkedHashMap<String, String>();
public MediaWikiClient() {
this(IMAGEJ_WIKI_URL);
}
public MediaWikiClient(final String baseURL) {
if (baseURL.endsWith("/index.php")) this.baseURL = baseURL.substring(0, baseURL.length() - 9);
else if (baseURL.endsWith("/")) this.baseURL = baseURL;
else this.baseURL = baseURL + "/";
}
/**
* Returns the up-cased first character (or <code>0</code> if it cannot be
* up-cased, e.g. if it is already upper-case).
*
* @param word the word whose first character needs to be up-cased.
* @return the first character in upper-case, or <code>0</code> if it could
* not be up-cased.
*/
private static char firstToUpperCase(final String word) {
if (word.length() == 0) return 0;
char first = word.charAt(0);
if (Character.isLowerCase(first)) return Character.toUpperCase(first);
return 0;
}
public static boolean isCapitalized(final String word) {
return firstToUpperCase(word) == 0;
}
public static String capitalize(final String word) {
char first = firstToUpperCase(word);
if (first == 0) return word;
final StringBuilder builder = new StringBuilder();
builder.append(first);
builder.append(word.substring(1));
return builder.toString();
}
public String getPageSource(final String title) throws IOException {
final XML xml = query("titles", title, "export", "true", "exportnowrap", "true");
return xml.cdata("/mediawiki/page/revision/text");
}
public boolean userExists(final String name) throws IOException {
if (!isCapitalized(name)) {
throw new IOException(
"User name cannot start with a lower-case character: " + name);
}
final XML xml = query("list", "users", "ususers", name);
final NodeList list = xml.xpath("/api/query/users/user");
int count = list.getLength();
for (int i = 0; i < count; i++) {
final NamedNodeMap node = list.item(i).getAttributes();
if (node != null && node.getNamedItem("missing") == null) return true;
}
return false;
}
public boolean createUser(final String userName, final String realName, final String email, final String reason) throws IOException {
final String[] headers = {
"Requested-User", userName
};
final XML xml = request(headers, "createimagejwikiaccount",
"name", userName, "email", email, "realname", realName, "reason", reason);
final String error = getAttribute(xml.xpath("/api/error"), "info");
if (error != null) {
System.err.println("Error creating user " + userName + ": " + error);
return false;
}
if (userName.equals(getAttribute(xml.xpath("/api/createimagejwikiaccount"), "created"))) {
return true;
}
return false;
}
public boolean changeUploadPassword(final String password) throws IOException {
if (currentUser == null) throw new IOException("Can only change the password for a logged-in user");
System.err.println("action: changeuploadpassword");
final XML xml = request(null, "changeuploadpassword", "password", password);
final String error = getAttribute(xml.xpath("/api/error"), "info");
if (error != null) {
System.err.println("Error setting upload password for user '" + currentUser + "': " + error);
return false;
}
final NodeList response = xml.xpath("/api/changeuploadpassword");
final boolean result = "0".equals(getAttribute(response, "result"));
if (!result) {
System.err.println("a1: " + response.item(0));
System.err.println("Error: " + getAttribute(response, "output"));
}
return result;
}
public boolean login(final String user, final String password) throws IOException {
XML xml = request(null, "login", "lgname", user, "lgpassword", password);
final String loginToken = getAttribute(xml.xpath("/api/login"), "token");
if (loginToken == null) {
System.err.println("Did not get a token!");
return false;
}
xml = request(null, "login", "lgname", user, "lgpassword", password, "lgtoken", loginToken);
final boolean result = "Success".equals(getAttribute(xml.xpath("/api/login"), "result"));
currentUser = result ? user : null;
return result;
}
public void logout() throws IOException {
if (currentUser == null) return;
request(null, "logout");
cookies.clear();
currentUser = null;
}
public XML request(final String[] headers, final String action, final String... parameters) throws IOException {
if (parameters.length % 2 != 0) throw new IllegalArgumentException("Requires key/value pairs");
final boolean requiresPOST = postActions.contains(action);
try {
final StringBuilder url = new StringBuilder();
url.append(baseURL).append("api.php?action=").append(action).append("&format=xml");
if (!requiresPOST) {
for (int i = 0; i < parameters.length; i += 2) {
url.append("&").append(URLEncoder.encode(parameters[i], "UTF-8"));
url.append("=").append(URLEncoder.encode(parameters[i + 1], "UTF-8"));
}
}
final URLConnection connection = new URL(url.toString()).openConnection();
for (final Entry<String, String> entry : cookies.entrySet()) {
connection.addRequestProperty("Cookie", entry.getKey() + "=" + entry.getValue());
}
if (headers != null) {
if (headers.length % 2 != 0) throw new IllegalArgumentException("Requires key/value pairs");
for (int i = 0; i < headers.length; i += 2) {
connection.setRequestProperty(headers[i], headers[i + 1]);
}
}
final HttpURLConnection http = (connection instanceof HttpURLConnection) ? (HttpURLConnection) connection : null;
if (http != null && requiresPOST) {
http.setRequestMethod("POST");
final String boundary = "---e69de29bb2d1d6434b8b29ae775ad8c2e48c5391";
http.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
http.setDoOutput(true);
http.connect();
final PrintStream ps = new PrintStream(http.getOutputStream());
for (int i = 0; i < parameters.length; i += 2) {
ps.print("--" + boundary + "\r\n"
+ "Content-Disposition: "
+ "form-data; name=\""
+ parameters[i] + "\"\r\n\r\n"
+ parameters[i + 1] + "\r\n");
}
ps.println("--" + boundary + "--");
ps.close();
}
final List<String> newCookies = http.getHeaderFields().get("Set-Cookie");
if (newCookies != null) {
for (final String cookie : newCookies) {
final int equal = cookie.indexOf("=");
if (equal < 0) continue;
final String key = cookie.substring(0, equal);
final String value = cookie.substring(equal + 1);
if (value.startsWith("deleted; ")) cookies.remove(key);
else cookies.put(key, value);
}
}
return new XML(connection.getInputStream());
} catch (ParserConfigurationException e) {
throw new IOException(e);
} catch (SAXException e) {
throw new IOException(e);
}
}
public XML query(final String... parameters) throws IOException {
return request(null, "query", parameters);
}
public static String getAttribute(final NodeList list, final String attributeName) {
if (list == null || list.getLength() != 1) return null;
final NamedNodeMap attrs = list.item(0).getAttributes();
if (attrs == null) return null;
final Node node = attrs.getNamedItem(attributeName);
return node == null ? null : node.getNodeValue();
}
} |
package net.jodah.concurrentunit;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import net.jodah.concurrentunit.internal.ReentrantCircuit;
/**
* Waits on a test, carrying out assertions, until being resumed.
*
* @author Jonathan Halterman
*/
public class Waiter {
private static final String TIMEOUT_MESSAGE = "Test timed out while waiting for an expected result";
private final Thread mainThread;
private AtomicInteger remainingResumes = new AtomicInteger(0);
private final ReentrantCircuit circuit = new ReentrantCircuit();
private volatile Throwable failure;
/**
* Creates a new Waiter.
*/
public Waiter() {
mainThread = Thread.currentThread();
circuit.open();
}
/**
* Asserts that the {@code expected} values equals the {@code actual} value
*
* @throws AssertionError when the assertion fails
*/
public void assertEquals(Object expected, Object actual) {
if (expected == null && actual == null)
return;
if (expected != null && expected.equals(actual))
return;
fail(format(expected, actual));
}
/**
* Asserts that the {@code condition} is false.
*
* @throws AssertionError when the assertion fails
*/
public void assertFalse(boolean condition) {
if (condition)
fail("expected false");
}
/**
* Asserts that the {@code object} is not null.
*
* @throws AssertionError when the assertion fails
*/
public void assertNotNull(Object object) {
if (object == null)
fail("expected not null");
}
/**
* Asserts that the {@code object} is null.
*
* @throws AssertionError when the assertion fails
*/
public void assertNull(Object object) {
if (object != null)
fail(format("null", object));
}
/**
* Asserts that the {@code condition} is true.
*
* @throws AssertionError when the assertion fails
*/
public void assertTrue(boolean condition) {
if (!condition)
fail("expected true");
}
public void await() throws Throwable {
await(0, TimeUnit.MILLISECONDS, 1);
}
public void await(long delay) throws Throwable {
await(delay, TimeUnit.MILLISECONDS, 1);
}
public void await(long delay, TimeUnit timeUnit) throws Throwable {
await(delay, timeUnit, 1);
}
public void await(long delay, int expectedResumes) throws Throwable {
await(delay, TimeUnit.MILLISECONDS, expectedResumes);
}
public void await(long delay, TimeUnit timeUnit, int expectedResumes) throws Throwable {
if (Thread.currentThread() != mainThread)
throw new IllegalStateException("Must be called from within the main test thread");
remainingResumes.set(expectedResumes);
try {
if (delay == 0)
circuit.await();
else if (!circuit.await(delay, timeUnit))
throw new TimeoutException(TIMEOUT_MESSAGE);
} catch (InterruptedException e) {
} finally {
remainingResumes.set(0);
circuit.open();
if (failure != null) {
Throwable f = failure;
failure = null;
throw f;
}
}
}
/**
* Resumes the waiter when the expected number of {@link #resume()} calls have occurred.
*/
public void resume() {
if (remainingResumes.decrementAndGet() <= 0)
circuit.close();
}
/**
* Fails the current test.
*
* @throws AssertionError
*/
public void fail() {
fail(new AssertionError());
}
/**
* Fails the current test for the given {@code reason}.
*
* @throws AssertionError
*/
public void fail(String reason) {
fail(new AssertionError(reason));
}
/**
* Fails the current test with the given {@code reason}, sets the number of expected resumes to 0, and throws the
* {@code reason} in the current thread and the main test thread.
*
* @throws AssertionError wrapping the {@code reason}
*/
public void fail(Throwable reason) {
AssertionError ae = null;
if (reason instanceof AssertionError)
ae = (AssertionError) reason;
else {
ae = new AssertionError();
ae.initCause(reason);
}
failure = reason;
circuit.close();
throw ae;
}
private String format(Object expected, Object actual) {
return "expected:<" + expected + "> but was:<" + actual + ">";
}
} |
package org.apache.couchdb.lucene;
import static org.apache.couchdb.lucene.Utils.text;
import static org.apache.couchdb.lucene.Utils.token;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.LogByteSizeMergePolicy;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.TermEnum;
import org.apache.lucene.index.IndexWriter.MaxFieldLength;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
/**
* High-level wrapper class over Lucene.
*/
public final class Index {
private static final DateFormat DATE_FORMAT = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss 'GMT'Z '('z')'");
private static final Database DB = new Database(Config.DB_URL);
private static final Tika TIKA = new Tika();
private static final Object MUTEX = new Object();
private static final Timer TIMER = new Timer("Timer", true);
private static class CheckpointTask extends TimerTask {
@Override
public void run() {
wakeupIndexer();
}
}
private static class Indexer implements Runnable {
private Directory dir;
private boolean running = true;
private long lastCommit = System.currentTimeMillis();
public void run() {
try {
this.dir = FSDirectory.getDirectory(Config.INDEX_DIR);
while (running) {
updateIndex();
waitForUpdateNotification();
}
} catch (final IOException e) {
Log.errlog(e);
}
}
private synchronized void updateIndex() throws IOException {
if (IndexWriter.isLocked(dir)) {
Log.errlog("Forcibly unlocking locked index at startup.");
IndexWriter.unlock(dir);
}
final String[] dbnames = DB.getAllDatabases();
Arrays.sort(dbnames);
Rhino rhino = null;
boolean commit = false;
final IndexWriter writer = newWriter();
final Progress progress = new Progress();
try {
final IndexReader reader = IndexReader.open(dir);
try {
// Load status.
progress.load(reader);
// Remove documents from deleted databases.
final TermEnum terms = reader.terms(new Term(Config.DB, ""));
try {
do {
final Term term = terms.term();
if (term == null || Config.DB.equals(term.field()) == false)
break;
if (Arrays.binarySearch(dbnames, term.text()) < 0) {
Log.errlog("Database '%s' has been deleted," + " removing all documents from index.",
term.text());
delete(term.text(), writer);
commit = true;
}
} while (terms.next());
} finally {
terms.close();
}
} finally {
reader.close();
}
// Update all extant databases.
for (final String dbname : dbnames) {
// Database might supply a transformation function.
final JSONObject designDoc = DB.getDoc(dbname, "_design/lucene");
if (designDoc != null && designDoc.containsKey("transform")) {
String transform = designDoc.getString("transform");
// Strip start and end double quotes.
transform = transform.replaceAll("^\"*", "");
transform = transform.replaceAll("\"*$", "");
rhino = new Rhino(transform);
} else {
rhino = null;
}
commit |= updateDatabase(writer, dbname, progress, rhino);
}
} catch (final Exception e) {
Log.errlog(e);
commit = false;
} finally {
if (commit) {
progress.save(writer);
writer.close();
lastCommit = System.currentTimeMillis();
final IndexReader reader = IndexReader.open(dir);
try {
Log.errlog("Committed changes to index (%,d documents in index, %,d deletes).", reader
.numDocs(), reader.numDeletedDocs());
} finally {
reader.close();
}
} else {
writer.rollback();
}
}
}
private void waitForUpdateNotification() {
synchronized (MUTEX) {
try {
MUTEX.wait();
} catch (final InterruptedException e) {
running = false;
}
}
}
private IndexWriter newWriter() throws IOException {
final IndexWriter result = new IndexWriter(dir, Config.ANALYZER, MaxFieldLength.UNLIMITED);
// Customize merge policy.
final LogByteSizeMergePolicy mp = new LogByteSizeMergePolicy();
mp.setMergeFactor(5);
mp.setMaxMergeMB(1000);
result.setMergePolicy(mp);
// Customer other settings.
result.setUseCompoundFile(false);
result.setRAMBufferSizeMB(Config.RAM_BUF);
return result;
}
private boolean updateDatabase(final IndexWriter writer, final String dbname, final Progress progress,
final Rhino rhino) throws HttpException, IOException {
final long cur_seq = progress.getSeq(dbname);
final long target_seq = DB.getInfo(dbname).getLong("update_seq");
final boolean time_threshold_passed = (System.currentTimeMillis() - lastCommit) >= Config.TIME_THRESHOLD * 1000;
final boolean change_threshold_passed = (target_seq - cur_seq) >= Config.CHANGE_THRESHOLD;
if (!(time_threshold_passed || change_threshold_passed)) {
return false;
}
final String cur_sig = progress.getSignature(dbname);
final String new_sig = rhino == null ? Progress.NO_SIGNATURE : rhino.getSignature();
boolean result = false;
// Reindex the database if sequence is 0 or signature changed.
if (progress.getSeq(dbname) == 0 || cur_sig.equals(new_sig) == false) {
Log.errlog("Indexing '%s' from scratch.", dbname);
delete(dbname, writer);
progress.update(dbname, new_sig, 0);
result = true;
}
long update_seq = progress.getSeq(dbname);
while (update_seq < target_seq) {
final JSONObject obj = DB.getAllDocsBySeq(dbname, update_seq, Config.BATCH_SIZE);
if (!obj.has("rows")) {
Log.errlog("no rows found (%s).", obj);
return false;
}
// Process all rows
final JSONArray rows = obj.getJSONArray("rows");
for (int i = 0, max = rows.size(); i < max; i++) {
final JSONObject row = rows.getJSONObject(i);
final JSONObject value = row.optJSONObject("value");
final JSONObject doc = row.optJSONObject("doc");
// New or updated document.
if (doc != null) {
updateDocument(writer, dbname, rows.getJSONObject(i), rhino);
result = true;
}
// Deleted document.
if (value != null && value.optBoolean("deleted")) {
writer.deleteDocuments(new Term(Config.ID, row.getString("id")));
result = true;
}
update_seq = row.getLong("key");
}
}
if (result) {
progress.update(dbname, new_sig, update_seq);
Log.errlog("%s: index caught up to %,d.", dbname, update_seq);
}
return result;
}
private void delete(final String dbname, final IndexWriter writer) throws IOException {
writer.deleteDocuments(new Term(Config.DB, dbname));
}
private void updateDocument(final IndexWriter writer, final String dbname, final JSONObject obj,
final Rhino rhino) throws IOException {
final Document doc = new Document();
JSONObject json = obj.getJSONObject("doc");
// Skip design documents.
if (json.getString(Config.ID).startsWith("_design")) {
return;
}
// Pass through user-defined transformation (if any).
if (rhino != null) {
json = JSONObject.fromObject(rhino.parse(json.toString()));
if (json.isNullObject())
return;
}
// Standard properties.
doc.add(token(Config.DB, dbname, false));
final String id = (String) json.remove(Config.ID);
// Discard _rev
json.remove("_rev");
// Index _id and _rev as tokens.
doc.add(token(Config.ID, id, true));
// Index all attributes.
add(doc, null, json, false);
// Attachments
if (json.has("_attachments")) {
final JSONObject attachments = json.getJSONObject("_attachments");
final Iterator it = attachments.keys();
while (it.hasNext()) {
final String name = (String) it.next();
final JSONObject att = attachments.getJSONObject(name);
final String url = DB.url(String.format("%s/%s/%s", dbname, DB.encode(id), DB.encode(name)));
final GetMethod get = new GetMethod(url);
try {
final int sc = Database.CLIENT.executeMethod(get);
if (sc == 200) {
TIKA.parse(get.getResponseBodyAsStream(), att.getString("content_type"), doc);
} else {
Log.errlog("Failed to retrieve attachment: %d", sc);
}
} finally {
get.releaseConnection();
}
}
}
// write it
writer.updateDocument(new Term(Config.ID, id), doc);
}
private void add(final Document out, final String key, final Object value, final boolean store) {
if (value instanceof JSONObject) {
final JSONObject json = (JSONObject) value;
for (final Object obj : json.keySet()) {
add(out, (String) obj, json.get(obj), store);
}
} else if (value instanceof String) {
try {
final Date date = DATE_FORMAT.parse((String) value);
out.add(new Field(key, (String) value, Store.YES, Field.Index.NO));
out.add(new Field(key, Long.toString(date.getTime()), Store.NO, Field.Index.NOT_ANALYZED_NO_NORMS));
} catch (final java.text.ParseException e) {
out.add(text(key, (String) value, store));
}
} else if (value instanceof Number) {
out.add(token(key, value.toString(), store));
} else if (value instanceof Boolean) {
out.add(token(key, value.toString(), store));
} else if (value instanceof JSONArray) {
final JSONArray arr = (JSONArray) value;
for (int i = 0, max = arr.size(); i < max; i++) {
add(out, key, arr.get(i), store);
}
} else if (value == null) {
Log.errlog("%s was null.", key);
} else {
Log.errlog("Unsupported data type: %s.", value.getClass());
}
}
}
/**
* update notifications look like this;
*
* {"type":"updated","db":"cas"}
*
* type can be created, updated or deleted.
*/
public static void main(final String[] args) {
start("indexer", new Indexer());
TIMER.schedule(new CheckpointTask(), Config.TIME_THRESHOLD * 1000, Config.TIME_THRESHOLD * 1000);
final Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
final String line = scanner.nextLine();
final JSONObject obj = JSONObject.fromObject(line);
if (obj.has("type") && obj.has("db")) {
wakeupIndexer();
}
}
}
private static void wakeupIndexer() {
synchronized (MUTEX) {
MUTEX.notify();
}
}
private static void start(final String name, final Runnable runnable) {
final Thread thread = new Thread(runnable, name);
thread.setDaemon(true);
thread.start();
}
} |
package edu.wustl.query.util.global;
import java.awt.Color;
/**
*
* @author baljeet_dhindhwal
* @version 1.0
*
*/
public class Constants extends edu.wustl.common.util.global.Constants
{
//Shopping cart related
/** Constant for QUERY_SHOPPING_CART */
public static final String QUERY_SHOPPING_CART = "queryShoppingCart";
/** Constant for */
public static final String CHECK_ALL_ACROSS_ALL_PAGES = "isCheckAllAcrossAllChecked";
/** Constant for */
public static final String CHECK_ALL_PAGES = "checkAllPages";
/** Constant for */
public static final String SELECTED_COLUMN_META_DATA = "selectedColumnMetaData";
/** Constant for */
public static final String DELETE = "delete";
/** Constant for */
public static final String VALIDATION_MESSAGE_FOR_ORDERING = "validationMessageForOrdering";
/** Constant for */
public static final String PAGEOF_QUERY_MODULE = "pageOfQueryModule";
/** Constant for */
public static final String IS_LIST_EMPTY = "isListEmpty";
/** Constant for */
public static final String SHOPPING_CART_DELETE = "shoppingCartDelete";
/** Constant for */
public static final String SHOPPING_CART_ADD = "shoppingCartAdd";
/** Constant for */
public static final String PAGINATION_DATA_LIST = "paginationDataList";
/** Constant for */
public static final String LABEL_TREE_NODE = "Label";
/** Constant for */
public static final String HAS_CONDITION_ON_IDENTIFIED_FIELD = "hasConditionOnIdentifiedField";
/** Constant for */
public static final String NODE_SEPARATOR = "::";
/** Constant for */
public static final String UNDERSCORE = "_";
/** Constant for */
public static final String ADD_TO_ORDER_LIST = "addToOrderList";
/** Constant for */
public static final String REQUEST_TO_ORDER = "requestToOrder";
/** Constant for */
public static final String EDIT_QUERY = "editQuery";
/** Constant for */
public static final String BULK_TRANSFERS = "bulkTransfers";
/** Constant for */
public static final String BULK_DISPOSALS = "bulkDisposals";
/** Constant for */
public static final String OUTPUT_TERMS_COLUMNS = "outputTermsColumns";
/** Constant for */
public static final String SUCCESS = "success";
/** Constant for */
public static final String ENTITY_SEPARATOR = ";";
/** Constant for */
public static final String ATTRIBUTE_SEPARATOR = "|";
/** Constant for */
public static final String KEY_SEPARATOR = "*&*";
/** Constant for */
public static final String KEY_CODE = "key";
/** Constant for */
public static final String EXPORT_DATA_LIST = "exportDataList";
/** Constant for */
public static final String ENTITY_IDS_MAP = "entityIdsMap";
/** Constant for */
public static final String FINISH = "finish";
/** Constant for */
public static final String QUERY_REASUL_OBJECT_DATA_MAP = "queryReasultObjectDataMap";
/** Constant for */
public static final String DEFINE_VIEW_QUERY_REASULT_OBJECT_DATA_MAP = "defineViewQueryReasultObjectDataMap";
/** Constant for */
public static final String CONTAINTMENT_ASSOCIATION = "CONTAINTMENT";
/** Constant for */
public static final String MAIN_ENTITY_MAP = "mainEntityMap";
/** Constant for */
public static final String SPECIMENT_VIEW_ATTRIBUTE = "defaultViewAttribute";
/** Constant for */
public static final String PAGEOF_SPECIMEN_COLLECTION_REQUIREMENT_GROUP = "pageOfSpecimenCollectionRequirementGroup";
/** Constant for */
public static final String NO_MAIN_OBJECT_IN_QUERY = "noMainObjectInQuery";
/** Constant for */
public static final String QUERY_ALREADY_DELETED = "queryAlreadyDeleted";
/** Constant for */
public static final String BACK = "back";
/** Constant for */
public static final String RESTORE = "restore";
/** Constant for */
public static final String SELECTED_COLUMN_NAME_VALUE_BEAN_LIST = "selectedColumnNameValueBeanList";
/** Constant for */
public static final String TREE_DATA = "treeData";
/** Constant for */
public static final String ID_NODES_MAP = "idNodesMap";
/** Constant for */
public static final String DEFINE_RESULTS_VIEW = "DefineResultsView";
/** Constant for */
public static final String CURRENT_PAGE = "currentPage";
/** Constant for */
public static final String ADD_LIMITS = "AddLimits";
/** Constant for */
public static final int QUERY_INTERFACE_BIZLOGIC_ID = 67;
/** Constant for */
public static final String SQL = "SQL";
/** Constant for */
public static final String ID_COLUMN_ID = "ID_COLUMN_ID";
/** Constant for */
public static final String ID = "id";
/** Constant for */
public static final String SAVE_TREE_NODE_LIST = "rootOutputTreeNodeList";
/** Constant for */
public static final String ATTRIBUTE_COLUMN_NAME_MAP = "attributeColumnNameMap";
/** Constant for */
public static final String IS_SAVED_QUERY = "isSavedQuery";
/** Constant for */
public static final String TREE_ROOTS = "treeRoots";
/** Constant for */
public static final String NO_OF_TREES = "noOfTrees";
/** Constant for */
public static final String TREE_NODE_LIMIT_EXCEEDED_RECORDS = "treeNodeLimitExceededRecords";
/** Constant for */
public static final String VIEW_LIMITED_RECORDS = "viewLimitedRecords";
/** Constant for */
public static final String SAVE_GENERATED_SQL = "sql";
/** Constant for */
public static final String TREENO_ZERO = "zero";
/** Constant for */
public static final String COLUMN_NAMES = "columnNames";
/** Constant for */
public static final String INDEX = "index";
/** Constant for */
public static final String[] ATTRIBUTE_NAMES_FOR_TREENODE_LABEL = {"firstName", "lastName",
"title", "name", "label", "shorttitle"};
/** Constant for */
public static final String COLUMN_NAME = "Column";
/** Constant for */
public static final String ON = " ON ";
/** Constant for */
public static final String OFF = "off";
/** Constant for */
public static final String PAGE_OF_QUERY_MODULE = "pageOfQueryModule";
/** Constant for */
public static final String PAGE_OF_QUERY_RESULTS = "pageOfQueryResults";
/** Constant for */
public static final String RANDOM_NUMBER = "randomNumber";
/** Constant for */
public static final String IS_NOT_NULL = "is not null";
/** Constant for */
public static final String IS_NULL = "is null";
/** Constant for */
public static final String IN = "in";
/** Constant for */
public static final String Not_In = "Not In";
/** Constant for */
public static final String Equals = "Equals";
/** Constant for */
public static final String Not_Equals = "Not Equals";
/** Constant for */
public static final String Between = "Between";
/** Constant for */
public static final String Less_Than = "Less than";
/** Constant for */
public static final String Less_Than_Or_Equals = "Less than or Equal to";
/** Constant for */
public static final String Greater_Than = "Greater than";
/** Constant for */
public static final String Greater_Than_Or_Equals = "Greater than or Equal to";
/** Constant for */
public static final String Contains = "Contains";
/** Constant for */
public static final String STRATS_WITH = "Starts With";
/** Constant for */
public static final String ENDS_WITH = "Ends With";
/** Constant for */
public static final String NOT_BETWEEN = "Not Between";
/** Constant for */
public static final String INVALID_CONDITION_VALUES = "InvalidValues";
/** Constant for */
public static final String SAVE_QUERY_PAGE = "Save Query Page";
/** Constant for */
public static final String EXECUTE_QUERY_PAGE = "Execute Query Page";
/** Constant for */
public static final String FETCH_QUERY_ACTION = "FetchQuery.do";
/** Constant for */
public static final String EXECUTE_QUERY_ACTION = "ExecuteQueryAction.do";
/** Constant for */
public static final String EXECUTE_QUERY = "executeQuery";
/** Constant for */
public static final String SHOPPING_CART_FILE_NAME = "MyList.csv";
/** Constant for */
public static final String APPLICATION_DOWNLOAD = "application/download";
/** Constant for */
public static final String DOT_CSV = ".csv";
/** Constant for */
public static final String HTML_CONTENTS = "HTMLContents";
/** Constant for */
public static final String INPUT_APPLET_DATA = "inputAppletData";
/** Constant for */
public static final String SHOW_ALL = "showall";
/** Constant for */
public static final String SHOW_ALL_ATTRIBUTE = "Show all attributes";
/** Constant for */
public static final String SHOW_SELECTED_ATTRIBUTE = "Show selected attributes";
/** Constant for */
public static final String ADD_EDIT_PAGE = "Add Edit Page";
/** Constant for */
public static final String IS_QUERY_SAVED = "isQuerySaved";
/** Constant for */
public static final String CONDITIONLIST = "conditionList";
/** Constant for */
public static final String QUERY_SAVED = "querySaved";
public static final String Query_Type="queryType";
/** Constant for */
public static final String DISPLAY_NAME_FOR_CONDITION = "_displayName";
/** Constant for */
public static final String SHOW_ALL_LINK = "showAllLink";
/** Constant for */
public static final String VIEW_ALL_RECORDS = "viewAllRecords";
/** Constant for */
public static final String POPUP_MESSAGE = "popupMessage";
/** Constant for */
public static final String ID_COLUMNS_MAP = "idColumnsMap";
/** Constant for */
public static final String TREE_NODE_ID = "nodeId";
/** Constant for */
public static final String HASHED_NODE_ID = "-1";
/** Constant for */
public static final String BUTTON_CLICKED = "buttonClicked";
/** Constant for */
public static final String UPDATE_SESSION_DATA = "updateSessionData";
/** Constant for */
public static final String EVENT_PARAMETERS_LIST = "eventParametersList";
/** Constant for */
public static final String VIEW = "view";
/** Constant for */
public static final String APPLET_SERVER_URL_PARAM_NAME = "serverURL";
/** Constant for */
public static final String TEMP_OUPUT_TREE_TABLE_NAME = "TEMP_OUTPUTTREE";
/** Constant for */
public static final String CREATE_TABLE = "Create table ";
/** Constant for */
public static final String AS = "as";
/** Constant for */
public static final String TREE_NODE_FONT = "<font color='#FF9BFF' face='Verdana'><i>";
/** Constant for */
public static final String TREE_NODE_FONT_CLOSE = "</i></font>";
/** Constant for */
public static final String ZERO_ID = "0";
/** Constant for */
public static final String NULL_ID = "NULL";
/** Constant for */
public static final String UNIQUE_ID_SEPARATOR = "UQ";
/** Constant for */
public static final String SELECT_DISTINCT = "select distinct ";
/** Constant for */
public static final String SELECT = "SELECT ";
/** Constant for */
public static final String FILE_TYPE = "file";
/** Constant for */
public static final String FROM = " from ";
/** Constant for */
public static final String WHERE = " where ";
/** Constant for */
public static final String LIKE = " LIKE ";
/** Constant for */
public static final String LEFT_JOIN = " LEFT JOIN ";
/** Constant for */
public static final String INNER_JOIN = " INNER JOIN ";
/** Constant for */
public static final String HASHED_OUT = "
/** Constant for */
public static final String DYNAMIC_UI_XML = "dynamicUI.xml";
/** Constant for */
public static final String DATE = "date";
/** Constant for */
public static final String DATE_FORMAT = "MM-dd-yyyy";
/** Constant for */
public static final String DEFINE_SEARCH_RULES = "Define Limits For";
/** Constant for */
public static final String CLASSES_PRESENT_IN_QUERY = "Objects Present In Query";
/** Constant for */
public static final String CLASS = "class";
/** Constant for */
public static final String ATTRIBUTE = "attribute";
/** Constant for */
public static final String FILE = "file";
/** Constant for */
public static final String MISSING_TWO_VALUES = "missingTwoValues";
/** Constant for */
public static final String METHOD_NAME = "method";
/** Constant for */
public static final String categorySearchForm = "categorySearchForm";
/** Constant for */
public static final int ADVANCE_QUERY_TABLES = 2;
/** Constant for */
public static final String DATE_TYPE = "Date";
/** Constant for */
public static final String INTEGER_TYPE = "Integer";
/** Constant for */
public static final String FLOAT_TYPE = "Float";
/** Constant for */
public static final String DOUBLE_TYPE = "Double";
/** Constant for */
public static final String LONG_TYPE = "Long";
/** Constant for */
public static final String SHORT_TYPE = "Short";
/** Constant for */
public static final String FIRST_NODE_ATTRIBUTES = "firstDropDown";
/** Constant for */
public static final String ARITHMETIC_OPERATORS = "secondDropDown";
/** Constant for */
public static final String SECOND_NODE_ATTRIBUTES = "thirdDropDown";
/** Constant for */
public static final String RELATIONAL_OPERATORS = "fourthDropDown";
/** Constant for */
public static final String TIME_INTERVALS_LIST = "timeIntervals";
/** Constant for */
public static final String ENTITY_LABEL_LIST = "entityList";
/** Constant for */
public static final String DefineSearchResultsViewAction = "/DefineSearchResultsView.do";
/** Constant for */
public static final Color BG_COLOR = new Color(0xf4f4f5);
// Dagviewapplet constants
/** Constant for */
public static final String QUERY_OBJECT = "queryObject";
/** Constant for */
public static final String SESSION_ID = "session_id";
/** Constant for */
public static final String STR_TO_CREATE_QUERY_OBJ = "strToCreateQueryObject";
/** Constant for */
public static final String ENTITY_NAME = "entityName";
/** Constant for */
public static final String INIT_DATA = "initData";
/** Constant for */
public static final String ATTRIBUTES = "Attributes";
/** Constant for */
public static final String ATTRIBUTE_OPERATORS = "AttributeOperators";
/** Constant for */
public static final String FIRST_ATTR_VALUES = "FirstAttributeValues";
/** Constant for */
public static final String SECOND_ATTR_VALUES = "SecondAttributeValues";
/** Constant for */
public static final String SHOW_ENTITY_INFO = "showEntityInformation";
/** Constant for */
public static final String SRC_ENTITY = "srcEntity";
/** Constant for */
public static final String PATHS = "paths";
/** Constant for */
public static final String DEST_ENTITY = "destEntity";
/** Constant for */
public static final String ERROR_MESSAGE = "errorMessage";
/** Constant for */
public static final String SHOW_VALIDATION_MESSAGES = "showValidationMessages";
/** Constant for */
public static final String SHOW_RESULTS_PAGE = "showViewSearchResultsJsp";
/** Constant for */
public static final String ATTR_VALUES = "AttributeValues";
/** Constant for */
public static final String SHOW_ERROR_PAGE = "showErrorPage";
/** Constant for */
public static final String GET_DATA = "getData";
/** Constant for */
public static final String SET_DATA = "setData";
/** Constant for */
public static final String EMPTY_LIMIT_ERROR_MESSAGE = "<font color='red'>Please enter at least one condition to add a limit to limit set.</font>";
/** Constant for */
public static final String EMPTY_DAG_ERROR_MESSAGE = "<font color='red'>Limit set should contain at least one limit.</font>";
/** Constant for */
public static final String MULTIPLE_ROOTS_EXCEPTION = "<font color='red'>Expression graph should be a connected graph.</font>";
/** Constant for */
public static final String EDIT_LIMITS = "<font color='blue'>Limit succesfully edited.</font>";
/** Constant for */
public static final String DELETE_LIMITS = "<font color='blue'>Limit succesfully deleted.</font>";
/** Constant for */
public static final String MAXIMUM_TREE_NODE_LIMIT = "resultView.maximumTreeNodeLimit";
//public static final String ATTRIBUTES = "Attributes";
/** Constant for */
public static final String SESSION_EXPIRY_WARNING_ADVANCE_TIME = "session.expiry.warning.advanceTime";
/** Constant for */
public static final String SearchCategory = "SearchCategory.do";
/** Constant for */
public static final String DefineSearchResultsViewJSPAction = "ViewSearchResultsJSPAction.do";
/** Constant for */
public static final String NAME = "name";
/** Constant for */
public static final String TREE_VIEW_FRAME = "treeViewFrame";
/** Constant for */
public static final String QUERY_TREE_VIEW_ACTION = "QueryTreeView.do";
/** Constant for */
public static final String QUERY_GRID_VIEW_ACTION = "QueryGridView.do";
/** Constant for */
public static final String GRID_DATA_VIEW_FRAME = "gridFrame";
/** Constant for */
public static final String PAGE_NUMBER = "pageNum";
/** Constant for */
public static final String TOTAL_RESULTS = "totalResults";
/** Constant for */
public static final String RESULTS_PER_PAGE = "numResultsPerPage";
/** Constant for */
public static final String SPREADSHEET_COLUMN_LIST = "spreadsheetColumnList";
/** Constant for */
public static final String PAGE_OF = "pageOf";
/** Constant for */
public static final String PAGE_OF_GET_DATA ="pageOfGetData";
/** Constant for */
public static final String PAGE_OF_GET_COUNT ="pageOfGetCount";
/** Constant for */
public static final String SPREADSHEET_EXPORT_ACTION = "SpreadsheetExport.do";
/** Constant for */
public static final int[] RESULT_PERPAGE_OPTIONS = {10, 50, 100, 500, 1000};
/** Constant for */
public static final String PAGE_OF_PARTICIPANT_CP_QUERY = "pageOfParticipantCPQuery";
/** Constant for */
public static final String CONFIGURE_GRID_VIEW_ACTION = "ConfigureGridView.do";
/** Constant for */
public static final String SAVE_QUERY_ACTION = "SaveQueryAction.do";
/** Constant for */
public static final int CHARACTERS_IN_ONE_LINE = 110;
/** Constant for */
public static final String SINGLE_QUOTE_ESCAPE_SEQUENCE = "`";
/** Constant for */
public static final String ViewSearchResultsAction = "ViewSearchResultsAction.do";
/** Constant for */
public static final String QUERY_IDENTIFIER_NOT_VALID = "Query identifier is not valid.";
/** Constant for */
public static final String NO_RESULT_FOUND = "No result found.";
/** Constant for */
public static final String QUERY_ID = "queryId";
/** Constant for */
public static final String QUERY_COLUMN_NAME = "Column";
/** Constant for */
public static final String QUERY_OPENING_PARENTHESIS = "(";
/** Constant for */
public static final String QUERY_CLOSING_PARENTHESIS = ")";
/** Constant for */
public static final String QUERY_DOT = ".";
/** Constant for */
public static final String QUERY_UNDERSCORE = "_";
/** Constant for */
public static final String QUERY_COMMA = " ,";
/** Constant for */
public static final String QUERY_EQUALS = " = ";
/** Constant for */
public static final String QUERY_FILE = "file";
/** Constant for */
public static final String STR_TO_DATE = "STR_TO_DATE";
/** Constant for */
public static final String QUERY_FROM_XMLTABLE = " from xmltable";
/** Constant for */
public static final String QUERY_FOR = " for ";
/** Constant for */
public static final String QUERY_LET = " let ";
/** Constant for */
public static final String QUERY_ORDER_BY = " order by ";
/** Constant for */
public static final String QUERY_RETURN = " return ";
/** Constant for */
public static final char QUERY_DOLLAR = '$';
/** Constant for */
public static final String QUERY_XMLCOLUMN = "db2-fn:xmlcolumn";
/** Constant for */
public static final String QUERY_XMLDATA = "XMLDATA";
/** Constant for */
public static final String QUERY_AND = " and ";
/** Constant for */
public static final String QUERY_TEMPORAL_CONDITION = "TEMPORAL_CONDITION";
/** Constant for */
public static final String TRUE = "true";
/** Constant for */
public static final String FALSE = "false";
/** Constant for */
public static final String Is_PAGING = "isPaging";
/** Constant for */
public static final String CONTENT_TYPE_TEXT = "text/html";
/**
*
* @param s
* @return
*/
public static final String getOracleTermString(String s)
{
return "day-from-dateTime(" + s + ") * 86400" + "hours-from-dateTime(" + s + ") * 3600"
+ "minutes-from-dateTime(" + s + ") * 60" + "seconds-from-dateTime(" + s + ")";
}
/**
*
* @param s
* @return the actual time in seconds
*/
public static final String getDB2TermString(String s)
{
return "extract(day from " + s + ")*86400 + extract(hour from " + s
+ ")*3600 + extract(minute from " + s + ")*60 + extract(second from " + s + ")";
}
public static final String VERSION = "VERSION";
//Constants related to Export functionality
/** Constant for */
public static final String SEARCH_RESULT = "SearchResult.csv";
/** Constant for */
public static final String ZIP_FILE_EXTENTION = ".zip";
/** Constant for */
public static final String CSV_FILE_EXTENTION = ".csv";
/** Constant for */
public static final String EXPORT_ZIP_NAME = "SearchResult.zip";
/** Constant for */
public static final String PRIMARY_KEY_TAG_NAME = "PRIMARY_KEY";
/** Constant for */
public static final String ID_COLUMN_NAME = "ID_COLUMN_NAME";
/** Constant for */
public static final String PRIMARY_KEY_ATTRIBUTE_SEPARATOR = "!~!~!";
//Taraben Khoiwala
/** Constant for */
public static final String PERMISSIBLEVALUEFILTER = "PV_FILTER";
/** Constant for */
public static final int ADVANCE_QUERY_INTERFACE_ID = 24;
/** Constant for */
public static final String PUBLIC_QUERY_PROTECTION_GROUP = "Public_Query_Protection_Group";
/** Constant for */
public static final String MY_QUERIES = "MyQueries";
public static final String SAHRED_QUERIES = "sharedQueries";
/** Constant for */
public static final String[] NUMBER = {"long", "double", "short", "integer", "float"};
/** Constant for */
public static final String NEWLINE = "\n";
/** Constant for */
public static final String DATATYPE_BOOLEAN = "boolean";
/** Constant for */
public static final String DATATYPE_NUMBER = "number";
/** Constant for */
public static final int MAX_PV_SIZE = 500;
/** Constant for */
public static final int MAX_SIZE = 500;
/** Constant for */
public static final int WORKFLOW_BIZLOGIC_ID = 101;
/** Constant for */
public static final String MY_QUERIES_FOR_WORKFLOW = "myQueriesForWorkFlow";
public static final String SAHRED_QUERIES_FOR_WORKFLOW = "sharedQueriesForWorkFlow";
public static final String MY_QUERIES_FOR_MAIN_MENU = "myQueriesForMainMenu";
public static final String SHARED_QUERIES_FOR_MAIN_MENU = "sharedQueriesForMainMenu";
/** Constant for */
public static final String PUBLIC_QUERIES_FOR_WORKFLOW = "publicQueryForWorkFlow";
/** Constant for */
public static final String DISPLAY_QUERIES_IN_POPUP = "displayQueriesInPopup";
/** Constant for */
public static final String PAGE_OF_MY_QUERIES = "MyQueries";
/** Constant for */
public static final int WORKFLOW_FORM_ID = 101;
/** Constant for */
public static final String ELEMENT_ENTITY_GROUP = "entity-group";
/** Constant for */
public static final String ELEMENT_ENTITY = "entity";
/** Constant for */
public static final String ELEMENT_NAME = "name";
/** Constant for */
public static final String ELEMENT_ATTRIBUTE = "attribute";
/** Constant for */
public static final String ELEMENT_TAG = "tag";
/** Constant for */
public static final String ELEMENT_TAG_NAME = "tag-name";
/** Constant for */
public static final String ELEMENT_TAG_VALUE = "tag-value";
/** Constant for */
public static final String TAGGED_VALUE_NOT_SEARCHABLE = "NOT_SEARCHABLE";
/** Constant for */
public static final String TAGGED_VALUE_NOT_VIEWABLE = "NOT_VIEWABLE";
/** Constant for */
public static final String VI_IGNORE_PREDICATE = "VI_IGNORE_PREDICATE";
/** Constant for default condition tagged value**/
public static final String TAGGED_VALUE_DEFAULT_CONDITION = "DEFAULT_CONDITION";
/** Constant for */
public static final String TAGGED_VALUE_PRIMARY_KEY = "PRIMARY_KEY";
/** Constant for */
public static final String TAGGED_VALUE_PV_FILTER = "PV_FILTER";
/** Constant for */
public static final String TAGGED_VALUE_VI_HIDDEN = "VI_HIDDEN";
/** Constant for */
public static final String CONTAINMENT_OBJECTS_MAP = "containmentObjectMap";
/** Constant for */
public static final String ENTITY_EXPRESSION_ID_MAP = "entityExpressionIdMap";
//added by amit_doshi
/** Constant for */
public static final String PV_TREE_VECTOR = "PermissibleValueTreeVector";
/** Constant for */
public static final String PROPERTIESFILENAME = "vocab.properties";
/** Constant for */
public static final int SEARCH_PV_FROM_VOCAB_BILOGIC_ID = 12;
/** Constant for */
public static final String ATTRIBUTE_INTERFACE = "AttributeInterface";
/** Constant for */
public static final String ENTITY_INTERFACE = "EntityInterface";
/** Constant for */
public static final String VOCABULIRES = "Vocabulries";
/** Constant for */
public static final String ENUMRATED_ATTRIBUTE = "EnumratedAttribute";
/** Constant for */
public static final String COMPONENT_ID = "componentId";
/** Constant for */
public static final String NO_RESULT = "No results found";
/** Constant for */
public static final String PV_HTML = "PVHTML";
/** Constant for */
public static final String DEFINE_VIEW_MSG = "DefineView";
/** Constant for */
public static final String ENTITY_NOT_PRESENT = "not present";
/** Constant for */
public static final String ENTITY_PRESENT = "present";
/** Constant for */
public static final String MAIN_ENTITY_MSG = "Main Entity";
/** Constant for */
public static final String NOT_PRESENT_MSG = " Is Not Present In DAG";
/** Constant for */
public static final String MAIN_ENTITY_LIST = "mainEntityList";
/** Constant for */
public static final String SELECTED_CONCEPT_LIST = "SELECTED_CONCEPT_LIST";
/** Constant for */
public static final String TAGGED_VALUE_MAIN_ENTIY = "MAIN_ENTITY";
/** Constant for */
public static final String BASE_MAIN_ENTITY = "BASE_MAIN_ENTITY";
/** Constant for */
public static final String QUERY_NO_ROOTEXPRESSION="query.noRootExpression.message";
/** Constant for */
public static final String ENTITY_LIST = "entityList";
/** Constant for */
public static final String MAIN_ENTITY_EXPRESSIONS_MAP = "mainEntityExpressionsMap";
/** Constant for */
public static final String MAIN_EXPRESSION_TO_ADD_CONTAINMENTS = "expressionsToAddContainments";
/** Constant for */
public static final String ALL_ADD_LIMIT_EXPRESSIONS = "allLimitExpressionIds";
/** Constant for */
public static final String MAIN_EXPRESSIONS_ENTITY_EXP_ID_MAP = "mainExpEntityExpressionIdMap";
/** Constant for */
public static final String MAIN_ENTITY_ID= "entityId";
/** Constant for */
public static final String XML_FILE_NAME = "fileName";
public static final String PERMISSIBLEVALUEVIEW = "PV_VIEW";
public static final String VI_INFO_MESSAGE1 = "This entity contains more than ";
public static final String VI_INFO_MESSAGE2 = " Permissible values.Please search for the specific term ";
//Start : Added for changes in Query Design for CIDER Query
public static final String PROJECT_ID = "projectId";
//End : Added for changes in Query Design for CIDER Query
/** Constant for Advanced Query 'JNDI' name **/
public static final String JNDI_NAME_QUERY = "java:/query";
/** Constant for CIDER 'JNDI' name **/
public static final String JNDI_NAME_CIDER = "java:/cider";
// CONSTANTS for columns in table 'QUERY_EXECUTION_LOG'
/** Constant for CREATIONTIME **/
public static final String CREATIONTIME = "CREATIONTIME";
/** Constant for USER_ID **/
public static final String USER_ID = "USER_ID";
/** Constant for STATUS **/
public static final String QUERY_STATUS = "QUERY_STATUS";
/** Constant for PROJECT_ID **/
public static final String PRJCT_ID = "PROJECT_ID";
/** Constant for QUERY_EXECUTION_ID **/
public static final String QUERY_EXECUTION_ID = "QUERY_EXECUTION_ID";
/** Constant for QUERY_EXECUTION_ID **/
public static final String COUNT_QUERY_EXECUTION_ID = "COUNT_QUERY_EXECUTION_ID";
public static final String COUNT_QUERY_UPI = "UPI";
public static final String COUNT_QUERY_DOB = "DATE_OF_BIRTH";
/** Constant for QUERY_EXECUTION_ID **/
public static final String DATA_QUERY_EXECUTION_ID = "DATA_QUERY_EXECUTION_ID";
/** Constant for QUERY_ID **/
public static final String QRY_ID = "QUERY_ID";
/** Constant for GENERATING_QUERY **/
public static final String GENERATING_QUERY = "Generating Query";
/** Constant for QUERY_IN_PROGRESS **/
public static final String QUERY_IN_PROGRESS = "In Progress";
/** Constant for QUERY_COMPLETED **/
public static final String QUERY_COMPLETED = "Completed";
/** Constant for QUERY_CANCELLED **/
public static final String QUERY_CANCELLED = "Cancelled";
/** Constant for XQUERY_FAILED **/
public static final String QUERY_FAILED = "Query Failed";
/** Constant for separator used in tag values for default conditions **/
public static final String DEFAULT_CONDITIONS_SEPARATOR="!=!";
/** Constant for default conditions current date **/
public static final String DEFAULT_CONDITION_CURRENT_DATE="CURRENT_DATE";
/** Constant for default conditions facility id **/
public static final String DEFAULT_CONDITION_FACILITY_ID="FACILITY_ID";
/** Constant for default conditions project rule research opt out **/
public static final String DEFAULT_CONDITION_RULES_OPT_OUT="RULES_OPT_OUT";
/** Constant for default conditions project rule minors **/
public static final String DEFAULT_CONDITION_RULES_MINOR="RULES_MINOR";
/** Constant for secure condition for Age **/
public static final String SECURE_CONDITION_AGE="AGE";
/** Constant for space **/
public static final String SPACE=" ";
public static final String SHOW_LAST = "showLast";
public static final String EXECUTION_LOG_ID = "executionLogId";
public static final int SHOW_LAST_COUNT = 25;
public static final String TOTAL_PAGES = "totalPages";
public static final String RESULTS_PER_PAGE_OPTIONS = "resultsPerPageOptions";
public static final String RECENT_QUERIES_BEAN_LIST = "recentQueriesBeanList";
public static final int PER_PAGE_RESULTS = 10;
public static final String RESULT_OBJECT = "resultObject";
public static final String QUERY_COUNT = "queryCount";
public static final String GET_COUNT_STATUS = "status";
public static final String EXECUTION_ID = "executionId";
public static final String QUERY_TYPE_GET_COUNT="GetCount";
public static final String QUERY_TYPE_GET_DATA="GetData";
public static final int[] SHOW_LAST_OPTION = {25, 50, 100, 200};
//Constants for Get Count
/** Constant for abortExecution*/
public static final String ABORT_EXECUTION="abortExecution";
/** Constant for query_exec_id*/
public static final String QUERY_EXEC_ID="query_exec_id";
/** Constant for isNewQuery*/
public static final String IS_NEW_QUERY="isNewQuery";
/** Constant for selectedProject */
public static final String SELECTED_PROJECT="selectedProject";
/** Constant for Query Exception */
public static final String QUERY_EXCEPTION="queryException";
/** Constant for Wait */
public static final String WAIT="wait";
/** Constant for Query Title */
public static final String QUERY_TITLE="queryTitle";
public static final String MY_QUERIESFOR_DASHBOARD = "myQueriesforDashboard";
public static final String WORKFLOW_NAME = "worflowName";
public static final String WORKFLOW_ID = "worflowId";
public static final String IS_WORKFLOW="isWorkflow";
public static final String PAGE_OF_WORKFLOW="workflow";
public static final String FORWARD_TO_HASHMAP = "forwardToHashMap";
public static final String NEXT_PAGE_OF = "nextPageOf";
public static final String QUERYWIZARD = "queryWizard";
public static final String DATA_QUERY_ID = "dataQueryId ";
public static final String COUNT_QUERY_ID = "countQueryId ";
public static final String PROJECT_NAME_VALUE_BEAN = "projectsNameValueBeanList";
/** Constant for WORFLOW_ID */
public static final String WORFLOW_ID = "workflowId";
/** Constant for WORFLOW_NAME */
public static final String WORFLOW_NAME = "worflowName";
/** constants for VI*/
public static final String SRC_VOCAB_MESSAGE = "SourceVocabMessage";
public static final Object ABORT = "abort";
public static final String SELECTED_BOX = "selectedCheckBox";
public static final String OPERATION = "operation";
public static final String SEARCH_TERM = "searchTerm";
public static final String MED_MAPPED_N_VALID_PVCONCEPT = "Normal_Bold_Enabled";
public static final String MED_MAPPED_N_NOT_VALIED_PVCONCEPT = "Bold_Italic_Disabled";
public static final String NOT_MED_MAPPED_PVCONCEPT = "Normal_Italic_Disabled";
public static final String NOT_MED_VALED_PVCONCEPT = "Normal_Disabled";
public static final String ID_DEL = "ID_DEL";
public static final String MSG_DEL = "@MSG@"; // if you change its value,kindly change in queryModule.js its hard coded there
public static final String NOT_AVAILABLE = "Not Available";
/**
* Query ITABLE
*/
public static final String ITABLE = "QUERY_ITABLE";
/**
* COUNT QUERY EXECUTION LOG TABLE
*/
public static final String COUNT_QUERY_EXECUTION_LOG = "COUNT_QUERY_EXECUTION_LOG";
/**
* DATA QUERY EXECUTION LOG TABLE
*/
public static final String DATA_QUERY_EXECUTION_LOG = "DATA_QUERY_EXECUTION_LOG";
/**
* QUERY EXECUTION LOG TABLE
*/
public static final String QUERY_EXECUTION_LOG = "QUERY_EXECUTION_LOG";
/**
* QUERY SECURITY LOG TABLE
*/
public static final String QUERY_SECURITY_LOG = "QUERY_SECURITY_LOG";
/** Constant for DATE_OF_BIRTH **/
public static final String DATE_OF_BIRTH = "DATE_OF_BIRTH";
/** Constant for VIEW_FLAG **/
public static final String VIEW_FLAG = "VIEW_FLAG";
/** Constant for XQUERY_STRING **/
public static final String XQUERY_STRING = "XQUERY_STRING";
/** Constant for QUERY_TYPE **/
public static final String QUERY_TYPE = "QUERY_TYPE";
/** Constant for IP_ADDRESS **/
public static final String IP_ADDRESS = "IP_ADDRESS";
/** Constant for QUERY_COUNT **/
public static final String QRY_COUNT = "QUERY_COUNT";
/** Constant for DEID_SEQUENCE **/
public static final String DEID_SEQUENCE = "DEID_SEQUENCE";
/** Constant for ITABLE_ATTRIBUTES**/
public static final String TAGGED_VALUE_ITABLE_ATTRIBUTES = "ITABLE_ATTRIBUTES";
/** Constant for SECURE CONDITION **/
public static final String TAGGED_VALUE_SECURE_CONDITION = "SECURE_CONDITION";
public static final int AGE = 89;
public static final int MINOR = 18;
/**
* constant for PATIENT_DATA_QUERY
*/
public static final String PATIENT_DATA_QUERY = "patientDataQuery";
public static final String PATIENT_QUERY_ROOT_OUT_PUT_NODE_LIST = "patientDataRootOutPutList";
public static final String PATIENT_QUERY_UNIQUE_ID_MAP = "uniqueIDNodeMap";
/** Constant for Equal to operator */
public static final String EQUALS = " = ";
/** Constant for... */
public static final String EXECUTION_ID_OF_QUERY = "queryExecutionId";
/** Constant for AbstractQuery */
public static final String ABSTRACT_QUERY = "abstractQuery";
} |
package org.avmframework;
import org.avmframework.variable.Variable;
import java.util.ArrayList;
import java.util.List;
public abstract class AbstractVector {
protected List<Variable> variables = new ArrayList<>();
public Variable getVariable(int index) {
return variables.get(index);
}
public int size() {
return variables.size();
}
protected void deepCopyVariables(AbstractVector copy) {
copy.variables.clear();
for (Variable var : variables) {
copy.variables.add(var.deepCopy());
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof AbstractVector)) return false;
AbstractVector that = (AbstractVector) o;
return variables != null ? variables.equals(that.variables) : that.variables == null;
}
@Override
public int hashCode() {
return variables != null ? variables.hashCode() : 0;
}
@Override
public String toString() {
boolean first = true;
String out = "[";
for (Variable var : variables) {
if (first) {
first = false;
} else {
out += ", ";
}
out += var;
}
out += "]";
return out;
}
} |
package org.baswell.routes;
import static org.baswell.routes.utils.RoutesMethods.*;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.baswell.routes.criteria.RouteCriteria;
import org.baswell.routes.criteria.RouteCriteriaBuilder;
import org.baswell.routes.invoking.RouteMethodParameter;
import org.baswell.routes.invoking.RouteMethodParametersBuilder;
import org.baswell.routes.parsing.RouteParser;
import org.baswell.routes.parsing.RouteTree;
import org.baswell.routes.response.RouteResponseType;
import org.baswell.routes.response.RouteResponseTypeMapper;
public class RoutingTable
{
public static RoutingTable routingTable;
final RoutesConfig routesConfig;
private Map<String, Pattern> symbolToPatterns = new HashMap<String, Pattern>();
private List<Object> addedObjects = new ArrayList<Object>();
private List<RouteNode> routeNodes;
public RoutingTable()
{
this(new RoutesConfig());
}
public RoutingTable(RoutesConfig routesConfig)
{
this.routesConfig = routesConfig == null ? new RoutesConfig() : routesConfig;
RoutingTable.routingTable = this;
}
public RoutingTable defineSymbol(String symbol, Class clazz) throws InvalidPatternException
{
if (typesToPatterns.containsKey(clazz))
{
return defineSymbol(symbol, typesToPatterns.get(clazz));
}
else
{
throw new InvalidPatternException("Invalid pattern class: " + clazz);
}
}
public RoutingTable defineSymbol(String symbol, String pattern) throws InvalidPatternException
{
try
{
symbolToPatterns.put(symbol, Pattern.compile(pattern));
return this;
}
catch (PatternSyntaxException e)
{
throw new InvalidPatternException("Invalid pattern: " + pattern);
}
}
public List<RouteNode> getRouteNodes()
{
return new ArrayList<RouteNode>(routeNodes);
}
public RoutingTable add(Object... instancesOrClasses)
{
for (Object obj : instancesOrClasses) addedObjects.add(obj);
return this;
}
public void build() throws InvalidRouteException
{
RouteParser parser = new RouteParser();
RouteCriteriaBuilder criteriaBuilder = new RouteCriteriaBuilder();
RouteMethodParametersBuilder parametersBuilder = new RouteMethodParametersBuilder();
RouteResponseTypeMapper returnTypeMapper = new RouteResponseTypeMapper();
routeNodes = new ArrayList<RouteNode>();
for (Object addedObject : addedObjects)
{
boolean instanceIsClass = (addedObject instanceof Class);
Class routesClass = instanceIsClass ? (Class) addedObject : addedObject.getClass();
List<BeforeRouteNode> classBeforeNodes = getBeforeRouteNodes(routesClass);
List<AfterRouteNode> classAfterNodes = getAfterRouteNodes(routesClass);
Routes routesAnnotation = (Routes) routesClass.getAnnotation(Routes.class);
int numRoutesPaths;
boolean routeUnannotatedPublicMethods;
if (routesAnnotation == null)
{
numRoutesPaths = 1;
routeUnannotatedPublicMethods = routesConfig.routeUnannoatedPublicMethods;
}
else
{
numRoutesPaths = Math.max(1, routesAnnotation.value().length);
routeUnannotatedPublicMethods = routesAnnotation.routeUnannoatedPublicMethods().length == 0 ? routesConfig.routeUnannoatedPublicMethods : routesAnnotation.routeUnannoatedPublicMethods()[0];
}
List<RouteNode> classRoutes = new ArrayList<RouteNode>();
for (Method method : routesClass.getMethods())
{
if (isMain(method)) continue;
Route routeAnnotation = method.getAnnotation(Route.class);
if ((routeAnnotation != null) || (routeUnannotatedPublicMethods && Modifier.isPublic(method.getModifiers()) && (method.getDeclaringClass() == routesClass)))
{
for (int i = 0; i < numRoutesPaths; i++)
{
RouteConfig routeConfig = new RouteConfig(method, routesConfig, routesAnnotation, routeAnnotation, i);
RouteTree tree = parser.parse(routeConfig.route);
RouteInstance routeInstance = instanceIsClass ? new RouteInstance(routesClass, routesConfig.routeInstanceFactory) : new RouteInstance(addedObject);
RouteCriteria criteria = criteriaBuilder.buildCriteria(method, tree, symbolToPatterns, routeConfig, routesConfig);
List<RouteMethodParameter> parameters = parametersBuilder.buildParameters(method, tree);
RouteResponseType responseType = returnTypeMapper.mapResponseType(method, routeConfig);
List<BeforeRouteNode> beforeNodes = new ArrayList<BeforeRouteNode>();
for (BeforeRouteNode beforeNode : classBeforeNodes)
{
if ((beforeNode.onlyTags.isEmpty() || containsOne(beforeNode.onlyTags, routeConfig.tags)) && (beforeNode.exceptTags.isEmpty() || !containsOne(beforeNode.exceptTags, routeConfig.tags)))
{
beforeNodes.add(beforeNode);
}
}
List<AfterRouteNode> afterNodes = new ArrayList<AfterRouteNode>();
for (AfterRouteNode afterNode : classAfterNodes)
{
if ((afterNode.onlyTags.isEmpty() || containsOne(afterNode.onlyTags, routeConfig.tags)) && (afterNode.exceptTags.isEmpty() || !containsOne(afterNode.exceptTags, routeConfig.tags)))
{
afterNodes.add(afterNode);
}
}
classRoutes.add(new RouteNode(routeNodes.size(), method, routeConfig, routeInstance, criteria, parameters, responseType, beforeNodes, afterNodes));
}
}
}
if (!classRoutes.isEmpty())
{
routeNodes.addAll(classRoutes);
}
else
{
throw new InvalidRouteException("Route class: " + routesClass + " has no routes.");
}
}
Collections.sort(routeNodes);
}
RouteNode find(RequestPath path, RequestParameters parameters, HttpMethod httpMethod, Format format)
{
for (RouteNode routeNode : routeNodes)
{
if (routeNode.criteria.matches(httpMethod, format, path, parameters))
{
return routeNode;
}
}
return null;
}
static List<BeforeRouteNode> getBeforeRouteNodes(Class clazz) throws InvalidRoutesMethodDeclaration
{
List<BeforeRouteNode> nodes = new ArrayList<BeforeRouteNode>();
for (Method method : clazz.getMethods())
{
BeforeRoute beforeRoute = method.getAnnotation(BeforeRoute.class);
if (beforeRoute != null)
{
Class returnType = method.getReturnType();
if ((returnType == boolean.class) || (returnType == Boolean.class) || (returnType == void.class))
{
boolean returnsBoolean = returnType != void.class;
List<RouteMethodParameter> routeParameters = new RouteMethodParametersBuilder().buildParameters(method);
Integer order = beforeRoute.order().length == 0 ? null : beforeRoute.order()[0];
nodes.add(new BeforeRouteNode(method, routeParameters, returnsBoolean, new HashSet<String>(Arrays.asList(beforeRoute.onlyTags())), new HashSet<String>(Arrays.asList(beforeRoute.exceptTags())), order));
}
else
{
throw new InvalidRoutesMethodDeclaration("Before method: " + method + " must have return type of boolean or void.");
}
}
}
Collections.sort(nodes);
return nodes;
}
static List<AfterRouteNode> getAfterRouteNodes(Class clazz) throws InvalidRoutesMethodDeclaration
{
List<AfterRouteNode> nodes = new ArrayList<AfterRouteNode>();
for (Method method : clazz.getMethods())
{
AfterRoute afterRoute = method.getAnnotation(AfterRoute.class);
if (afterRoute != null)
{
Class returnType = method.getReturnType();
if (returnType == void.class)
{
List<RouteMethodParameter> routeParameters = new RouteMethodParametersBuilder().buildParameters(method);
Integer order = afterRoute.order().length == 0 ? null : afterRoute.order()[0];
nodes.add(new AfterRouteNode(method, routeParameters, new HashSet<String>(Arrays.asList(afterRoute.onlyTags())), new HashSet<String>(Arrays.asList(afterRoute.exceptTags())), order));
}
else
{
throw new InvalidRoutesMethodDeclaration("After method: " + method + " must have void return type.");
}
}
}
Collections.sort(nodes);
return nodes;
}
static boolean containsOne(Set<String> set, Set<String> contains)
{
for (String string : contains)
{
if (set.contains(string)) return true;
}
return false;
}
static boolean isMain(Method method)
{
if (method.getName().equals("main") && Modifier.isPublic(method.getModifiers()) && Modifier.isStatic(method.getModifiers()))
{
if (method.getReturnType() == void.class)
{
Class[] parameters = method.getParameterTypes();
return (parameters.length == 1) && (parameters[0] == String[].class);
}
else
{
return false;
}
}
else
{
return false;
}
}
} |
package net.runelite.api;
/**
* Utility class used for mapping animation IDs.
* <p>
* Note: This class is not complete and may not contain a specific animation
* required.
*/
public final class AnimationID
{
public static final int IDLE = -1;
public static final int HERBLORE_PESTLE_AND_MORTAR = 364;
public static final int WOODCUTTING_BRONZE = 879;
public static final int WOODCUTTING_IRON = 877;
public static final int WOODCUTTING_STEEL = 875;
public static final int WOODCUTTING_BLACK = 873;
public static final int WOODCUTTING_MITHRIL = 871;
public static final int WOODCUTTING_ADAMANT = 869;
public static final int WOODCUTTING_RUNE = 867;
public static final int WOODCUTTING_GILDED = 8303;
public static final int WOODCUTTING_DRAGON = 2846;
public static final int WOODCUTTING_DRAGON_OR = 24;
public static final int WOODCUTTING_INFERNAL = 2117;
public static final int WOODCUTTING_3A_AXE = 7264;
public static final int WOODCUTTING_CRYSTAL = 8324;
public static final int WOODCUTTING_TRAILBLAZER = 8778; // Same animation as Infernal axe (or)
public static final int CONSUMING = 829; // consuming consumables
public static final int FIREMAKING = 733;
public static final int DEATH = 836;
public static final int COOKING_FIRE = 897;
public static final int COOKING_RANGE = 896;
public static final int COOKING_WINE = 7529;
public static final int FLETCHING_BOW_CUTTING = 1248;
public static final int HUNTER_LAY_BOXTRAP_BIRDSNARE = 5208; //same for laying bird snares and box traps
public static final int HUNTER_LAY_DEADFALLTRAP = 5212; //setting up deadfall trap
public static final int HUNTER_LAY_NETTRAP = 5215; //setting up net trap
public static final int HUNTER_LAY_MANIACAL_MONKEY_BOULDER_TRAP = 7259; // setting up maniacal monkey boulder trap
public static final int HUNTER_CHECK_BIRD_SNARE = 5207;
public static final int HUNTER_CHECK_BOX_TRAP = 5212;
public static final int HERBLORE_MAKE_TAR = 5249;
public static final int FLETCHING_STRING_NORMAL_SHORTBOW = 6678;
public static final int FLETCHING_STRING_NORMAL_LONGBOW = 6684;
public static final int FLETCHING_STRING_OAK_SHORTBOW = 6679;
public static final int FLETCHING_STRING_OAK_LONGBOW = 6685;
public static final int FLETCHING_STRING_WILLOW_SHORTBOW = 6680;
public static final int FLETCHING_STRING_WILLOW_LONGBOW = 6686;
public static final int FLETCHING_STRING_MAPLE_SHORTBOW = 6681;
public static final int FLETCHING_STRING_MAPLE_LONGBOW = 6687;
public static final int FLETCHING_STRING_YEW_SHORTBOW = 6682;
public static final int FLETCHING_STRING_YEW_LONGBOW = 6688;
public static final int FLETCHING_STRING_MAGIC_SHORTBOW = 6683;
public static final int FLETCHING_STRING_MAGIC_LONGBOW = 6689;
public static final int FLETCHING_ATTACH_BOLT_TIPS_TO_BRONZE_BOLT = 8472;
public static final int FLETCHING_ATTACH_BOLT_TIPS_TO_IRON_BROAD_BOLT = 8473;
public static final int FLETCHING_ATTACH_BOLT_TIPS_TO_BLURITE_BOLT = 8474;
public static final int FLETCHING_ATTACH_BOLT_TIPS_TO_STEEL_BOLT = 8475;
public static final int FLETCHING_ATTACH_BOLT_TIPS_TO_MITHRIL_BOLT = 8476;
public static final int FLETCHING_ATTACH_BOLT_TIPS_TO_ADAMANT_BOLT = 8477;
public static final int FLETCHING_ATTACH_BOLT_TIPS_TO_RUNE_BOLT = 8478;
public static final int FLETCHING_ATTACH_BOLT_TIPS_TO_DRAGON_BOLT = 8479;
public static final int FLETCHING_ATTACH_HEADS = 8480;
public static final int FLETCHING_ATTACH_FEATHERS_TO_ARROWSHAFT = 8481;
public static final int GEM_CUTTING_OPAL = 890;
public static final int GEM_CUTTING_JADE = 891;
public static final int GEM_CUTTING_REDTOPAZ = 892;
public static final int GEM_CUTTING_SAPPHIRE = 888;
public static final int GEM_CUTTING_EMERALD = 889;
public static final int GEM_CUTTING_RUBY = 887;
public static final int GEM_CUTTING_DIAMOND = 886;
public static final int GEM_CUTTING_AMETHYST = 6295;
public static final int CRAFTING_LEATHER = 1249;
public static final int CRAFTING_GLASSBLOWING = 884;
public static final int CRAFTING_SPINNING = 894;
public static final int CRAFTING_POTTERS_WHEEL = 883;
public static final int CRAFTING_POTTERY_OVEN = 24975;
public static final int CRAFTING_LOOM = 2270;
public static final int SMITHING_SMELTING = 899;
public static final int SMITHING_CANNONBALL = 827; //cball smithing uses this and SMITHING_SMELTING
public static final int SMITHING_ANVIL = 898;
public static final int SMITHING_IMCANDO_HAMMER = 8911;
public static final int FISHING_BIG_NET = 620;
public static final int FISHING_NET = 621;
public static final int FISHING_POLE_CAST = 623; // pole is in the water
public static final int FISHING_CAGE = 619;
public static final int FISHING_HARPOON = 618;
public static final int FISHING_BARBTAIL_HARPOON = 5108;
public static final int FISHING_DRAGON_HARPOON = 7401;
public static final int FISHING_DRAGON_HARPOON_OR = 88;
public static final int FISHING_INFERNAL_HARPOON = 7402;
public static final int FISHING_CRYSTAL_HARPOON = 8336;
public static final int FISHING_TRAILBLAZER_HARPOON = 8784; // Same animation as Infernal harpoon (or)
public static final int FISHING_OILY_ROD = 622;
public static final int FISHING_KARAMBWAN = 1193;
public static final int FISHING_CRUSHING_INFERNAL_EELS = 7553;
public static final int FISHING_CUTTING_SACRED_EELS = 7151;
public static final int FISHING_BAREHAND = 6709;
public static final int FISHING_BAREHAND_WINDUP_1 = 6703;
public static final int FISHING_BAREHAND_WINDUP_2 = 6704;
public static final int FISHING_BAREHAND_CAUGHT_SHARK_1 = 6705;
public static final int FISHING_BAREHAND_CAUGHT_SHARK_2 = 6706;
public static final int FISHING_BAREHAND_CAUGHT_SWORDFISH_1 = 6707;
public static final int FISHING_BAREHAND_CAUGHT_SWORDFISH_2 = 6708;
public static final int FISHING_BAREHAND_CAUGHT_TUNA_1 = 6710;
public static final int FISHING_BAREHAND_CAUGHT_TUNA_2 = 6711;
public static final int FISHING_PEARL_ROD = 8188;
public static final int FISHING_PEARL_FLY_ROD = 8189;
public static final int FISHING_PEARL_BARBARIAN_ROD = 8190;
public static final int FISHING_PEARL_ROD_2 = 8191;
public static final int FISHING_PEARL_FLY_ROD_2 = 8192;
public static final int FISHING_PEARL_BARBARIAN_ROD_2 = 8193;
public static final int FISHING_PEARL_OILY_ROD = 6932;
public static final int MINING_BRONZE_PICKAXE = 625;
public static final int MINING_IRON_PICKAXE = 626;
public static final int MINING_STEEL_PICKAXE = 627;
public static final int MINING_BLACK_PICKAXE = 3873;
public static final int MINING_MITHRIL_PICKAXE = 629;
public static final int MINING_ADAMANT_PICKAXE = 628;
public static final int MINING_RUNE_PICKAXE = 624;
public static final int MINING_GILDED_PICKAXE = 8313;
public static final int MINING_DRAGON_PICKAXE = 7139;
public static final int MINING_DRAGON_PICKAXE_UPGRADED = 642;
public static final int MINING_DRAGON_PICKAXE_OR = 8346;
public static final int MINING_DRAGON_PICKAXE_OR_TRAILBLAZER = 8887;
public static final int MINING_INFERNAL_PICKAXE = 4482;
public static final int MINING_3A_PICKAXE = 7283;
public static final int MINING_CRYSTAL_PICKAXE = 8347;
public static final int MINING_TRAILBLAZER_PICKAXE = 8787; // Same animation as Infernal pickaxe (or)
public static final int MINING_TRAILBLAZER_PICKAXE_2 = 8788;
public static final int MINING_TRAILBLAZER_PICKAXE_3 = 8789;
public static final int MINING_MOTHERLODE_BRONZE = 6753;
public static final int MINING_MOTHERLODE_IRON = 6754;
public static final int MINING_MOTHERLODE_STEEL = 6755;
public static final int MINING_MOTHERLODE_BLACK = 3866;
public static final int MINING_MOTHERLODE_MITHRIL = 6757;
public static final int MINING_MOTHERLODE_ADAMANT = 6756;
public static final int MINING_MOTHERLODE_RUNE = 6752;
public static final int MINING_MOTHERLODE_GILDED = 8312;
public static final int MINING_MOTHERLODE_DRAGON = 6758;
public static final int MINING_MOTHERLODE_DRAGON_UPGRADED = 335;
public static final int MINING_MOTHERLODE_DRAGON_OR = 8344;
public static final int MINING_MOTHERLODE_DRAGON_OR_TRAILBLAZER = 8886;
public static final int MINING_MOTHERLODE_INFERNAL = 4481;
public static final int MINING_MOTHERLODE_3A = 7282;
public static final int MINING_MOTHERLODE_CRYSTAL = 8345;
public static final int MINING_MOTHERLODE_TRAILBLAZER = 8786; // Same animation as Infernal pickaxe (or)
public static final int DENSE_ESSENCE_CHIPPING = 7201;
public static final int DENSE_ESSENCE_CHISELING = 7202;
public static final int HERBLORE_POTIONMAKING = 363; //used for both herb and secondary
public static final int MAGIC_CHARGING_ORBS = 726;
public static final int MAGIC_MAKE_TABLET = 4068;
public static final int MAGIC_ENCHANTING_JEWELRY = 931;
public static final int MAGIC_ENCHANTING_AMULET_1 = 719; // sapphire, opal, diamond
public static final int MAGIC_ENCHANTING_AMULET_2 = 720; // emerald, jade, dragonstone
public static final int MAGIC_ENCHANTING_AMULET_3 = 721; // ruby, topaz, onyx, zenyte
public static final int MAGIC_ENCHANTING_BOLTS = 4462;
public static final int BURYING_BONES = 827;
public static final int USING_GILDED_ALTAR = 3705;
public static final int LOOKING_INTO = 832;
public static final int DIG = 830;
public static final int DEMONIC_GORILLA_MAGIC_ATTACK = 7225;
public static final int DEMONIC_GORILLA_MELEE_ATTACK = 7226;
public static final int DEMONIC_GORILLA_RANGED_ATTACK = 7227;
public static final int DEMONIC_GORILLA_AOE_ATTACK = 7228;
public static final int DEMONIC_GORILLA_PRAYER_SWITCH = 7228;
public static final int DEMONIC_GORILLA_DEFEND = 7224;
public static final int BOOK_HOME_TELEPORT_1 = 4847;
public static final int BOOK_HOME_TELEPORT_2 = 4850;
public static final int BOOK_HOME_TELEPORT_3 = 4853;
public static final int BOOK_HOME_TELEPORT_4 = 4855;
public static final int BOOK_HOME_TELEPORT_5 = 4857;
public static final int COW_HOME_TELEPORT_1 = 1696;
public static final int COW_HOME_TELEPORT_2 = 1697;
public static final int COW_HOME_TELEPORT_3 = 1698;
public static final int COW_HOME_TELEPORT_4 = 1699;
public static final int COW_HOME_TELEPORT_5 = 1700;
public static final int COW_HOME_TELEPORT_6 = 1701;
public static final int LEAGUE_HOME_TELEPORT_1 = 8798;
public static final int LEAGUE_HOME_TELEPORT_2 = 8799;
public static final int LEAGUE_HOME_TELEPORT_3 = 8801;
public static final int LEAGUE_HOME_TELEPORT_4 = 8803;
public static final int LEAGUE_HOME_TELEPORT_5 = 8805;
public static final int LEAGUE_HOME_TELEPORT_6 = 8807;
public static final int CONSTRUCTION = 3676;
public static final int CONSTRUCTION_IMCANDO = 8912;
public static final int SAND_COLLECTION = 895;
public static final int PISCARILIUS_CRANE_REPAIR = 7199;
public static final int HOME_MAKE_TABLET = 4067;
public static final int DRAGONFIRE_SHIELD_SPECIAL = 6696;
// Ectofuntus animations
public static final int ECTOFUNTUS_FILL_SLIME_BUCKET = 4471;
public static final int ECTOFUNTUS_GRIND_BONES = 1648;
public static final int ECTOFUNTUS_INSERT_BONES = 1649;
public static final int ECTOFUNTUS_EMPTY_BIN = 1650;
// NPC animations
public static final int TZTOK_JAD_MAGIC_ATTACK = 2656;
public static final int TZTOK_JAD_RANGE_ATTACK = 2652;
public static final int HELLHOUND_DEFENCE = 6566;
// Farming
public static final int FARMING_HARVEST_FRUIT_TREE = 2280;
public static final int FARMING_HARVEST_BUSH = 2281;
public static final int FARMING_HARVEST_HERB = 2282;
public static final int FARMING_USE_COMPOST = 2283;
public static final int FARMING_CURE_WITH_POTION = 2288;
public static final int FARMING_PLANT_SEED = 2291;
public static final int FARMING_HARVEST_FLOWER = 2292;
public static final int FARMING_MIX_ULTRACOMPOST = 7699;
public static final int FARMING_HARVEST_ALLOTMENT = 830;
// Lunar spellbook
public static final int ENERGY_TRANSFER_VENGEANCE_OTHER = 4411;
public static final int MAGIC_LUNAR_SHARED = 4413; // Utilized by Fertile Soil, Boost/Stat Potion Share, NPC Contact, Bake Pie
public static final int MAGIC_LUNAR_CURE_PLANT = 4432;
public static final int MAGIC_LUNAR_GEOMANCY = 7118;
public static final int MAGIC_LUNAR_PLANK_MAKE = 6298;
public static final int MAGIC_LUNAR_STRING_JEWELRY = 4412;
// Arceuus spellbook
public static final int MAGIC_ARCEUUS_RESURRECT_CROPS = 7118;
// Battlestaff Crafting
public static final int CRAFTING_BATTLESTAVES = 7531;
// Death Animations
public static final int CAVE_KRAKEN_DEATH = 3993;
public static final int WIZARD_DEATH = 2553;
public static final int GARGOYLE_DEATH = 1520;
public static final int MARBLE_GARGOYLE_DEATH = 7813;
public static final int LIZARD_DEATH = 2778;
public static final int ROCKSLUG_DEATH = 1568;
public static final int ZYGOMITE_DEATH = 3327;
public static final int IMP_DEATH = 172;
// POH Animations
public static final int INCENSE_BURNER = 3687;
} |
package com.cesarferreira.rxpaper;
import android.content.Context;
import android.text.TextUtils;
import com.cesarferreira.rxpaper.exceptions.UnableToPerformOperationException;
import io.paperdb.Paper;
import rx.Observable;
import rx.Subscriber;
public class RxPaper {
private Context mContext;
private static RxPaper mRxPaper;
private static String mCustomBook;
public static RxPaper with(Context context) {
return init(context, "");
}
public static RxPaper with(Context context, String customBook) {
return init(context, customBook);
}
private static RxPaper init(Context context, String customBook) {
mRxPaper = new RxPaper(context, customBook);
Paper.init(context);
return mRxPaper;
}
private RxPaper(Context context, String customBook) {
this.mContext = context;
mCustomBook = customBook;
}
private static boolean hasBook() {
return !TextUtils.isEmpty(mCustomBook);
}
/**
* Saves any types of POJOs or collections in Book storage.
*
* @param key object key is used as part of object's file name
* @param value object to save, must have no-arg constructor, can't be null.
* @return this Book instance
*/
public <T> Observable<Boolean> write(final String key, final T value) {
return Observable.create(new Observable.OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> subscriber) {
if (!subscriber.isUnsubscribed()) {
try {
if (hasBook()) {
Paper.book(mCustomBook).write(key, value);
} else {
Paper.book().write(key, value);
}
subscriber.onNext(true);
} catch (Exception e) {
subscriber.onError(new UnableToPerformOperationException("Can't write"));
}
subscriber.onCompleted();
}
}
});
}
/**
* Instantiates saved object using original object class (e.g. LinkedList). Support limited
* backward and forward compatibility: removed fields are ignored, new fields have their
* default values.
* <p/>
* All instantiated objects must have no-arg constructors.
*
* @param key object key to read
* @param defaultValue will be returned if key doesn't exist
* @return the saved object instance observable or null
*/
public <T> Observable<T> read(final String key, final T defaultValue) {
return Observable.create(new Observable.OnSubscribe<T>() {
@Override
public void call(Subscriber<? super T> subscriber) {
if (!subscriber.isUnsubscribed()) {
T value;
if (hasBook()) {
value = Paper.book(mCustomBook).read(key, defaultValue);
} else {
value = Paper.book().read(key, defaultValue);
}
if (value == null) {
subscriber.onError(new UnableToPerformOperationException(key + " is empty"));
} else {
subscriber.onNext(value);
}
subscriber.onCompleted();
}
}
});
}
/**
* Instantiates saved object using original object class (e.g. LinkedList). Support limited
* backward and forward compatibility: removed fields are ignored, new fields have their
* default values.
* <p/>
* All instantiated objects must have no-arg constructors.
*
* @param key object key to read
* @return an Observable with the saved object instance or null
*/
public <T> Observable<T> read(final String key) {
return Observable.create(new Observable.OnSubscribe<T>() {
@Override
public void call(Subscriber<? super T> subscriber) {
if (!subscriber.isUnsubscribed()) {
T value;
if (hasBook()) {
value = Paper.book(mCustomBook).read(key);
} else {
value = Paper.book().read(key);
}
if (value == null) {
subscriber.onError(new UnableToPerformOperationException(key + " is empty"));
} else {
subscriber.onNext(value);
}
subscriber.onCompleted();
}
}
});
}
/**
* Delete saved object for given key if it is exist.
*
* @param key object key
*/
public Observable<Boolean> delete(final String key) {
return Observable.create(new Observable.OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> subscriber) {
if (!subscriber.isUnsubscribed()) {
try {
if (hasBook()) {
Paper.book(mCustomBook).delete(key);
} else {
Paper.book().delete(key);
}
subscriber.onNext(true);
} catch (Exception e) {
subscriber.onError(new UnableToPerformOperationException("Can't delete"));
}
subscriber.onCompleted();
}
}
});
}
/**
* Check if given key exist.
*
* @param key object key
*/
public Observable<Boolean> exists(final String key) {
return Observable.create(new Observable.OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> subscriber) {
if (!subscriber.isUnsubscribed()) {
try {
boolean exists;
if (hasBook()) {
exists = Paper.book(mCustomBook).exist(key);
} else {
exists = Paper.book().exist(key);
}
subscriber.onNext(exists);
} catch (Exception e) {
subscriber.onError(new UnableToPerformOperationException("Can't check if key exists"));
}
subscriber.onCompleted();
}
}
});
}
public Observable<Boolean> destroy() {
return Observable.create(new Observable.OnSubscribe<Boolean>() {
@Override
public void call(Subscriber<? super Boolean> subscriber) {
if (!subscriber.isUnsubscribed()) {
try {
if (hasBook()) {
Paper.book(RxPaper.mCustomBook).destroy();
} else {
Paper.book().destroy();
}
subscriber.onNext(true);
} catch (Exception e) {
subscriber.onError(new UnableToPerformOperationException("Can't destroy"));
}
subscriber.onCompleted();
}
}
});
}
} |
package io.fotoapparat.sample;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageView;
import java.io.File;
import io.fotoapparat.Fotoapparat;
import io.fotoapparat.photo.BitmapPhoto;
import io.fotoapparat.preview.Frame;
import io.fotoapparat.preview.FrameProcessor;
import io.fotoapparat.result.PendingResult;
import io.fotoapparat.result.PhotoResult;
import io.fotoapparat.view.CameraView;
import static io.fotoapparat.log.Loggers.fileLogger;
import static io.fotoapparat.log.Loggers.logcat;
import static io.fotoapparat.log.Loggers.loggers;
import static io.fotoapparat.parameter.selector.AspectRatioSelectors.standardRatio;
import static io.fotoapparat.parameter.selector.FlashSelectors.autoFlash;
import static io.fotoapparat.parameter.selector.FlashSelectors.autoRedEye;
import static io.fotoapparat.parameter.selector.FlashSelectors.off;
import static io.fotoapparat.parameter.selector.FlashSelectors.torch;
import static io.fotoapparat.parameter.selector.FocusModeSelectors.autoFocus;
import static io.fotoapparat.parameter.selector.FocusModeSelectors.continuousFocus;
import static io.fotoapparat.parameter.selector.FocusModeSelectors.fixed;
import static io.fotoapparat.parameter.selector.LensPositionSelectors.back;
import static io.fotoapparat.parameter.selector.LensPositionSelectors.front;
import static io.fotoapparat.parameter.selector.Selectors.firstAvailable;
import static io.fotoapparat.parameter.selector.SizeSelectors.biggestSize;
public class MainActivity extends AppCompatActivity {
private final PermissionsDelegate permissionsDelegate = new PermissionsDelegate(this);
private Fotoapparat fotoapparat;
private boolean hasCameraPermission;
private CameraView cameraView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cameraView = (CameraView) findViewById(R.id.camera_view);
hasCameraPermission = permissionsDelegate.hasCameraPermission();
if (hasCameraPermission) {
cameraView.setVisibility(View.VISIBLE);
} else {
permissionsDelegate.requestCameraPermission();
}
fotoapparat = Fotoapparat
.with(this)
.into(cameraView)
.photoSize(standardRatio(biggestSize()))
.lensPosition(firstAvailable(
front(),
back()
))
.focusMode(firstAvailable(
continuousFocus(),
autoFocus(),
fixed()
))
.flash(firstAvailable(
autoRedEye(),
autoFlash(),
torch(),
off()
))
.frameProcessor(new SampleFrameProcessor())
.logger(loggers(
logcat(),
fileLogger(this)
))
.build();
cameraView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
takePicture();
}
});
}
private void takePicture() {
PhotoResult photoResult = fotoapparat.takePicture();
photoResult.saveToFile(new File(
getExternalFilesDir("photos"),
"photo.jpg"
));
photoResult
.toBitmap()
.whenAvailable(new PendingResult.Callback<BitmapPhoto>() {
@Override
public void onResult(BitmapPhoto result) {
ImageView imageView = (ImageView) findViewById(R.id.result);
imageView.setImageBitmap(result.bitmap);
imageView.setRotation(-result.rotationDegrees);
}
});
}
@Override
protected void onStart() {
super.onStart();
if (hasCameraPermission) {
fotoapparat.start();
}
}
@Override
protected void onStop() {
super.onStop();
if (hasCameraPermission) {
fotoapparat.stop();
}
}
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull String[] permissions,
@NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (permissionsDelegate.resultGranted(requestCode, permissions, grantResults)) {
fotoapparat.start();
cameraView.setVisibility(View.VISIBLE);
}
}
private class SampleFrameProcessor implements FrameProcessor {
@Override
public void processFrame(Frame frame) {
// Do nothing
}
}
} |
package org.jfree.chart.axis;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.geom.Rectangle2D;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.List;
import org.jfree.chart.ui.RectangleEdge;
import org.jfree.chart.ui.TextAnchor;
import org.jfree.chart.util.PaintUtilities;
import org.jfree.chart.event.AxisChangeEvent;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.plot.ValueAxisPlot;
import org.jfree.chart.text.TextUtilities;
import org.jfree.chart.util.ParamChecks;
import org.jfree.chart.util.SerialUtilities;
import org.jfree.data.Range;
/**
* A standard linear value axis that replaces integer values with symbols.
*/
public class SymbolAxis extends NumberAxis implements Serializable {
/** For serialization. */
private static final long serialVersionUID = 7216330468770619716L;
/** The default grid band paint. */
public static final Paint DEFAULT_GRID_BAND_PAINT
= new Color(232, 234, 232, 128);
/**
* The default paint for alternate grid bands.
*
* @since 1.0.7
*/
public static final Paint DEFAULT_GRID_BAND_ALTERNATE_PAINT
= new Color(0, 0, 0, 0); // transparent
/** The list of symbols to display instead of the numeric values. */
private List<String> symbols;
/** Flag that indicates whether or not grid bands are visible. */
private boolean gridBandsVisible;
/** The paint used to color the grid bands (if the bands are visible). */
private transient Paint gridBandPaint;
/**
* The paint used to fill the alternate grid bands.
*
* @since 1.0.7
*/
private transient Paint gridBandAlternatePaint;
/**
* Constructs a symbol axis, using default attribute values where
* necessary.
*
* @param label the axis label (<code>null</code> permitted).
* @param sv the list of symbols to display instead of the numeric
* values.
*/
public SymbolAxis(String label, String[] sv) {
super(label);
this.symbols = Arrays.asList(sv);
this.gridBandsVisible = true;
this.gridBandPaint = DEFAULT_GRID_BAND_PAINT;
this.gridBandAlternatePaint = DEFAULT_GRID_BAND_ALTERNATE_PAINT;
setAutoTickUnitSelection(false, false);
setAutoRangeStickyZero(false);
}
/**
* Returns an array of the symbols for the axis.
*
* @return The symbols.
*/
public String[] getSymbols() {
String[] result = new String[this.symbols.size()];
result = this.symbols.toArray(result);
return result;
}
/**
* Returns <code>true</code> if the grid bands are showing, and
* <code>false</code> otherwise.
*
* @return <code>true</code> if the grid bands are showing, and
* <code>false</code> otherwise.
*
* @see #setGridBandsVisible(boolean)
*/
public boolean isGridBandsVisible() {
return this.gridBandsVisible;
}
/**
* Sets the visibility of the grid bands and notifies registered
* listeners that the axis has been modified.
*
* @param flag the new setting.
*
* @see #isGridBandsVisible()
*/
public void setGridBandsVisible(boolean flag) {
if (this.gridBandsVisible != flag) {
this.gridBandsVisible = flag;
fireChangeEvent();
}
}
/**
* Returns the paint used to color the grid bands.
*
* @return The grid band paint (never <code>null</code>).
*
* @see #setGridBandPaint(Paint)
* @see #isGridBandsVisible()
*/
public Paint getGridBandPaint() {
return this.gridBandPaint;
}
/**
* Sets the grid band paint and sends an {@link AxisChangeEvent} to
* all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getGridBandPaint()
*/
public void setGridBandPaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.gridBandPaint = paint;
fireChangeEvent();
}
/**
* Returns the paint used for alternate grid bands.
*
* @return The paint (never <code>null</code>).
*
* @see #setGridBandAlternatePaint(Paint)
* @see #getGridBandPaint()
*
* @since 1.0.7
*/
public Paint getGridBandAlternatePaint() {
return this.gridBandAlternatePaint;
}
/**
* Sets the paint used for alternate grid bands and sends a
* {@link AxisChangeEvent} to all registered listeners.
*
* @param paint the paint (<code>null</code> not permitted).
*
* @see #getGridBandAlternatePaint()
* @see #setGridBandPaint(Paint)
*
* @since 1.0.7
*/
public void setGridBandAlternatePaint(Paint paint) {
ParamChecks.nullNotPermitted(paint, "paint");
this.gridBandAlternatePaint = paint;
fireChangeEvent();
}
/**
* This operation is not supported by this axis.
*
* @param g2 the graphics device.
* @param dataArea the area in which the plot and axes should be drawn.
* @param edge the edge along which the axis is drawn.
*/
@Override
protected void selectAutoTickUnit(Graphics2D g2, Rectangle2D dataArea,
RectangleEdge edge) {
throw new UnsupportedOperationException();
}
/**
* Draws the axis on a Java 2D graphics device (such as the screen or a
* printer).
*
* @param g2 the graphics device (<code>null</code> not permitted).
* @param cursor the cursor location.
* @param plotArea the area within which the plot and axes should be drawn
* (<code>null</code> not permitted).
* @param dataArea the area within which the data should be drawn
* (<code>null</code> not permitted).
* @param edge the axis location (<code>null</code> not permitted).
* @param plotState collects information about the plot
* (<code>null</code> permitted).
*
* @return The axis state (never <code>null</code>).
*/
@Override
public AxisState draw(Graphics2D g2,
double cursor,
Rectangle2D plotArea,
Rectangle2D dataArea,
RectangleEdge edge,
PlotRenderingInfo plotState) {
AxisState info = new AxisState(cursor);
if (isVisible()) {
info = super.draw(g2, cursor, plotArea, dataArea, edge, plotState);
}
if (this.gridBandsVisible) {
drawGridBands(g2, plotArea, dataArea, edge, info.getTicks());
}
return info;
}
/**
* Draws the grid bands. Alternate bands are colored using
* <CODE>gridBandPaint</CODE> (<CODE>DEFAULT_GRID_BAND_PAINT</CODE> by
* default).
*
* @param g2 the graphics device.
* @param plotArea the area within which the chart should be drawn.
* @param dataArea the area within which the plot should be drawn (a
* subset of the drawArea).
* @param edge the axis location.
* @param ticks the ticks.
*/
protected void drawGridBands(Graphics2D g2, Rectangle2D plotArea,
Rectangle2D dataArea, RectangleEdge edge, List<ValueTick> ticks) {
Shape savedClip = g2.getClip();
g2.clip(dataArea);
if (RectangleEdge.isTopOrBottom(edge)) {
drawGridBandsHorizontal(g2, plotArea, dataArea, true, ticks);
}
else if (RectangleEdge.isLeftOrRight(edge)) {
drawGridBandsVertical(g2, plotArea, dataArea, true, ticks);
}
g2.setClip(savedClip);
}
/**
* Draws the grid bands for the axis when it is at the top or bottom of
* the plot.
*
* @param g2 the graphics device.
* @param plotArea the area within which the chart should be drawn.
* @param dataArea the area within which the plot should be drawn
* (a subset of the drawArea).
* @param firstGridBandIsDark True: the first grid band takes the
* color of <CODE>gridBandPaint</CODE>.
* False: the second grid band takes the
* color of <CODE>gridBandPaint</CODE>.
* @param ticks the ticks.
*/
protected void drawGridBandsHorizontal(Graphics2D g2, Rectangle2D plotArea,
Rectangle2D dataArea, boolean firstGridBandIsDark,
List<ValueTick> ticks) {
boolean currentGridBandIsDark = firstGridBandIsDark;
double yy = dataArea.getY();
double xx1, xx2;
//gets the outline stroke width of the plot
double outlineStrokeWidth;
if (getPlot().getOutlineStroke() != null) {
outlineStrokeWidth
= ((BasicStroke) getPlot().getOutlineStroke()).getLineWidth();
}
else {
outlineStrokeWidth = 1d;
}
for (ValueTick tick : ticks) {
xx1 = valueToJava2D(tick.getValue() - 0.5d, dataArea,
RectangleEdge.BOTTOM);
xx2 = valueToJava2D(tick.getValue() + 0.5d, dataArea,
RectangleEdge.BOTTOM);
if (currentGridBandIsDark) {
g2.setPaint(this.gridBandPaint);
} else {
g2.setPaint(this.gridBandAlternatePaint);
}
Rectangle2D band = new Rectangle2D.Double(xx1, yy + outlineStrokeWidth,
xx2 - xx1, dataArea.getMaxY() - yy - outlineStrokeWidth);
g2.fill(band);
currentGridBandIsDark = !currentGridBandIsDark;
}
g2.setPaintMode();
}
/**
* Draws the grid bands for the axis when it is at the top or bottom of
* the plot.
*
* @param g2 the graphics device.
* @param drawArea the area within which the chart should be drawn.
* @param plotArea the area within which the plot should be drawn (a
* subset of the drawArea).
* @param firstGridBandIsDark True: the first grid band takes the
* color of <CODE>gridBandPaint</CODE>.
* False: the second grid band takes the
* color of <CODE>gridBandPaint</CODE>.
* @param ticks a list of ticks.
*/
protected void drawGridBandsVertical(Graphics2D g2, Rectangle2D drawArea,
Rectangle2D plotArea, boolean firstGridBandIsDark,
List<ValueTick> ticks) {
boolean currentGridBandIsDark = firstGridBandIsDark;
double xx = plotArea.getX();
double yy1, yy2;
//gets the outline stroke width of the plot
double outlineStrokeWidth;
Stroke outlineStroke = getPlot().getOutlineStroke();
if (outlineStroke != null && outlineStroke instanceof BasicStroke) {
outlineStrokeWidth = ((BasicStroke) outlineStroke).getLineWidth();
}
else {
outlineStrokeWidth = 1d;
}
for (ValueTick tick : ticks) {
yy1 = valueToJava2D(tick.getValue() + 0.5d, plotArea,
RectangleEdge.LEFT);
yy2 = valueToJava2D(tick.getValue() - 0.5d, plotArea,
RectangleEdge.LEFT);
if (currentGridBandIsDark) {
g2.setPaint(this.gridBandPaint);
} else {
g2.setPaint(this.gridBandAlternatePaint);
}
Rectangle2D band = new Rectangle2D.Double(xx + outlineStrokeWidth, yy1,
plotArea.getMaxX() - xx - outlineStrokeWidth, yy2 - yy1);
g2.fill(band);
currentGridBandIsDark = !currentGridBandIsDark;
}
g2.setPaintMode();
}
/**
* Rescales the axis to ensure that all data is visible.
*/
@Override
protected void autoAdjustRange() {
Plot plot = getPlot();
if (plot == null) {
return; // no plot, no data
}
if (plot instanceof ValueAxisPlot) {
// ensure that all the symbols are displayed
double upper = this.symbols.size() - 1;
double lower = 0;
double range = upper - lower;
// ensure the autorange is at least <minRange> in size...
double minRange = getAutoRangeMinimumSize();
if (range < minRange) {
upper = (upper + lower + minRange) / 2;
lower = (upper + lower - minRange) / 2;
}
// this ensure that the grid bands will be displayed correctly.
double upperMargin = 0.5;
double lowerMargin = 0.5;
if (getAutoRangeIncludesZero()) {
if (getAutoRangeStickyZero()) {
if (upper <= 0.0) {
upper = 0.0;
}
else {
upper = upper + upperMargin;
}
if (lower >= 0.0) {
lower = 0.0;
}
else {
lower = lower - lowerMargin;
}
}
else {
upper = Math.max(0.0, upper + upperMargin);
lower = Math.min(0.0, lower - lowerMargin);
}
}
else {
if (getAutoRangeStickyZero()) {
if (upper <= 0.0) {
upper = Math.min(0.0, upper + upperMargin);
}
else {
upper = upper + upperMargin * range;
}
if (lower >= 0.0) {
lower = Math.max(0.0, lower - lowerMargin);
}
else {
lower = lower - lowerMargin;
}
}
else {
upper = upper + upperMargin;
lower = lower - lowerMargin;
}
}
setRange(new Range(lower, upper), false, false);
}
}
/**
* Calculates the positions of the tick labels for the axis, storing the
* results in the tick label list (ready for drawing).
*
* @param g2 the graphics device.
* @param state the axis state.
* @param dataArea the area in which the data should be drawn.
* @param edge the location of the axis.
*
* @return A list of ticks.
*/
@Override
public List<ValueTick> refreshTicks(Graphics2D g2, AxisState state,
Rectangle2D dataArea, RectangleEdge edge) {
List<ValueTick> ticks = null;
if (RectangleEdge.isTopOrBottom(edge)) {
ticks = refreshTicksHorizontal(g2, dataArea, edge);
}
else if (RectangleEdge.isLeftOrRight(edge)) {
ticks = refreshTicksVertical(g2, dataArea, edge);
}
return ticks;
}
/**
* Calculates the positions of the tick labels for the axis, storing the
* results in the tick label list (ready for drawing).
*
* @param g2 the graphics device.
* @param dataArea the area in which the data should be drawn.
* @param edge the location of the axis.
*
* @return The ticks.
*/
@Override
protected List<ValueTick> refreshTicksHorizontal(Graphics2D g2,
Rectangle2D dataArea, RectangleEdge edge) {
List<ValueTick> ticks = new java.util.ArrayList<ValueTick>();
Font tickLabelFont = getTickLabelFont();
g2.setFont(tickLabelFont);
double size = getTickUnit().getSize();
int count = calculateVisibleTickCount();
double lowestTickValue = calculateLowestVisibleTickValue();
double previousDrawnTickLabelPos = 0.0;
double previousDrawnTickLabelLength = 0.0;
if (count <= ValueAxis.MAXIMUM_TICK_COUNT) {
for (int i = 0; i < count; i++) {
double currentTickValue = lowestTickValue + (i * size);
double xx = valueToJava2D(currentTickValue, dataArea, edge);
String tickLabel;
NumberFormat formatter = getNumberFormatOverride();
if (formatter != null) {
tickLabel = formatter.format(currentTickValue);
}
else {
tickLabel = valueToString(currentTickValue);
}
// avoid to draw overlapping tick labels
Rectangle2D bounds = TextUtilities.getTextBounds(tickLabel, g2,
g2.getFontMetrics());
double tickLabelLength = isVerticalTickLabels()
? bounds.getHeight() : bounds.getWidth();
boolean tickLabelsOverlapping = false;
if (i > 0) {
double avgTickLabelLength = (previousDrawnTickLabelLength
+ tickLabelLength) / 2.0;
if (Math.abs(xx - previousDrawnTickLabelPos)
< avgTickLabelLength) {
tickLabelsOverlapping = true;
}
}
if (tickLabelsOverlapping) {
tickLabel = ""; // don't draw this tick label
}
else {
// remember these values for next comparison
previousDrawnTickLabelPos = xx;
previousDrawnTickLabelLength = tickLabelLength;
}
TextAnchor anchor;
TextAnchor rotationAnchor;
double angle = 0.0;
if (isVerticalTickLabels()) {
anchor = TextAnchor.CENTER_RIGHT;
rotationAnchor = TextAnchor.CENTER_RIGHT;
if (edge == RectangleEdge.TOP) {
angle = Math.PI / 2.0;
}
else {
angle = -Math.PI / 2.0;
}
}
else {
if (edge == RectangleEdge.TOP) {
anchor = TextAnchor.BOTTOM_CENTER;
rotationAnchor = TextAnchor.BOTTOM_CENTER;
}
else {
anchor = TextAnchor.TOP_CENTER;
rotationAnchor = TextAnchor.TOP_CENTER;
}
}
ticks.add(new NumberTick(currentTickValue,
tickLabel, anchor, rotationAnchor, angle));
}
}
return ticks;
}
/**
* Calculates the positions of the tick labels for the axis, storing the
* results in the tick label list (ready for drawing).
*
* @param g2 the graphics device.
* @param dataArea the area in which the plot should be drawn.
* @param edge the location of the axis.
*
* @return The ticks.
*/
@Override
protected List<ValueTick> refreshTicksVertical(Graphics2D g2,
Rectangle2D dataArea, RectangleEdge edge) {
List<ValueTick> ticks = new java.util.ArrayList<ValueTick>();
Font tickLabelFont = getTickLabelFont();
g2.setFont(tickLabelFont);
double size = getTickUnit().getSize();
int count = calculateVisibleTickCount();
double lowestTickValue = calculateLowestVisibleTickValue();
double previousDrawnTickLabelPos = 0.0;
double previousDrawnTickLabelLength = 0.0;
if (count <= ValueAxis.MAXIMUM_TICK_COUNT) {
for (int i = 0; i < count; i++) {
double currentTickValue = lowestTickValue + (i * size);
double yy = valueToJava2D(currentTickValue, dataArea, edge);
String tickLabel;
NumberFormat formatter = getNumberFormatOverride();
if (formatter != null) {
tickLabel = formatter.format(currentTickValue);
}
else {
tickLabel = valueToString(currentTickValue);
}
// avoid to draw overlapping tick labels
Rectangle2D bounds = TextUtilities.getTextBounds(tickLabel, g2,
g2.getFontMetrics());
double tickLabelLength = isVerticalTickLabels()
? bounds.getWidth() : bounds.getHeight();
boolean tickLabelsOverlapping = false;
if (i > 0) {
double avgTickLabelLength = (previousDrawnTickLabelLength
+ tickLabelLength) / 2.0;
if (Math.abs(yy - previousDrawnTickLabelPos)
< avgTickLabelLength) {
tickLabelsOverlapping = true;
}
}
if (tickLabelsOverlapping) {
tickLabel = ""; // don't draw this tick label
}
else {
// remember these values for next comparison
previousDrawnTickLabelPos = yy;
previousDrawnTickLabelLength = tickLabelLength;
}
TextAnchor anchor = null;
TextAnchor rotationAnchor = null;
double angle = 0.0;
if (isVerticalTickLabels()) {
anchor = TextAnchor.BOTTOM_CENTER;
rotationAnchor = TextAnchor.BOTTOM_CENTER;
if (edge == RectangleEdge.LEFT) {
angle = -Math.PI / 2.0;
}
else {
angle = Math.PI / 2.0;
}
}
else {
if (edge == RectangleEdge.LEFT) {
anchor = TextAnchor.CENTER_RIGHT;
rotationAnchor = TextAnchor.CENTER_RIGHT;
}
else {
anchor = TextAnchor.CENTER_LEFT;
rotationAnchor = TextAnchor.CENTER_LEFT;
}
}
ticks.add(new NumberTick(currentTickValue,
tickLabel, anchor, rotationAnchor, angle));
}
}
return ticks;
}
/**
* Converts a value to a string, using the list of symbols.
*
* @param value value to convert.
*
* @return The symbol.
*/
public String valueToString(double value) {
String strToReturn;
try {
strToReturn = this.symbols.get((int) value);
}
catch (IndexOutOfBoundsException ex) {
strToReturn = "";
}
return strToReturn;
}
/**
* Tests this axis for equality with an arbitrary object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof SymbolAxis)) {
return false;
}
SymbolAxis that = (SymbolAxis) obj;
if (!this.symbols.equals(that.symbols)) {
return false;
}
if (this.gridBandsVisible != that.gridBandsVisible) {
return false;
}
if (!PaintUtilities.equal(this.gridBandPaint, that.gridBandPaint)) {
return false;
}
if (!PaintUtilities.equal(this.gridBandAlternatePaint,
that.gridBandAlternatePaint)) {
return false;
}
return super.equals(obj);
}
/**
* Provides serialization support.
*
* @param stream the output stream.
*
* @throws IOException if there is an I/O error.
*/
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.defaultWriteObject();
SerialUtilities.writePaint(this.gridBandPaint, stream);
SerialUtilities.writePaint(this.gridBandAlternatePaint, stream);
}
/**
* Provides serialization support.
*
* @param stream the input stream.
*
* @throws IOException if there is an I/O error.
* @throws ClassNotFoundException if there is a classpath problem.
*/
private void readObject(ObjectInputStream stream)
throws IOException, ClassNotFoundException {
stream.defaultReadObject();
this.gridBandPaint = SerialUtilities.readPaint(stream);
this.gridBandAlternatePaint = SerialUtilities.readPaint(stream);
}
} |
package org.jfree.chart.util;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.LinearGradientPaint;
import java.awt.Paint;
import java.awt.RadialGradientPaint;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
/**
* Utility code that relates to {@code Paint} objects.
*/
public class PaintUtils {
/**
* Private constructor prevents object creation.
*/
private PaintUtils() {
}
/**
* Returns {@code true} if the two {@code Paint} objects are equal
* OR both {@code null}. This method handles
* {@code GradientPaint}, {@code LinearGradientPaint} and
* {@code RadialGradientPaint} as a special cases, since those classes do
* not override the {@code equals()} method.
*
* @param p1 paint 1 ({@code null} permitted).
* @param p2 paint 2 ({@code null} permitted).
*
* @return A boolean.
*/
public static boolean equal(Paint p1, Paint p2) {
if (p1 == p2) {
return true;
}
// handle cases where either or both arguments are null
if (p1 == null) {
return (p2 == null);
}
if (p2 == null) {
return false;
}
// handle GradientPaint as a special case...
if (p1 instanceof GradientPaint && p2 instanceof GradientPaint) {
GradientPaint gp1 = (GradientPaint) p1;
GradientPaint gp2 = (GradientPaint) p2;
return gp1.getColor1().equals(gp2.getColor1())
&& gp1.getColor2().equals(gp2.getColor2())
&& gp1.getPoint1().equals(gp2.getPoint1())
&& gp1.getPoint2().equals(gp2.getPoint2())
&& gp1.isCyclic() == gp2.isCyclic()
&& gp1.getTransparency() == gp1.getTransparency();
} else if (p1 instanceof LinearGradientPaint
&& p2 instanceof LinearGradientPaint) {
LinearGradientPaint lgp1 = (LinearGradientPaint) p1;
LinearGradientPaint lgp2 = (LinearGradientPaint) p2;
return lgp1.getStartPoint().equals(lgp2.getStartPoint())
&& lgp1.getEndPoint().equals(lgp2.getEndPoint())
&& Arrays.equals(lgp1.getFractions(), lgp2.getFractions())
&& Arrays.equals(lgp1.getColors(), lgp2.getColors())
&& lgp1.getCycleMethod() == lgp2.getCycleMethod()
&& lgp1.getColorSpace() == lgp2.getColorSpace()
&& lgp1.getTransform().equals(lgp2.getTransform());
} else if (p1 instanceof RadialGradientPaint
&& p2 instanceof RadialGradientPaint) {
RadialGradientPaint rgp1 = (RadialGradientPaint) p1;
RadialGradientPaint rgp2 = (RadialGradientPaint) p2;
return rgp1.getCenterPoint().equals(rgp2.getCenterPoint())
&& rgp1.getRadius() == rgp2.getRadius()
&& rgp1.getFocusPoint().equals(rgp2.getFocusPoint())
&& Arrays.equals(rgp1.getFractions(), rgp2.getFractions())
&& Arrays.equals(rgp1.getColors(), rgp2.getColors())
&& rgp1.getCycleMethod() == rgp2.getCycleMethod()
&& rgp1.getColorSpace() == rgp2.getColorSpace()
&& rgp1.getTransform().equals(rgp2.getTransform());
} else {
return p1.equals(p2);
}
}
/**
* Converts a color into a string. If the color is equal to one of the
* defined constant colors, that name is returned instead. Otherwise the
* color is returned as hex-string.
*
* @param c the color.
* @return the string for this color.
*/
public static String colorToString(Color c) {
try {
Field[] fields = Color.class.getFields();
for (int i = 0; i < fields.length; i++) {
Field f = fields[i];
if (Modifier.isPublic(f.getModifiers())
&& Modifier.isFinal(f.getModifiers())
&& Modifier.isStatic(f.getModifiers())) {
final String name = f.getName();
final Object oColor = f.get(null);
if (oColor instanceof Color) {
if (c.equals(oColor)) {
return name;
}
}
}
}
} catch (Exception e) {
}
// no defined constant color, so this must be a user defined color
final String color = Integer.toHexString(c.getRGB() & 0x00ffffff);
final StringBuffer retval = new StringBuffer(7);
retval.append("
final int fillUp = 6 - color.length();
for (int i = 0; i < fillUp; i++) {
retval.append("0");
}
retval.append(color);
return retval.toString();
}
/**
* Converts a given string into a color.
*
* @param value the string, either a name or a hex-string.
* @return the color.
*/
public static Color stringToColor(String value) {
if (value == null) {
return Color.BLACK;
}
try {
// get color by hex or octal value
return Color.decode(value);
} catch (NumberFormatException nfe) {
// if we can't decode lets try to get it by name
try {
// try to get a color by name using reflection
final Field f = Color.class.getField(value);
return (Color) f.get(null);
} catch (Exception ce) {
// if we can't get any color return black
return Color.BLACK;
}
}
}
} |
package org.jfree.chart.util;
import java.awt.GradientPaint;
import java.awt.LinearGradientPaint;
import java.awt.Paint;
import java.awt.RadialGradientPaint;
import java.util.Arrays;
import java.util.Map;
/**
* Utility code that relates to {@code Paint} objects.
*/
public class PaintUtils {
/**
* Private constructor prevents object creation.
*/
private PaintUtils() {
}
/**
* Returns {@code true} if the two {@code Paint} objects are equal
* OR both {@code null}. This method handles
* {@code GradientPaint}, {@code LinearGradientPaint} and
* {@code RadialGradientPaint} as a special cases, since those classes do
* not override the {@code equals()} method.
*
* @param p1 paint 1 ({@code null} permitted).
* @param p2 paint 2 ({@code null} permitted).
*
* @return A boolean.
*/
public static boolean equal(Paint p1, Paint p2) {
if (p1 == p2) {
return true;
}
// handle cases where either or both arguments are null
if (p1 == null) {
return (p2 == null);
}
if (p2 == null) {
return false;
}
// handle GradientPaint as a special case...
if (p1 instanceof GradientPaint && p2 instanceof GradientPaint) {
GradientPaint gp1 = (GradientPaint) p1;
GradientPaint gp2 = (GradientPaint) p2;
return gp1.getColor1().equals(gp2.getColor1())
&& gp1.getColor2().equals(gp2.getColor2())
&& gp1.getPoint1().equals(gp2.getPoint1())
&& gp1.getPoint2().equals(gp2.getPoint2())
&& gp1.isCyclic() == gp2.isCyclic()
&& gp1.getTransparency() == gp1.getTransparency();
} else if (p1 instanceof LinearGradientPaint
&& p2 instanceof LinearGradientPaint) {
LinearGradientPaint lgp1 = (LinearGradientPaint) p1;
LinearGradientPaint lgp2 = (LinearGradientPaint) p2;
return lgp1.getStartPoint().equals(lgp2.getStartPoint())
&& lgp1.getEndPoint().equals(lgp2.getEndPoint())
&& Arrays.equals(lgp1.getFractions(), lgp2.getFractions())
&& Arrays.equals(lgp1.getColors(), lgp2.getColors())
&& lgp1.getCycleMethod() == lgp2.getCycleMethod()
&& lgp1.getColorSpace() == lgp2.getColorSpace()
&& lgp1.getTransform().equals(lgp2.getTransform());
} else if (p1 instanceof RadialGradientPaint
&& p2 instanceof RadialGradientPaint) {
RadialGradientPaint rgp1 = (RadialGradientPaint) p1;
RadialGradientPaint rgp2 = (RadialGradientPaint) p2;
return rgp1.getCenterPoint().equals(rgp2.getCenterPoint())
&& rgp1.getRadius() == rgp2.getRadius()
&& rgp1.getFocusPoint().equals(rgp2.getFocusPoint())
&& Arrays.equals(rgp1.getFractions(), rgp2.getFractions())
&& Arrays.equals(rgp1.getColors(), rgp2.getColors())
&& rgp1.getCycleMethod() == rgp2.getCycleMethod()
&& rgp1.getColorSpace() == rgp2.getColorSpace()
&& rgp1.getTransform().equals(rgp2.getTransform());
} else {
return p1.equals(p2);
}
}
/**
* Returns {@code true} if the maps contain the same keys and
* {@link Paint} values, and {@code false} otherwise.
*
* @param m1 map 1 ({@code null} not permitted).
* @param m2 map 2 ({@code null} not permitted).
*
* @return A boolean.
*/
public static boolean equalMaps(Map<?, Paint> m1, Map<?, Paint> m2) {
if (m1.size() != m2.size()) {
return false;
}
for (Map.Entry<?, Paint> entry : m1.entrySet()) {
if (!m2.containsKey(entry.getKey())) {
return false;
}
if (!PaintUtils.equal(entry.getValue(),
m2.get(entry.getKey()))) {
return false;
}
}
return true;
}
} |
package org.jpmml.converter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.dmg.pmml.DataDictionary;
import org.dmg.pmml.DataField;
import org.dmg.pmml.DataType;
import org.dmg.pmml.DefineFunction;
import org.dmg.pmml.DerivedField;
import org.dmg.pmml.Expression;
import org.dmg.pmml.Field;
import org.dmg.pmml.FieldName;
import org.dmg.pmml.Header;
import org.dmg.pmml.OpType;
import org.dmg.pmml.PMML;
import org.dmg.pmml.TransformationDictionary;
public class PMMLEncoder {
private Map<FieldName, DataField> dataFields = new LinkedHashMap<>();
private Map<FieldName, DerivedField> derivedFields = new LinkedHashMap<>();
private Map<String, DefineFunction> defineFunctions = new LinkedHashMap<>();
public PMML encodePMML(){
if(!Collections.disjoint(this.dataFields.keySet(), this.derivedFields.keySet())){
throw new IllegalArgumentException();
}
List<DataField> dataFields = new ArrayList<>(this.dataFields.values());
DataDictionary dataDictionary = new DataDictionary();
if(dataFields.size() > 0){
(dataDictionary.getDataFields()).addAll(dataFields);
}
List<DerivedField> derivedFields = new ArrayList<>(this.derivedFields.values());
List<DefineFunction> defineFunctions = new ArrayList<>(this.defineFunctions.values());
TransformationDictionary transformationDictionary = null;
if(derivedFields.size() > 0 || defineFunctions.size() > 0){
transformationDictionary = new TransformationDictionary();
if(derivedFields.size() > 0){
(transformationDictionary.getDerivedFields()).addAll(derivedFields);
} // End if
if(defineFunctions.size() > 0){
(transformationDictionary.getDefineFunctions()).addAll(defineFunctions);
}
}
Header header = encodeHeader();
PMML pmml = new PMML("4.3", header, dataDictionary)
.setTransformationDictionary(transformationDictionary);
return pmml;
}
public Header encodeHeader(){
return PMMLUtil.createHeader(getClass());
}
public DataField getDataField(FieldName name){
return this.dataFields.get(name);
}
public void addDataField(DataField dataField){
FieldName name = dataField.getName();
checkName(name);
this.dataFields.put(name, dataField);
}
public DataField createDataField(FieldName name, OpType opType, DataType dataType){
return createDataField(name, opType, dataType, null);
}
public DataField createDataField(FieldName name, OpType opType, DataType dataType, List<String> values){
DataField dataField = new DataField(name, opType, dataType);
if(values != null && values.size() > 0){
PMMLUtil.addValues(dataField, values);
}
addDataField(dataField);
return dataField;
}
public DataField removeDataField(FieldName name){
DataField dataField = this.dataFields.remove(name);
if(dataField == null){
throw new IllegalArgumentException(name.getValue());
}
return dataField;
}
public DerivedField getDerivedField(FieldName name){
return this.derivedFields.get(name);
}
public void addDerivedField(DerivedField derivedField){
FieldName name = derivedField.getName();
checkName(name);
this.derivedFields.put(name, derivedField);
}
public DerivedField createDerivedField(FieldName name, OpType opType, DataType dataType, Expression expression){
DerivedField derivedField = new DerivedField(opType, dataType)
.setName(name)
.setExpression(expression);
addDerivedField(derivedField);
return derivedField;
}
public DerivedField removeDerivedField(FieldName name){
DerivedField derivedField = this.derivedFields.remove(name);
if(derivedField == null){
throw new IllegalArgumentException(name.getValue());
}
return derivedField;
}
public Field<?> getField(FieldName name){
DataField dataField = getDataField(name);
DerivedField derivedField = getDerivedField(name);
if(dataField != null && derivedField == null){
return dataField;
} else
if(dataField == null && derivedField != null){
return derivedField;
}
throw new IllegalArgumentException(name.getValue());
}
public Field<?> toContinuous(FieldName name){
Field<?> field = getField(name);
DataType dataType = field.getDataType();
switch(dataType){
case INTEGER:
case FLOAT:
case DOUBLE:
break;
default:
throw new IllegalArgumentException("Field " + name.getValue() + " has data type " + dataType);
}
field.setOpType(OpType.CONTINUOUS);
return field;
}
public Field<?> toCategorical(FieldName name, List<String> values){
Field<?> field = getField(name);
dataField:
if(field instanceof DataField){
DataField dataField = (DataField)field;
List<String> existingValues = PMMLUtil.getValues(dataField);
if(existingValues != null && existingValues.size() > 0){
if((existingValues).equals(values)){
break dataField;
}
throw new IllegalArgumentException("Field " + name.getValue() + " has valid values " + existingValues);
}
PMMLUtil.addValues(dataField, values);
}
field.setOpType(OpType.CATEGORICAL);
return field;
}
public DefineFunction getDefineFunction(String name){
return this.defineFunctions.get(name);
}
public void addDefineFunction(DefineFunction defineFunction){
String name = defineFunction.getName();
if(name == null){
throw new NullPointerException();
} // End if
if(this.defineFunctions.containsKey(name)){
throw new IllegalArgumentException(name);
}
this.defineFunctions.put(name, defineFunction);
}
public Map<FieldName, DataField> getDataFields(){
return this.dataFields;
}
public Map<FieldName, DerivedField> getDerivedFields(){
return this.derivedFields;
}
public Map<String, DefineFunction> getDefineFunctions(){
return this.defineFunctions;
}
private void checkName(FieldName name){
if(name == null){
throw new NullPointerException();
} // End if
if(this.dataFields.containsKey(name) || this.derivedFields.containsKey(name)){
throw new IllegalArgumentException(name.getValue());
}
}
} |
package org.jpmml.sparkml;
import java.util.Arrays;
import java.util.List;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import org.apache.spark.ml.classification.DecisionTreeClassificationModel;
import org.apache.spark.ml.regression.DecisionTreeRegressionModel;
import org.apache.spark.ml.tree.CategoricalSplit;
import org.apache.spark.ml.tree.ContinuousSplit;
import org.apache.spark.ml.tree.DecisionTreeModel;
import org.apache.spark.ml.tree.InternalNode;
import org.apache.spark.ml.tree.LeafNode;
import org.apache.spark.ml.tree.Split;
import org.apache.spark.ml.tree.TreeEnsembleModel;
import org.apache.spark.mllib.tree.impurity.ImpurityCalculator;
import org.dmg.pmml.MiningFunctionType;
import org.dmg.pmml.Node;
import org.dmg.pmml.Predicate;
import org.dmg.pmml.ScoreDistribution;
import org.dmg.pmml.SimplePredicate;
import org.dmg.pmml.TreeModel;
import org.dmg.pmml.True;
import org.jpmml.converter.ModelUtil;
import org.jpmml.converter.ValueUtil;
public class TreeModelUtil {
private TreeModelUtil(){
}
static
public TreeModel encodeDecisionTree(DecisionTreeModel model, FeatureSchema schema){
org.apache.spark.ml.tree.Node node = model.rootNode();
if(model instanceof DecisionTreeRegressionModel){
return encodeTreeModel(MiningFunctionType.REGRESSION, node, schema);
} else
if(model instanceof DecisionTreeClassificationModel){
return encodeTreeModel(MiningFunctionType.CLASSIFICATION, node, schema);
}
throw new IllegalArgumentException();
}
static
public List<TreeModel> encodeDecisionTreeEnsemble(TreeEnsembleModel model, final FeatureSchema schema){
Function<DecisionTreeModel, TreeModel> function = new Function<DecisionTreeModel, TreeModel>(){
private FeatureSchema segmentSchema = new FeatureSchema(null, schema.getTargetCategories(), schema.getActiveFields(), schema.getFeatures());
@Override
public TreeModel apply(DecisionTreeModel model){
return encodeDecisionTree(model, this.segmentSchema);
}
};
return Lists.newArrayList(Lists.transform(Arrays.asList(model.trees()), function));
}
static
public TreeModel encodeTreeModel(MiningFunctionType miningFunction, org.apache.spark.ml.tree.Node node, FeatureSchema schema){
Node root = encodeNode(miningFunction, node, schema)
.setPredicate(new True());
TreeModel treeModel = new TreeModel(miningFunction, ModelUtil.createMiningSchema(schema, root), root)
.setSplitCharacteristic(TreeModel.SplitCharacteristic.BINARY_SPLIT);
return treeModel;
}
static
public Node encodeNode(MiningFunctionType miningFunction, org.apache.spark.ml.tree.Node node, FeatureSchema schema){
if(node instanceof InternalNode){
return encodeInternalNode(miningFunction, (InternalNode)node, schema);
} else
if(node instanceof LeafNode){
return encodeLeafNode(miningFunction, (LeafNode)node, schema);
}
throw new IllegalArgumentException();
}
static
private Node encodeInternalNode(MiningFunctionType miningFunction, InternalNode internalNode, FeatureSchema schema){
Node result = createNode(miningFunction, internalNode, schema);
Predicate[] predicates = encodeSplit(internalNode.split(), schema);
Node leftChild = encodeNode(miningFunction, internalNode.leftChild(), schema)
.setPredicate(predicates[0]);
Node rightChild = encodeNode(miningFunction, internalNode.rightChild(), schema)
.setPredicate(predicates[1]);
result.addNodes(leftChild, rightChild);
return result;
}
static
private Node encodeLeafNode(MiningFunctionType miningFunction, LeafNode leafNode, FeatureSchema schema){
Node result = createNode(miningFunction, leafNode, schema);
return result;
}
static
private Node createNode(MiningFunctionType miningFunction, org.apache.spark.ml.tree.Node node, FeatureSchema schema){
Node result = new Node();
switch(miningFunction){
case REGRESSION:
{
String score = ValueUtil.formatValue(node.prediction());
result.setScore(score);
}
break;
case CLASSIFICATION:
{
List<String> targetCategories = schema.getTargetCategories();
if(targetCategories == null){
throw new IllegalArgumentException();
}
int index = ValueUtil.asInt(node.prediction());
result.setScore(targetCategories.get(index));
ImpurityCalculator impurityCalculator = node.impurityStats();
result.setRecordCount((double)impurityCalculator.count());
double[] stats = impurityCalculator.stats();
for(int i = 0; i < stats.length; i++){
ScoreDistribution scoreDistribution = new ScoreDistribution(targetCategories.get(i), stats[i]);
result.addScoreDistributions(scoreDistribution);
}
}
break;
default:
throw new UnsupportedOperationException();
}
return result;
}
static
private Predicate[] encodeSplit(Split split, FeatureSchema schema){
if(split instanceof ContinuousSplit){
return encodeContinuousSplit((ContinuousSplit)split, schema);
} else
if(split instanceof CategoricalSplit){
return encodeCategoricalSplit((CategoricalSplit)split, schema);
}
throw new IllegalArgumentException();
}
static
private Predicate[] encodeContinuousSplit(ContinuousSplit continuousSplit, FeatureSchema schema){
ContinuousFeature feature = (ContinuousFeature)schema.getFeature(continuousSplit.featureIndex());
double threshold = continuousSplit.threshold();
// XXX
threshold += 1e-15;
String value = ValueUtil.formatValue(threshold);
SimplePredicate leftPredicate = new SimplePredicate(feature.getName(), SimplePredicate.Operator.LESS_OR_EQUAL)
.setValue(value);
SimplePredicate rightPredicate = new SimplePredicate(feature.getName(), SimplePredicate.Operator.GREATER_THAN)
.setValue(value);
return new Predicate[]{leftPredicate, rightPredicate};
}
static
private Predicate[] encodeCategoricalSplit(CategoricalSplit categoricalSplit, FeatureSchema schema){
CategoricalFeature<?> feature = (CategoricalFeature<?>)schema.getFeature(categoricalSplit.featureIndex());
SimplePredicate.Operator leftOperator;
SimplePredicate.Operator rightOperator;
if(Arrays.equals(TRUE, categoricalSplit.leftCategories()) && Arrays.equals(FALSE, categoricalSplit.rightCategories())){
leftOperator = SimplePredicate.Operator.EQUAL;
rightOperator = SimplePredicate.Operator.NOT_EQUAL;
} else
if(Arrays.equals(FALSE, categoricalSplit.leftCategories()) && Arrays.equals(TRUE, categoricalSplit.rightCategories())){
leftOperator = SimplePredicate.Operator.NOT_EQUAL;
rightOperator = SimplePredicate.Operator.EQUAL;
} else
{
throw new IllegalArgumentException();
}
String value = ValueUtil.formatValue(feature.getValue());
SimplePredicate leftPredicate = new SimplePredicate(feature.getName(), leftOperator)
.setValue(value);
SimplePredicate rightPredicate = new SimplePredicate(feature.getName(), rightOperator)
.setValue(value);
return new Predicate[]{leftPredicate, rightPredicate};
}
private static final double[] TRUE = {1.0d};
private static final double[] FALSE = {0.0d};
} |
package org.junit.rules;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import org.junit.Rule;
/**
* The TemporaryFolder Rule allows creation of files and folders that should
* be deleted when the test method finishes (whether it passes or
* fails).
* By default no exception will be thrown in case the deletion fails.
*
* <p>Example of usage:
* <pre>
* public static class HasTempFolder {
* @Rule
* public TemporaryFolder folder= new TemporaryFolder();
*
* @Test
* public void testUsingTempFolder() throws IOException {
* File createdFile= folder.newFile("myfile.txt");
* File createdFolder= folder.newFolder("subfolder");
* // ...
* }
* }
* </pre>
*
* <p>TemporaryFolder rule supports assured deletion mode, which
* will fail the test in case deletion fails with {@link AssertionError}.
*
* <p>Creating TemporaryFolder with assured deletion:
* <pre>
* @Rule
* public TemporaryFolder folder= TemporaryFolder.builder().assureDeletion().build();
* </pre>
*
* @since 4.7
*/
public class TemporaryFolder extends ExternalResource {
private final File parentFolder;
private final boolean assureDeletion;
private File folder;
private static final int TEMP_DIR_ATTEMPTS = 10000;
private static final String TMP_PREFIX = "junit";
/**
* Create a temporary folder which uses system default temporary-file
* directory to create temporary resources.
*/
public TemporaryFolder() {
this((File) null);
}
/**
* Create a temporary folder which uses the specified directory to create
* temporary resources.
*
* @param parentFolder folder where temporary resources will be created.
* If {@code null} then system default temporary-file directory is used.
*/
public TemporaryFolder(File parentFolder) {
this.parentFolder = parentFolder;
this.assureDeletion = false;
}
/**
* Create a {@link TemporaryFolder} initialized with
* values from a builder.
*/
protected TemporaryFolder(Builder builder) {
this.parentFolder = builder.parentFolder;
this.assureDeletion = builder.assureDeletion;
}
/**
* Returns a new builder for building an instance of {@link TemporaryFolder}.
*
* @since 4.13
*/
public static Builder builder() {
return new Builder();
}
/**
* Builds an instance of {@link TemporaryFolder}.
*
* @since 4.13
*/
public static class Builder {
private File parentFolder;
private boolean assureDeletion;
protected Builder() {}
/**
* Specifies which folder to use for creating temporary resources.
* If {@code null} then system default temporary-file directory is
* used.
*
* @return this
*/
public Builder parentFolder(File parentFolder) {
this.parentFolder = parentFolder;
return this;
}
/**
* Setting this flag assures that no resources are left undeleted. Failure
* to fulfill the assurance results in failure of tests with an
* {@link AssertionError}.
*
* @return this
*/
public Builder assureDeletion() {
this.assureDeletion = true;
return this;
}
/**
* Builds a {@link TemporaryFolder} instance using the values in this builder.
*/
public TemporaryFolder build() {
return new TemporaryFolder(this);
}
}
@Override
protected void before() throws Throwable {
create();
}
@Override
protected void after() {
delete();
}
// testing purposes only
/**
* for testing purposes only. Do not use.
*/
public void create() throws IOException {
folder = createTemporaryFolderIn(parentFolder);
}
/**
* Returns a new fresh file with the given name under the temporary folder.
*/
public File newFile(String fileName) throws IOException {
File file = new File(getRoot(), fileName);
if (!file.createNewFile()) {
throw new IOException(
"a file with the name \'" + fileName + "\' already exists in the test folder");
}
return file;
}
/**
* Returns a new fresh file with a random name under the temporary folder.
*/
public File newFile() throws IOException {
return File.createTempFile(TMP_PREFIX, null, getRoot());
}
/**
* Returns a new fresh folder with the given name under the temporary
* folder.
*/
public File newFolder(String folder) throws IOException {
return newFolder(new String[]{folder});
}
/**
* Returns a new fresh folder with the given name(s) under the temporary
* folder.
*/
public File newFolder(String... folderNames) throws IOException {
File file = getRoot();
for (int i = 0; i < folderNames.length; i++) {
String folderName = folderNames[i];
validateFolderName(folderName);
file = new File(file, folderName);
if (!file.mkdir() && isLastElementInArray(i, folderNames)) {
throw new IOException(
"a folder with the name \'" + folderName + "\' already exists");
}
}
return file;
}
/**
* Validates if multiple path components were used while creating a folder.
*
* @param folderName
* Name of the folder being created
*/
private void validateFolderName(String folderName) throws IOException {
File tempFile = new File(folderName);
if (tempFile.getParent() != null) {
String errorMsg = "Folder name cannot consist of multiple path components separated by a file separator."
+ " Please use newFolder('MyParentFolder','MyFolder') to create hierarchies of folders";
throw new IOException(errorMsg);
}
}
private boolean isLastElementInArray(int index, String[] array) {
return index == array.length - 1;
}
/**
* Returns a new fresh folder with a random name under the temporary folder.
*/
public File newFolder() throws IOException {
return createTemporaryFolderIn(getRoot());
}
private File createTemporaryFolderIn(File parentFolder) throws IOException {
File createdFolder = null;
for (int i = 0; i < TEMP_DIR_ATTEMPTS; ++i) {
// Use createTempFile to get a suitable folder name.
String suffix = ".tmp";
File tmpFile = File.createTempFile(TMP_PREFIX, suffix, parentFolder);
String tmpName = tmpFile.toString();
// Discard .tmp suffix of tmpName.
String folderName = tmpName.substring(0, tmpName.length() - suffix.length());
createdFolder = new File(folderName);
if (createdFolder.mkdir()) {
tmpFile.delete();
return createdFolder;
}
tmpFile.delete();
}
throw new IOException("Unable to create temporary directory in: "
+ parentFolder.toString() + ". Tried " + TEMP_DIR_ATTEMPTS + " times. "
+ "Last attempted to create: " + createdFolder.toString());
}
/**
* @return the location of this temporary folder.
*/
public File getRoot() {
if (folder == null) {
throw new IllegalStateException(
"the temporary folder has not yet been created");
}
return folder;
}
/**
* Delete all files and folders under the temporary folder. Usually not
* called directly, since it is automatically applied by the {@link Rule}.
*
* @throws AssertionError if unable to clean up resources
* and deletion of resources is assured.
*/
public void delete() {
if (!tryDelete()) {
if (assureDeletion) {
fail("Unable to clean up temporary folder " + folder);
}
}
}
/**
* Tries to delete all files and folders under the temporary folder and
* returns whether deletion was successful or not.
*
* @return {@code true} if all resources are deleted successfully,
* {@code false} otherwise.
*/
protected boolean tryDelete() {
if (folder == null) {
return true;
}
return recursiveDelete(folder);
}
private boolean recursiveDelete(File file) {
// Try deleting file before assuming file is a directory
// to prevent following symbolic links.
if (file.delete()) {
return true;
}
boolean result = true;
File[] files = file.listFiles();
if (files != null) {
for (File each : files) {
result = result && recursiveDelete(each);
}
}
return result && file.delete();
}
} |
package org.junit.runners;
import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.runner.Runner;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.model.FrameworkField;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;
import org.junit.runners.model.Statement;
/**
* <p>
* The custom runner <code>Parameterized</code> implements parameterized tests.
* When running a parameterized test class, instances are created for the
* cross-product of the test methods and the test data elements.
* </p>
*
* For example, to test a Fibonacci function, write:
*
* <pre>
* @RunWith(Parameterized.class)
* public class FibonacciTest {
* @Parameters(name= "{index}: fib[{0}]={1}")
* public static Iterable<Object[]> data() {
* return Arrays.asList(new Object[][] { { 0, 0 }, { 1, 1 }, { 2, 1 },
* { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } });
* }
*
* private int fInput;
*
* private int fExpected;
*
* public FibonacciTest(int input, int expected) {
* fInput= input;
* fExpected= expected;
* }
*
* @Test
* public void test() {
* assertEquals(fExpected, Fibonacci.compute(fInput));
* }
* }
* </pre>
*
* <p>
* Each instance of <code>FibonacciTest</code> will be constructed using the
* two-argument constructor and the data values in the
* <code>@Parameters</code> method.
*
* <p>
* In order that you can easily identify the individual tests, you may provide a
* name for the <code>@Parameters</code> annotation. This name is allowed
* to contain placeholders, which are replaced at runtime. The placeholders are
* <dl>
* <dt>{index}</dt>
* <dd>the current parameter index</dd>
* <dt>{0}</dt>
* <dd>the first parameter value</dd>
* <dt>{1}</dt>
* <dd>the second parameter value</dd>
* <dt>...</dt>
* <dd></dd>
* </dl>
* In the example given above, the <code>Parameterized</code> runner creates
* names like <code>[1: fib(3)=2]</code>. If you don't use the name parameter,
* then the current parameter index is used as name.
* </p>
*
* You can also write:
*
* <pre>
* @RunWith(Parameterized.class)
* public class FibonacciTest {
* @Parameters
* public static Iterable<Object[]> data() {
* return Arrays.asList(new Object[][] { { 0, 0 }, { 1, 1 }, { 2, 1 },
* { 3, 2 }, { 4, 3 }, { 5, 5 }, { 6, 8 } });
* }
*
* @Parameter(0)
* public int fInput;
*
* @Parameter(1)
* public int fExpected;
*
* @Test
* public void test() {
* assertEquals(fExpected, Fibonacci.compute(fInput));
* }
* }
* </pre>
*
* <p>
* Each instance of <code>FibonacciTest</code> will be constructed with the default constructor
* and fields annotated by <code>@Parameter</code> will be initialized
* with the data values in the <code>@Parameters</code> method.
* </p>
*
* @since 4.0
*/
public class Parameterized extends Suite {
/**
* Annotation for a method which provides parameters to be injected into the
* test class constructor by <code>Parameterized</code>
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public static @interface Parameters {
/**
* <p>
* Optional pattern to derive the test's name from the parameters. Use
* numbers in braces to refer to the parameters or the additional data
* as follows:
* </p>
*
* <pre>
* {index} - the current parameter index
* {0} - the first parameter value
* {1} - the second parameter value
* etc...
* </pre>
* <p>
* Default value is "{index}" for compatibility with previous JUnit
* versions.
* </p>
*
* @return {@link MessageFormat} pattern string, except the index
* placeholder.
* @see MessageFormat
*/
String name() default "{index}";
}
/**
* Annotation for fields of the test class which will be initialized by the
* method annotated by <code>Parameters</code><br/>
* By using directly this annotation, the test class constructor isn't needed.<br/>
* Index range must start at 0.
* Default value is 0.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public static @interface Parameter {
/**
* Method that returns the index of the parameter in the array
* returned by the method annotated by <code>Parameters</code>.<br/>
* Index range must start at 0.
* Default value is 0.
*
* @return the index of the parameter.
*/
int value() default 0;
}
protected class TestClassRunnerForParameters extends BlockJUnit4ClassRunner {
private final Object[] fParameters;
private final String fPattern;
private final int fIndex;
protected TestClassRunnerForParameters(Class<?> type, String pattern, int index, Object[] parameters) throws InitializationError {
super(type);
fPattern = pattern;
fIndex = index;
fParameters = parameters;
}
@Override
public Object createTest() throws Exception {
if (fieldsAreAnnotated()) {
return createTestUsingFieldInjection();
} else {
return createTestUsingConstructorInjection();
}
}
private Object createTestUsingConstructorInjection() throws Exception {
return getTestClass().getOnlyConstructor().newInstance(fParameters);
}
private Object createTestUsingFieldInjection() throws Exception {
List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter();
if (annotatedFieldsByParameter.size() != fParameters.length) {
throw new Exception("Wrong number of parameters and @Parameter fields." +
" @Parameter fields counted: " + annotatedFieldsByParameter.size() + ", available parameters: " + fParameters.length + ".");
}
Object testClassInstance = getTestClass().getJavaClass().newInstance();
for (FrameworkField each : annotatedFieldsByParameter) {
Field field = each.getField();
Parameter annotation = field.getAnnotation(Parameter.class);
int index = annotation.value();
try {
field.set(testClassInstance, fParameters[index]);
} catch (IllegalArgumentException iare) {
throw new Exception(getTestClass().getName() + ": Trying to set " + field.getName() +
" with the value " + fParameters[index] +
" that is not the right type (" + fParameters[index].getClass().getSimpleName() + " instead of " +
field.getType().getSimpleName() + ").", iare);
}
}
return testClassInstance;
}
@Override
protected String getName() {
String finalPattern = fPattern.replaceAll("\\{index\\}", Integer.toString(fIndex));
String name = MessageFormat.format(finalPattern, fParameters);
return "[" + name + "]";
}
@Override
protected String testName(FrameworkMethod method) {
return method.getName() + getName();
}
@Override
protected void validateConstructor(List<Throwable> errors) {
validateOnlyOneConstructor(errors);
if (fieldsAreAnnotated()) {
validateZeroArgConstructor(errors);
}
}
@Override
protected void validateFields(List<Throwable> errors) {
super.validateFields(errors);
if (fieldsAreAnnotated()) {
List<FrameworkField> annotatedFieldsByParameter = getAnnotatedFieldsByParameter();
int[] usedIndices = new int[annotatedFieldsByParameter.size()];
for (FrameworkField each : annotatedFieldsByParameter) {
int index = each.getField().getAnnotation(Parameter.class).value();
if (index < 0 || index > annotatedFieldsByParameter.size() - 1) {
errors.add(
new Exception("Invalid @Parameter value: " + index + ". @Parameter fields counted: " +
annotatedFieldsByParameter.size() + ". Please use an index between 0 and " +
(annotatedFieldsByParameter.size() - 1) + ".")
);
} else {
usedIndices[index]++;
}
}
for (int index = 0; index < usedIndices.length; index++) {
int numberOfUse = usedIndices[index];
if (numberOfUse == 0) {
errors.add(new Exception("@Parameter(" + index + ") is never used."));
} else if (numberOfUse > 1) {
errors.add(new Exception("@Parameter(" + index + ") is used more than once (" + numberOfUse + ")."));
}
}
}
}
@Override
protected Statement classBlock(RunNotifier notifier) {
return childrenInvoker(notifier);
}
@Override
protected Annotation[] getRunnerAnnotations() {
return new Annotation[0];
}
}
private static final List<Runner> NO_RUNNERS = Collections.<Runner>emptyList();
private final ArrayList<Runner> runners = new ArrayList<Runner>();
/**
* Only called reflectively. Do not use programmatically.
*/
public Parameterized(Class<?> klass) throws Throwable {
super(klass, NO_RUNNERS);
Parameters parameters = getParametersMethod().getAnnotation(
Parameters.class);
createRunnersForParameters(allParameters(), parameters.name());
}
@Override
protected List<Runner> getChildren() {
return runners;
}
protected Runner createRunner(String pattern, int index, Object[] parameters) throws InitializationError {
return new TestClassRunnerForParameters(getTestClass().getJavaClass(), pattern, index, parameters);
}
@SuppressWarnings("unchecked")
private Iterable<Object[]> allParameters() throws Throwable {
Object parameters = getParametersMethod().invokeExplosively(null);
if (parameters instanceof Iterable) {
return (Iterable<Object[]>) parameters;
} else {
throw parametersMethodReturnedWrongType();
}
}
private FrameworkMethod getParametersMethod() throws Exception {
List<FrameworkMethod> methods = getTestClass().getAnnotatedMethods(
Parameters.class);
for (FrameworkMethod each : methods) {
if (each.isStatic() && each.isPublic()) {
return each;
}
}
throw new Exception("No public static parameters method on class "
+ getTestClass().getName());
}
private void createRunnersForParameters(Iterable<Object[]> allParameters, String namePattern) throws Exception {
try {
int i = 0;
for (Object[] parametersOfSingleTest : allParameters) {
runners.add(createRunner(namePattern, i++, parametersOfSingleTest));
}
} catch (ClassCastException e) {
throw parametersMethodReturnedWrongType();
}
}
private Exception parametersMethodReturnedWrongType() throws Exception {
String className = getTestClass().getName();
String methodName = getParametersMethod().getName();
String message = MessageFormat.format(
"{0}.{1}() must return an Iterable of arrays.",
className, methodName);
return new Exception(message);
}
private List<FrameworkField> getAnnotatedFieldsByParameter() {
return getTestClass().getAnnotatedFields(Parameter.class);
}
private boolean fieldsAreAnnotated() {
return !getAnnotatedFieldsByParameter().isEmpty();
}
} |
package org.lantern.state;
import static org.lantern.Tr.tr;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import org.apache.commons.lang.SystemUtils;
import org.lantern.MessageKey;
import org.lantern.Messages;
import org.lantern.event.Events;
import org.lantern.event.ResetEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.eventbus.Subscribe;
import com.google.inject.Inject;
import com.google.inject.Singleton;
@Singleton
public class InternalState {
private final Logger log = LoggerFactory.getLogger(getClass());
private Modal lastModal;
private final Modal[] modalSeqGive = {
Modal.authorize, Modal.lanternFriends,
Modal.finished, Modal.none,
};
private final Modal[] modalSeqGet = {
Modal.authorize, Modal.lanternFriends, Modal.proxiedSites,
Modal.finished, Modal.none,
};
private final Collection<Modal> modalsCompleted = new HashSet<Modal>();
private final Model model;
private boolean notInvited = false;
private final Messages msgs;
public Modal getLastModal() {
return this.lastModal;
}
public void setLastModal(final Modal lastModal) {
this.lastModal = lastModal;
}
@Inject
public InternalState(final Model model, final Messages msgs) {
this.model = model;
this.msgs = msgs;
Events.register(this);
}
public void advanceModal(final Modal backToIfNone) {
final Modal[] seq;
if (this.model.getSettings().getMode() == Mode.get) {
seq = modalSeqGet;
} else if(this.model.getSettings().getMode() == Mode.give) {
seq = modalSeqGive;
} else {
Events.syncModal(this.model, Modal.welcome);
return;
}
Modal next = null;
for (final Modal modal : seq) {
if (!this.modalsCompleted.contains(modal)) {
log.info("Got modal!! ({})", modal);
next = modal;
break;
}
}
log.debug("next modal: {}", next);
if (backToIfNone != null && next != null && next == Modal.none) {
next = backToIfNone;
}
if (next == Modal.none) {
this.model.setSetupComplete(true);
Events.sync(SyncPath.SETUPCOMPLETE, true);
if (!model.isWelcomeMessageShown()) {
model.setWelcomeMessageShown(true);
final MessageKey iconLoc;
if (SystemUtils.IS_OS_MAC_OSX || SystemUtils.IS_OS_LINUX) {
iconLoc = MessageKey.ICONLOC_MENUBAR;
} else if (SystemUtils.IS_OS_WINDOWS) {
iconLoc = MessageKey.ICONLOC_SYSTRAY;
} else {
log.warn("unsupported OS");
iconLoc = MessageKey.ICONLOC_UNKNOWN;
}
this.msgs.info(MessageKey.SETUP, tr(iconLoc));
}
}
Events.syncModal(this.model, next);
}
public void setCompletedTo(final Modal stopAt) {
final Modal[] seq;
if (this.model.getSettings().getMode() == Mode.get) {
seq = modalSeqGet;
} else {
seq = modalSeqGive;
}
if(!Arrays.asList(seq).contains(stopAt)) return;
for (final Modal modal : seq) {
if(modal == stopAt) break;
if (!this.modalsCompleted.contains(modal)) {
setModalCompleted(modal);
}
}
return;
}
public void setModalCompleted(final Modal modal) {
this.modalsCompleted.add(modal);
}
@Subscribe
public void onReset(final ResetEvent re) {
modalsCompleted.clear();
setNotInvited(false);
}
public boolean isNotInvited() {
return notInvited;
}
public void setNotInvited(boolean notInvited) {
this.notInvited = notInvited;
}
} |
package org.libsmith.anvil.text;
import javax.annotation.Nonnull;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
/**
* @author Dmitriy Balakin <dmitriy.balakin@0x0000.ru>
* @created 21.03.16 2:54
*/
public class Strings {
public static boolean isEmpty(CharSequence charSequence) {
return charSequence == null || charSequence.toString().isEmpty();
}
public static boolean isEmpty(Supplier<? extends CharSequence> supplier) {
CharSequence val = supplier == null ? null : supplier.get();
return val == null || val.toString().isEmpty();
}
public static <T extends CharSequence> boolean isEmpty(LazyCharSequence<T> supplier) {
return isEmpty((Supplier<T>) supplier);
}
public static boolean isNotEmpty(CharSequence string) {
return string != null && !string.toString().isEmpty();
}
public static boolean isNotEmpty(Supplier<? extends CharSequence> supplier) {
CharSequence val = supplier == null ? null : supplier.get();
return val != null && !val.toString().isEmpty();
}
public static <T extends CharSequence> boolean isNotEmpty(LazyCharSequence<T> supplier) {
return isNotEmpty((Supplier<T>) supplier);
}
public static boolean isBlank(CharSequence charSequence) {
if (charSequence != null) {
for (int p = 0, l = charSequence.length(); p < l; p++) {
if (!Character.isWhitespace(charSequence.charAt(p))) {
return false;
}
}
}
return true;
}
public static boolean isBlank(Supplier<? extends CharSequence> supplier) {
CharSequence val = supplier == null ? null : supplier.get();
return isBlank(val);
}
public static <T extends CharSequence> boolean isBlank(LazyCharSequence<T> supplier) {
return isBlank((Supplier<T>) supplier);
}
public static boolean isNotBlank(CharSequence charSequence) {
return !isBlank(charSequence);
}
public static boolean isNotBlank(Supplier<? extends CharSequence> supplier) {
CharSequence val = supplier == null ? null : supplier.get();
return !isBlank(val);
}
public static <T extends CharSequence> boolean isNotBlank(LazyCharSequence<T> supplier) {
return !isBlank((Supplier<T>) supplier);
}
public static <T extends CharSequence> LazyCharSequence<T> lazy(Supplier<T> supplier) {
return new LazyCharSequence<>(supplier);
}
public static LazyCharSequence<String> lazy(CharSequence charSequence) {
return new LazyCharSequence<>(() -> charSequence == null ? null : charSequence.toString());
}
public static LazyCharSequence<String> lazy(CharSequence pattern, Object ... arguments) {
return new LazyCharSequence<>(() -> pattern == null ? null
: MessageFormat.format(pattern.toString(), arguments));
}
public static LazyStringBuilder lazyStringBuilder() {
return new LazyStringBuilder();
}
public static class LazyStringBuilder implements Appendable, CharSequence {
private StringBuilder stringBuilder = new StringBuilder();
private List<Supplier<?>> suppliers = new ArrayList<>();
protected LazyStringBuilder()
{ }
public LazyStringBuilder append(LazyCharSequence<?> supplier) {
return append((Supplier<?>) supplier);
}
public LazyStringBuilder append(Supplier<?> supplier) {
suppliers.add(supplier == null ? () -> "null" : supplier);
return this;
}
public LazyStringBuilder append(Object object) {
return append(() -> String.valueOf(object));
}
@Override
public LazyStringBuilder append(CharSequence csq) throws IOException {
suppliers.add(() -> csq);
return this;
}
@Override
public LazyStringBuilder append(CharSequence csq, int start, int end) throws IOException {
suppliers.add(() -> (csq == null ? "null" : csq).subSequence(start, end));
return this;
}
@Override
public LazyStringBuilder append(char c) throws IOException {
suppliers.add(() -> c);
return this;
}
@Override
public int length() {
return build().length();
}
@Override
public char charAt(int index) {
return build().charAt(index);
}
@Override
public CharSequence subSequence(int start, int end) {
return build().subSequence(start, end);
}
@Override
public @Nonnull String toString() {
return build().toString();
}
private StringBuilder build() {
suppliers.stream().map(Supplier::get).forEach(stringBuilder::append);
return stringBuilder;
}
}
public static class LazyCharSequence<T extends CharSequence> implements Supplier<T>, CharSequence {
private final Supplier<T> supplier;
private T value;
protected LazyCharSequence(Supplier<T> supplier) {
this.supplier = supplier;
}
@Override
public int length() {
return get().length();
}
@Override
public char charAt(int index) {
return get().charAt(index);
}
@Override
public CharSequence subSequence(int start, int end) {
return get().subSequence(start, end);
}
@Override
public T get() {
return value == null ? value = supplier.get() : value;
}
@Override
public @Nonnull String toString() {
return get().toString();
}
}
} |
package org.lightmare.remote.rpc;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.io.IOException;
import org.lightmare.config.ConfigKeys;
import org.lightmare.config.Configuration;
import org.lightmare.remote.rcp.RcpHandler;
import org.lightmare.remote.rcp.decoders.RcpDecoder;
import org.lightmare.remote.rpc.decoders.RpcEncoder;
import org.lightmare.remote.rpc.wrappers.RpcWrapper;
import org.lightmare.utils.concurrent.ThreadFactoryUtil;
/**
* Client class to produce remote procedure call
*
* @author levan
* @since 0.0.21-SNAPSHOT
*/
public class RPCall {
private String host;
private int port;
private RcpHandler handler;
private static int timeout;
private static int workerPoolSize;
private static EventLoopGroup worker;
private static final int ZERO_TIMEOUT = 0;
/**
* Implementation of {@link ChannelInitializer} on {@link SocketChannel} for
* RPC service client
*
* @author Levan
*
*/
protected static class ChannelInitializerImpl extends
ChannelInitializer<SocketChannel> {
private RcpHandler handler;
public ChannelInitializerImpl(RcpHandler handler) {
this.handler = handler;
}
@Override
public void initChannel(SocketChannel ch) throws Exception {
RpcEncoder rpcEncoder = new RpcEncoder();
RcpDecoder rcpDecoder = new RcpDecoder();
ch.pipeline().addLast(rpcEncoder, rcpDecoder, handler);
}
}
public RPCall(String host, int port) {
this.host = host;
this.port = port;
}
public static void configure(Configuration config) {
if (worker == null) {
workerPoolSize = config.getIntValue(ConfigKeys.WORKER_POOL.key);
timeout = config.getIntValue(ConfigKeys.CONNECTION_TIMEOUT.key);
worker = new NioEventLoopGroup(workerPoolSize,
new ThreadFactoryUtil("netty-worker-thread",
(Thread.MAX_PRIORITY - 1)));
}
}
private Bootstrap getBootstrap() {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(worker);
bootstrap.channel(NioSocketChannel.class);
bootstrap.option(ChannelOption.SO_KEEPALIVE, Boolean.TRUE);
if (timeout > ZERO_TIMEOUT) {
bootstrap.option(ChannelOption.SO_TIMEOUT, timeout);
}
handler = new RcpHandler();
bootstrap.handler(new ChannelInitializerImpl(handler));
return bootstrap;
}
public Object call(RpcWrapper wrapper) throws IOException {
Object value;
try {
Bootstrap bootstrap = getBootstrap();
try {
ChannelFuture future = bootstrap.connect(host, port).sync();
future.channel().closeFuture().sync();
} catch (InterruptedException ex) {
throw new IOException(ex);
}
value = handler.getWrapper();
} finally {
worker.shutdownGracefully();
}
return value;
}
} |
package org.lightmare.utils;
/**
* Utility class for JNDI names
*
* @author levan
* @since 0.0.60-SNAPSHOT
*/
public class NamingUtils {
// User transaction JNDI name
public static final String USER_TRANSACTION_NAME = "java:comp/UserTransaction";
// String prefixes for EJB JNDI names
public static final String JPA_NAME_PREF = "java:comp/env/";
public static final String EJB_NAME_PREF = "ejb:";
private static final String DS_JNDI_FREFIX = "java:/";
private static final String EJB_NAME_DELIM = "\\";
private static final String EJB_APP_DELIM = "!";
// Digital values for naming utilities
public static final int EJB_NAME_LENGTH = 4;
private static final int BEAN_NAMES_INDEX = 1;
private static final int INTERFACE_IDEX = 0;
private static final int BEAN_INDEX = 1;
// Error messages
public static final String COULD_NOT_UNBIND_NAME_ERROR = "Could not unbind jndi name %s cause %s";
/**
* Descriptor class which contains EJB bean class name and its interface
* class name
*
* @author levan
*
*/
public static class BeanDescriptor {
private String beanName;
private String interfaceName;
public BeanDescriptor(String beanName, String interfaceName) {
this.beanName = beanName;
this.interfaceName = interfaceName;
}
public String getBeanName() {
return beanName;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
public String getInterfaceName() {
return interfaceName;
}
public void setInterfaceName(String interfaceName) {
this.interfaceName = interfaceName;
}
}
/**
* Creates JNDI name prefixes for JPA objects
*
* @param jndiName
* @return
*/
public static String createJpaJndiName(String jndiName) {
return StringUtils.concat(JPA_NAME_PREF, jndiName);
}
/**
* Converts passed JNDI name to JPA name
*
* @param jndiName
* @return {@link String}
*/
public static String formatJpaJndiName(String jndiName) {
String name = jndiName.replace(JPA_NAME_PREF, StringUtils.EMPTY_STRING);
return name;
}
/**
* Creates EJB names from passed JNDI name
*
* @param jndiName
* @return {@link String}
*/
public static String createEjbJndiName(String jndiName) {
return StringUtils.concat(EJB_NAME_PREF, jndiName);
}
/**
* Converts passed JNDI name to bean name
*
* @param jndiName
* @return {@link String}
*/
public static String formatEjbJndiName(String jndiName) {
String name = jndiName.replace(EJB_NAME_PREF, StringUtils.EMPTY_STRING);
return name;
}
/**
* Clears JNDI prefix "java:/" for data source name
*
* @param jndiName
* @return {@link String}
*/
public static String clearDataSourceName(String jndiName) {
String clearName;
if (StringUtils.valid(jndiName) && jndiName.startsWith(DS_JNDI_FREFIX)) {
clearName = jndiName.replace(DS_JNDI_FREFIX,
StringUtils.EMPTY_STRING);
} else {
clearName = jndiName;
}
return clearName;
}
/**
* Adds JNDI prefix "java:/" to data source name
*
* @param clearName
* @return {@link String}
*/
public static String toJndiDataSourceName(String clearName) {
String jndiName;
if (StringUtils.valid(clearName)
&& StringUtils.notContains(clearName, DS_JNDI_FREFIX)) {
jndiName = StringUtils.concat(DS_JNDI_FREFIX, clearName);
} else {
jndiName = clearName;
}
return jndiName;
}
/**
* Parses bean JNDI name for lookup bean
*
* @param jndiName
* @return {@link BeanDescriptor}
*/
public static BeanDescriptor parseEjbJndiName(String jndiName) {
BeanDescriptor descriptor;
String pureName = jndiName.substring(EJB_NAME_LENGTH);
String[] formatedNames = pureName.split(EJB_NAME_DELIM);
String beanNames = formatedNames[BEAN_NAMES_INDEX];
String[] beanDescriptors = beanNames.split(EJB_APP_DELIM);
String interfaceName = beanDescriptors[INTERFACE_IDEX];
String beanName = beanDescriptors[BEAN_INDEX];
descriptor = new BeanDescriptor(beanName, interfaceName);
return descriptor;
}
} |
package sword.blemesh.sdk.app.ui;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import sword.blemesh.sdk.R;
import sword.blemesh.sdk.app.BleMeshService;
import sword.blemesh.sdk.app.adapter.PeerAdapter;
import sword.blemesh.sdk.mesh_graph.Peer;
import sword.blemesh.sdk.transport.Transport;
/**
* A Fragment that supports discovering peers and sending or receiving data to/from them.
*
* The three static creators instantiate the Fragment in one of three modes:
*
* <ul>
* <li> SEND : The Fragment is created with a username, service name and data payload that will
* be sent to a peer the user selects. Completion will be indicated by the callback method
* {@link sword.blemesh.sdk.app.ui.PeerFragment.PeerFragmentListener#onFinished(Exception)}
* </li>
*
* <li> RECEIVE : The Fragment is created with a username and service name and will await transfer
* from a sending peer. Completion will be indicated by the callback method
* {@link sword.blemesh.sdk.app.ui.PeerFragment.PeerFragmentListener#onFinished(Exception)}
* </li>
*
* <li> BOTH : The Fragment is created with a username and service name and will await transfer
* from a sending peer and request data to send when a receiving peer is selected.
* Completion will only be indicated in case of error by the callback method
* {@link sword.blemesh.sdk.app.ui.PeerFragment.PeerFragmentListener#onFinished(Exception)}
* </li>
* </ul>
*
* An Activity that hosts PeerFragment must implement
* {@link sword.blemesh.sdk.app.ui.PeerFragment.PeerFragmentListener}
*/
public class PeerFragment extends BleMeshFragment implements BleMeshService.Callback,
BleMeshFragment.Callback {
/** Bundle parameters */
// BleMeshFragment provides username, servicename
private static final String ARG_MODE = "mode";
private static final String ARG_PAYLOAD = "payload";
public enum Mode { SEND, RECEIVE, BOTH }
public interface PeerFragmentListener {
/**
* A transfer was received from a peer.
* Called when mode is {@link Mode#RECEIVE} or {@link Mode#BOTH}
*/
void onDataReceived(@NonNull PeerFragment fragment,
@Nullable byte[] payload,
@NonNull Peer sender);
/**
* A transfer was sent to a peer.
* Called when mode is {@link Mode#SEND} or {@link Mode#BOTH}
*/
void onDataSent(@NonNull PeerFragment fragment,
@Nullable byte[] data,
@NonNull Peer recipient,
@NonNull Peer desc);
/**
* The user selected recipient to receive data. Provide that data in a call
* to {@link #sendDataToPeer(byte[], Peer)}
* Called when mode is {@link Mode#BOTH}
*/
void onDataRequestedForPeer(@NonNull PeerFragment fragment,
@NonNull Peer recipient);
/**
* The fragment is complete and should be removed by the host Activity.
*
* If exception is null, the fragment has completed it's requested operation,
* else an error occurred.
*/
void onFinished(@NonNull PeerFragment fragment,
@Nullable Exception exception);
void onNewLog(@NonNull String logText);
}
private ViewGroup emptyContainer;
private RecyclerView recyclerView;
private PeerAdapter peerAdapter;
private PeerFragmentListener callback;
private BleMeshService.ServiceBinder serviceBinder;
private Mode mode;
private byte[] payload;
public static PeerFragment toSend(@NonNull byte[] toSend,
@NonNull String username,
@NonNull String serviceName) {
Bundle bundle = new Bundle();
bundle.putSerializable(ARG_PAYLOAD, toSend);
return init(bundle, Mode.SEND, username, serviceName);
}
public static PeerFragment toReceive(@NonNull String username,
@NonNull String serviceName) {
return init(null, Mode.RECEIVE, username, serviceName);
}
public static PeerFragment toSendAndReceive(@NonNull String username,
@NonNull String serviceName) {
return init(null, Mode.BOTH, username, serviceName);
}
private static PeerFragment init(@Nullable Bundle bundle,
@NonNull Mode mode,
@NonNull String username,
@NonNull String serviceName) {
if (bundle == null) bundle = new Bundle();
bundle.putSerializable(ARG_MODE, mode);
bundle.putString(BleMeshFragment.ARG_USERNAME, username);
bundle.putString(BleMeshFragment.ARG_SERVICENAME, serviceName);
PeerFragment fragment = new PeerFragment();
fragment.setArguments(bundle);
return fragment;
}
public PeerFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setBleMeshCallback(this);
if (getArguments() != null) {
mode = (Mode) getArguments().getSerializable(ARG_MODE);
payload = (byte[]) getArguments().getSerializable(ARG_PAYLOAD);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
Context context = getActivity();
View root = inflater.inflate(R.layout.fragment_peer, container, false);
peerAdapter = new PeerAdapter(context, new ArrayList<Peer>());
emptyContainer = (ViewGroup) root.findViewById(R.id.empty_container);
recyclerView = (RecyclerView) root.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(context));
recyclerView.setAdapter(peerAdapter);
peerAdapter.setOnPeerViewClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onPeerSelected((Peer) v.getTag());
}
});
return root;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
callback = (PeerFragmentListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement PeerFragmentListener");
}
}
@Override
public void onDetach() {
super.onDetach();
callback = null;
}
/**
* Send data to recipient. Used when mode is {@link Mode#BOTH}.
*
* Should be called by a client in response to the PeerFragmentCallback method:
* {@link sword.blemesh.sdk.app.ui.PeerFragment.PeerFragmentListener#onDataRequestedForPeer(PeerFragment, Peer)}
*/
public void sendDataToPeer(byte[] data, Peer recipient) {
serviceBinder.send(data, recipient);
}
/** An available peer was selected from {@link sword.blemesh.sdk.app.adapter.PeerAdapter} */
public void onPeerSelected(Peer peer) {
switch (mode) {
case SEND:
serviceBinder.send(payload, peer);
break;
case BOTH:
callback.onDataRequestedForPeer(this, peer);
break;
case RECEIVE:
// do nothing
break;
}
}
@Override
public void onDataRecevied(@NonNull BleMeshService.ServiceBinder binder, byte[] data, @NonNull Peer sender, Exception exception) {
if (callback == null) return; // Fragment was detached but not destroyed
callback.onDataReceived(this, data, sender);
/* if (mode == Mode.RECEIVE)
callback.onFinished(this, null);*/
}
@Override
public void onDataSent(@NonNull BleMeshService.ServiceBinder binder, byte[] data, @NonNull Peer recipient, @NonNull Peer desc, Exception exception) {
if (callback == null) return; // Fragment was detached but not destroyed
callback.onDataSent(this, data, recipient, desc);
/* if (mode == Mode.SEND)
callback.onFinished(this, null);*/
}
@Override
public void onPeerStatusUpdated(@NonNull BleMeshService.ServiceBinder binder, @NonNull Peer peer, @NonNull Transport.ConnectionStatus newStatus, boolean peerIsHost) {
switch (newStatus) {
case CONNECTED:
peerAdapter.notifyPeerAdded(peer);
emptyContainer.setVisibility(View.GONE);
break;
case DISCONNECTED:
peerAdapter.notifyPeerRemoved(peer);
if (peerAdapter.getItemCount() == 0) {
emptyContainer.setVisibility(View.VISIBLE);
}
break;
}
}
@Override
public void onPeersStatusUpdated(@NonNull BleMeshService.ServiceBinder binder,
@NonNull LinkedHashMap<String, Peer> vertexes,
@NonNull boolean isJoinAction){
peerAdapter.notifyPeersUpdated(vertexes,isJoinAction);
if(isJoinAction){
emptyContainer.setVisibility(View.GONE);
}else{
if (peerAdapter.getItemCount() == 0) { //only local node left;
emptyContainer.setVisibility(View.VISIBLE);
}
}
}
@Override
public void onNewLog(@NonNull String logText) {
callback.onNewLog(logText);
}
@Override
public void onServiceReady(@NonNull BleMeshService.ServiceBinder serviceBinder) {
this.serviceBinder = serviceBinder;
this.serviceBinder.setCallback(this);
switch (mode) {
case SEND:
this.serviceBinder.scanForOtherUsers();
break;
case RECEIVE:
this.serviceBinder.advertiseLocalUser();
break;
case BOTH:
this.serviceBinder.startTransport();
}
}
@Override
public void onFinished(Exception e) {
if (callback == null) return; // Fragment was detached but not destroyed
callback.onFinished(this, e);
}
} |
package org.minimalj.frontend.form;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.function.Function;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.minimalj.application.Configuration;
import org.minimalj.frontend.Frontend;
import org.minimalj.frontend.Frontend.FormContent;
import org.minimalj.frontend.Frontend.IComponent;
import org.minimalj.frontend.form.element.BigDecimalFormElement;
import org.minimalj.frontend.form.element.CheckBoxFormElement;
import org.minimalj.frontend.form.element.CodeFormElement;
import org.minimalj.frontend.form.element.Enable;
import org.minimalj.frontend.form.element.EnumFormElement;
import org.minimalj.frontend.form.element.EnumSetFormElement;
import org.minimalj.frontend.form.element.FormElement;
import org.minimalj.frontend.form.element.IntegerFormElement;
import org.minimalj.frontend.form.element.LocalDateFormElement;
import org.minimalj.frontend.form.element.LocalDateTimeFormElement;
import org.minimalj.frontend.form.element.LocalTimeFormElement;
import org.minimalj.frontend.form.element.LongFormElement;
import org.minimalj.frontend.form.element.PasswordFormElement;
import org.minimalj.frontend.form.element.SelectionFormElement;
import org.minimalj.frontend.form.element.SmallCodeListFormElement;
import org.minimalj.frontend.form.element.StringFormElement;
import org.minimalj.frontend.form.element.TableFormElement;
import org.minimalj.frontend.form.element.TextFormElement;
import org.minimalj.frontend.form.element.UnknownFormElement;
import org.minimalj.model.Code;
import org.minimalj.model.Keys;
import org.minimalj.model.Selection;
import org.minimalj.model.annotation.Enabled;
import org.minimalj.model.annotation.NotEmpty;
import org.minimalj.model.annotation.Visible;
import org.minimalj.model.properties.ChainedProperty;
import org.minimalj.model.properties.PropertyInterface;
import org.minimalj.model.validation.ValidationMessage;
import org.minimalj.security.model.Password;
import org.minimalj.util.ChangeListener;
import org.minimalj.util.CloneHelper;
import org.minimalj.util.Codes;
import org.minimalj.util.EqualsHelper;
import org.minimalj.util.ExceptionUtils;
import org.minimalj.util.FieldUtils;
import org.minimalj.util.mock.Mocking;
public class Form<T> {
private static Logger logger = Logger.getLogger(Form.class.getSimpleName());
public static final boolean EDITABLE = true;
public static final boolean READ_ONLY = false;
public static final int DEFAULT_COLUMN_WIDTH = 100;
public static final Object GROW_FIRST_ELEMENT = new Object();
protected final boolean editable;
private final int columns;
private final FormContent formContent;
private boolean ignoreCaption;
private final LinkedHashMap<PropertyInterface, FormElement<?>> elements = new LinkedHashMap<>();
private final FormChangeListener formChangeListener = new FormChangeListener();
private ChangeListener<Form<?>> changeListener;
private boolean changeFromOutside;
private final Map<String, List<PropertyInterface>> dependencies = new HashMap<>();
@SuppressWarnings("rawtypes")
private final Map<PropertyInterface, Map<PropertyInterface, PropertyUpdater>> propertyUpdater = new HashMap<>();
private final Map<IComponent, Object[]> keysForTitle = new HashMap<>();
private T object;
public Form() {
this(EDITABLE);
}
public Form(boolean editable) {
this(editable, 1);
}
public Form(int columns) {
this(EDITABLE, columns);
}
public Form(boolean editable, int columns) {
this(editable, columns, DEFAULT_COLUMN_WIDTH);
}
public Form(boolean editable, int columns, int columnWidth) {
this.editable = editable;
this.columns = columns;
this.formContent = Frontend.getInstance().createFormContent(columns, columnWidth);
}
public Form(boolean editable, List<Integer> columnWidths) {
this.editable = editable;
this.columns = columnWidths.size();
this.formContent = Frontend.getInstance().createFormContent(columnWidths);
}
// Methods to create the form
public FormContent getContent() {
return formContent;
}
protected FormElement<?> createElement(Object key) {
FormElement<?> element = null;
PropertyInterface property;
boolean forcedReadonly = false;
if (key instanceof ReadOnlyWrapper) {
forcedReadonly = true;
key = ((ReadOnlyWrapper) key).key;
}
if (key == null) {
throw new NullPointerException("Key must not be null");
} else if (key instanceof Function) {
return createElement(((Function) key).apply(this.editable &&!forcedReadonly));
} else if (key instanceof FormElement) {
element = (FormElement<?>) key;
property = element.getProperty();
if (property == null) throw new IllegalArgumentException(IComponent.class.getSimpleName() + " has no key");
} else {
property = Keys.getProperty(key);
if (property != null) {
boolean editable = !forcedReadonly && this.editable
&& !(FieldUtils.isAllowedPrimitive(property.getClazz()) && property.isFinal());
element = createElement(property, editable);
}
}
return element;
}
@SuppressWarnings("rawtypes")
protected FormElement<?> createElement(PropertyInterface property, boolean editable) {
Class<?> fieldClass = property.getClazz();
if (fieldClass == String.class) {
return editable ? new StringFormElement(property) : new TextFormElement(property);
} else if (fieldClass == Boolean.class) {
return new CheckBoxFormElement(property, editable);
} else if (fieldClass == Integer.class) {
return new IntegerFormElement(property, editable);
} else if (fieldClass == Long.class) {
return new LongFormElement(property, editable);
} else if (fieldClass == BigDecimal.class) {
return new BigDecimalFormElement(property, editable);
} else if (fieldClass == LocalDate.class) {
return new LocalDateFormElement(property, editable);
} else if (fieldClass == LocalTime.class) {
return new LocalTimeFormElement(property, editable);
} else if (fieldClass == LocalDateTime.class) {
return new LocalDateTimeFormElement(property, editable);
} else if (Code.class.isAssignableFrom(fieldClass)) {
return editable ? new CodeFormElement(property) : new TextFormElement(property);
} else if (Enum.class.isAssignableFrom(fieldClass)) {
return editable ? new EnumFormElement(property) : new TextFormElement(property);
} else if (fieldClass == Set.class) {
return new EnumSetFormElement(property, editable);
} else if (fieldClass == List.class && Codes.isCode(property.getGenericClass())) {
return new SmallCodeListFormElement(property, editable);
} else if (fieldClass == Password.class) {
return new PasswordFormElement(new ChainedProperty(property, Keys.getProperty(Password.$.getPassword())));
} else if (fieldClass == Selection.class) {
return new SelectionFormElement(property);
}
logger.severe("No FormElement could be created for: " + property.getName() + " of class " + fieldClass.getName());
return new UnknownFormElement(property);
}
public void setIgnoreCaption(boolean ignoreCaption) {
this.ignoreCaption = ignoreCaption;
}
public void line(Object... keys) {
if (keys[0] == GROW_FIRST_ELEMENT) {
assertColumnCount(keys.length - 1);
for (int i = 1; i < keys.length; i++) {
int elementSpan = i == 1 ? columns - keys.length + 2 : 1;
add(keys[i], elementSpan);
}
} else {
assertColumnCount(keys.length);
int span = columns / keys.length;
int rest = columns;
for (int i = 0; i < keys.length; i++) {
int elementSpan = i < keys.length - 1 ? span : rest;
add(keys[i], elementSpan);
rest = rest - elementSpan;
}
}
}
private void assertColumnCount(int elementCount) {
if (elementCount > columns) {
logger.severe("This form was constructed for " + columns + " column(s) but should be filled with " + elementCount + " form elements");
logger.fine("The solution is most probably to add/set the correct number of columns when calling the Form constructor");
throw new IllegalArgumentException("Not enough columns (" + columns + ") for form elements (" + elementCount + ")");
}
}
private void add(Object key, int elementSpan) {
boolean forcedNotEmpty = false;
if (key instanceof NotEmptyWrapper) {
forcedNotEmpty = true;
key = ((NotEmptyWrapper) key).key;
}
FormElement<?> element = createElement(key);
if (element != null) {
add(element, elementSpan, forcedNotEmpty);
} else {
formContent.add(null, false, Frontend.getInstance().createText("" + key), null, elementSpan);
}
}
private void add(FormElement<?> element, int span, boolean forcedNotEmpty) {
boolean required = forcedNotEmpty || element.getProperty().getAnnotation(NotEmpty.class) != null && element.getProperty().getClazz() != Boolean.class;
formContent.add(ignoreCaption ? null : element.getCaption(), required, element.getComponent(), element.getConstraint(), span);
registerNamedElement(element);
addDependencies(element);
}
public static Object readonly(Object key) {
ReadOnlyWrapper wrapper = new ReadOnlyWrapper();
wrapper.key = key;
return wrapper;
}
private static class ReadOnlyWrapper {
private Object key;
}
public static Object notEmpty(Object key, boolean notEmpty) {
return notEmpty ? notEmpty(key) : key;
}
public static Object notEmpty(Object key) {
NotEmptyWrapper wrapper = new NotEmptyWrapper();
wrapper.key = key;
return wrapper;
}
private static class NotEmptyWrapper {
private Object key;
}
public void addTitle(String text, Object... keys) {
IComponent label = Frontend.getInstance().createTitle(text);
formContent.add(null, false, label, null, -1);
if (keys.length > 0) {
keysForTitle.put(label, keys);
}
}
/**
* Declares that if the <i>from</i> property changes all
* the properties with <i>to</i> could change. This is normally used
* if the to <i>to</i> property is a getter that calculates something that
* depends on the <i>from</i> in some way.
*
* @param from the key or property of the field triggering the update
* @param to the field possible changed its value implicitly
*/
public void addDependecy(Object from, Object... to) {
PropertyInterface fromProperty = Keys.getProperty(from);
List<PropertyInterface> list = dependencies.computeIfAbsent(fromProperty.getPath(), p -> new ArrayList<>());
for (Object key : to) {
list.add(Objects.requireNonNull(Keys.getProperty(key)));
}
}
private void addDependecy(PropertyInterface fromProperty, PropertyInterface to) {
addDependecy(fromProperty.getPath(), to);
}
private void addDependecy(String fromPropertyPath, PropertyInterface to) {
List<PropertyInterface> list = dependencies.computeIfAbsent(fromPropertyPath, p -> new ArrayList<>());
list.add(to);
}
/**
* Declares that if the key or property <i>from</i> changes the specified
* updater should be called and after its return the <i>to</i> key or property
* could have changed.<p>
*
* This is used if there is a more complex relation between two fields.
*
* @param <FROM> the type (class) of the fromKey / field
* @param <TO> the type (class) of the toKey / field
* @param from the field triggering the update
* @param updater the updater doing the change of the to field
* @param to the changed field by the updater
*/
public <FROM, TO> void addDependecy(FROM from, PropertyUpdater<FROM, TO, T> updater, TO to) {
PropertyInterface fromProperty = Keys.getProperty(from);
PropertyInterface toProperty = Keys.getProperty(to);
propertyUpdater.computeIfAbsent(fromProperty, p -> new HashMap<>()).put(toProperty, updater);
addDependecy(from, to);
}
@FunctionalInterface
public interface PropertyUpdater<FROM, TO, EDIT_OBJECT> {
/**
*
* @param input The new value of the property that has changed
* @param copyOfEditObject The current object of the This reference should <b>not</b> be changed.
* It should be treated as a read only version or a copy of the object.
* It's probably not a real copy as it is to expensive to copy the object for every call.
* @return The new value the updater wants to set to the toKey property
*/
public TO update(FROM input, EDIT_OBJECT copyOfEditObject);
}
private void registerNamedElement(FormElement<?> field) {
elements.put(field.getProperty(), field);
field.setChangeListener(formChangeListener);
}
private void addDependencies(FormElement<?> field) {
PropertyInterface property = field.getProperty();
List<PropertyInterface> dependencies = Keys.getDependencies(property);
for (PropertyInterface dependency : dependencies) {
addDependecy(dependency, field.getProperty());
}
// a.b.c
String path = property.getPath();
while (path != null && path.contains(".")) {
int pos = path.lastIndexOf('.');
addDependecy(path.substring(0, pos), property);
path = path.substring(0, pos);
}
}
public final void mock() {
changeFromOutside = true;
try {
fillWithDemoData(object);
} catch (Exception x) {
logger.log(Level.SEVERE, "Fill with demo data failed", x);
} finally {
readValueFromObject();
changeFromOutside = false;
}
}
protected void fillWithDemoData(T object) {
for (FormElement<?> field : elements.values()) {
PropertyInterface property = field.getProperty();
if (field instanceof Mocking) {
Mocking demoEnabledElement = (Mocking) field;
demoEnabledElement.mock();
property.setValue(object, field.getValue());
}
}
}
/**
*
* @return Collection provided by a LinkedHashMap so it will be a ordered set
*/
public Collection<PropertyInterface> getProperties() {
return elements.keySet();
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void set(PropertyInterface property, Object value) {
FormElement element = elements.get(property);
try {
element.setValue(value);
} catch (Exception x) {
ExceptionUtils.logReducedStackTrace(logger, x);
}
}
private void setValidationMessage(PropertyInterface property, List<ValidationMessage> validationMessages) {
FormElement<?> formElement = elements.get(property);
if (formElement instanceof TableFormElement) {
TableFormElement<?> positionListFormElement = (TableFormElement<?>) formElement;
positionListFormElement.setValidationMessages(validationMessages);
} else {
formContent.setValidationMessages(formElement.getComponent(), validationMessages.stream().map(ValidationMessage::getFormattedText).collect(Collectors.toList()));
}
}
public void setObject(T object) {
if (editable && changeListener == null) throw new IllegalStateException("Listener has to be set on a editable Form");
if (logger.isLoggable(Level.FINE)) {
logDependencies();
}
changeFromOutside = true;
this.object = object;
readValueFromObject();
changeFromOutside = false;
}
private void readValueFromObject() {
for (PropertyInterface property : getProperties()) {
Object propertyValue = property.getValue(object);
set(property, propertyValue);
}
updateEnable();
updateVisible();
}
private void logDependencies() {
logger.fine("Dependencies in " + this.getClass().getSimpleName());
for (Map.Entry<String, List<PropertyInterface>> entry : dependencies.entrySet()) {
logger.fine(entry.getKey() + " -> " + entry.getValue().stream().map(PropertyInterface::getPath).collect(Collectors.joining(", ")));
}
}
private String getName(FormElement<?> field) {
PropertyInterface property = field.getProperty();
return property.getName();
}
public void setChangeListener(ChangeListener<Form<?>> changeListener) {
this.changeListener = Objects.requireNonNull(changeListener);
}
private class FormChangeListener implements ChangeListener<FormElement<?>> {
@Override
public void changed(FormElement<?> changedField) {
if (changeFromOutside) return;
if (changeListener == null) {
if (editable) logger.severe("Editable Form must have a listener");
return;
}
PropertyInterface property = changedField.getProperty();
Object newValue = changedField.getValue();
logger.fine(() -> "ChangeEvent from element: " + getName(changedField) + ", property: " + property.getPath() + ", value: " + newValue);
HashSet<PropertyInterface> changedProperties = new HashSet<>();
setValue(property, newValue, changedProperties);
logger.fine(() -> "Changed properties: " + changedProperties.stream().map(PropertyInterface::getPath).collect(Collectors.joining(", ")));
if (!changedProperties.isEmpty()) {
// propagate all possible changed values to the form elements
updateDependingFormElements(changedField, changedProperties);
// update enable/disable status of the form elements
updateEnable();
updateVisible();
changeListener.changed(Form.this);
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
private void updateDependingFormElements(FormElement<?> changedFormElement, HashSet<PropertyInterface> changedProperties) {
for (PropertyInterface changedProperty : changedProperties) {
for (FormElement formElement : elements.values()) {
if (formElement == changedFormElement) {
// don't need to update the FormElement where the change comes from
continue;
}
PropertyInterface formElementProperty = formElement.getProperty();
String formElementPath = formElementProperty.getPath();
String changedPropertyPath = changedProperty.getPath();
if (formElementPath.equals(changedPropertyPath) || formElementPath.startsWith(changedPropertyPath) && formElementPath.charAt(changedPropertyPath.length()) == '.') {
Object newValue = formElementProperty.getValue(object);
formElement.setValue(newValue);
}
}
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
private void executeUpdater(PropertyInterface property, Object updaterInput, Object clonedObject, HashSet<PropertyInterface> changedProperties) {
if (propertyUpdater.containsKey(property)) {
Map<PropertyInterface, PropertyUpdater> updaters = propertyUpdater.get(property);
for (Map.Entry<PropertyInterface, PropertyUpdater> entry : updaters.entrySet()) {
Object updaterOutput = entry.getValue().update(updaterInput, clonedObject);
setValue(entry.getKey(), updaterOutput, changedProperties);
}
}
}
private void setValue(PropertyInterface property, Object newValue, HashSet<PropertyInterface> changedProperties) {
Object oldToValue = property.getValue(object);
if (!EqualsHelper.equals(oldToValue, newValue) || newValue instanceof Collection) {
Object clonedObject = CloneHelper.clone(object); // clone before change!
property.setValue(object, newValue);
executeUpdater(property, newValue, clonedObject, changedProperties);
addChangedPropertyRecursive(property, changedProperties);
} else if (newValue instanceof Collection) {
// same instance of Collection can have changed content always assume a change. But not need of setValue .
Object clonedObject = CloneHelper.clone(object);
executeUpdater(property, newValue, clonedObject, changedProperties);
addChangedPropertyRecursive(property, changedProperties);
}
}
private void addChangedPropertyRecursive(PropertyInterface property, HashSet<PropertyInterface> changedProperties) {
changedProperties.add(property);
HashSet<PropertyInterface> changedRoots = new HashSet<>(changedProperties);
changedRoots.forEach(root -> changedProperties.addAll(collectDependencies(root)));
}
private HashSet<PropertyInterface> collectDependencies(PropertyInterface property) {
HashSet<PropertyInterface> collection = new HashSet<>();
collectDependencies(property, collection);
return collection;
}
private void collectDependencies(PropertyInterface property, HashSet<PropertyInterface> collection) {
if (!collection.contains(property)) {
collection.add(property);
if (dependencies.containsKey(property.getName())) {
for (PropertyInterface dependingProperty : dependencies.get(property.getName())) {
collectDependencies(dependingProperty, collection);
}
}
}
}
}
private void updateEnable() {
for (Map.Entry<PropertyInterface, FormElement<?>> element : elements.entrySet()) {
PropertyInterface property = element.getKey();
boolean enabled = evaluate(object, property, Enabled.class);
if (element.getValue() instanceof Enable) {
((Enable) element.getValue()).setEnabled(enabled);
} else if (!enabled) {
if (editable) {
logger.severe("element " + property.getPath() + " should implement Enable");
} else {
logger.fine("element " + property.getPath() + " should maybe implement Enable");
}
}
}
}
private void updateVisible() {
for (Map.Entry<PropertyInterface, FormElement<?>> element : elements.entrySet()) {
PropertyInterface property = element.getKey();
boolean visible = evaluate(object, property, Visible.class);
formContent.setVisible(element.getValue().getComponent(), visible);
}
for (Map.Entry<IComponent, Object[]> element : keysForTitle.entrySet()) {
boolean visible = false;
for (Object key : element.getValue()) {
if (evaluate(object, Keys.getProperty(key), Visible.class)) {
visible = true;
break;
}
}
formContent.setVisible(element.getKey(), visible);
}
}
// TODO move to properties package, remove use of getPath, write tests
static boolean evaluate(Object object, PropertyInterface property, Class<? extends Annotation> annotationClass) {
for (PropertyInterface p2 : ChainedProperty.getChain(property)) {
Annotation annotation = p2.getAnnotation(annotationClass);
if (annotation != null) {
// No common class between Enabled and Visible
String condition = annotation instanceof Enabled ? ((Enabled) annotation).value() : ((Visible) annotation).value();
if (!evaluateCondition(object, p2, condition)) {
return false;
}
}
}
return true;
}
static boolean evaluateCondition(Object object, PropertyInterface property, String methodName) {
boolean invert = methodName.startsWith("!");
if (invert)
methodName = methodName.substring(1);
try {
Class<?> clazz = object.getClass();
Method method = clazz.getMethod(methodName);
if (!((Boolean) method.invoke(object) ^ invert)) {
return false;
}
} catch (Exception x) {
String fieldName = property.getName();
if (!fieldName.equals(property.getPath())) {
fieldName += " (" + property.getPath() + ")";
}
logger.log(Level.SEVERE, "Update enable of " + fieldName + " failed", x);
}
return true;
}
public boolean indicate(List<ValidationMessage> validationMessages) {
List<ValidationMessage> unused = new ArrayList<>(validationMessages);
boolean relevantValidationMessage = false;
for (PropertyInterface property : getProperties()) {
List<ValidationMessage> filteredValidationMessages = ValidationMessage.filterValidationMessage(validationMessages, property);
setValidationMessage(property, filteredValidationMessages);
relevantValidationMessage |= !filteredValidationMessages.isEmpty();
unused.removeAll(filteredValidationMessages);
}
if (!unused.isEmpty()) {
for (ValidationMessage unusedMessage : unused) {
logger.log(Configuration.isDevModeActive() ? Level.WARNING : Level.FINER, "Unused validation message for: " + unusedMessage.getProperty().getPath());
}
}
return relevantValidationMessage;
}
} |
package ru.job4j.max;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Test.
*
* @author Vladimir Zhirnov (harabe@yandex.ru)
* @version $Id$
* @since 0.1
*/
public class MaxTest {
/**
* Test add.
*/
@Test
public void testMaxValue() {
Max maxValueOne = new Max();
int result = maxValue.max(2, 1);
assertThat(result, is(2));
}
} |
package kochetov;
import java.util.*;
public class MyTree<E> {
/**
* Root.
*/
private MyLeaf<E> root;
/**
* Size.
*/
private int size = 0;
/**
* Add to root.
* @param value - value
*/
public void addChild(E value) {
this.size++;
this.addChild(root, value);
}
/**
* Getter size.
* @return size length tree
*/
public int size() {
return this.size;
}
/**
* Add to root.
* @param parent - root
* @param value - value
*/
private void addChild(MyLeaf<E> parent, E value) {
if (this.root == null) {
this.root = new MyLeaf<>(null, value);
} else if (parent != null) {
if (parent.left == null) {
parent.left = new MyLeaf<>(parent, value);
} else if (parent.right == null) {
parent.right = new MyLeaf<>(parent, value);
} else if (this.size % 2 == 0) {
addChild(parent.left, value);
} else {
addChild(parent.right, value);
}
}
}
/**
* Get all children for root.
* @return children list
*/
public List<E> getChildren() {
return this.getList(this.root);
}
/**
* Get all children for leaf.
* @param leaf starting MyLeaf
* @return children list
*/
private List<E> getList(MyLeaf<E> leaf) {
List<E> result = new ArrayList<E>();
result.add(leaf.value);
if (leaf.left != null) {
result.addAll(this.getList(leaf.left));
}
if (leaf.right != null) {
result.addAll(this.getList(leaf.right));
}
return result;
}
private class MyLeaf<E> {
/**
* Parent.
*/
private MyLeaf<E> parent;
/**
* Left.
*/
private MyLeaf<E> left;
/**
* Right.
*/
private MyLeaf<E> right;
/**
* Value.
*/
private E value;
/**
* Constructor.
* @param parent - parent leaf
* @param value - value
*/
public MyLeaf(MyLeaf<E> parent, E value) {
this.parent = parent;
this.value = value;
}
}
} |
package org.myrobotlab.service;
import static org.myrobotlab.service.OpenCV.BACKGROUND;
import static org.myrobotlab.service.OpenCV.FILTER_DETECTOR;
import static org.myrobotlab.service.OpenCV.FILTER_FACE_DETECT;
import static org.myrobotlab.service.OpenCV.FILTER_FIND_CONTOURS;
import static org.myrobotlab.service.OpenCV.FILTER_LK_OPTICAL_TRACK;
import static org.myrobotlab.service.OpenCV.FOREGROUND;
import static org.myrobotlab.service.OpenCV.PART;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.myrobotlab.framework.Service;
import org.myrobotlab.framework.ServiceType;
import org.myrobotlab.framework.interfaces.Attachable;
import org.myrobotlab.image.SerializableImage;
import org.myrobotlab.logging.Level;
import org.myrobotlab.logging.LoggerFactory;
import org.myrobotlab.logging.LoggingFactory;
import org.myrobotlab.math.geometry.Point2df;
import org.myrobotlab.math.geometry.Rectangle;
import org.myrobotlab.opencv.OpenCVData;
import org.myrobotlab.opencv.OpenCVFilterDetector;
import org.myrobotlab.service.interfaces.ServoControl;
import org.slf4j.Logger;
// TODO - attach() ??? Static name peer key list ???
/**
*
* Tracking - This service connects to the video stream from OpenCV It then uses
* LK tracking for a point in the video stream. As that point moves the x and y
* servos that are attached to a camera will move to keep the point in the
* screen. (controlling yaw and pitch.)
*
*/
public class Tracking extends Service {
private static final long serialVersionUID = 1L;
public final static Logger log = LoggerFactory.getLogger(Tracking.class.getCanonicalName());
long lastTimestamp = 0;
long waitInterval = 5000;
int lastNumberOfObjects = 0;
// Tracking states - TODO split states into groups
public final static String STATE_LK_TRACKING_POINT = "state lucas kanade tracking";
public final static String STATE_IDLE = "state idle";
public final static String STATE_NEED_TO_INITIALIZE = "state initializing";
public static final String STATUS_CALIBRATING = "state calibrating";
public static final String STATE_LEARNING_BACKGROUND = "state learning background";
public static final String STATE_SEARCH_FOREGROUND = "state search foreground";
public static final String STATE_SEARCHING_FOREGROUND = "state searching foreground";
public static final String STATE_WAITING_FOR_OBJECTS_TO_STABILIZE = "state waiting for objects to stabilize";
public static final String STATE_WAITING_FOR_OBJECTS_TO_DISAPPEAR = "state waiting for objects to disappear";
public static final String STATE_STABILIZED = "state stabilized";
public static final String STATE_FACE_DETECT = "state face detect";
// memory constants
private String state = STATE_IDLE;
transient public Pid pid;
transient public OpenCV opencv;
// transient public ServoControl x, y;
private class TrackingServoData {
transient ServoControl servoControl = null;
int scanStep = 2;
Double currentServoPos;
String name;
String axis;
TrackingServoData(String name) {
this.name = name;
}
}
transient private HashMap<String, TrackingServoData> servoControls = new HashMap<String, TrackingServoData>();
// statistics
public int updateModulus = 1;
public long cnt = 0;
// public long latencyx = 0;
// MRL points
public Point2df lastPoint = new Point2df(0.5F, 0.5F);
double sizeIndexForBackgroundForegroundFlip = 0.10;
/**
* call back of all video data video calls this whenever a frame is processed
*
*/
// TODO: should be a function of the current frame rate for now, require at
// least 1.
int faceFoundFrameCount = 0;
int faceFoundFrameCountMin = 2;
// int faceLostFrameCount = 0;
// int faceLostFrameCountMin = 20;
boolean scan = false;
String[] axis = new String[] { "x", "y" };
// FIXME !! question remains does the act of creating meta update the
// reservatinos ?
// e.g if I come to the party does the reservations get updated or do I
// crash the party ??
public Tracking(String n) throws Exception {
super(n);
pid = (Pid) createPeer("pid");
// the kp should be proportional to the input min/max of the servo.. for now
// we'll go with 45 for now.
pid.setPID("x", 3.0, 1.0, 0.1);
pid.setControllerDirection("x", Pid.DIRECTION_DIRECT);
pid.setMode("x", Pid.MODE_AUTOMATIC);
pid.setOutputRange("x", -5, 5); // <- not correct - based on maximum
pid.setSampleTime("x", 30);
pid.setSetpoint("x", 0.5); // set center
pid.setPID("y", 3.0, 1.0, 0.1);
pid.setControllerDirection("y", Pid.DIRECTION_DIRECT);
pid.setMode("y", Pid.MODE_AUTOMATIC);
pid.setOutputRange("y", 5, -5); // <- not correct - based on maximum
pid.setSampleTime("y", 30);
pid.setSetpoint("y", 0.5); // set center
}
// reset better ?
public void clearTrackingPoints() {
opencv.invokeFilterMethod(FILTER_LK_OPTICAL_TRACK, "clearPoints");
// reset position
rest();
}
/**
* generic method to compute filter output after setState()
*/
public void execFilterFunctions(String filterName, String state) {
if (!Arrays.asList(OpenCV.getPossibleFilters()).contains(filterName)) {
log.error("Sorry, {} is an unknown filter.", filterName);
return;
}
log.info("starting {} related to {}", state, filterName);
clearTrackingPoints();
if (opencv.getFilter(filterName) == null) {
opencv.addFilter(filterName);
}
opencv.setActiveFilter(filterName);
opencv.capture();
setState(state);
}
public void faceDetect() {
execFilterFunctions(FILTER_FACE_DETECT, STATE_FACE_DETECT);
}
public void startLKTracking() {
execFilterFunctions(FILTER_LK_OPTICAL_TRACK, STATE_LK_TRACKING_POINT);
}
public void trackPoint() {
trackPoint(0.5F, 0.5F);
}
public void trackPoint(Float x, Float y) {
if (!STATE_LK_TRACKING_POINT.equals(state)) {
startLKTracking();
}
opencv.invokeFilterMethod(FILTER_LK_OPTICAL_TRACK, "samplePoint", x, y);
}
public void findFace() {
scan = true;
}
public OpenCVData foundFace(OpenCVData data) {
return data;
}
// TODO - enhance with location - not just heading
// TODO - array of attributes expanded Object[] ... ???
// TODO - use GEOTAG - LAT LONG ALT DIRECTION LOCATION CITY GPS TIME OFFSET
/*
* public OpenCVData setLocation(OpenCVData data) {
* data.setX(x.getPosition()); data.setY(y.getPosition()); return data; }
*/
public OpenCV getOpenCV() {
return opencv;
}
public String getState() {
return state;
}
public ServoControl getX() {
return servoControls.get("x").servoControl;
}
public Pid getPID() {
return pid;
}
public ServoControl getY() {
return servoControls.get("y").servoControl;
}
public boolean isIdle() {
return STATE_IDLE.equals(state);
}
public void learnBackground() {
((OpenCVFilterDetector) opencv.getFilter(FILTER_DETECTOR)).learn();
setState(STATE_LEARNING_BACKGROUND);
}
// ubermap !!!
// for (Object key : map.keySet())
// map.get(key))
public void publish(HashMap<String, SerializableImage> images) {
for (Map.Entry<String, SerializableImage> o : images.entrySet()) {
// Map.Entry<String,SerializableImage> pairs = o;
log.info(o.getKey());
publish(o.getValue());
}
}
public void publish(SerializableImage image) {
invoke("publishFrame", image);
}
public SerializableImage publishFrame(SerializableImage image) {
return image;
}
public void rest() {
log.info("rest");
for (TrackingServoData sc : servoControls.values()) {
if (sc.servoControl.isAttached()) {
// avoid dangerous moves
Double velocity = sc.servoControl.getSpeed();
sc.servoControl.setVelocity(20.0);
sc.servoControl.moveToBlocking(sc.servoControl.getRest());
sc.servoControl.setVelocity(velocity);
}
}
}
public void searchForeground() {
((OpenCVFilterDetector) opencv.getFilter(FILTER_DETECTOR)).search();
setState(STATE_SEARCHING_FOREGROUND);
}
public void setIdle() {
setState(STATE_IDLE);
}
public OpenCVData onOpenCVData(OpenCVData data) {
// log.info("OnOpenCVData");
SerializableImage img = new SerializableImage(data.getDisplay(), data.getSelectedFilter());
float width = img.getWidth();
float height = img.getHeight();
switch (state) {
case STATE_FACE_DETECT:
// check for bounding boxes
List<Rectangle> bb = data.getBoundingBoxArray();
if (bb != null && bb.size() > 0) {
// found face
// find centroid of first bounding box
Point2df thisPoint = new Point2df();
thisPoint.x = ((bb.get(0).x + bb.get(0).width / 2) / width);
thisPoint.y = ((bb.get(0).y + bb.get(0).height / 2) / height);
// keep calm and save MORE cpu!
if (thisPoint != lastPoint) {
updateTrackingPoint(thisPoint);
}
++faceFoundFrameCount;
// dead zone and state shift
if (faceFoundFrameCount > faceFoundFrameCountMin) {
// TODO # of frames for verification
log.info("found face");
invoke("foundFace", data);
// ensure bumpless transfer ??
// pid.init("x");
// pid.init("y");
// data.saveToDirectory("data");
}
} else {
// lost track
// log.info("Lost track...");
faceFoundFrameCount = 0;
if (scan) {
log.info("Scan enabled...");
TrackingServoData x = servoControls.get("x");
TrackingServoData y = servoControls.get("y");
double xpos = x.servoControl.getPos();
if (xpos + x.scanStep >= x.servoControl.getMax() && x.scanStep > 0 || xpos + x.scanStep <= x.servoControl.getMin() && x.scanStep < 0) {
x.scanStep *= -1;
double newY = y.servoControl.getMin() + (Math.random() * (y.servoControl.getMax() - y.servoControl.getMin()));
y.servoControl.moveTo(newY);
}
x.servoControl.moveTo(xpos + x.scanStep);
}
// state = STATE_FACE_DETECT_LOST_TRACK;
}
// if scanning stop scanning
// if bounding boxes & no current tracking points
// set set of tracking points in square - search for eyes?
// find average point ?
break;
case STATE_IDLE:
lastPoint.x = 0.5F;
lastPoint.y = 0.5F;
// setForegroundBackgroundFilter(); FIXME - setFGBGFilters for
// different detection
break;
// TODO: test startLKTracking -> maybe fix targetPoint.get(0) for image
// proportion between 0>1
case STATE_LK_TRACKING_POINT:
// extract tracking info
// data.setSelectedFilterName(LKOpticalTrackFilterName);
List<Point2df> targetPoint = data.getPointArray();
if (targetPoint != null && targetPoint.size() > 0) {
targetPoint.get(0).x = targetPoint.get(0).x / width;
targetPoint.get(0).y = targetPoint.get(0).y / height;
// keep calm and save MORE cpu!
if (targetPoint.get(0) != lastPoint) {
updateTrackingPoint(targetPoint.get(0));
}
}
break;
case STATE_LEARNING_BACKGROUND:
waitInterval = 3000;
waitForObjects(data, width, height);
break;
case STATE_SEARCHING_FOREGROUND:
waitInterval = 3000;
waitForObjects(data, width, height);
break;
default:
error("recieved opencv data but unknown state");
break;
}
return data;
}
public void setState(String newState) {
state = newState;
info(state);
}
public void stopScan() {
scan = false;
}
public void stopTracking() {
log.info("stop tracking, all filters disabled");
setState(STATE_IDLE);
clearTrackingPoints();
opencv.disableAll();
}
public OpenCVData toProcess(OpenCVData data) {
return data;
}
// FIXME - NEED A lost tracking event !!!!
// FIXME - this is WAY TO OPENCV specific !
// OpenCV should have a publishTrackingPoint method !
// This should be updateTrackingPoint(Point2Df) & perhaps Point3Df :)
final public void updateTrackingPoint(Point2df targetPoint) {
++cnt;
// describe this time delta
// latency = System.currentTimeMillis() - targetPoint.timestamp;
log.info("Update Tracking Point {}", targetPoint);
// pid.setInput("x", targetPoint.x);
// pid.setInput("y", targetPoint.y);
// TODO - work on removing currentX/YServoPos - and use the servo's
// directly ???
// if I'm at my min & and the target is further min - don't compute
// pid
for (TrackingServoData tsd : servoControls.values()) {
pid.setInput(tsd.axis, targetPoint.get(tsd.axis));
if (pid.compute(tsd.name)) {
// TODO: verify this.. we want the pid output to be the input for our
// servo..min/max are input min/max on the servo to
// ensure proper scaling
// of values between services.
tsd.currentServoPos += pid.getOutput(tsd.name);
tsd.servoControl.moveTo(tsd.currentServoPos);
tsd.currentServoPos = tsd.servoControl.getPos();
} else {
log.warn("{} data under-run", tsd.servoControl.getName());
}
}
lastPoint = targetPoint;
if (cnt % updateModulus == 0) {
// moz4r : //keep calm and save MORE cpu!
// broadcastState(); // update graphics ?
// info(String.format("computeX %f computeY %f", pid.getOutput("x"),
// pid.getOutput("y")));
}
}
public void waitForObjects(OpenCVData data, float width, float height) {
data.setSelectedFilter(FILTER_FIND_CONTOURS);
List<Rectangle> objects = data.getBoundingBoxArray();
int numberOfNewObjects = (objects == null) ? 0 : objects.size();
// if I'm not currently learning the background and
// countour == background ??
// set state to learn background
if (!STATE_LEARNING_BACKGROUND.equals(state) && numberOfNewObjects == 1) {
Rectangle rect = objects.get(0);
// publish(data.getImages());
if ((width - rect.width) / width < sizeIndexForBackgroundForegroundFlip && (height - rect.height) / height < sizeIndexForBackgroundForegroundFlip) {
learnBackground();
info(String.format("%s - object found was nearly whole view - foreground background flip", state));
}
}
if (numberOfNewObjects != lastNumberOfObjects) {
info(String.format("%s - unstable change from %d to %d objects - reset clock - was stable for %d ms limit is %d ms", state, lastNumberOfObjects, numberOfNewObjects,
System.currentTimeMillis() - lastTimestamp, waitInterval));
lastTimestamp = System.currentTimeMillis();
}
if (waitInterval < System.currentTimeMillis() - lastTimestamp) {
// setLocation(data);
// number of objects have stated the same
if (STATE_LEARNING_BACKGROUND.equals(state)) {
if (numberOfNewObjects == 0) {
// process background
// data.putAttribute(BACKGROUND);
data.put(PART, BACKGROUND);
invoke("toProcess", data);
// ready to search foreground
searchForeground();
}
} else {
if (numberOfNewObjects > 0) {
data.put(PART, FOREGROUND);
invoke("toProcess", data);
}
}
}
lastNumberOfObjects = numberOfNewObjects;
}
public void connect(OpenCV opencv, ServoControl x, ServoControl y) {
log.info("Connect 2 servos for head tracking!... aye aye captain. Also.. an open cv instance.");
attach(opencv);
attach(x, y);
// don't understand this, it should be getMin and getMax, no ? but
// seem worky..
pid.setOutputRange("x", -x.getMax(), x.getMax());
pid.setOutputRange("y", -y.getMax(), y.getMax());
// target the center !
pid.setSetpoint("x", 0.5);
pid.setSetpoint("y", 0.5);
// TODO: remove this sleep stmt
sleep(100);
rest();
}
/**
* This static method returns all the details of the class without it having
* to be constructed. It has description, categories, dependencies, and peer
* definitions.
*
* @return ServiceType - returns all the data
*
*/
static public ServiceType getMetaData() {
ServiceType meta = new ServiceType(Tracking.class.getCanonicalName());
meta.addDescription("uses a video input and vision library to visually track objects");
meta.addCategory("vision", "video", "sensor", "control");
meta.addPeer("pid", "Pid", "Pid service - for all your pid needs");
meta.addPeer("opencv", "OpenCV", "Tracking OpenCV instance");
return meta;
}
public void attach(ServoControl servo, String axis) {
if (!(axis.equals("x") || axis.equals("y"))) {
log.info("Axis must be x or y");
return;
}
TrackingServoData tsd = new TrackingServoData(axis);
tsd.servoControl = servo;
tsd.axis = axis;
servoControls.put(axis, tsd);
tsd.currentServoPos = servo.getPos();
log.info("Tracking attach : Axis : {} Servo {} current position {}", axis, servo.getName(), servo.getPos());
}
public void attach(ServoControl x, ServoControl y) {
attach(x, "x");
attach(y, "y");
}
public void attach(OpenCV opencv) {
this.opencv = opencv;
opencv.addListener("publishOpenCVData", getName(), "onOpenCVData");
}
/**
* Routing attach - routes ServiceInterface.attach(service) to appropriate
* methods for this class
*/
@Override
public void attach(Attachable service) throws Exception {
if (OpenCV.class.isAssignableFrom(service.getClass())) {
attach((OpenCV) service);
return;
}
error("%s doesn't know how to attach a %s", getClass().getSimpleName(), service.getClass().getSimpleName());
}
public static void main(String[] args) {
try {
LoggingFactory.init(Level.INFO);
Runtime.start("gui", "SwingGui");
// Runtime.start("webgui", "WebGui");
VirtualArduino virtual = (VirtualArduino) Runtime.start("virtual", "VirtualArduino");
virtual.connect("COM3");
Arduino arduino = (Arduino) Runtime.start("arduino", "Arduino");
arduino.connect("COM3");
Tracking t01 = (Tracking) Runtime.start("t01", "Tracking");
Servo rothead = (Servo) Runtime.start("rothead", "Servo");
Servo neck = (Servo) Runtime.start("neck", "Servo");
rothead.attach(arduino, 0);
neck.attach(arduino, 1);
OpenCV opencv = (OpenCV) Runtime.start("opencv", "OpenCV");
t01.connect(opencv, rothead, neck);
opencv.capture();
// t01.trackPoint();
t01.faceDetect();
// tracker.getGoodFeatures();
} catch (Exception e) {
e.printStackTrace();
}
}
} |
package org.neo4j.rdf.sparql;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
import java.util.concurrent.atomic.AtomicInteger;
import name.levering.ryan.sparql.common.QueryException;
import name.levering.ryan.sparql.model.FilterConstraint;
import name.levering.ryan.sparql.model.GroupConstraint;
import name.levering.ryan.sparql.model.OptionalConstraint;
import name.levering.ryan.sparql.model.TripleConstraint;
import name.levering.ryan.sparql.model.logic.ExpressionLogic;
import name.levering.ryan.sparql.parser.model.ASTAndNode;
import name.levering.ryan.sparql.parser.model.ASTEqualsNode;
import name.levering.ryan.sparql.parser.model.ASTGreaterThanEqualsNode;
import name.levering.ryan.sparql.parser.model.ASTGreaterThanNode;
import name.levering.ryan.sparql.parser.model.ASTLessThanEqualsNode;
import name.levering.ryan.sparql.parser.model.ASTLessThanNode;
import name.levering.ryan.sparql.parser.model.ASTLiteral;
import name.levering.ryan.sparql.parser.model.ASTOrNode;
import name.levering.ryan.sparql.parser.model.ASTRegexFuncNode;
import name.levering.ryan.sparql.parser.model.ASTVar;
import name.levering.ryan.sparql.parser.model.BinaryExpressionNode;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.RelationshipType;
import org.neo4j.graphmatching.PatternGroup;
import org.neo4j.graphmatching.PatternMatcher;
import org.neo4j.graphmatching.PatternNode;
import org.neo4j.graphmatching.PatternRelationship;
import org.neo4j.graphmatching.filter.CompareExpression;
import org.neo4j.graphmatching.filter.FilterBinaryNode;
import org.neo4j.graphmatching.filter.FilterExpression;
import org.neo4j.graphmatching.filter.RegexPattern;
import org.neo4j.rdf.model.Literal;
import org.neo4j.rdf.model.Statement;
import org.neo4j.rdf.model.Uri;
import org.neo4j.rdf.model.Value;
import org.neo4j.rdf.model.Wildcard;
import org.neo4j.rdf.model.WildcardStatement;
import org.neo4j.rdf.sparql.Neo4jVariable.VariableType;
import org.neo4j.rdf.store.representation.AbstractNode;
import org.neo4j.rdf.store.representation.AbstractRelationship;
import org.neo4j.rdf.store.representation.AbstractRepresentation;
import org.neo4j.rdf.store.representation.RepresentationStrategy;
import org.openrdf.model.URI;
import org.openrdf.model.datatypes.XMLDatatypeUtil;
/**
* Builds a pattern consisting of {@link PatternNode}s and
* {@link PatternRelationship}s based on a SPARQL query. It uses a
* {@link AbstractRepresentation} (retrieved from the supplied
* {@link RepresentationStrategy}) to figure out how to structure the pattern.
*
* The resulting pattern can be used to find matches using a
* {@link PatternMatcher}.
*/
public class QueryGraph
{
private AtomicInteger blankLabelCounter = new AtomicInteger();
private List<Neo4jVariable> variableList;
private Map<String, ASTVar> astVariables = new HashMap<String, ASTVar>();
private Map<AbstractNode, PatternNode> graph =
new HashMap<AbstractNode, PatternNode>();
private List<Map<AbstractNode, PatternNode>> optionalGraphs =
new LinkedList<Map<AbstractNode, PatternNode>>();
private MetaModelProxy metaModelProxy;
private RepresentationStrategy representationStrategy;
private PatternGraphBuilder graphBuilder;
private Set<AbstractNode> possibleStartNodes = new HashSet<AbstractNode>();
QueryGraph( RepresentationStrategy representationStrategy,
MetaModelProxy metaModel, List<Neo4jVariable> variableList,
AtomicInteger blankLabelCounter )
{
this( representationStrategy, metaModel, variableList );
this.blankLabelCounter = blankLabelCounter;
}
QueryGraph( RepresentationStrategy representationStrategy,
MetaModelProxy metaModel, List<Neo4jVariable> variableList )
{
this.variableList = variableList;
this.metaModelProxy = metaModel;
this.representationStrategy = representationStrategy;
this.graphBuilder = new PatternGraphBuilder();
}
PatternNodeAndNodePair getStartNode()
{
int lowestCount = Integer.MAX_VALUE;
PatternNode startNode = null;
Node node = null;
for ( AbstractNode abstractNode : this.possibleStartNodes )
{
int count = this.metaModelProxy.getCount( abstractNode );
if ( count < lowestCount )
{
lowestCount = count;
startNode = this.graph.get( abstractNode );
node = this.representationStrategy.getExecutor().lookupNode(
abstractNode );
}
}
return new PatternNodeAndNodePair( startNode, node );
}
Collection<PatternNode> getOptionalGraphs()
{
Collection<PatternNode> optionalStartNodes =
new ArrayList<PatternNode>();
for ( Map<AbstractNode, PatternNode> optionalGraph :
this.optionalGraphs )
{
optionalStartNodes.add(
this.getOverLappingNode( this.graph, optionalGraph ) );
}
return optionalStartNodes;
}
/**
* @param firstGraph the first graph.
* @param secondGraph the second graph.
* @return the node which is the "link" between two graphs, f.ex.
* the regular graph and and optional graph.
*/
private PatternNode getOverLappingNode(
Map<AbstractNode, PatternNode> firstGraph,
Map<AbstractNode, PatternNode> secondGraph )
{
for ( PatternNode node : firstGraph.values() )
{
for ( PatternNode mainNode : secondGraph.values() )
{
if ( node.getLabel().equals( mainNode.getLabel() ) )
{
return mainNode;
}
}
}
throw new QueryException(
"Optional graphs must be connected to the main statements" );
}
void build( GroupConstraint groupConstraint )
{
this.build( groupConstraint, false );
}
void build( GroupConstraint groupConstraint, boolean optional )
{
PatternGroup group = new PatternGroup();
ArrayList<Statement> statements = new ArrayList<Statement>();
Collection<FilterConstraint> filters =
new ArrayList<FilterConstraint>();
for ( Object constraint : groupConstraint.getConstraints() )
{
if ( constraint instanceof TripleConstraint )
{
Statement statement =
this.constructStatement( ( TripleConstraint ) constraint );
statements.add( statement );
}
else if ( constraint instanceof OptionalConstraint )
{
QueryGraph optionalGraph =
new QueryGraph( this.representationStrategy,
this.metaModelProxy, this.variableList,
this.blankLabelCounter );
optionalGraph.build( ( ( OptionalConstraint )
constraint ).getConstraint(), true );
this.optionalGraphs.add( optionalGraph.getGraph() );
}
else if ( constraint instanceof FilterConstraint )
{
filters.add( ( FilterConstraint ) constraint );
}
else
{
throw new QueryException( "Operation not supported." );
}
}
AbstractRepresentation representation = new AbstractRepresentation();
for ( Statement statement : statements )
{
representation = this.representationStrategy.
getAbstractRepresentation( statement, representation );
}
this.graph = this.graphBuilder.buildPatternGraph(
representation, group, this.variableList, optional );
// Apply filters
for ( FilterConstraint filter : filters )
{
addFilter( filter, group, optional );
}
}
private void addFilter( FilterConstraint constraint, PatternGroup group,
boolean optional )
{
group.addFilter( toFilterExpression( constraint.getExpression() ) );
}
private FilterExpression toFilterExpression( ExpressionLogic expression )
{
FilterExpression result = null;
if ( expression instanceof ASTAndNode ||
expression instanceof ASTOrNode )
{
BinaryExpressionNode binaryNode = ( BinaryExpressionNode )
expression;
boolean operatorAnd = expression instanceof ASTAndNode;
result = new FilterBinaryNode(
toFilterExpression( binaryNode.getLeftExpression() ),
operatorAnd,
toFilterExpression( binaryNode.getRightExpression() ) );
}
else
{
if ( expression instanceof ASTGreaterThanEqualsNode ||
expression instanceof ASTEqualsNode ||
expression instanceof ASTGreaterThanNode ||
expression instanceof ASTLessThanEqualsNode ||
expression instanceof ASTLessThanNode )
{
result = formCompareExpression( expression );
}
else if ( expression instanceof ASTRegexFuncNode )
{
result = formRegexPattern( expression );
}
else
{
throw new RuntimeException( expression +
" not supported" );
}
}
return result;
}
private FilterExpression formCompareExpression(
ExpressionLogic expressionLogic )
{
BinaryExpressionNode binaryNode =
( BinaryExpressionNode ) expressionLogic;
String operator = binaryNode.getOperator();
ASTVar var = ( ASTVar ) binaryNode.getLeftExpression();
ASTLiteral value = ( ASTLiteral ) binaryNode.getRightExpression();
URI datatype = value.getDatatype();
Object realValue = null;
String stringValue = value.toString();
if ( XMLDatatypeUtil.isDecimalDatatype( datatype ) ||
XMLDatatypeUtil.isFloatingPointDatatype( datatype ) )
{
realValue = new Double( stringValue );
}
else if ( XMLDatatypeUtil.isIntegerDatatype( datatype ) )
{
realValue = new Integer( stringValue );
}
else
{
realValue = value.getLabel();
}
Neo4jVariable variable = getVariable( var );
return new CompareExpression( var.getName(), variable.getProperty(),
operator, realValue );
}
private FilterExpression formRegexPattern( ExpressionLogic expressionLogic )
{
ASTRegexFuncNode regexNode = ( ASTRegexFuncNode ) expressionLogic;
List<?> arguments = regexNode.getArguments();
ASTVar variable = ( ASTVar ) arguments.get( 0 );
ASTLiteral regexValue = ( ASTLiteral ) arguments.get( 1 );
ASTLiteral regexOptions = arguments.size() > 2 ?
( ASTLiteral ) arguments.get( 2 ) : null;
Neo4jVariable neo4jVariable = getVariable( variable );
return new RegexPattern( variable.getName(),
neo4jVariable.getProperty(), regexValue.getLabel(),
regexOptions == null ? "" : regexOptions.getLabel() );
}
private Neo4jVariable getVariableOrNull( ASTVar var )
{
for ( Neo4jVariable variable : this.variableList )
{
if ( var.getName().equals( variable.getName() ) )
{
return variable;
}
}
return null;
}
private Neo4jVariable getVariable( ASTVar var )
{
Neo4jVariable variable = getVariableOrNull( var );
if ( variable == null )
{
throw new RuntimeException( "Undefined variable for " + var );
}
return variable;
}
private Map<AbstractNode, PatternNode> getGraph()
{
return this.graph;
}
private Statement constructStatement( TripleConstraint triple )
{
this.collectVariables( triple.getSubjectExpression(),
triple.getObjectExpression() );
Value subject = this.createUriOrWildcard(
triple.getSubjectExpression() );
Value predicate =
new Uri( triple.getPredicateExpression().toString() );
Value object = null;
if ( triple.getObjectExpression() instanceof ASTLiteral )
{
object = new Literal( triple.getObjectExpression().toString() );
}
else
{
object = this.createUriOrWildcard( triple.getObjectExpression() );
}
return new WildcardStatement( subject, predicate, object,
new Wildcard( "context" ) );
}
private Value createUriOrWildcard( ExpressionLogic expression )
{
Value value = null;
if ( expression instanceof ASTVar )
{
value = new Wildcard( ( ( ASTVar ) expression ).getName() );
}
else
{
value = new Uri( expression.toString() );
}
return value;
}
private void collectVariables( ExpressionLogic... expressions )
{
for ( ExpressionLogic expression : expressions )
{
if ( expression instanceof ASTVar )
{
this.astVariables.put(
expression.toString(), ( ASTVar ) expression );
}
}
}
private class PatternGraphBuilder
{
public Map<AbstractNode, PatternNode> buildPatternGraph(
AbstractRepresentation representation, PatternGroup group,
List<Neo4jVariable> variableMapping )
{
return buildPatternGraph( representation, group,
variableMapping, false );
}
public Map<AbstractNode, PatternNode> buildPatternGraph(
AbstractRepresentation representation, PatternGroup group,
List<Neo4jVariable> variableMapping, boolean optional )
{
for ( AbstractNode node : representation.nodes() )
{
PatternNode patternNode = this.createPatternNode( node, group );
graph.put( node, patternNode );
if ( node.getUriOrNull() != null )
{
possibleStartNodes.add( node );
}
}
for ( AbstractRelationship relationship :
representation.relationships() )
{
AbstractNode startNode = relationship.getStartNode();
AbstractNode endNode = relationship.getEndNode();
final String name = relationship.getRelationshipTypeName();
RelationshipType relType = new RelationshipType()
{
public String name()
{
return name;
}
};
if ( !optional )
{
graph.get( startNode ).createRelationshipTo(
graph.get( endNode ), relType );
}
else
{
graph.get( startNode ).createOptionalRelationshipTo(
graph.get( endNode ), relType );
}
}
return graph;
}
private PatternNode createPatternNode( AbstractNode node,
PatternGroup group )
{
PatternNode patternNode = null;
if ( node.isWildcard() )
{
Wildcard wildcard = node.getWildcardOrNull();
patternNode =
new PatternNode( group, wildcard.getVariableName() );
this.addVariable( wildcard.getVariableName(), VariableType.URI,
patternNode, representationStrategy.getExecutor().
getNodeUriPropertyKey( node ) );
}
else
{
Uri uri = node.getUriOrNull();
patternNode = new PatternNode( group, uri == null ?
( "_blank_" + blankLabelCounter.incrementAndGet() ) :
uri.getUriAsString() );
if ( uri != null )
{
patternNode.addPropertyEqualConstraint(
representationStrategy.getExecutor().
getNodeUriPropertyKey( node ), uri.getUriAsString() );
}
}
for ( Entry<String, Collection<Object>> entry :
node.properties().entrySet() )
{
for ( Object value : entry.getValue() )
{
if ( value instanceof Wildcard )
{
this.addVariable( ( ( Wildcard ) value ).
getVariableName(), VariableType.LITERAL,
patternNode, entry.getKey() );
}
else
{
patternNode.addPropertyEqualConstraint(
entry.getKey(), value );
}
}
}
return patternNode;
}
private void addVariable( String variableName, VariableType type,
PatternNode patternNode, String property )
{
for ( Neo4jVariable variable : variableList )
{
if ( variableName.equals( variable.getName() ) )
{
return;
}
}
variableList.add(
new Neo4jVariable( variableName, type, patternNode, property ) );
}
}
} |
package com.thoughtworks.xstream.mapper;
import com.thoughtworks.xstream.alias.ClassMapper;
import com.thoughtworks.xstream.converters.SingleValueConverter;
import com.thoughtworks.xstream.converters.enums.EnumSingleValueConverter;
import com.thoughtworks.xstream.core.JVM;
/**
* Mapper that handles the special case of polymorphic enums in Java 1.5. This renames MyEnum$1
* to MyEnum making it less bloaty in the XML and avoiding the need for an alias per enum value
* to be specified. Additionally every enum is treated automatically as immutable type.
*
* @author Joe Walnes
* @author Jörg Schaible
*/
public class EnumMapper extends MapperWrapper {
// Dynamically try to load Enum class. Pre JDK1.5 will silently fail.
private static JVM jvm = new JVM();
private static final Class enumClass = jvm.loadClass("java.lang.Enum");
private static final boolean active = enumClass != null;
private static final Class enumSetClass = active
? jvm.loadClass("java.util.EnumSet")
: null;
public EnumMapper(Mapper wrapped) {
super(wrapped);
}
/**
* @deprecated As of 1.2, use {@link #EnumMapper(Mapper)}
*/
public EnumMapper(ClassMapper wrapped) {
this((Mapper)wrapped);
}
public String serializedClass(Class type) {
if (!active || type == null) {
return super.serializedClass(type);
} else {
if (enumClass.isAssignableFrom(type) && type.getSuperclass() != enumClass) {
return super.serializedClass(type.getSuperclass());
} else if (enumSetClass.isAssignableFrom(type)) {
return super.serializedClass(enumSetClass);
} else {
return super.serializedClass(type);
}
}
}
public boolean isImmutableValueType(Class type) {
return (active && enumClass.isAssignableFrom(type)) || super.isImmutableValueType(type);
}
public SingleValueConverter getConverterFromItemType(Class type) {
if (active && enumClass.isAssignableFrom(type)) {
return new EnumSingleValueConverter(type);
}
return super.getConverterFromItemType(type);
}
} |
package org.zanata.model;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.EntityListeners;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;
import javax.persistence.PostPersist;
import javax.persistence.PrePersist;
import javax.persistence.PreRemove;
import javax.persistence.PreUpdate;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Version;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.search.annotations.Analyze;
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.FieldBridge;
import org.hibernate.search.annotations.SortableField;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.zanata.hibernate.search.DateBridge;
import com.google.common.annotations.VisibleForTesting;
@Slf4j
@EntityListeners({ ModelEntityBase.EntityListener.class })
@MappedSuperclass
public class ModelEntityBase implements Serializable, HashableState {
private static final long serialVersionUID = -6139220551322868743L;
protected Long id;
protected Date creationDate;
protected Date lastChanged;
protected Integer versionNum;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long getId() {
return id;
}
@VisibleForTesting
public void setId(Long id) {
this.id = id;
}
@Version
@Column(nullable = false)
public Integer getVersionNum() {
return versionNum;
}
public void setVersionNum(Integer versionNum) {
this.versionNum = versionNum;
}
@Temporal(TemporalType.TIMESTAMP)
@Column(nullable = false)
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
// TODO extract lastChanged from ModelEntityBase and use with @Embedded
// NB: also used in HSimpleComment
@Temporal(TemporalType.TIMESTAMP)
@Column(nullable = false)
@Field(analyze = Analyze.NO)
@FieldBridge(impl = DateBridge.class)
@SortableField
public Date getLastChanged() {
return lastChanged;
}
public void setLastChanged(Date lastChanged) {
this.lastChanged = lastChanged;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result =
prime
* result
+ ((getCreationDate() == null) ? 0 : getCreationDate().hashCode());
result = prime * result + ((getId() == null) ? 0 : getId().hashCode());
result =
prime * result
+ ((getLastChanged() == null) ? 0 : getLastChanged().hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
// Subclasses *must* override equals to check that their class is a
// match for the object they are comparing. Simple comparison of the
// result of getClass() is not possible here because the compared object
// may be a Hibernate proxy. Hibernate proxies are a subclass of the
// class that they are proxying.
assert overridesEquals(this);
assert overridesEquals(obj);
ModelEntityBase other = (ModelEntityBase) obj;
if (getCreationDate() == null) {
if (other.getCreationDate() != null)
return false;
} else if (!getCreationDate().equals(other.getCreationDate()))
return false;
if (getId() == null) {
if (other.getId() != null)
return false;
} else if (!getId().equals(other.getId()))
return false;
if (getLastChanged() == null) {
if (other.getLastChanged() != null)
return false;
} else if (!getLastChanged().equals(other.getLastChanged()))
return false;
return true;
}
private boolean overridesEquals(Object obj) {
try {
return obj.getClass().getDeclaredMethod("equals", Object.class) != null;
} catch (NoSuchMethodException e) {
log.error("class does not override equals: " + obj.getClass(), e);
return false;
}
}
@Override
public String toString() {
return getClass().getSimpleName() + "@"
+ Integer.toHexString(hashCode()) + "[id=" + id
+ ",versionNum=" + versionNum + "]";
}
protected boolean logPersistence() {
return true;
}
@Override
public void writeHashState(ByteArrayOutputStream buff) throws IOException {
buff.write(versionNum.byteValue());
}
public static class EntityListener {
@SuppressWarnings("unused")
@PrePersist
private void onPersist(ModelEntityBase meb) {
Date now = new Date();
if (meb.creationDate == null) {
meb.creationDate = now;
}
if (meb.lastChanged == null) {
meb.lastChanged = now;
}
}
@SuppressWarnings("unused")
@PostPersist
private void postPersist(ModelEntityBase meb) {
if (meb.logPersistence()) {
Logger log = LoggerFactory.getLogger(meb.getClass());
log.info("persist entity: {}", meb);
}
}
@SuppressWarnings("unused")
@PreUpdate
private void onUpdate(ModelEntityBase meb) {
meb.lastChanged = new Date();
}
@SuppressWarnings("unused")
@PreRemove
private void onRemove(ModelEntityBase meb) {
if (meb.logPersistence()) {
Logger log = LoggerFactory.getLogger(meb.getClass());
log.info("remove entity: {}", meb);
}
}
}
} |
package ru.ifmo.ctddev.gmwcs.graph;
public abstract class Unit implements Comparable<Unit> {
protected int num;
protected double weight;
public Unit(int num, double weight) {
this.num = num;
this.weight = weight;
}
@Override
public int hashCode() {
return num;
}
public int getNum() {
return num;
}
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
@Override
public boolean equals(Object o) {
return (o.getClass() == getClass() && num == ((Unit) o).num);
}
@Override
public int compareTo(Unit u) {
if (u.weight != weight) {
return Double.compare(u.weight, weight);
}
return Integer.compare(u.getNum(), num);
}
} |
package org.cache2k.benchmark;
import com.carrotsearch.junitbenchmarks.BenchmarkOptions;
import static org.junit.Assert.*;
import org.cache2k.benchmark.util.AccessTrace;
import org.cache2k.benchmark.util.DistAccessPattern;
import org.cache2k.benchmark.util.Patterns;
import org.cache2k.benchmark.util.RandomAccessPattern;
import org.junit.Test;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
/**
* All cache benchmarks in one class. There are three different types
* of methods: The test* methods check for some basic cache behaviour
* to ensure sanity, the benchmarkXy methods do a speed measurement,
* the benchmarkXy_NNN do a efficiency test on a given trace.
*/
@SuppressWarnings(value={"unchecked", "unused"})
@BenchmarkOptions(benchmarkRounds = 3, warmupRounds = 2)
public class BenchmarkCollection extends TracesAndTestsCollection {
public static final boolean SKIP_MULTI_THREAD = true;
public static final int TRACE_LENGTH = 3 * 1000 * 1000;
public static final AccessTrace traceRandomForSize1Replacement =
new AccessTrace(new RandomAccessPattern(10), 1000);
public static final AccessTrace trace1001misses =
new AccessTrace(
Patterns.sequence(1000),
Patterns.sequence(1000),
Patterns.sequence(1000, 1001));
static final AccessTrace mostlyHitTrace =
new AccessTrace(new Patterns.InterleavedSequence(0, 500, 1, 0, TRACE_LENGTH / 500));
@Test
public void benchmarkHits() {
runBenchmark(mostlyHitTrace, 500);
}
@Test
public void benchmarkHits2000() {
runBenchmark(mostlyHitTrace, 2000);
}
static final AccessTrace allMissTrace =
new AccessTrace(Patterns.sequence(TRACE_LENGTH))
.setOptHitCount(500, 0)
.setRandomHitCount(500, 0)
.setOptHitCount(50000, 0)
.setRandomHitCount(50000, 0)
.setOptHitCount(500000, 0)
.setRandomHitCount(500000, 0)
.setOptHitCount(5000000, 0)
.setRandomHitCount(5000000, 0)
.setOptHitCount(5000, 0)
.setRandomHitCount(5000, 0);
@Test
public void benchmarkMiss() {
BenchmarkCache<Integer, Integer> c = freshCache(500);
runBenchmark(c, allMissTrace);
logHitRate(c, allMissTrace, c.getMissCount());
c.destroy();
}
@Test
public void benchmarkMiss_5000() {
BenchmarkCache<Integer, Integer> c = freshCache(5000);
runBenchmark(c, allMissTrace);
logHitRate(c, allMissTrace, c.getMissCount());
c.destroy();
}
@Test
public void benchmarkMiss_50000() {
BenchmarkCache<Integer, Integer> c = freshCache(50000);
runBenchmark(c, allMissTrace);
logHitRate(c, allMissTrace, c.getMissCount());
c.destroy();
}
@Test
public void benchmarkMiss_500000() {
BenchmarkCache<Integer, Integer> c = freshCache(500000);
runBenchmark(c, allMissTrace);
logHitRate(c, allMissTrace, c.getMissCount());
c.destroy();
}
public static final AccessTrace randomTrace =
new AccessTrace(new RandomAccessPattern(1000), TRACE_LENGTH);
@Test
public void benchmarkRandom() throws Exception {
runBenchmark(randomTrace, 500);
}
static final AccessTrace effective90Trace =
new AccessTrace(new DistAccessPattern(1000), TRACE_LENGTH);
class MultiThreadSource extends BenchmarkCacheFactory.Source {
@Override
public int get(int v) {
Random random = ThreadLocalRandom.current();
int sum = v;
for (int i = 0; i < 1000; i++) {
sum += random.nextInt();
}
return sum;
}
}
@Test
public void benchmarkEff90() throws Exception {
runBenchmark(effective90Trace, 500);
}
@Test
public void benchmarkEff95Threads1() throws Exception {
runMultiThreadBenchmark(new MultiThreadSource(), 1, effective95Trace, 500);
}
@Test
public void benchmarkEff95Threads2() throws Exception {
runMultiThreadBenchmark(new MultiThreadSource(), 2, effective95Trace, 500);
}
@Test
public void benchmarkEff95Threads4() throws Exception {
if (SKIP_MULTI_THREAD) { return; }
runMultiThreadBenchmark(new MultiThreadSource(), 4, effective95Trace, 500);
}
@Test
public void benchmarkEff95Threads6() throws Exception {
if (SKIP_MULTI_THREAD) { return; }
runMultiThreadBenchmark(new MultiThreadSource(), 6, effective95Trace, 500);
}
@Test
public void benchmarkEff95Threads8() throws Exception {
if (SKIP_MULTI_THREAD) { return; }
runMultiThreadBenchmark(new MultiThreadSource(), 8, effective95Trace, 500);
}
static final AccessTrace effective95Trace =
new AccessTrace(new DistAccessPattern(900), TRACE_LENGTH);
@Test @BenchmarkOptions(benchmarkRounds = 1, warmupRounds = 0)
public void benchmarkEff95() throws Exception {
runBenchmark(effective95Trace, 500);
}
@Test @BenchmarkOptions(benchmarkRounds = 1, warmupRounds = 0)
public void benchmarkTotalRandom_100() {
runBenchmark(randomTrace, 100);
}
@Test @BenchmarkOptions(benchmarkRounds = 1, warmupRounds = 0)
public void benchmarkTotalRandom_200() {
runBenchmark(randomTrace, 200);
}
@Test @BenchmarkOptions(benchmarkRounds = 1, warmupRounds = 0)
public void benchmarkTotalRandom_350() {
runBenchmark(randomTrace, 350);
}
@Test @BenchmarkOptions(benchmarkRounds = 1, warmupRounds = 0)
public void benchmarkTotalRandom_500() {
runBenchmark(randomTrace, 500);
}
@Test @BenchmarkOptions(benchmarkRounds = 1, warmupRounds = 0)
public void benchmarkTotalRandom_800() {
runBenchmark(randomTrace, 800);
}
} |
package seedu.cmdo.model.task;
import java.time.Duration;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import seedu.cmdo.commons.exceptions.IllegalValueException;
/**
* Represents a Task's Due date in the To Do List.
* Guarantees: immutable; is valid as declared in {@link #isValidDueByDate(String)}
*/
public class DueByDate {
public static final String MESSAGE_DUEBYDATE_CONSTRAINTS = "Due by? You should enter a day, or a date.";
// public static final String DUEBYDATE_VALIDATION_REGEX = ".*";
public final LocalDate start;
public final LocalDate end;
public final Boolean isRange;
public DueByDate(LocalDate dueByDate) throws IllegalValueException {
assert dueByDate != null;
this.end = LocalDate.MIN;
this.start = dueByDate;
this.isRange = false;
}
public DueByDate(LocalDate dueByDateStart, LocalDate dueByDateEnd) {
assert dueByDateStart != null && dueByDateEnd != null;
this.start = dueByDateStart;
this.end = dueByDateEnd;
this.isRange = true;
}
@Override
public String toString() {
if (isRange)
return new StringBuilder(start.toString() + "/to/" + end.toString()).toString();
else
return start.toString();
}
public boolean isRange() {
return isRange;
}
/*
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof DueDay // instanceof handles nulls
&& this.value.equals(((DueDay) other).value)); // state check
}
*/
// @Override
// public int hashCode() {
/*
* Produces a friendly string of values in the format MM/DD/YYYY
*
* @@author A0139661Y
*/
public String getFriendlyString() {
// If floating date, return do not print anything
if (start.equals(LocalDate.MIN) && end.equals(LocalDate.MIN))
return "";
if (!isRange) {
return new StringBuilder(start.format(DateTimeFormatter.ofPattern("MM/dd/uuuu"))).toString();
}
return new StringBuilder(start.format(DateTimeFormatter.ofPattern("MM/dd/uuuu"))
+ " - "
+ end.format(DateTimeFormatter.ofPattern("MM/dd/uuuu")))
.toString();
}
// Operates on the premise that the start date is always specified.
// @@author A0139661Y
public String getFriendlyStartString() {
return start.format(DateTimeFormatter.ofPattern("MM/dd/uuuu")).toString();
}
// @@author A0139661Y
public String getFriendlyEndString() {
if (end.equals(LocalDate.MIN)) {
return "";
} else return end.format(DateTimeFormatter.ofPattern("MM/dd/uuuu")).toString();
}
} |
package seedu.scheduler.model;
import javafx.collections.ObservableList;
import seedu.scheduler.model.entry.Entry;
import seedu.scheduler.model.entry.ReadOnlyEntry;
import seedu.scheduler.model.entry.UniqueEntryList;
import seedu.scheduler.model.tag.Tag;
import seedu.scheduler.model.tag.UniqueTagList;
import java.util.*;
import java.util.stream.Collectors;
/**
* Wraps all data at the scheduler level
* Duplicates are not allowed (by .equals comparison)
*/
public class Scheduler implements ReadOnlyScheduler {
private final UniqueEntryList entrys;
private final UniqueTagList tags;
{
entrys = new UniqueEntryList();
tags = new UniqueTagList();
}
public Scheduler() {}
/**
* Entrys and Tags are copied into this scheduler
*/
public Scheduler(ReadOnlyScheduler toBeCopied) {
this(toBeCopied.getUniqueEntryList(), toBeCopied.getUniqueTagList());
}
/**
* Entrys and Tags are copied into this scheduler
*/
public Scheduler(UniqueEntryList entrys, UniqueTagList tags) {
resetData(entrys.getInternalList(), tags.getInternalList());
}
public static ReadOnlyScheduler getEmptyScheduler() {
return new Scheduler();
}
//// list overwrite operations
public ObservableList<Entry> getEntrys() {
return entrys.getInternalList();
}
public void setEntrys(List<Entry> entrys) {
this.entrys.getInternalList().setAll(entrys);
}
public void setTags(Collection<Tag> tags) {
this.tags.getInternalList().setAll(tags);
}
public void resetData(Collection<? extends ReadOnlyEntry> newEntrys, Collection<Tag> newTags) {
setEntrys(newEntrys.stream().map(Entry::new).collect(Collectors.toList()));
setTags(newTags);
}
public void resetData(ReadOnlyScheduler newData) {
resetData(newData.getEntryList(), newData.getTagList());
}
//// entry-level operations
/**
* Adds a entry to the scheduler.
* Also checks the new entry's tags and updates {@link #tags} with any new tags found,
* and updates the Tag objects in the entry to point to those in {@link #tags}.
*
* @throws UniqueEntryList.DuplicateEntryException if an equivalent entry already exists.
*/
public void addEntry(Entry p) throws UniqueEntryList.DuplicateEntryException {
syncTagsWithMasterList(p);
entrys.add(p);
}
/**
* Ensures that every tag in this entry:
* - exists in the master list {@link #tags}
* - points to a Tag object in the master list
*/
private void syncTagsWithMasterList(Entry entry) {
final UniqueTagList entryTags = entry.getTags();
tags.mergeFrom(entryTags);
// Create map with values = tag object references in the master list
final Map<Tag, Tag> masterTagObjects = new HashMap<>();
for (Tag tag : tags) {
masterTagObjects.put(tag, tag);
}
// Rebuild the list of entry tags using references from the master list
final Set<Tag> commonTagReferences = new HashSet<>();
for (Tag tag : entryTags) {
commonTagReferences.add(masterTagObjects.get(tag));
}
entry.setTags(new UniqueTagList(commonTagReferences));
}
public boolean removeEntry(ReadOnlyEntry key) throws UniqueEntryList.EntryNotFoundException {
if (entrys.remove(key)) {
return true;
} else {
throw new UniqueEntryList.EntryNotFoundException();
}
}
/**
* Edits(replace) a specified entry in the list.
*
* @throws UniqueEntryList.DuplicateEntryException if an equivalent entry already exists.
* @throws UniqueEntryList.EntryNotFoundException if no such entry could be found in the list.
*
* @@author A0152962B
*/
public void editEntry(int index, Entry r, ReadOnlyEntry toEdit) throws UniqueEntryList.DuplicateEntryException, UniqueEntryList.EntryNotFoundException {
entrys.edit(index, r, toEdit);
}
//// tag-level operations
public void addTag(Tag t) throws UniqueTagList.DuplicateTagException {
tags.add(t);
}
//// util methods
@Override
public String toString() {
return entrys.getInternalList().size() + " entrys, " + tags.getInternalList().size() + " tags";
// TODO: refine later
}
@Override
public List<ReadOnlyEntry> getEntryList() {
return Collections.unmodifiableList(entrys.getInternalList());
}
@Override
public List<Tag> getTagList() {
return Collections.unmodifiableList(tags.getInternalList());
}
@Override
public UniqueEntryList getUniqueEntryList() {
return this.entrys;
}
@Override
public UniqueTagList getUniqueTagList() {
return this.tags;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof Scheduler // instanceof handles nulls
&& this.entrys.equals(((Scheduler) other).entrys)
&& this.tags.equals(((Scheduler) other).tags));
}
@Override
public int hashCode() {
// use this method for custom fields hashing instead of implementing your own
return Objects.hash(entrys, tags);
}
} |
//@@author A0139925U
package seedu.tache.model.task;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.ocpsoft.prettytime.PrettyTime;
import com.joestelmach.natty.DateGroup;
import com.joestelmach.natty.Parser;
import seedu.tache.commons.exceptions.IllegalValueException;
public class DateTime implements Comparable {
private static final String EXPLICIT_DATE_TREE_IDENTIFIER = "EXPLICIT_DATE";
private static final String EXPLICIT_TIME_TREE_IDENTIFIER = "EXPLICIT_TIME";
public static final String MESSAGE_DATE_CONSTRAINTS = "Unknown date format. It is recommended to "
+ "interchangeably use the following few formats:"
+ "\nMM-DD-YY hh:mm:ss or MM/DD/YY 10.30pm";
public static final String DEFAULT_TIME_STRING = "00:00:00";
private final Date date;
public DateTime(String date) throws IllegalValueException {
assert date != null;
String trimmedStartDate = date.trim();
List<DateGroup> temp = new Parser().parse(trimmedStartDate);
if (temp.isEmpty()) {
throw new IllegalValueException(MESSAGE_DATE_CONSTRAINTS);
}
this.date = temp.get(0).getDates().get(0);
String syntaxTree = temp.get(0).getSyntaxTree().toStringTree();
boolean hasExplicitDate = syntaxTree.contains(EXPLICIT_DATE_TREE_IDENTIFIER);
boolean hasExplicitTime = syntaxTree.contains(EXPLICIT_TIME_TREE_IDENTIFIER);
if (hasExplicitDate ^ hasExplicitTime) {
if (hasExplicitDate) {
this.date.setHours(0);
this.date.setMinutes(0);
this.date.setSeconds(0);
}
}
}
public DateTime(DateTime source) throws IllegalValueException {
this(source.getAmericanDateTime());
}
@Override
public String toString() {
return new PrettyTime().format(date);
}
public String getDateOnly() {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
return sdf.format(date);
}
public void setDateOnly(String date) throws IllegalValueException {
List<DateGroup> temp = new Parser().parse(date);
if (temp.isEmpty()) {
throw new IllegalValueException(MESSAGE_DATE_CONSTRAINTS);
}
Date parsedDate = temp.get(0).getDates().get(0);
this.date.setDate(parsedDate.getDate());
this.date.setMonth(parsedDate.getMonth());
this.date.setYear(parsedDate.getYear());
}
public void setTimeOnly(String time) throws IllegalValueException {
List<DateGroup> temp = new Parser().parse(time);
if (temp.isEmpty()) {
throw new IllegalValueException(MESSAGE_DATE_CONSTRAINTS);
}
Date parsedTime = temp.get(0).getDates().get(0);
this.date.setHours(parsedTime.getHours());
this.date.setMinutes(parsedTime.getMinutes());
this.date.setSeconds(parsedTime.getSeconds());
}
public void setDefaultTime() throws IllegalValueException {
setTimeOnly(DEFAULT_TIME_STRING);
}
public String getTimeOnly() {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
return sdf.format(date);
}
public String getAmericanDateTime() {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
return sdf.format(date);
}
public String getAmericanDateOnly() {
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
return sdf.format(date);
}
@Override
public int compareTo(Object other) {
assert other instanceof DateTime;
if (this.equals(other)) {
return 0;
} else if (date.after(((DateTime) other).getDate())) {
return 1;
} else {
return -1;
}
}
//@@author A0142255M
/**
* Returns a String which represents a moment to be parsed by FullCalendar.
* A moment (FullCalendar terminology) refers to a point in time.
*/
public String getDateTimeForFullCalendar() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
return sdf.format(date);
}
public Date getDate() {
return date;
}
@Override
public boolean equals(Object other) {
return other == this // short circuit if same object
|| (other instanceof DateTime // instanceof handles nulls
&& this.date.equals(((DateTime) other).getDate())); // state check
}
/**
* Returns true if the date is earlier than today.
*/
public boolean hasPassed() {
Date today = new Date();
return this.date.before(today);
}
//@@author A0139961U
public boolean isSameDate(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
return sdf.format(date).equals(sdf.format(this.date));
}
public boolean isToday() {
Date today = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
return sdf.format(today).equals(sdf.format(this.date));
}
public boolean isSameWeek() {
Date today = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(today);
int thisWeekNo = cal.get(Calendar.WEEK_OF_YEAR);
cal.setTime(this.date);
return (thisWeekNo == cal.get(Calendar.WEEK_OF_YEAR));
}
public static Date removeTime(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
//@@author A0150120H
/**
* Returns if the parser can find any date and/or time text
* @param s String to check
* @return true if it can be parsed as a date and/or time, false otherwise
*/
public static boolean canParse(String s) {
return new Parser().parse(s).size() > 0;
}
/**
* Returns if the String contains a time field
* @param s String to check
* @return true if the Parser sees a time field, false otherwise
*/
public static boolean isTime(String s) {
Parser dateTimeParser = new Parser();
List<DateGroup> list = dateTimeParser.parse(s);
if (list.isEmpty()) {
return false;
} else {
return list.get(0).getSyntaxTree().toStringTree().contains(EXPLICIT_DATE_TREE_IDENTIFIER);
}
}
/**
* Returns if the String contains a date field
* @param s String to check
* @return true if the Parser sees a date field, false otherwise
*/
public static boolean isDate(String s) {
Parser dateTimeParser = new Parser();
List<DateGroup> list = dateTimeParser.parse(s);
if (list.isEmpty()) {
return false;
} else {
return list.get(0).getSyntaxTree().toStringTree().contains(EXPLICIT_DATE_TREE_IDENTIFIER);
}
}
//@@author
/*@Override
public int hashCode() {
return (startDate.hashCode() && endDate.hashCode());
}*/
} |
package tigase.cluster;
import tigase.conf.Configurable;
import tigase.disco.ServiceEntity;
import tigase.disco.ServiceIdentity;
import tigase.disco.XMPPService;
import tigase.server.DisableDisco;
import tigase.server.Packet;
import tigase.server.ServerComponent;
import tigase.util.DNSResolver;
import tigase.util.TigaseStringprepException;
import tigase.vhosts.VHostListener;
import tigase.vhosts.VHostManagerIfc;
import tigase.xml.Element;
import tigase.xmpp.BareJID;
import tigase.xmpp.JID;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.Map;
import java.util.Queue;
public class VirtualComponent
implements ServerComponent, XMPPService, Configurable, DisableDisco,
VHostListener {
/**
* Parameter to set service discovery item category name for the virtual
* component. Please refer to service discovery documentation for a correct
* category or check what is returned by your real component instance.
*/
public static final String DISCO_CATEGORY_PROP_KEY = "disco-category";
/** Field description */
public static final String DISCO_CATEGORY_PROP_VAL = "conference";
/**
* Comma separated list of features for the service discovery item represented
* by this virtual component. Please check with the real component to obtain a
* correct list of features.
*/
public static final String DISCO_FEATURES_PROP_KEY = "disco-features";
/** Field description */
public static final String DISCO_FEATURES_PROP_VAL = "http://jabber.org/protocol/muc";
/**
* Parameter to set service discovery item name for the virtual component
* instance. You should refer to service discovery documentation for a proper
* name for your component.
*/
public static final String DISCO_NAME_PROP_KEY = "disco-name";
/** Field description */
public static final String DISCO_NAME_PROP_VAL = "Multi User Chat";
/**
* Parameter to set service discovery node name. In most cases you should
* leave it empty unless you really know what you are doing.
*/
public static final String DISCO_NODE_PROP_KEY = "disco-node";
/** Field description */
public static final String DISCO_NODE_PROP_VAL = "";
/**
* Parameter to set service discovery item type for the virtual component. You
* should refer to a service discovery documentation for a correct type for
* your component. Or, alternatively you can have a look what returns your
* real component.
*/
public static final String DISCO_TYPE_PROP_KEY = "disco-type";
/** A default value for service discovery item type, which is 'text' */
public static final String DISCO_TYPE_PROP_VAL = "text";
/**
* If set, then it is used as the component domain name part. This domains is
* displayed on the service discovery information, instead of virtual host based on
* the user's query.
*/
public static final String FIXED_DOMAIN_PROP_KEY = "fixed-domain";
/**
* Virtual component parameter setting packet redirect destination address.
*/
public static final String REDIRECT_TO_PROP_KEY = "redirect-to";
/**
* Variable <code>log</code> is a class logger.
*/
private static final Logger log = Logger.getLogger("tigase.cluster.VirtualComponent");
/** Field description */
protected VHostManagerIfc vHostManager = null;
private JID componentId = null;
private String discoCategory = null;
private String[] discoFeatures = null;
private String discoName = null;
private String discoNode = null;
private String discoType = null;
private String fixedDomain = null;
private String name = null;
private JID redirectTo = null;
private ServiceEntity serviceEntity = null;
/**
* Method description
*
*
* @return
*/
@Override
public boolean handlesLocalDomains() {
return false;
}
/**
* Method description
*
*
* @return
*/
@Override
public boolean handlesNameSubdomains() {
return true;
}
/**
* Method description
*
*
* @return
*/
@Override
public boolean handlesNonLocalDomains() {
return false;
}
/**
* Method description
*
*/
@Override
public void initializationCompleted() {}
/**
* Method description
*
*
* @param packet
* @param results
*/
@Override
public void processPacket(Packet packet, Queue<Packet> results) {
if (redirectTo != null) {
packet.setPacketTo(redirectTo);
results.add(packet);
} else {
log.log(Level.INFO, "No redirectTo address, dropping packet: {0}", packet);
}
}
/**
* Method description
*
*/
@Override
public void release() {}
/**
* Method description
*
*
* @return
*/
@Override
public JID getComponentId() {
return componentId;
}
/**
* Method description
*
*
* @param params
*
* @return
*/
@Override
public Map<String, Object> getDefaults(Map<String, Object> params) {
Map<String, Object> defs = new LinkedHashMap<String, Object>();
defs.put(REDIRECT_TO_PROP_KEY, "");
if (params.get(CLUSTER_NODES) != null) {
String[] cl_nodes = ((String) params.get(CLUSTER_NODES)).split(",");
for (String node : cl_nodes) {
if (!node.equals(DNSResolver.getDefaultHostname())) {
defs.put(REDIRECT_TO_PROP_KEY, BareJID.toString(getName(), node));
break;
}
}
}
defs.put(DISCO_NAME_PROP_KEY, DISCO_NAME_PROP_VAL);
defs.put(DISCO_NODE_PROP_KEY, DISCO_NODE_PROP_VAL);
defs.put(DISCO_TYPE_PROP_KEY, DISCO_TYPE_PROP_VAL);
defs.put(DISCO_CATEGORY_PROP_KEY, DISCO_CATEGORY_PROP_VAL);
defs.put(DISCO_FEATURES_PROP_KEY, DISCO_FEATURES_PROP_VAL);
defs.put(FIXED_DOMAIN_PROP_KEY, null);
return defs;
}
/**
* Method description
*
*
* @param from
*
* @return
*/
@Override
public List<Element> getDiscoFeatures(JID from) {
return null;
}
/**
* Method description
*
*
* @param node
* @param jid
* @param from
*
* @return
*/
@Override
public Element getDiscoInfo(String node, JID jid, JID from) {
return null;
}
/**
* Method description
*
*
* @param node
* @param jid
* @param from
*
* @return
*/
@Override
public List<Element> getDiscoItems(String node, JID jid, JID from) {
String domain = jid.toString();
if (fixedDomain != null) {
domain = fixedDomain;
}
Element result = serviceEntity.getDiscoItem(null, getName() + "." + domain);
return Arrays.asList(result);
}
/**
* Method description
*
*
* @return
*/
@Override
public String getName() {
return name;
}
/**
* Method description
*
*
* @param name
*/
@Override
public void setName(String name) {
this.name = name;
this.componentId = JID.jidInstanceNS(name, DNSResolver.getDefaultHostname(), null);
}
/**
* Method description
*
*
* @param properties
*/
@Override
public void setProperties(Map<String, Object> properties) {
fixedDomain = (String) properties.get(FIXED_DOMAIN_PROP_KEY);
if (fixedDomain != null) {
this.componentId = JID.jidInstanceNS(null, name + "." + fixedDomain, null);
}
String redirect = (String) properties.get(REDIRECT_TO_PROP_KEY);
if (redirect != null) {
if (redirect.isEmpty()) {
redirectTo = null;
} else {
try {
redirectTo = JID.jidInstance(redirect);
} catch (TigaseStringprepException ex) {
redirectTo = null;
log.log(Level.WARNING,
"stringprep processing failed for given redirect address: {0}", redirect);
}
}
}
if (properties.get(DISCO_NAME_PROP_KEY) != null) {
discoName = (String) properties.get(DISCO_NAME_PROP_KEY);
}
if (properties.get(DISCO_NODE_PROP_KEY) != null) {
discoNode = (String) properties.get(DISCO_NODE_PROP_KEY);
if (discoNode.isEmpty()) {
discoNode = null;
}
}
if (properties.get(DISCO_CATEGORY_PROP_KEY) != null) {
discoCategory = (String) properties.get(DISCO_CATEGORY_PROP_KEY);
}
if (properties.get(DISCO_TYPE_PROP_KEY) != null) {
discoType = (String) properties.get(DISCO_TYPE_PROP_KEY);
}
if (properties.get(DISCO_TYPE_PROP_KEY) != null) {
discoFeatures = ((String) properties.get(DISCO_TYPE_PROP_KEY)).split(",");
}
if ((discoName != null) && (discoCategory != null) && (discoType != null) &&
(discoFeatures != null)) {
serviceEntity = new ServiceEntity(getName(), null, discoName);
serviceEntity.addIdentities(new ServiceIdentity(discoCategory, discoType,
discoName));
for (String feature : discoFeatures) {
serviceEntity.addFeatures(feature);
}
}
}
/**
* Method description
*
*
* @param manager
*/
@Override
public void setVHostManager(VHostManagerIfc manager) {
this.vHostManager = manager;
}
}
//~ Formatted in Tigase Code Convention on 13/04/14 |
package uk.me.csquared.ratpacktest;
import ratpack.server.RatpackServer;
public class Main {
public static void main(String[] args) throws Exception{
RatpackServer.start(server -> server
.handlers(chain -> chain
.get(ctx -> ctx.render("Hello World!"))
.get(":name", ctx -> ctx.render("Hello " +
ctx.getPathTokens().get("name") + "!"))
)
);
}
} |
package uk.me.csquared.ratpacktest;
import ratpack.server.RatpackServer;
public class Main {
public static void main(String[] args) throws Exception{
RatpackServer.start(server -> server
.handlers(chain -> chain
.get(ctx -> ctx.render("Hello World!"))
.get(":name", ctx -> ctx.render("Hello " +
ctx.getPathTokens().get("name!") + "!"))
)
);
}
} |
package xyz.cofe.lang2.cli;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.logging.Level;
import java.util.logging.Logger;
import xyz.cofe.collection.Pair;
import xyz.cofe.files.FileUtil;
import xyz.cofe.text.Text;
public class ScriptReader {
private static void logFine(String message,Object ... args){
Logger.getLogger(ScriptReader.class.getName()).log(Level.FINE, message, args);
}
private static void logFiner(String message,Object ... args){
Logger.getLogger(ScriptReader.class.getName()).log(Level.FINER, message, args);
}
private static void logFinest(String message,Object ... args){
Logger.getLogger(ScriptReader.class.getName()).log(Level.FINEST, message, args);
}
private static void logInfo(String message,Object ... args){
Logger.getLogger(ScriptReader.class.getName()).log(Level.INFO, message, args);
}
private static void logWarning(String message,Object ... args){
Logger.getLogger(ScriptReader.class.getName()).log(Level.WARNING, message, args);
}
private static void logSevere(String message,Object ... args){
Logger.getLogger(ScriptReader.class.getName()).log(Level.SEVERE, message, args);
}
private static void logException(Throwable ex){
Logger.getLogger(ScriptReader.class.getName()).log(Level.SEVERE, null, ex);
}
//</editor-fold>
private static String readScriptHeaderText(URL file,Charset cs,int size){
if( file==null )return null;
try {
InputStream fin = file.openStream();
byte[] headerBytes = new byte[size];
int readed = fin.read(headerBytes);
if( readed>0 ){
String headerText = new String(headerBytes, 0, readed, cs);
fin.close();
return headerText;
}
fin.close();
return null;
} catch (IOException ex) {
return null;
}
}
private static String readScriptHeaderText(File file,Charset cs,int size){
if( file==null )return null;
if( !file.exists() || !file.isFile() || !file.canRead() )return null;
try {
FileInputStream fin = new FileInputStream(file);
try {
byte[] headerBytes = new byte[size];
int readed = fin.read(headerBytes);
if( readed>0 ){
String headerText = new String(headerBytes, 0, readed, cs);
fin.close();
return headerText;
}
fin.close();
return null;
} catch (IOException ex) {
return null;
}
} catch (FileNotFoundException ex) {
return null;
}
}
public static String readScriptFile(File file,Charset cs){
if( cs==null )cs = Charset.defaultCharset();
if (file== null) {
throw new IllegalArgumentException("file==null");
}
File f = file;
if( !f.exists() ){
System.err.println("Файл "+f+" не найден");
return null;
}
if( !f.isFile() ){
System.err.println("Не является файлом "+f);
return null;
}
ScriptHeader header = null;
Charset latin1 = Charset.forName("latin1");
String headerText = readScriptHeaderText(file,latin1,64*1024);
if( headerText!=null ){
header = ScriptHeader.parse(headerText);
}
if( header!=null && header.getSourceCharset()!=null ){
cs = header.getSourceCharset();
}
String code = FileUtil.readAllText(file, cs);
if( code==null ){
System.err.println("Невозможно прочесть файл "+file);
return null;
}
String ccode = cleanupScriptHeader(code, header);
return ccode;
}
public static String readScriptFile(URL file,Charset cs){
if( file==null )throw new IllegalArgumentException( "file==null" );
if( cs==null )cs = Charset.defaultCharset();
ScriptHeader header = null;
Charset latin1 = Charset.forName("latin1");
String headerText = readScriptHeaderText(file,latin1,64*1024);
if( headerText!=null ){
header = ScriptHeader.parse(headerText);
}
if( header!=null && header.getSourceCharset()!=null ){
cs = header.getSourceCharset();
}
String code = FileUtil.readAllText(file, cs);
if( code==null ){
System.err.println("Невозможно прочесть файл "+file);
return null;
}
String ccode = cleanupScriptHeader(code, header);
return ccode;
}
private static String cleanupScriptHeader(String content, ScriptHeader header){
// skip shebang
StringBuilder result = new StringBuilder();
boolean hasShebang = false;
int shebangBegin = 0;
int shebangEnd = 0;
if( header!=null && header.hasShebang() ){
hasShebang = true;
shebangBegin = 0;
int i = content.indexOf(header.getShebangEnd());
if( i>=0 ){
shebangEnd = i + header.getShebangEnd().length();
}else{
hasShebang = false;
}
}
int nextIdx = 0;
if( hasShebang ){
for( int i=0; i<shebangEnd - shebangBegin; i++ ){
char c = content.charAt(i);
if( c=='\n' || c=='\r' ){
result.append(c);
}else{
result.append(' ');
}
}
nextIdx = shebangEnd;
}
//skip whitespace to next line
if( nextIdx>0 ){
Pair<Integer,String> n = Text.nextNewLine(content, nextIdx);
if( n!=null && n.A()>nextIdx ){
int skip = n.A() - nextIdx;
int spaces = 0;
if( skip>n.B().length() ){
spaces = skip - n.B().length();
}
if( spaces>0 )result.append( Text.repeat(" ", spaces) );
result.append(n.B());
nextIdx = n.A();
}
}
//skip bash comments
StringBuilder sb = result;
int state = 0;
for( int i=nextIdx; i<content.length(); i++ ){
char c0 = content.charAt(i);
char c1 = i<(content.length()-1) ? content.charAt(i+1) : (char)0;
switch( state ){
case 0:
if( c0=='
state = 1;
sb.append(" ");
}else{
state = 100;
sb.append(c0);
}
break;
case 1:
if( c0=='\n' && c1=='\r' ){
//Acorn BBC, RISC OS
state = 2;
sb.append("\n");
}else if( c0=='\r' && c1=='\n' ){
//CR+LF - Windows,Dos
state = 3;
sb.append("\r");
}else if( c0=='\n' && c1!='\r' ){
// Unix, linux, ....
state = 0;
sb.append("\n");
}else if( c0=='\r' && c1!='\n' ){
// Mac os
state = 0;
sb.append("\r");
}else{
state = 1;
sb.append(" ");
}
break;
case 2:
state = 0;
sb.append("\r");
break;
case 3:
state = 0;
sb.append("\n");
break;
case 100:
sb.append(c0);
break;
}
}
return result.toString();
}
} |
package com.nasa;
/**
* Project: NASA Path in conjunction with University of Maryland University
* College
*
* @author jadovan
*/
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class DijkstraPaths {
private List<Node> nodes;
private List<Edge> edges;
private ArrayList<String> nodeIndexList;
CreateNodes cn = new CreateNodes();
public List getShortestPaths(String source, String destination, List<Node> nodes) {
nodeIndexList = new ArrayList<String>();
for (Node node : nodes) {
nodeIndexList.add(node.getNodeId());
}
int sourceIndex = nodeIndexList.indexOf(source);
int destinationIndex = nodeIndexList.indexOf(destination);
Graph graph = new Graph(nodes, getEdgesFromNodes(nodes, 70));
Dijkstra dijkstra = new Dijkstra(graph);
System.out.println("got d");
dijkstra.execute(nodes.get(sourceIndex));
System.out.println("got results");
return dijkstra.getPath(nodes.get(destinationIndex));
}
// This method processes the Dijkstra Algorithm for the three shortest paths
public void ExecutePaths(String source, String destination) {
cn.createS0LabHandHoldNodeList();
int sourceIndex = cn.s0LabHandHoldNodeIndexList.indexOf(source);
int destinationIndex = cn.s0LabHandHoldNodeIndexList.indexOf(destination);
Graph graph = new Graph(pathNodes(), pathOneEdges());
Dijkstra dijkstra = new Dijkstra(graph);
dijkstra.execute(nodes.get(sourceIndex));
LinkedList<Node> path = dijkstra.getPath(nodes.get(destinationIndex));
System.out.println("1st path from " + nodes.get(sourceIndex).getNodeId()
+ " to " + nodes.get(destinationIndex).getNodeId());
if (path != null) {
path.forEach((node1) -> {
System.out.println(node1.getNodeId());
});
} else {
System.out.println("1st path could not be determined between these nodes.");
}
graph = new Graph(pathNodes(), pathTwoEdges());
dijkstra = new Dijkstra(graph);
dijkstra.execute(nodes.get(sourceIndex));
path = dijkstra.getPath(nodes.get(destinationIndex));
System.out.println("\n2nd path from " + nodes.get(sourceIndex).getNodeId()
+ " to " + nodes.get(destinationIndex).getNodeId());
if (path != null) {
path.forEach((node2) -> {
System.out.println(node2.getNodeId());
});
} else {
System.out.println("2nd path could not be determined between these nodes.");
}
graph = new Graph(pathNodes(), pathThreeEdges());
dijkstra = new Dijkstra(graph);
dijkstra.execute(nodes.get(sourceIndex));
path = dijkstra.getPath(nodes.get(destinationIndex));
System.out.println("\n3rd path from " + nodes.get(sourceIndex).getNodeId()
+ " to " + nodes.get(destinationIndex).getNodeId());
if (path != null) {
path.forEach((node3) -> {
System.out.println(node3.getNodeId());
});
} else {
System.out.println("3rd path could not be determined between these nodes.");
}
}
// This method is used for creating the Edge lanes to be processed by the Dijkstra Algorithm
private void addLane(String laneId, int sourceLocNo, int destLocNo,
double duration) {
Edge lane = new Edge(laneId, nodes.get(sourceLocNo), nodes.get(destLocNo), duration);
edges.add(lane);
}
// This method adds node locations for the shortest paths
private List pathNodes() {
nodes = new ArrayList<>();
cn.createS0LabHandHoldNodeList();
// These for loops add lanes to the s0 and lab nodes for the shortest paths
for (int i = 0; i < cn.s0LabHandHoldNodeList.size(); i++) {
Node location = new Node(cn.s0LabHandHoldNodeList.get(i).getNodeId());
nodes.add(location);
}
return nodes;
}
private List getEdgesFromNodes(List<Node> nodes, double weightThreshold) {
ArrayList<Edge> edges = new ArrayList<>();
for (int j = 0; j < nodes.size(); j++) {
for (int k = 0; k < nodes.size(); k++) {
String s0LabNodesJ = nodeIndexList.get(j);
String s0LabNodesK = nodeIndexList.get(k);
double weight = cn.node_distance_formula(nodes.get(j), nodes.get(k));
if (weight <= weightThreshold) {
String laneId = "Edge_" + j;
Edge lane = new Edge(laneId, nodes.get(nodeIndexList.indexOf(s0LabNodesJ)), nodes.get(nodeIndexList.indexOf(s0LabNodesK)), weight);
edges.add(lane);
}
}
}
return edges;
}
// This method adds lanes for the first shortest path
private List pathOneEdges() {
edges = new ArrayList<>();
cn.createS0LabHandHoldNodeList();
for (int j = 0; j < cn.s0LabHandHoldNodeList.size(); j++) {
for (int k = 0; k < cn.s0LabHandHoldNodeList.size(); k++) {
String s0LabNodesJ = cn.s0LabHandHoldNodeIndexList.get(j);
String s0LabNodesK = cn.s0LabHandHoldNodeIndexList.get(k);
double weight = cn.node_distance_formula(cn.s0LabHandHoldNodeList.get(j), cn.s0LabHandHoldNodeList.get(k));
if (weight <= 54) {
addLane("Edge_" + j, cn.s0LabHandHoldNodeIndexList.indexOf(s0LabNodesJ),
cn.s0LabHandHoldNodeIndexList.indexOf(s0LabNodesK), weight);
}
}
}
return edges;
}
// This method adds lanes for the second shortest path
private List pathTwoEdges() {
edges = new ArrayList<>();
cn.createS0LabHandHoldNodeList();
for (int j = 0; j < cn.s0LabHandHoldNodeList.size(); j++) {
for (int k = 0; k < cn.s0LabHandHoldNodeList.size(); k++) {
String s0LabNodesJ = cn.s0LabHandHoldNodeIndexList.get(j);
String s0LabNodesK = cn.s0LabHandHoldNodeIndexList.get(k);
double weight = cn.node_distance_formula(cn.s0LabHandHoldNodeList.get(j), cn.s0LabHandHoldNodeList.get(k));
if (weight <= 62) {
addLane("Edge_" + j, cn.s0LabHandHoldNodeIndexList.indexOf(s0LabNodesJ),
cn.s0LabHandHoldNodeIndexList.indexOf(s0LabNodesK), weight);
}
}
}
return edges;
}
// This method adds lanes for the third shortest path
private List pathThreeEdges() {
edges = new ArrayList<>();
cn.createS0LabHandHoldNodeList();
for (int j = 0; j < cn.s0LabHandHoldNodeList.size(); j++) {
for (int k = 0; k < cn.s0LabHandHoldNodeList.size(); k++) {
String s0LabNodesJ = cn.s0LabHandHoldNodeIndexList.get(j);
String s0LabNodesK = cn.s0LabHandHoldNodeIndexList.get(k);
double weight = cn.node_distance_formula(cn.s0LabHandHoldNodeList.get(j), cn.s0LabHandHoldNodeList.get(k));
if (weight <= 70) {
addLane("Edge_" + j, cn.s0LabHandHoldNodeIndexList.indexOf(s0LabNodesJ),
cn.s0LabHandHoldNodeIndexList.indexOf(s0LabNodesK), weight);
}
}
}
return edges;
}
} |
package apoc.index;
import apoc.util.TestUtil;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.factory.GraphDatabaseBuilder;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.graphdb.factory.GraphDatabaseSettings;
import org.neo4j.kernel.api.exceptions.KernelException;
import java.util.Arrays;
import java.util.Collection;
import static apoc.util.TestUtil.registerProcedure;
import static apoc.util.TestUtil.testResult;
import static org.junit.Assert.assertEquals;
import static org.neo4j.helpers.collection.Iterators.count;
/**
* test to verify that fulltext indexes are updated, even across restarts of Neo4j
* @author Stefan Armbruster
*/
@RunWith(Parameterized.class)
public class UpdateFreetextIndexTest {
@Parameterized.Parameters(name = "with index config {0}, autoUpdate.enabled = {1}, async = {2}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ "{}", true, false, false},
{ "{autoUpdate:false}", true, false, false},
{ "{autoUpdate:true}", true, false, true},
{ "{autoUpdate:true}", false, false, false},
{ "{}", true, true, false},
{ "{autoUpdate:false}", true, true, false},
{ "{autoUpdate:true}", true, true, true},
{ "{autoUpdate:true}", false, true, false}
});
}
@Parameterized.Parameter(value = 0)
public String paramIndexConfigMapAsString;
@Parameterized.Parameter(value = 1)
public boolean paramEnableAutoUpdatesInApocConfig;
@Parameterized.Parameter(value = 2)
public boolean paramDoUpdatesAsync;
@Parameterized.Parameter(value = 3)
public boolean paramExpectUpdates;
@Rule
public TemporaryFolder tmpFolder = new TemporaryFolder();
@Test
public void shouldIndexGetUpdatedAcrossRestarts() throws KernelException, InterruptedException {
// establish a graph db with a free text index
GraphDatabaseService graphDatabaseService = initGraphDatabase();
try {
registerProcedure(graphDatabaseService, FreeTextSearch.class);
graphDatabaseService.execute("create (:Article{text:'John owns a house in New York.'}) create (:Article{text:'Susan lives in a house together with John'})").close();
Thread.sleep(1000);
String indexingCypher = String.format("call apoc.index.addAllNodesExtended('fulltext',{Article:['text']},%s)", paramIndexConfigMapAsString);
graphDatabaseService.execute(indexingCypher).close();
// create another fulltext index
indexingCypher = String.format("call apoc.index.addAllNodesExtended('fulltext2',{Article2:['text']},%s)", paramIndexConfigMapAsString);
graphDatabaseService.execute(indexingCypher).close();
TestUtil.testResult(graphDatabaseService, "call apoc.index.search('fulltext', 'house')", result ->
assertEquals(2, count(result))
);
TestUtil.testResult(graphDatabaseService, "call apoc.index.search('fulltext2', 'house')", result ->
assertEquals(0, count(result))
);
} finally {
graphDatabaseService.shutdown();
}
// restart graph db, add another node and check if it got indexed
graphDatabaseService = initGraphDatabase();
try {
registerProcedure(graphDatabaseService, FreeTextSearch.class);
graphDatabaseService.execute("create (:Article{text:'Mr. baker is renovating John\\'s house'}) ");
if (paramDoUpdatesAsync) {
Thread.sleep(300);
}
testResult(graphDatabaseService, "call apoc.index.search('fulltext', 'house')", result ->
assertEquals(2 + (paramExpectUpdates ? 1 : 0), count(result))
);
graphDatabaseService.execute("match (n) set n:Article2");
if (paramDoUpdatesAsync) {
Thread.sleep(300);
}
testResult(graphDatabaseService, "call apoc.index.search('fulltext2', 'house')", result ->
assertEquals(paramExpectUpdates ? 3 : 0, count(result))
);
} finally {
graphDatabaseService.shutdown();
}
}
private GraphDatabaseService initGraphDatabase() {
GraphDatabaseBuilder graphDatabaseBuilder = new GraphDatabaseFactory().newEmbeddedDatabaseBuilder(tmpFolder.getRoot());
graphDatabaseBuilder.setConfig(GraphDatabaseSettings.pagecache_memory, "8M");
graphDatabaseBuilder.setConfig("apoc.autoIndex.enabled", Boolean.toString(paramEnableAutoUpdatesInApocConfig));
graphDatabaseBuilder.setConfig("apoc.autoIndex.async", Boolean.toString(paramDoUpdatesAsync));
graphDatabaseBuilder.setConfig("apoc.autoIndex.async_rollover_opscount", "10");
graphDatabaseBuilder.setConfig("apoc.autoIndex.async_rollover_millis", "100");
return graphDatabaseBuilder.newGraphDatabase();
}
} |
package JavaProject;
import epic.sequences.SemiCRF;
import epic.sequences.SemiConllNerPipeline;
import org.apache.commons.lang3.SystemUtils;
import org.apache.commons.lang3.math.NumberUtils;
import java.io.*;
import java.nio.channels.FileChannel;
import java.util.*;
public class InformationDensity {
public static void main(String[] args) {
Properties prop = new Properties();
String pathToEpic = "";
try {
prop.load(new FileInputStream("src/main/resources/config.properties"));
pathToEpic = prop.getProperty("pathToEpic");
} catch (IOException ex) {
System.out.println("Could not find config file. " + ex);
System.exit(0);
}
WordVec allWordsVec = createWordVec(pathToEpic,Integer.parseInt(args[0]));
File fileNameWordFreq = new File(pathToEpic + "/epic/data/wordFreq.txt");
File allSentencesFile = new File(pathToEpic + "/epic/data/allSentences.txt");
String s = null;
double similarities[] = new double[2];
List<String> allSentences = new ArrayList<>();
List<Double> ids = new ArrayList<>();
double simScore = 0;
double delta = Double.parseDouble(args[1]);
PrintWriter writer;
long startTime= System.currentTimeMillis();
try {
FileReader tmpR = new FileReader(allSentencesFile);
BufferedReader tmp = new BufferedReader(tmpR);
int startIndex;
while ((s = tmp.readLine()) != null) {
String[] split = s.split(" ");
startIndex = split[0].length();
allSentences.add(s.substring(startIndex));
ids.add(Double.parseDouble(split[0]));
}
} catch (FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
allSentencesFile + "'");
} catch (IOException ex) {
System.out.println(
"Error reading file '"
+ allSentencesFile + "'");
}
try {
System.out.println("********* FILE WRITING DONE**********");
writer = new PrintWriter(pathToEpic+"/epic/data/informationDensity.txt", "UTF-8");
int c = 0;
List<double[]> wordVecs1;
List<double[]> wordVecs2;
CalculateSimilarity cs = new CalculateSimilarity();
startTime = System.currentTimeMillis();
String objectSentence;
String pairSentence;
double scores[] = new double[allSentences.size()];
long startfor;
long endfor;
int b = 1;
int limit = 10;
for (int obj = 0; obj < limit; obj++) {//allSentences.size()
objectSentence = allSentences.get(obj).toLowerCase();
objectSentence = objectSentence.replaceAll("\\p{Punct}+","");
wordVecs1 = createSentenceWordVector(objectSentence,allWordsVec);
simScore = 0;
double med = 0;
startfor = System.currentTimeMillis();
for (int u = obj; u < allSentences.size();u++) {
if((b % 1000)==0) {
System.out.println("1000 runs took " + med/1000 + " milliseconds on average");
startfor = System.currentTimeMillis();
}
pairSentence = allSentences.get(u).toLowerCase();
pairSentence = pairSentence.replaceAll("\\p{Punct}+","");
wordVecs2 = createSentenceWordVector(pairSentence,allWordsVec);
similarities = cs.CalculateSimilarity(objectSentence, pairSentence, fileNameWordFreq, allWordsVec,wordVecs1,wordVecs2);
scores[u] += similarities[0]*delta+(1-similarities[1])*(1-delta);
simScore += similarities[0]*delta+similarities[1]*(1-delta);
b++;
endfor = System.currentTimeMillis();
med += endfor-startfor;
}
scores[obj] += simScore;
long currTime = System.currentTimeMillis();
System.out.println("That took " + (currTime - startTime) + " milliseconds");
c++;
}
for(int u = 0; u < allSentences.size(); u++) {
writer.write(Double.toString(scores[u]/(2*allSentences.size()))+"\n");
}
writer.close();
} catch (FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
pathToEpic +"/epic/data/informationDensity.txt" + "'");
} catch (IOException ex) {
System.out.println(
"Error reading file '"
+ pathToEpic +"/epic/data/informationDensity.txt" + "'");
}
long endTime = System.currentTimeMillis();
System.out.println("That took " + (endTime - startTime) + " milliseconds");
}
/**
* Creates word vectors for the current sentence.
* @param sent The current sentence
* @param allWordsVec A WordVec object containing vectors for most words found in relevant sentences
* @return A list of vectors of doubles representing the wordvectors for each word in the sentence. Hence it should
* the same length as the amount of words in sent.
*/
public static List<double[]> createSentenceWordVector(String sent, WordVec allWordsVec){
List<double[]> wordVecs = new ArrayList<double[]>();
String[] splitSent = sent.split(" ");
for(int i = 0; i < splitSent.length; i++) // For each word
{
double[] wordVector = allWordsVec.getVectorOfWord(splitSent[i]);
//if (wordVector[0]!=-100) {
wordVecs.add(wordVector);
}
return wordVecs;
}
/**
* Creates a WordVec object containing all the words in the unlabeled pool and their word vectors. Currently
* needs the name of the user. Should be a relative path.
* @param pathToEpic path to Epic for the current user
* @return A WordVec object
*/
public static WordVec createWordVec(String pathToEpic, int dimension){
System.out.println("******** Create WordVec **********\n");
File wordVec;
if (dimension == 2) {
wordVec = new File(pathToEpic +"/epic/data/wordVecs2D.txt");
}
else {wordVec = new File(pathToEpic +"/epic/epic/data/wordVecs.txt");}
File uniqMals = new File(pathToEpic +"/epic/epic/data/uniqMals.txt");
List<String> words = new ArrayList<>();
List<double[]> vectors = new ArrayList<>();
WordVec allWords;
double vector[] = new double[dimension];
double n1[] = new double[dimension];
double stuxnet[] = new double[dimension];
try {
FileReader tmpW = new FileReader(wordVec);
BufferedReader tmp = new BufferedReader(tmpW);
String word;
String line = null;
int cMal = 0;
int cNons = 0;
boolean number1 = true;
while ((line=tmp.readLine()) != null) {
String[] splitLine = line.split(" ");
word = splitLine[0];
Arrays.fill(vector, 0.0);
if (splitLine.length>1) {
for (int i = 1; i < splitLine.length; i++) {
vector[i - 1] = Double.parseDouble(splitLine[i]);
}
if (word.equals("stuxnet")){
stuxnet = vector.clone();
}
if (number1){
n1 = vector.clone();
number1 = false;
}
}
else{
boolean wordIsMalware = false;
Scanner scanner = new Scanner(uniqMals);
while (scanner.hasNextLine()) {
String nextToken = scanner.next();
if (nextToken.equalsIgnoreCase(word)) {
wordIsMalware = true;
break;
}
}
if (wordIsMalware) {
cMal++;
vector = stuxnet.clone();
}
else if (NumberUtils.isNumber(word))
{
vector = n1.clone();
}
else {
cNons++;
Arrays.fill(vector, -100.0);
}
}
words.add(word);
vectors.add(vector.clone());
}
allWords = new WordVec(words,vectors);
return allWords;
} catch (FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
wordVec.getAbsolutePath() + "'");
} catch (IOException ex) {
System.out.println(
"Error reading file '"
+ wordVec.getAbsolutePath() + "'");
}
allWords = new WordVec(words,vectors);
return allWords;
}
} |
package com.jcabi.log;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.hamcrest.Matchers;
import org.junit.Assert;
import org.junit.Test;
/**
* ParseInformation test case.
* @author Jose V. Dal Pra Junior (jrdalpra@gmail.com)
* @version $Id$
* @since 0.18
*/
public class ParseInformationTest {
/**
* Just a word used at several test cases.
*/
private static final String WHITE = "white";
/**
* ParseInformation can parse if the information correctly if is using
* the right pattern.
*/
@Test
@SuppressWarnings("PMD.UseConcurrentHashMap")
public final void parsesTheInformationCorrectly() {
final Map<String, String> parsed = new ParseInformation(
"white:10,black:20"
).parse();
Assert.assertThat(parsed, Matchers.hasEntry(WHITE, "10"));
Assert.assertThat(parsed, Matchers.hasEntry("black", "20"));
}
/**
* ParseInformation can throw an an exception when parsing wrong info.
*/
@Test
public final void throwsAnExceptionWhenParsingSomethingWrong() {
try {
new ParseInformation(WHITE).parse();
Assert.fail("Should never enter this assert!");
} catch (final IllegalStateException ex) {
Assert.assertThat(
ex.getMessage(), Matchers.equalTo(
String.format(
StringUtils.join(
"Information is not using the pattern ",
"KEY1:VALUE,KEY2:VALUE %s"
), WHITE
)
)
);
}
}
} |
package com.neo4j.docker;
import com.neo4j.docker.utils.HostFileSystemOperations;
import com.neo4j.docker.utils.PwGen;
import com.neo4j.docker.utils.SetContainerUser;
import com.neo4j.docker.utils.TestSettings;
import org.junit.Assume;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
import org.neo4j.driver.*;
import org.testcontainers.containers.DockerComposeContainer;
import org.testcontainers.containers.wait.strategy.*;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.UUID;
public class TestCausalCluster
{
private static final int DEFAULT_BOLT_PORT = 7687;
@Test
void testCausalClusteringBasic() throws Exception
{
Assume.assumeTrue( "No causal clustering for community edition",
TestSettings.EDITION == TestSettings.Edition.ENTERPRISE );
Path tmpDir = HostFileSystemOperations.createTempFolder( "CC_cluster_" );
File compose_file = new File(tmpDir.toString(), "causal-cluster-compose.yml");
Files.copy(getResource("causal-cluster-compose.yml"), Paths.get(compose_file.getPath()));
Files.createDirectories( tmpDir.resolve( "core1" ) );
Files.createDirectories( tmpDir.resolve( "core2" ) );
Files.createDirectories( tmpDir.resolve( "core3" ) );
Files.createDirectories( tmpDir.resolve( "readreplica1" ) );
String content = new String(Files.readAllBytes(Paths.get(compose_file.getPath())));
String[] contentLines = content.split(System.getProperty("line.separator"));
String[] editedLines = new String[contentLines.length];
int i = 0;
for (String line : contentLines) {
editedLines[i] = line.replaceAll("%%IMAGE%%", TestSettings.IMAGE_ID);
editedLines[i] = editedLines[i].replaceAll("%%LOGS_DIR%%", tmpDir.toAbsolutePath().toString());
editedLines[i] = editedLines[i].replaceAll("%%USERIDGROUPID%%", SetContainerUser.getCurrentlyRunningUserString());
i++;
}
String editedContent = String.join("\n", editedLines);
DataOutputStream outstream= new DataOutputStream(new FileOutputStream(compose_file,false));
outstream.write(editedContent.getBytes());
outstream.close();
System.out.println("logs: " + compose_file.getName() + " and " + tmpDir.toString());
DockerComposeContainer clusteringContainer = new DockerComposeContainer(compose_file)
.withLocalCompose(true)
.withExposedService("core1", DEFAULT_BOLT_PORT)
.withExposedService("core1", 7474, Wait.forHttp( "/" ).forPort( 7474 ).forStatusCode( 200 ).withStartupTimeout( Duration.ofSeconds( 180 ) ))
.withExposedService("readreplica1", DEFAULT_BOLT_PORT);
clusteringContainer.start();
String core1Uri = "bolt://" + clusteringContainer.getServiceHost("core1", DEFAULT_BOLT_PORT)
+ ":" +
clusteringContainer.getServicePort("core1", DEFAULT_BOLT_PORT);
String rrUri = "bolt://" + clusteringContainer.getServiceHost("readreplica1", DEFAULT_BOLT_PORT)
+ ":" +
clusteringContainer.getServicePort("readreplica1", DEFAULT_BOLT_PORT);
try ( Driver coreDriver = GraphDatabase.driver( core1Uri, AuthTokens.basic( "neo4j", "neo")))
{
Session session = coreDriver.session();
StatementResult rs = session.run( "CREATE (arne:dog {name:'Arne'})-[:SNIFFS]->(bosse:dog {name:'Bosse'}) RETURN arne.name");
Assertions.assertEquals( "Arne", rs.single().get( 0 ).asString(), "did not receive expected result from cypher CREATE query" );
}
catch (Exception e)
{
clusteringContainer.stop();
return;
}
try ( Driver rrDriver = GraphDatabase.driver(rrUri, AuthTokens.basic("neo4j", "neo")))
{
Session session = rrDriver.session();
StatementResult rs = session.run( "MATCH (a:dog)-[:SNIFFS]->(b:dog) RETURN a.name");
Assertions.assertEquals( "Arne", rs.single().get( 0 ).asString(), "did not receive expected result from cypher MATCH query" );
}
catch (Exception e)
{
clusteringContainer.stop();
return;
}
clusteringContainer.stop();
}
private InputStream getResource(String path) {
InputStream resource = getClass().getClassLoader().getResourceAsStream(path);
return resource;
}
} |
package com.wizzardo.epoll;
import com.wizzardo.epoll.readable.ReadableBuilder;
import com.wizzardo.epoll.readable.ReadableByteArray;
import com.wizzardo.epoll.readable.ReadableByteBuffer;
import com.wizzardo.epoll.readable.ReadableData;
import com.wizzardo.epoll.threadpool.ThreadPool;
import com.wizzardo.tools.http.HttpClient;
import com.wizzardo.tools.io.FileTools;
import com.wizzardo.tools.misc.Stopwatch;
import com.wizzardo.tools.security.MD5;
import org.junit.Assert;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.*;
import java.nio.ByteBuffer;
import java.util.Enumeration;
import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
public class EpollServerTest {
@Test
public void startStopTest() throws InterruptedException {
int port = 9091;
EpollServer server = new EpollServer(port);
server.setIoThreadsCount(1);
server.start();
Thread.sleep(500);
server.close();
Thread.sleep(510);
String connectionRefuse = null;
try {
new Socket("localhost", port);
} catch (IOException e) {
connectionRefuse = e.getMessage();
}
Assert.assertEquals("Connection refused (Connection refused)", connectionRefuse);
}
@Test
public void echoTest() throws InterruptedException {
int port = 9090;
EpollServer server = new EpollServer(port) {
@Override
protected IOThread createIOThread(int number, int divider) {
return new IOThread(number, divider) {
@Override
public void onRead(Connection connection) {
try {
byte[] b = new byte[1024];
int r = connection.read(b, 0, b.length, this);
connection.write(b, 0, r, this);
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
};
server.setIoThreadsCount(1);
server.start();
try {
Socket s = new Socket("localhost", port);
OutputStream out = s.getOutputStream();
out.write("hello world!".getBytes());
InputStream in = s.getInputStream();
byte[] b = new byte[1024];
int r = in.read(b);
Assert.assertEquals("hello world!", new String(b, 0, r));
} catch (IOException e) {
e.printStackTrace();
assert e == null;
}
server.close();
}
@Test
public void builderTest() throws InterruptedException {
int port = 9094;
final ByteBufferWrapper partOne = new ByteBufferWrapper("Hello ".getBytes());
final ByteBufferWrapper partTwo = new ByteBufferWrapper("world!".getBytes());
EpollServer server = new EpollServer(port) {
@Override
protected IOThread createIOThread(int number, int divider) {
return new IOThread(number, divider) {
@Override
public void onConnect(Connection connection) {
connection.write(new ReadableBuilder()
.append(new ReadableByteBuffer(partOne))
.append(new ReadableByteBuffer(partTwo))
, this);
}
};
}
};
server.setIoThreadsCount(1);
server.start();
try {
Socket s = new Socket("localhost", port);
InputStream in = s.getInputStream();
byte[] b = new byte[1024];
int r = in.read(b);
Assert.assertEquals("Hello world!", new String(b, 0, r));
} catch (IOException e) {
e.printStackTrace();
assert e == null;
}
server.close();
}
@Test
public void builderTest_2() throws InterruptedException {
int port = 9094;
final ReadableData partOne = new ReadableByteArray("Hello ".getBytes());
final ReadableData partStatic = new ReadableByteBuffer(new ByteBufferWrapper("static ".getBytes()));
final ReadableData partTwo = new ReadableByteArray("world!".getBytes());
EpollServer server = new EpollServer(port) {
@Override
protected IOThread createIOThread(int number, int divider) {
return new IOThread(number, divider) {
@Override
public void onConnect(Connection connection) {
connection.write(new ReadableBuilder()
.append(partOne)
.append(partStatic)
.append(partTwo)
, this);
connection.close();
}
};
}
};
server.setIoThreadsCount(1);
server.start();
try {
Socket s = new Socket("localhost", port);
InputStream in = s.getInputStream();
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int r;
while ((r = in.read(b)) != -1) {
out.write(b, 0, r);
}
Assert.assertEquals("Hello static world!", new String(out.toByteArray()));
} catch (IOException e) {
e.printStackTrace();
assert e == null;
}
server.close();
}
static class BufferedConnection extends Connection {
final byte[] buffer = new byte[128];
volatile int count;
public BufferedConnection(int fd, int ip, int port) {
super(fd, ip, port);
}
}
// @Test
public void httpTest() throws InterruptedException {
int port = 8084;
final int poolSize = 2;
final ThreadPool pool = new ThreadPool(poolSize);
final ThreadLocal<ByteBufferProvider> threadLocal = new ThreadLocal<ByteBufferProvider>() {
@Override
protected ByteBufferProvider initialValue() {
return new ByteBufferProvider() {
ByteBufferWrapper wrapper = new ByteBufferWrapper(1000);
@Override
public ByteBufferWrapper getBuffer() {
return wrapper;
}
};
}
};
EpollServer<BufferedConnection> server = new EpollServer<BufferedConnection>(port) {
@Override
protected BufferedConnection createConnection(int fd, int ip, int port) {
return new BufferedConnection(fd, ip, port);
}
final byte[] data = "HTTP/1.1 200 OK\r\nConnection: Keep-Alive\r\nContent-Length: 5\r\nContent-Type: text/html;charset=UTF-8\r\n\r\nololo".getBytes();
// byte[] response = "HTTP/1.1 200 OK\r\nConnection: Close\r\nContent-Length: 5\r\nContent-Type: text/html;charset=UTF-8\r\n\r\nololo".getBytes();
// ReadableByteBuffer response = new ReadableByteBuffer(new ByteBufferWrapper(data));
@Override
protected IOThread<BufferedConnection> createIOThread(int number, int divider) {
return new IOThread<BufferedConnection>(number, divider) {
@Override
public void onRead(final BufferedConnection connection) {
// try {
// int r = connection.read(b, 0, b.length, this);
// System.out.println("read: " + r);
// System.out.println(new String(b, 0, r));
// connection.write(response.copy());
// System.out.println("on read");
if (poolSize == 0)
process(connection, this);
else
pool.add(new Runnable() {
@Override
public void run() {
process(connection, threadLocal.get());
}
});
}
private void process(BufferedConnection connection, ByteBufferProvider bufferProvider) {
try {
connection.count += connection.read(connection.buffer, connection.count, connection.buffer.length - connection.count, bufferProvider);
// System.out.println("read: "+connection.count);
} catch (IOException e) {
e.printStackTrace();
}
if (connection.count == 40) {// request size from wrk
connection.count = 0;
connection.write(data, bufferProvider);
}
}
};
}
};
server.setIoThreadsCount(2);
server.start();
Thread.sleep(25 * 60 * 1000);
server.close();
}
// @Test
public void httpsTest() throws InterruptedException {
int port = 8084;
EpollServer<Connection> server = new EpollServer<Connection>(port) {
@Override
protected Connection createConnection(int fd, int ip, int port) {
return new Connection(fd, ip, port) {
// @Override
// public void onWriteData(ReadableData readable, boolean hasMore) {
// if (readable.length() > 1000)
// try {
// close();
// } catch (IOException e) {
// e.printStackTrace();
};
}
byte[] image = FileTools.bytes("/home/wizzardo/interface.gif");
// byte[] data = "HTTP/1.1 200 OK\r\nConnection: Keep-Alive\r\nContent-Length: 5\r\nContent-Type: text/html;charset=UTF-8\r\n\r\nololo".getBytes();
byte[] data = ("HTTP/1.1 200 OK\r\nConnection: Keep-Alive\r\nContent-Length: " + image.length + "\r\nContent-Type: image/gif\r\n\r\n").getBytes();
// byte[] data = ("HTTP/1.1 200 OK\r\nConnection: Close\r\nContent-Length: " + image.length + "\r\nContent-Type: image/gif\r\n\r\n").getBytes();
// byte[] response = "HTTP/1.1 200 OK\r\nConnection: Close\r\nContent-Length: 5\r\nContent-Type: text/html;charset=UTF-8\r\n\r\nololo".getBytes();
// ReadableByteBuffer response = new ReadableByteBuffer(new ByteBufferWrapper(data));
@Override
protected IOThread<Connection> createIOThread(int number, int divider) {
return new IOThread<Connection>(number, divider) {
byte[] b = new byte[1024];
@Override
public void onRead(final Connection connection) {
try {
int r = connection.read(b, 0, b.length, this);
if (r == 0)
return;
// System.out.println("read: " + r);
// System.out.println(new String(b, 0, r));
// System.out.println("end");
// System.out.println("");
if (r >= 4 && b[r - 4] == '\r' && b[r - 3] == '\n' && b[r - 2] == '\r' && b[r - 1] == '\n') {
connection.write(data, this);
connection.write(image, this);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
};
server.setIoThreadsCount(4);
server.loadCertificates("/home/wizzardo/ssl_server/test_cert.pem", "/home/wizzardo/ssl_server/test_key.pem");
server.start();
Thread.sleep(25 * 60 * 1000);
server.close();
}
@Test
public void maxEventsTest() throws InterruptedException {
final int port = 9092;
final AtomicInteger connectionsCounter = new AtomicInteger();
EpollServer server = new EpollServer(null, port, 200) {
@Override
protected IOThread createIOThread(int number, int divider) {
return new IOThread(number, divider) {
@Override
public void onRead(Connection connection) {
try {
byte[] b = new byte[32];
int r = connection.read(b, 0, b.length, this);
// System.out.println("read: " + new String(b, 0, r));
connection.write(b, 0, r, this);
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onConnect(Connection connection) {
connectionsCounter.incrementAndGet();
// System.out.println("onConnect " + connections.get());
}
@Override
public void onDisconnect(Connection connection) {
connectionsCounter.decrementAndGet();
// System.out.println("onDisconnect " + connections.get());
}
};
}
};
server.setIoThreadsCount(1);
server.start();
final AtomicLong total = new AtomicLong(0);
long time = System.currentTimeMillis();
int threads = 100;
final int n = 10000;
final CountDownLatch latch = new CountDownLatch(threads);
final AtomicInteger counter = new AtomicInteger();
for (int j = 0; j < threads; j++) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Socket s = new Socket("localhost", port);
OutputStream out = s.getOutputStream();
InputStream in = s.getInputStream();
byte[] b = new byte[1024];
byte[] hello = "hello world!".getBytes();
for (int i = 0; i < n; i++) {
// System.out.println("write");
out.write(hello);
out.flush();
// System.out.println("wait for response");
int r = in.read(b);
total.addAndGet(r);
// System.out.println("get response: " + new String(b, 0, r));
Assert.assertEquals("hello world!", new String(b, 0, r));
}
s.close();
counter.incrementAndGet();
} catch (IOException e) {
e.printStackTrace();
} finally {
latch.countDown();
}
}
}).start();
Thread.sleep(10);
}
latch.await();
Thread.sleep(100);
Assert.assertEquals(threads, counter.get());
Assert.assertEquals(0, connectionsCounter.get());
System.out.println("total bytes were sent: " + total.get() * 2);
time = System.currentTimeMillis() - time;
System.out.println("for " + time + "ms");
System.out.println(total.get() * 1000.0 / time / 1024.0 / 1024.0);
server.close();
}
private String getLocalIp() throws UnknownHostException, SocketException {
System.out.println("Your Host addr: " + InetAddress.getLocalHost().getHostAddress()); // often returns "127.0.0.1"
Enumeration<NetworkInterface> n = NetworkInterface.getNetworkInterfaces();
for (; n.hasMoreElements(); ) {
NetworkInterface e = n.nextElement();
Enumeration<InetAddress> a = e.getInetAddresses();
for (; a.hasMoreElements(); ) {
InetAddress addr = a.nextElement();
if (addr.getAddress().length == 4 && !addr.getHostAddress().startsWith("127"))
return addr.getHostAddress();
}
}
return null;
}
@Test
public void hostBindTest() throws InterruptedException, UnknownHostException, SocketException {
int port = 9090;
String host = getLocalIp();
// String host = "192.168.1.144";
EpollServer server = new EpollServer(host, port) {
@Override
protected IOThread createIOThread(int number, int divider) {
return new IOThread(number, divider) {
@Override
public void onRead(Connection connection) {
try {
byte[] b = new byte[1024];
int r = connection.read(b, 0, b.length, this);
connection.write(b, 0, r, this);
} catch (IOException e) {
e.printStackTrace();
}
}
};
}
};
server.setIoThreadsCount(1);
server.start();
String message = null;
try {
new Socket("localhost", port);
} catch (IOException e) {
message = e.getMessage();
}
Assert.assertEquals("Connection refused (Connection refused)", message);
try {
Socket s = new Socket(host, port);
OutputStream out = s.getOutputStream();
out.write("hello world!".getBytes());
InputStream in = s.getInputStream();
byte[] b = new byte[1024];
int r = in.read(b);
Assert.assertEquals("hello world!", new String(b, 0, r));
} catch (IOException e) {
e.printStackTrace();
}
server.close();
}
@Test
public void testWriteEvents() throws IOException, InterruptedException {
int port = 9090;
String host = "localhost";
final byte[] data = new byte[10 * 1024 * 1024];
new Random().nextBytes(data);
String md5 = MD5.create().update(data).asString();
EpollServer server = new EpollServer(host, port) {
@Override
protected IOThread createIOThread(int number, int divider) {
return new IOThread(number, divider) {
@Override
public void onConnect(Connection connection) {
connection.write(data, this);
}
};
}
@Override
protected Connection createConnection(int fd, int ip, int port) {
return new Connection(fd, ip, port);
}
};
server.setIoThreadsCount(1);
server.start();
byte[] receive = new byte[10 * 1024 * 1024];
int offset = 0;
int r;
Socket socket = new Socket(host, port);
InputStream in = socket.getInputStream();
Thread.sleep(1000);
while ((r = in.read(receive, offset, receive.length - offset)) != -1) {
offset += r;
// System.out.println("read: "+r+"\tremaining: "+(receive.length - offset));
if (receive.length - offset == 0)
break;
}
Assert.assertEquals(md5, MD5.create().update(receive).asString());
Assert.assertEquals(0, in.available());
socket.close();
server.close();
}
@Test
public void testConnects() {
int port = 9090;
EpollServer server = new EpollServer(port) {
byte[] data = "HTTP/1.1 200 OK\r\nConnection: Close\r\nContent-Length: 2\r\nContent-Type: text/html;charset=UTF-8\r\n\r\nok".getBytes();
@Override
protected IOThread createIOThread(int number, int divider) {
return new IOThread(number, divider) {
byte[] b = new byte[1024];
@Override
public void onRead(Connection connection) {
try {
int r = connection.read(b, 0, b.length, this);
// System.out.println(new String(b, 0, r));
// connection.write(response.copy());
connection.write(data, this);
// System.out.println("write response");
connection.close();
// System.out.println("close");
} catch (IOException e) {
e.printStackTrace();
assert e == null;
}
}
};
}
};
server.setIoThreadsCount(4);
server.start();
int i = 0;
int n = 10000;
Stopwatch stopwatch = new Stopwatch("time");
try {
while (true) {
Assert.assertEquals("ok", HttpClient.createRequest("http://localhost:9090")
.header("Connection", "Close")
.get().asString());
i++;
if (i == n)
break;
}
} catch (Exception e) {
System.out.println(i);
e.printStackTrace();
}
server.close();
assert i == n;
System.out.println(stopwatch);
}
@Test
public void testAsyncWriteEvent() {
int port = 9090;
final AtomicReference<Connection> connectionRef = new AtomicReference<Connection>();
final AtomicInteger onWrite = new AtomicInteger();
EpollServer server = new EpollServer(port) {
@Override
protected IOThread createIOThread(int number, int divider) {
return new IOThread(number, divider) {
@Override
public void onConnect(Connection connection) {
connectionRef.set(connection);
}
@Override
public void onWrite(Connection connection) {
onWrite.incrementAndGet();
super.onWrite(connection);
}
};
}
};
server.setIoThreadsCount(1);
server.start();
try {
int pause = 20;
Socket s = new Socket("localhost", port);
Thread.sleep(pause);
Assert.assertNotNull(connectionRef.get());
// connectionRef.get().enableOnWriteEvent();
// Thread.sleep(pause);
Assert.assertEquals(1, onWrite.get());
connectionRef.get().disableOnWriteEvent();
Thread.sleep(pause);
connectionRef.get().enableOnWriteEvent();
Thread.sleep(pause);
Assert.assertEquals(2, onWrite.get());
} catch (IOException e) {
e.printStackTrace();
assert e == null;
} catch (InterruptedException e) {
e.printStackTrace();
assert e == null;
}
server.close();
}
@Test
public void testTimeout() {
int port = 9090;
final AtomicInteger onClose = new AtomicInteger();
EpollServer server = new EpollServer(port) {
@Override
protected IOThread createIOThread(int number, int divider) {
return new IOThread(number, divider) {
@Override
public void onDisconnect(Connection connection) {
onClose.incrementAndGet();
}
};
}
};
server.setTTL(500);
server.setIoThreadsCount(1);
server.start();
try {
int pause = 1100;
Socket s = new Socket("localhost", port);
Thread.sleep(pause);
Assert.assertEquals(1, onClose.get());
} catch (IOException e) {
e.printStackTrace();
assert e == null;
} catch (InterruptedException e) {
e.printStackTrace();
assert e == null;
}
server.close();
}
@Test
public void testCloseReadable() {
int port = 9090;
final AtomicInteger onClose = new AtomicInteger();
final AtomicInteger onCloseResource = new AtomicInteger();
EpollServer server = new EpollServer(port) {
@Override
protected IOThread createIOThread(int number, int divider) {
return new IOThread(number, divider) {
@Override
public void onDisconnect(Connection connection) {
onClose.incrementAndGet();
}
@Override
public void onConnect(Connection connection) {
connection.write(new ReadableData() {
long total = 1024 * 1024 * 1024;
int complete;
@Override
public int read(ByteBuffer byteBuffer) {
int l = byteBuffer.limit();
complete += l;
return l;
}
@Override
public void unread(int i) {
complete -= i;
}
@Override
public boolean isComplete() {
return remains() == 0;
}
@Override
public long complete() {
return complete;
}
@Override
public long length() {
return total;
}
@Override
public long remains() {
return total - complete;
}
@Override
public void close() throws IOException {
onCloseResource.incrementAndGet();
}
}, this);
}
};
}
};
server.setTTL(500);
server.setIoThreadsCount(1);
server.start();
try {
int pause = 1100;
Socket s = new Socket("localhost", port);
Thread.sleep(pause);
Assert.assertEquals(1, onClose.get());
Assert.assertEquals(1, onCloseResource.get());
} catch (IOException e) {
e.printStackTrace();
assert e == null;
} catch (InterruptedException e) {
e.printStackTrace();
assert e == null;
}
server.close();
}
} |
package com.jetbrains.python.sdk;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.util.containers.HashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.io.File;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* @author traff
*/
public class PythonEnvUtil {
public static final String PYTHONPATH = "PYTHONPATH";
private PythonEnvUtil() {
}
public static Map<String, String> setPythonUnbuffered(@NotNull Map<String, String> envs) {
envs.put("PYTHONUNBUFFERED", "1");
return envs;
}
public static Map<String, String> setPythonIOEncoding(@NotNull Map<String, String> envs, @NotNull String encoding) {
envs.put("PYTHONIOENCODING", encoding);
return envs;
}
/**
* @param source
* @return a copy of source map, or a new map if source is null.
*/
public static Map<String, String> cloneEnv(@Nullable Map<String, String> source) {
Map<String, String> new_env;
if (source != null) {
new_env = new HashMap<String, String>(source);
}
else {
new_env = new HashMap<String, String>();
}
return new_env;
}
/**
* Appends a value to the end os a path-like environment variable, using system-dependent path separator.
*
* @param source path-like string to append to
* @param value what to append
* @return modified path-like string
*/
@NotNull
public static String appendToPathEnvVar(@Nullable String source, @NotNull String value) {
if (StringUtil.isEmpty(source)) {
assert source != null;
Set<String> vals = Sets.newHashSet(source.split(File.pathSeparator));
if (!vals.contains(value)) {
return value + File.pathSeparatorChar + source;
}
else {
return source;
}
}
return value;
}
public static void addToEnv(Map<String, String> envs, String key, Collection<String> values) {
for (String val : values) {
addToEnv(envs, key, val);
}
}
public static void addToEnv(Map<String, String> envs, String key, String value) {
if (envs.containsKey(key)) {
envs.put(key, appendToPathEnvVar(envs.get(key), value));
}
else {
envs.put(key, value);
}
}
public static void addToPythonPath(Map<String, String> envs, Collection<String> values) {
addToEnv(envs, PYTHONPATH, values);
}
public static void addToPythonPath(Map<String, String> envs, String value) {
addToEnv(envs, PYTHONPATH, value);
}
@Nullable
public static List<String> getPythonPathList(Map<String, String> envs) {
String pythonPath = envs.get(PYTHONPATH);
if (pythonPath != null) {
String[] paths = pythonPath.split(Character.toString(File.pathSeparatorChar));
return Lists.newArrayList(paths);
}
else {
return null;
}
}
} |
package guitests.guihandles;
import java.util.List;
import java.util.stream.Collectors;
import guitests.GuiRobot;
import javafx.scene.Node;
import javafx.scene.control.Labeled;
import javafx.scene.layout.Region;
import javafx.stage.Stage;
import seedu.taskboss.model.category.UniqueTagList;
import seedu.taskboss.model.task.ReadOnlyTask;
/**
* Provides a handle to a task card in the task list panel.
*/
public class TaskCardHandle extends GuiHandle {
private static final String NAME_FIELD_ID = "#name";
private static final String ADDRESS_FIELD_ID = "#address";
private static final String PHONE_FIELD_ID = "#phone";
private static final String TAGS_FIELD_ID = "#tags";
private Node node;
public TaskCardHandle(GuiRobot guiRobot, Stage primaryStage, Node node) {
super(guiRobot, primaryStage, null);
this.node = node;
}
protected String getTextFromLabel(String fieldId) {
return getTextFromLabel(fieldId, node);
}
public String getFullName() {
return getTextFromLabel(NAME_FIELD_ID);
}
public String getAddress() {
return getTextFromLabel(ADDRESS_FIELD_ID);
}
public String getPhone() {
return getTextFromLabel(PHONE_FIELD_ID);
}
public List<String> getTags() {
return getTags(getTagsContainer());
}
private List<String> getTags(Region tagsContainer) {
return tagsContainer
.getChildrenUnmodifiable()
.stream()
.map(node -> ((Labeled) node).getText())
.collect(Collectors.toList());
}
private List<String> getTags(UniqueTagList tags) {
return tags
.asObservableList()
.stream()
.map(tag -> tag.tagName)
.collect(Collectors.toList());
}
private Region getTagsContainer() {
return guiRobot.from(node).lookup(TAGS_FIELD_ID).query();
}
public boolean isSameTask(ReadOnlyTask task) {
return getFullName().equals(task.getName().fullName)
&& getPhone().equals(task.getPhone().value)
&& getAddress().equals(task.getAddress().value)
&& getTags().equals(getTags(task.getTags()));
}
@Override
public boolean equals(Object obj) {
if (obj instanceof TaskCardHandle) {
TaskCardHandle handle = (TaskCardHandle) obj;
return getFullName().equals(handle.getFullName())
&& getPhone().equals(handle.getPhone())
&& getAddress().equals(handle.getAddress())
&& getTags().equals(handle.getTags());
}
return super.equals(obj);
}
@Override
public String toString() {
return getFullName() + " " + getAddress();
}
} |
package com.jetbrains.python.sdk;
import com.intellij.execution.ExecutionException;
import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.process.OSProcessHandler;
import com.intellij.execution.process.ProcessOutput;
import com.intellij.facet.Facet;
import com.intellij.facet.FacetConfiguration;
import com.intellij.facet.FacetManager;
import com.intellij.ide.DataManager;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.application.PathManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.projectRoots.*;
import com.intellij.openapi.roots.ModuleRootManager;
import com.intellij.openapi.roots.OrderRootType;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.SystemInfo;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.JarFileSystem;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ArrayUtil;
import com.jetbrains.python.PythonFileType;
import com.jetbrains.python.PythonHelpersLocator;
import com.jetbrains.python.facet.PythonFacetSettings;
import com.jetbrains.python.psi.LanguageLevel;
import com.jetbrains.python.psi.impl.PyBuiltinCache;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Collections;
import java.util.List;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author yole
*/
public class PythonSdkType extends SdkType {
private static final Logger LOG = Logger.getInstance("#" + PythonSdkType.class.getName());
public static PythonSdkType getInstance() {
return SdkType.findInstance(PythonSdkType.class);
}
public PythonSdkType() {
super("Python SDK");
}
public Icon getIcon() {
return PythonFileType.INSTANCE.getIcon();
}
public Icon getIconForAddAction() {
return PythonFileType.INSTANCE.getIcon();
}
/**
* Name of directory where skeleton files (despite the value) are stored.
*/
public static final String SKELETON_DIR_NAME = "python_stubs";
/**
* @return name of builtins skeleton file; for Python 2.x it is '{@code __builtins__.py}'.
*/
@NotNull
@NonNls
public String getBuiltinsFileName(Sdk sdk) {
final String version = sdk.getVersionString();
if (version != null && version.startsWith("Python 3")) {
return PyBuiltinCache.BUILTIN_FILE_3K;
}
return PyBuiltinCache.BUILTIN_FILE;
}
@NonNls
@Nullable
public String suggestHomePath() {
@NonNls final String PYTHON_STR = "python";
TreeSet<String> candidates = new TreeSet<String>();
if (SystemInfo.isWindows) {
VirtualFile rootDir = LocalFileSystem.getInstance().findFileByPath("C:\\");
if (rootDir != null) {
VirtualFile[] topLevelDirs = rootDir.getChildren();
for (VirtualFile dir : topLevelDirs) {
if (dir.isDirectory() && dir.getName().toLowerCase().startsWith(PYTHON_STR)) {
candidates.add(dir.getPath());
}
}
}
}
else if (SystemInfo.isLinux) {
VirtualFile rootDir = LocalFileSystem.getInstance().findFileByPath("/usr/lib");
if (rootDir != null) {
VirtualFile[] suspect_dirs = rootDir.getChildren();
for (VirtualFile dir : suspect_dirs) {
if (dir.isDirectory() && dir.getName().startsWith(PYTHON_STR)) {
candidates.add(dir.getPath());
}
}
}
}
else if (SystemInfo.isMac) {
final String pythonPath = "/Library/Frameworks/Python.framework/Versions/Current/";
if (new File(pythonPath).exists()) {
return pythonPath;
}
return "/System/Library/Frameworks/Python.framework/Versions/Current/";
}
if (candidates.size() > 0) {
// return latest version
String[] candidateArray = ArrayUtil.toStringArray(candidates);
return candidateArray[candidateArray.length - 1];
}
return null;
}
public boolean isValidSdkHome(final String path) {
return isPythonSdkHome(path) || isJythonSdkHome(path);
}
/**
* Checks if the path is a valid home.
* Valid CPython home must contain some standard libraries. Of them we look for re.py, __future__.py and site-packages/.
*
* @param path path to check.
* @return true if paths points to a valid home.
*/
@NonNls
private static boolean isPythonSdkHome(final String path) {
final File f = getPythonBinaryPath(path);
if (f == null || !f.exists()) {
return false;
}
// Extra check for linuxes
if (SystemInfo.isLinux) {
// on Linux, Python SDK home points to the /lib directory of a particular Python version
File f_re = new File(path, "re.py");
File f_future = new File(path, "__future__.py");
File f_site = new File(path, "site-packages");
File f_dist = new File(path, "dist-packages");
return (f_re.exists() && f_future.exists() && (f_site.exists() && f_site.isDirectory()) || (f_dist.exists() && f_dist.isDirectory()));
}
return true;
}
private static boolean isJythonSdkHome(final String path) {
File f = getJythonBinaryPath(path);
return f != null && f.exists();
}
@Nullable
private static File getJythonBinaryPath(final String path) {
if (SystemInfo.isWindows) {
return new File(path, "jython.bat");
}
else if (SystemInfo.isMac) {
return new File(new File(path, "bin"), "jython"); // TODO: maybe use a smarter way
}
else if (SystemInfo.isLinux) {
File jy_binary = new File(path, "jython"); // probably /usr/bin/jython
if (jy_binary.exists()) {
return jy_binary;
}
}
return null;
}
@Nullable
@NonNls
private static File getPythonBinaryPath(final String path) {
if (SystemInfo.isWindows) {
return new File(path, "python.exe");
}
else if (SystemInfo.isMac) {
return new File(new File(path, "bin"), "python");
}
else if (SystemInfo.isLinux) {
// most probably path is like "/usr/lib/pythonX.Y"; executable is most likely /usr/bin/pythonX.Y
Matcher m = Pattern.compile(".*/(python\\d\\.\\d)").matcher(path);
File py_binary;
if (m.matches()) {
String py_name = m.group(1);
py_binary = new File("/usr/bin/" + py_name); // XXX broken logic! can't match the lib to the bin
}
else {
py_binary = new File("/usr/bin/python"); // TODO: search in $PATH
}
if (py_binary.exists()) {
return py_binary;
}
}
return null;
}
public String suggestSdkName(final String currentSdkName, final String sdkHome) {
String name = getVersionString(sdkHome);
if (name == null) name = "Unknown at " + sdkHome; // last resort
return name;
}
public AdditionalDataConfigurable createAdditionalDataConfigurable(final SdkModel sdkModel, final SdkModificator sdkModificator) {
return null;
}
public void saveAdditionalData(final SdkAdditionalData additionalData, final Element additional) {
}
@Override
public SdkAdditionalData loadAdditionalData(final Sdk currentSdk, final Element additional) {
String url = findSkeletonsUrl(currentSdk);
if (url != null) {
final String path = VfsUtil.urlToPath(url);
File stubs_dir = new File(path);
if (!stubs_dir.exists()) {
generateBuiltinStubs(currentSdk.getHomePath(), path);
generateBinaryStubs(currentSdk.getHomePath(), path, null); // TODO: add a nice progress indicator somehow
}
}
return null;
}
@Nullable
public static String findSkeletonsUrl(Sdk sdk) {
final String[] urls = sdk.getRootProvider().getUrls(BUILTIN_ROOT_TYPE);
for (String url : urls) {
if (url.contains(SKELETON_DIR_NAME)) {
return url;
}
}
return null;
}
@NonNls
public String getPresentableName() {
return "Python SDK";
}
public void setupSdkPaths(final Sdk sdk) {
final Ref<SdkModificator> sdkModificatorRef = new Ref<SdkModificator>();
final ProgressManager progman = ProgressManager.getInstance();
final Project project = PlatformDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext());
final Task.Modal setup_task = new Task.Modal(project, "Setting up library files", false) {
public void run(@NotNull final ProgressIndicator indicator) {
sdkModificatorRef.set(setupSdkPathsUnderProgress(sdk, indicator));
}
};
progman.run(setup_task);
if (sdkModificatorRef.get() != null) sdkModificatorRef.get().commitChanges(); // commit in dispatch thread, not task's
}
protected SdkModificator setupSdkPathsUnderProgress(final Sdk sdk, @Nullable ProgressIndicator indicator) {
final SdkModificator sdkModificator = sdk.getSdkModificator();
setupSdkPaths(sdkModificator, indicator);
return sdkModificator;
//sdkModificator.commitChanges() must happen outside, and probably in a different thread.
}
/**
* In which root type built-in skeletons are put.
*/
public static final OrderRootType BUILTIN_ROOT_TYPE = OrderRootType.CLASSES;
public static void setupSdkPaths(SdkModificator sdkModificator, ProgressIndicator indicator) {
String sdk_path = sdkModificator.getHomePath();
String bin_path = getInterpreterPath(sdk_path);
@NonNls final String stubs_path =
PathManager.getSystemPath() + File.separator + SKELETON_DIR_NAME + File.separator + sdk_path.hashCode() + File.separator;
// we have a number of lib dirs, those listed in python's sys.path
if (indicator != null) {
indicator.setText("Adding library roots");
}
final List<String> paths = getSysPath(sdk_path, bin_path);
if ((paths != null) && paths.size() > 0) {
// add every path as root.
for (String path : paths) {
if (path.indexOf(File.separator) < 0) continue; // TODO: interpret possible 'special' paths reasonably
if (indicator != null) {
indicator.setText2(path);
}
VirtualFile child = LocalFileSystem.getInstance().findFileByPath(path);
if (child != null) {
@NonNls String suffix = child.getExtension();
if (suffix != null) suffix = suffix.toLowerCase(); // Why on earth empty suffix is null and not ""?
if ((!child.isDirectory()) && ("zip".equals(suffix) || "egg".equals(suffix))) {
// a .zip / .egg file must have its root extracted first
child = JarFileSystem.getInstance().getJarRootForLocalFile(child);
}
if (child != null) {
sdkModificator.addRoot(child, OrderRootType.SOURCES);
sdkModificator.addRoot(child, OrderRootType.CLASSES);
}
}
else LOG.info("Bogus sys.path entry " + path);
}
if (indicator != null) {
indicator.setText("Generating skeletons of __builtins__");
indicator.setText2("");
}
generateBuiltinStubs(sdk_path, stubs_path);
sdkModificator.addRoot(LocalFileSystem.getInstance().refreshAndFindFileByPath(stubs_path), BUILTIN_ROOT_TYPE);
}
if (!new File(stubs_path).exists()) {
generateBinaryStubs(sdk_path, stubs_path, indicator);
}
}
private static List<String> getSysPath(String sdk_path, String bin_path) {
@NonNls String script = // a script printing sys.path
"import sys\n" + "import os.path\n" + "for x in sys.path:\n" + " if x != os.path.dirname(sys.argv [0]): sys.stdout.write(x+chr(10))";
try {
final File scriptFile = File.createTempFile("script", ".py");
try {
PrintStream out = new PrintStream(scriptFile);
try {
out.print(script);
}
finally {
out.close();
}
return SdkUtil.getProcessOutput(sdk_path, new String[]{bin_path, scriptFile.getPath()}).getStdoutLines();
}
finally {
FileUtil.delete(scriptFile);
}
}
catch (IOException e) {
LOG.info(e);
return Collections.emptyList();
}
}
@Nullable
public String getVersionString(final String sdkHome) {
final String binaryPath = getInterpreterPath(sdkHome);
if (binaryPath == null) {
return null;
}
final boolean isJython = isJythonSdkHome(sdkHome);
@NonNls String version_regexp, version_opt;
if (isJython) {
version_regexp = "(Jython \\S+) on .*";
version_opt = "--version";
}
else { // CPython
version_regexp = "(Python \\S+).*";
version_opt = "-V";
}
Pattern pattern = Pattern.compile(version_regexp);
String version = SdkUtil.getFirstMatch(SdkUtil.getProcessOutput(sdkHome, new String[]{binaryPath, version_opt}).getStderrLines(), pattern);
return version;
}
@Nullable
public static String getInterpreterPath(final String sdkHome) {
final File file = isJythonSdkHome(sdkHome) ? getJythonBinaryPath(sdkHome) : getPythonBinaryPath(sdkHome);
return file != null ? file.getPath() : null;
}
private final static String GENERATOR3 = "generator3.py";
private final static String FIND_BINARIES = "find_binaries.py";
public static void generateBuiltinStubs(String sdkPath, final String stubsRoot) {
new File(stubsRoot).mkdirs();
GeneralCommandLine commandLine = new GeneralCommandLine();
commandLine.setExePath(getInterpreterPath(sdkPath)); // python
commandLine.addParameter(PythonHelpersLocator.getHelperPath(GENERATOR3));
commandLine.addParameter("-d");
commandLine.addParameter(stubsRoot); // -d stubs_root
commandLine.addParameter("-b"); // for builtins
commandLine.addParameter("-u"); // for update-only mode
try {
final OSProcessHandler handler = new OSProcessHandler(commandLine.createProcess(), commandLine.getCommandLineString());
handler.startNotify();
handler.waitFor();
handler.destroyProcess();
}
catch (ExecutionException e) {
LOG.error(e);
}
}
/**
* (Re-)generates skeletons for all binary python modules. Up-to-date stubs not regenerated.
* Does one module at a time: slower, but avoids certain conflicts.
*
* @param sdkPath where to find interpreter.
* @param stubsRoot where to put results (expected to exist).
* @param indicator ProgressIndicator to update, or null.
*/
public static void generateBinaryStubs(final String sdkPath, final String stubsRoot, ProgressIndicator indicator) {
if (indicator != null) {
indicator.setText("Generating skeletons of binary libs");
}
final int RUN_TIMEOUT = 10 * 1000; // 10 seconds per call is plenty enough; anything more is clearly wrong.
final String bin_path = getInterpreterPath(sdkPath);
final ProcessOutput run_result =
SdkUtil.getProcessOutput(sdkPath, new String[]{bin_path, PythonHelpersLocator.getHelperPath(FIND_BINARIES)});
if (run_result.getExitCode() == 0) {
for (String line : run_result.getStdoutLines()) {
// line = "mod_name path"
int cutpos = line.indexOf(' ');
String modname = line.substring(0, cutpos);
String mod_fname = modname.replace(".", File.separator); // "a.b.c" -> "a/b/c", no ext
String fname = line.substring(cutpos + 1);
//String ext = fname.substring(fname.lastIndexOf('.')); // no way ext is absent
// check if it's fresh
File f_orig = new File(fname);
File f_skel = new File(stubsRoot + File.separator + mod_fname + ".py");
if (f_orig.lastModified() >= f_skel.lastModified()) {
// stale skeleton, rebuild
if (indicator != null) {
indicator.setText2(modname);
}
LOG.info("Skeleton for " + modname);
final ProcessOutput gen_result = SdkUtil
.getProcessOutput(sdkPath, new String[]{bin_path, PythonHelpersLocator.getHelperPath(GENERATOR3), "-d", stubsRoot, modname},
RUN_TIMEOUT);
if (gen_result.getExitCode() != 0) {
StringBuffer sb = new StringBuffer("Skeleton for ");
sb.append(modname).append(" failed. stderr:
for (String err_line : gen_result.getStderrLines()) sb.append(err_line).append("\n");
sb.append("
LOG.warn(sb.toString());
}
}
}
}
else {
StringBuffer sb = new StringBuffer();
for (String err_line : run_result.getStderrLines()) sb.append(err_line).append("\n");
LOG.error("failed to run " + FIND_BINARIES + ", exit code " + run_result.getExitCode() + ", stderr '" + sb.toString() + "'");
}
}
public static List<Sdk> getAllSdks() {
return ProjectJdkTable.getInstance().getSdksOfType(getInstance());
}
@Nullable
public static Sdk findPythonSdk(Module module) {
if (module == null) return null;
final Sdk sdk = ModuleRootManager.getInstance(module).getSdk();
if (sdk != null && sdk.getSdkType() instanceof PythonSdkType) return sdk;
final Facet[] facets = FacetManager.getInstance(module).getAllFacets();
for (Facet facet : facets) {
final FacetConfiguration configuration = facet.getConfiguration();
if (configuration instanceof PythonFacetSettings) {
return ((PythonFacetSettings)configuration).getSdk();
}
}
return null;
}
public static LanguageLevel getLanguageLevelForSdk(@Nullable Sdk sdk) {
if (sdk != null) {
String version = sdk.getVersionString();
if (version != null) {
// HACK rewrite in some nicer way?
if (version.startsWith("Python ") || version.startsWith("Jython ")) {
String pythonVersion = version.substring("Python ".length());
return LanguageLevel.fromPythonVersion(pythonVersion);
}
}
}
return LanguageLevel.getDefault();
}
} |
package net.imagej.ops;
import net.imagej.ops.Ops.ASCII;
import net.imagej.ops.Ops.CreateImg;
import net.imagej.ops.Ops.Equation;
import net.imagej.ops.Ops.Eval;
import net.imagej.ops.Ops.FFT;
import net.imagej.ops.Ops.Gauss;
import net.imagej.ops.Ops.Help;
import net.imagej.ops.Ops.IFFT;
import net.imagej.ops.Ops.Identity;
import net.imagej.ops.Ops.Invert;
import net.imagej.ops.Ops.Join;
import net.imagej.ops.Ops.LogKernel;
import net.imagej.ops.Ops.Lookup;
import net.imagej.ops.Ops.Loop;
import org.junit.Test;
/**
* Tests that the ops of the global namespace have corresponding type-safe Java
* method signatures declared in the {@link OpService} class.
*
* @author Curtis Rueden
*/
public class GlobalNamespaceTest extends AbstractNamespaceTest {
/** Tests for {@link CreateImg} method convergence. */
@Test
public void testCreateImg() {
assertComplete(null, OpService.class, CreateImg.NAME);
}
/** Tests for {@link ASCII} method convergence. */
@Test
public void testASCII() {
assertComplete(null, OpService.class, ASCII.NAME);
}
/** Tests for {@link Equation} method convergence. */
@Test
public void testEquation() {
assertComplete(null, OpService.class, Equation.NAME);
}
/** Tests for {@link Eval} method convergence. */
@Test
public void testEval() {
assertComplete(null, OpService.class, Eval.NAME);
}
/** Tests for {@link FFT} method convergence. */
@Test
public void testFFT() {
assertComplete(null, OpService.class, FFT.NAME);
}
/** Tests for {@link Gauss} method convergence. */
@Test
public void testGauss() {
assertComplete(null, OpService.class, Gauss.NAME);
}
/** Tests for {@link Help} method convergence. */
@Test
public void testHelp() {
assertComplete(null, OpService.class, Help.NAME);
}
/** Tests for {@link Identity} method convergence. */
@Test
public void testIdentity() {
assertComplete(null, OpService.class, Identity.NAME);
}
/** Tests for {@link IFFT} method convergence. */
@Test
public void testIFFT() {
assertComplete(null, OpService.class, IFFT.NAME);
}
/** Tests for {@link Invert} method convergence. */
@Test
public void testInvert() {
assertComplete(null, OpService.class, Invert.NAME);
}
/** Tests for {@link Join} method convergence. */
@Test
public void testJoin() {
assertComplete(null, OpService.class, Join.NAME);
}
/** Tests for {@link LogKernel} method convergence. */
@Test
public void testLogKernel() {
assertComplete(null, OpService.class, LogKernel.NAME);
}
/** Tests for {@link Lookup} method convergence. */
@Test
public void testLookup() {
assertComplete(null, OpService.class, Lookup.NAME);
}
/** Tests for {@link Loop} method convergence. */
@Test
public void testLoop() {
assertComplete(null, OpService.class, Loop.NAME);
}
} |
package modelisation.simulator.mixed;
import java.util.ArrayList;
import java.util.ListIterator;
import modelisation.simulator.common.SimulatorElement;
import org.apache.log4j.Logger;
public class RequestQueue extends SimulatorElement {
protected static Logger logger = Logger.getLogger(RequestQueue.class.getName());
protected ArrayList list;
protected double youngestRequestCreationTime;
public RequestQueue() {
this.list = new ArrayList(2);
}
public void addRequest(Request request) {
if (request.isFromAgent()) {
this.addRequestFromAgent(request);
} else {
this.list.add(request);
}
this.updateYoungestCreationTime(request);
}
protected void addRequestFromAgent(Request request) {
int number = request.getNumber();
ListIterator it = this.list.listIterator();
Request r = null;
boolean shouldAdd = true;
while (it.hasNext()) {
r = (Request)it.next();
if (r.isFromAgent()) {
if (r.getNumber() < number) {
it.remove();
shouldAdd = true;
} else
shouldAdd = false;
}
}
if (shouldAdd)
this.list.add(request);
}
public void updateYoungestCreationTime(Request request) {
// double tmp = r.getCreationTime();
// if (this.youngestRequestCreationTime == 0) {
// this.youngestRequestCreationTime = tmp;
// } else if (tmp < this.youngestRequestCreationTime) {
// this.youngestRequestCreationTime = tmp;
Request r = null;
double tmp = -1;
ListIterator it = this.list.listIterator();
while (it.hasNext()) {
r = (Request)it.next();
if (tmp == -1) {
tmp = r.getCreationTime();
} else if (r.getCreationTime() < tmp) {
tmp = r.getCreationTime();
}
}
if (tmp == -1) {
this.youngestRequestCreationTime = 0;
} else {
this.youngestRequestCreationTime = tmp;
}
}
/**
* returns a request from the agent
*/
public Request removeRequestFromAgent() {
ListIterator it = this.list.listIterator();
Request r = null;
while (it.hasNext()) {
r = (Request)it.next();
if (r.isFromAgent()) {
it.remove();
this.updateYoungestCreationTime(r);
return r;
}
}
return null;
}
/**
* returns a request from the agent
*/
public Request removeRequestFromSource() {
ListIterator it = this.list.listIterator();
Request r = null;
while (it.hasNext()) {
r = (Request)it.next();
if (!r.isFromAgent()) {
it.remove();
this.updateYoungestCreationTime(r);
return r;
}
}
return null;
}
public int length() {
return this.list.size();
}
public boolean isEmpty() {
return (this.list.size() == 0);
}
public boolean hasRequestFromAgent() {
ListIterator it = this.list.listIterator();
Request r = null;
while (it.hasNext()) {
r = (Request)it.next();
if (r.isFromAgent()) {
return true;
}
}
return false;
}
public Request getRequestFromAgent() {
ListIterator it = this.list.listIterator();
Request r = null;
while (it.hasNext()) {
r = (Request)it.next();
if (r.isFromAgent()) {
return r;
}
}
return null;
}
public double getYoungestCreationTime() {
return this.youngestRequestCreationTime;
}
public void update(double time) {
}
public String toString() {
StringBuffer tmp = new StringBuffer();
ListIterator it = this.list.listIterator();
Request r = null;
while (it.hasNext()) {
r = (Request)it.next();
tmp.append(r);
// if (!r.isFromAgent()) {
// it.remove();
// return r;
}
return tmp.toString();
}
public static void main(String[] args) {
if (logger.isDebugEnabled()) {
logger.debug("Creating requestQueue");
}
RequestQueue rq = new RequestQueue();
if (logger.isDebugEnabled()) {
logger.debug("Adding a request from agent");
}
rq.addRequest(new Request(Request.AGENT, 2));
if (logger.isDebugEnabled()) {
logger.debug("Adding a request from source");
}
rq.addRequest(new Request(Request.SOURCE, 5));
if (logger.isDebugEnabled()) {
logger.debug("
logger.debug("Length of the list " + rq.length());
logger.debug(rq);
logger.debug("
logger.debug("Adding a request from agent, should not be added");
}
rq.addRequest(new Request(Request.AGENT, 1));
if (logger.isDebugEnabled()) {
logger.debug("
logger.debug("Length of the list " + rq.length());
logger.debug(rq);
logger.debug("
logger.debug("Adding a request from agent, should be added");
}
rq.addRequest(new Request(Request.AGENT, 7));
if (logger.isDebugEnabled()) {
logger.debug("
logger.debug("Length of the list " + rq.length());
logger.debug(rq);
logger.debug("
logger.debug("Removing request from agent");
logger.debug("Request is " + rq.removeRequestFromAgent());
logger.debug("Removing request fromm source");
logger.debug("Request is " + rq.removeRequestFromSource());
logger.debug("Length of the list " + rq.length());
}
}
} |
package net.imagej.ops;
import net.imagej.ops.Ops.ASCII;
import net.imagej.ops.Ops.CreateImg;
import net.imagej.ops.Ops.Equation;
import net.imagej.ops.Ops.Eval;
import net.imagej.ops.Ops.FFT;
import net.imagej.ops.Ops.Gauss;
import net.imagej.ops.Ops.Help;
import net.imagej.ops.Ops.IFFT;
import net.imagej.ops.Ops.Identity;
import net.imagej.ops.Ops.Invert;
import net.imagej.ops.Ops.Join;
import net.imagej.ops.Ops.LogKernel;
import net.imagej.ops.Ops.Lookup;
import net.imagej.ops.Ops.Loop;
import net.imagej.ops.Ops.Map;
import net.imagej.ops.Ops.Max;
import net.imagej.ops.Ops.Mean;
import net.imagej.ops.Ops.Median;
import net.imagej.ops.Ops.Min;
import net.imagej.ops.Ops.MinMax;
import net.imagej.ops.Ops.Normalize;
import net.imagej.ops.Ops.Project;
import net.imagej.ops.Ops.Scale;
import net.imagej.ops.Ops.Size;
import net.imagej.ops.Ops.Slicewise;
import net.imagej.ops.Ops.StdDeviation;
import org.junit.Test;
/**
* Tests that the ops of the global namespace have corresponding type-safe Java
* method signatures declared in the {@link OpService} class.
*
* @author Curtis Rueden
*/
public class GlobalNamespaceTest extends AbstractNamespaceTest {
/** Tests for {@link CreateImg} method convergence. */
@Test
public void testCreateImg() {
assertComplete(null, OpService.class, CreateImg.NAME);
}
/** Tests for {@link ASCII} method convergence. */
@Test
public void testASCII() {
assertComplete(null, OpService.class, ASCII.NAME);
}
/** Tests for {@link Equation} method convergence. */
@Test
public void testEquation() {
assertComplete(null, OpService.class, Equation.NAME);
}
/** Tests for {@link Eval} method convergence. */
@Test
public void testEval() {
assertComplete(null, OpService.class, Eval.NAME);
}
/** Tests for {@link FFT} method convergence. */
@Test
public void testFFT() {
assertComplete(null, OpService.class, FFT.NAME);
}
/** Tests for {@link Gauss} method convergence. */
@Test
public void testGauss() {
assertComplete(null, OpService.class, Gauss.NAME);
}
/** Tests for {@link Help} method convergence. */
@Test
public void testHelp() {
assertComplete(null, OpService.class, Help.NAME);
}
/** Tests for {@link Identity} method convergence. */
@Test
public void testIdentity() {
assertComplete(null, OpService.class, Identity.NAME);
}
/** Tests for {@link IFFT} method convergence. */
@Test
public void testIFFT() {
assertComplete(null, OpService.class, IFFT.NAME);
}
/** Tests for {@link Invert} method convergence. */
@Test
public void testInvert() {
assertComplete(null, OpService.class, Invert.NAME);
}
/** Tests for {@link Join} method convergence. */
@Test
public void testJoin() {
assertComplete(null, OpService.class, Join.NAME);
}
/** Tests for {@link LogKernel} method convergence. */
@Test
public void testLogKernel() {
assertComplete(null, OpService.class, LogKernel.NAME);
}
/** Tests for {@link Lookup} method convergence. */
@Test
public void testLookup() {
assertComplete(null, OpService.class, Lookup.NAME);
}
/** Tests for {@link Loop} method convergence. */
@Test
public void testLoop() {
assertComplete(null, OpService.class, Loop.NAME);
}
/** Tests for {@link Map} method convergence. */
@Test
public void testMap() {
assertComplete(null, OpService.class, Map.NAME);
}
/** Tests for {@link Max} method convergence. */
@Test
public void testMax() {
assertComplete(null, OpService.class, Max.NAME);
}
/** Tests for {@link Mean} method convergence. */
@Test
public void testMean() {
assertComplete(null, OpService.class, Mean.NAME);
}
/** Tests for {@link Median} method convergence. */
@Test
public void testMedian() {
assertComplete(null, OpService.class, Median.NAME);
}
/** Tests for {@link Min} method convergence. */
@Test
public void testMin() {
assertComplete(null, OpService.class, Min.NAME);
}
/** Tests for {@link MinMax} method convergence. */
@Test
public void testMinMax() {
assertComplete(null, OpService.class, MinMax.NAME);
}
/** Tests for {@link Normalize} method convergence. */
@Test
public void testNormalize() {
assertComplete(null, OpService.class, Normalize.NAME);
}
/** Tests for {@link Project} method convergence. */
@Test
public void testProject() {
assertComplete(null, OpService.class, Project.NAME);
}
/** Tests for {@link Scale} method convergence. */
@Test
public void testScale() {
assertComplete(null, OpService.class, Scale.NAME);
}
/** Tests for {@link Size} method convergence. */
@Test
public void testSize() {
assertComplete(null, OpService.class, Size.NAME);
}
/** Tests for {@link Slicewise} method convergence. */
@Test
public void testSlicewise() {
assertComplete(null, OpService.class, Slicewise.NAME);
}
/** Tests for {@link StdDeviation} method convergence. */
@Test
public void testStdDeviation() {
assertComplete(null, OpService.class, StdDeviation.NAME);
}
} |
package org.gitlab4j.api;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.util.List;
import org.gitlab4j.api.GitLabApi.ApiVersion;
import org.gitlab4j.api.models.Branch;
import org.gitlab4j.api.models.Commit;
import org.gitlab4j.api.models.CompareResults;
import org.gitlab4j.api.models.Project;
import org.gitlab4j.api.models.RepositoryFile;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.FixMethodOrder;
import org.junit.Test;
import org.junit.runners.MethodSorters;
/**
* In order for these tests to run you must set the following properties in test-gitlab4j.properties
*
* TEST_NAMESPACE
* TEST_PROJECT_NAME
* TEST_HOST_URL
* TEST_PRIVATE_TOKEN
*
* If any of the above are NULL, all tests in this class will be skipped.
*
* NOTE: &FixMethodOrder(MethodSorters.NAME_ASCENDING) is very important to insure that testCreate() is executed first.
*/
@FixMethodOrder(MethodSorters.NAME_ASCENDING)
public class TestRepositoryApi {
// The following needs to be set to your test repository
private static final String TEST_PROJECT_NAME;
private static final String TEST_NAMESPACE;
private static final String TEST_HOST_URL;
private static final String TEST_PRIVATE_TOKEN;
static {
TEST_NAMESPACE = TestUtils.getProperty("TEST_NAMESPACE");
TEST_PROJECT_NAME = TestUtils.getProperty("TEST_PROJECT_NAME");
TEST_HOST_URL = TestUtils.getProperty("TEST_HOST_URL");
TEST_PRIVATE_TOKEN = TestUtils.getProperty("TEST_PRIVATE_TOKEN");
}
private static final String TEST_BRANCH_NAME = "feature/test_branch";
private static final String TEST_PROTECT_BRANCH_NAME = "feature/protect_branch";
private static final String TEST_FILEPATH = "test-file.txt";
private static GitLabApi gitLabApi;
public TestRepositoryApi() {
super();
}
@BeforeClass
public static void setup() {
String problems = "";
if (TEST_NAMESPACE == null || TEST_NAMESPACE.trim().isEmpty()) {
problems += "TEST_NAMESPACE cannot be empty\n";
}
if (TEST_PROJECT_NAME == null || TEST_PROJECT_NAME.trim().isEmpty()) {
problems += "TEST_PROJECT_NAME cannot be empty\n";
}
if (TEST_HOST_URL == null || TEST_HOST_URL.trim().isEmpty()) {
problems += "TEST_HOST_URL cannot be empty\n";
}
if (TEST_PRIVATE_TOKEN == null || TEST_PRIVATE_TOKEN.trim().isEmpty()) {
problems += "TEST_PRIVATE_TOKEN cannot be empty\n";
}
if (problems.isEmpty()) {
gitLabApi = new GitLabApi(ApiVersion.V3, TEST_HOST_URL, TEST_PRIVATE_TOKEN);
teardown();
} else {
System.err.print(problems);
}
}
@AfterClass
public static void teardown() {
if (gitLabApi != null) {
try {
Project project = gitLabApi.getProjectApi().getProject(TEST_NAMESPACE, TEST_PROJECT_NAME);
try {
gitLabApi.getRepositoryFileApi().deleteFile(TEST_FILEPATH, project.getId(), TEST_BRANCH_NAME, "Cleanup test files.");
} catch (GitLabApiException ignore) {
}
try {
gitLabApi.getRepositoryApi().deleteBranch(project.getId(), TEST_BRANCH_NAME);
} catch (GitLabApiException ignore) {
}
gitLabApi.getRepositoryApi().deleteBranch(project.getId(), TEST_PROTECT_BRANCH_NAME);
} catch (GitLabApiException ignore) {
}
}
}
@Before
public void beforeMethod() {
assumeTrue(gitLabApi != null);
}
@Test
public void testCreateBranch() throws GitLabApiException {
Project project = gitLabApi.getProjectApi().getProject(TEST_NAMESPACE, TEST_PROJECT_NAME);
assertNotNull(project);
Branch branch = gitLabApi.getRepositoryApi().createBranch(project.getId(), TEST_BRANCH_NAME, "master");
assertNotNull(branch);
Branch fetchedBranch = gitLabApi.getRepositoryApi().getBranch(project.getId(), TEST_BRANCH_NAME);
assertNotNull(fetchedBranch);
assertEquals(branch.getName(), fetchedBranch.getName());
}
@Test
public void testDeleteBranch() throws GitLabApiException {
Project project = gitLabApi.getProjectApi().getProject(TEST_NAMESPACE, TEST_PROJECT_NAME);
assertNotNull(project);
gitLabApi.getRepositoryApi().deleteBranch(project.getId(), TEST_BRANCH_NAME);
}
@Test
public void testRepositoryArchiveViaInputStream() throws GitLabApiException, IOException {
Project project = gitLabApi.getProjectApi().getProject(TEST_NAMESPACE, TEST_PROJECT_NAME);
assertNotNull(project);
InputStream in = gitLabApi.getRepositoryApi().getRepositoryArchive(project.getId(), "master");
Path target = Files.createTempFile(TEST_PROJECT_NAME + "-", ".tar.gz");
Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
assertTrue(target.toFile().length() > 0);
Files.delete(target);
}
@Test
public void testRepositoryArchiveViaFile() throws GitLabApiException, IOException {
Project project = gitLabApi.getProjectApi().getProject(TEST_NAMESPACE, TEST_PROJECT_NAME);
assertNotNull(project);
File file = gitLabApi.getRepositoryApi().getRepositoryArchive(project.getId(), "master", (File)null);
assertTrue(file.length() > 0);
file.delete();
file = gitLabApi.getRepositoryApi().getRepositoryArchive(project.getId(), "master", new File("."));
assertTrue(file.length() > 0);
file.delete();
}
@Test
public void testRawFileViaFile() throws GitLabApiException, IOException {
Project project = gitLabApi.getProjectApi().getProject(TEST_NAMESPACE, TEST_PROJECT_NAME);
assertNotNull(project);
File file = gitLabApi.getRepositoryFileApi().getRawFile(project.getId(), "master", "README", null);
assertTrue(file.length() > 0);
file.delete();
file = gitLabApi.getRepositoryFileApi().getRawFile(project.getId(), "master", "README", new File("."));
assertTrue(file.length() > 0);
file.delete();
}
@Test
public void testRepositoryFileViaInputStream() throws GitLabApiException, IOException {
Project project = gitLabApi.getProjectApi().getProject(TEST_NAMESPACE, TEST_PROJECT_NAME);
assertNotNull(project);
InputStream in = gitLabApi.getRepositoryFileApi().getRawFile(project.getId(), "master", "README");
Path target = Files.createTempFile(TEST_PROJECT_NAME + "-README", "");
Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING);
assertTrue(target.toFile().length() > 0);
Files.delete(target);
}
@Test
public void testCompare() throws GitLabApiException {
Project project = gitLabApi.getProjectApi().getProject(TEST_NAMESPACE, TEST_PROJECT_NAME);
assertNotNull(project);
List<Commit> commits = gitLabApi.getCommitsApi().getCommits(project.getId());
assertNotNull(commits);
assertTrue(commits.size() > 1);
int numCommits = commits.size();
CompareResults compareResults = gitLabApi.getRepositoryApi().compare(project.getId(), commits.get(numCommits - 1).getId(), commits.get(numCommits - 2).getId());
assertNotNull(compareResults);
compareResults = gitLabApi.getRepositoryApi().compare(TEST_NAMESPACE + "/" + TEST_PROJECT_NAME, commits.get(numCommits - 1).getId(), commits.get(numCommits - 2).getId());
assertNotNull(compareResults);
}
@Test
public void testCreateFileAndDeleteFile() throws GitLabApiException {
Project project = gitLabApi.getProjectApi().getProject(TEST_NAMESPACE, TEST_PROJECT_NAME);
assertNotNull(project);
RepositoryFile file = new RepositoryFile();
file.setFilePath(TEST_FILEPATH);
file.setContent("This is a test file.");
RepositoryFile createdFile = gitLabApi.getRepositoryFileApi().createFile(file, project.getId(), TEST_BRANCH_NAME, "Testing createFile().");
assertNotNull(createdFile);
gitLabApi.getRepositoryFileApi().deleteFile(TEST_FILEPATH, project.getId(), TEST_BRANCH_NAME, "Testing deleteFile().");
}
@Test
public void testCreateFileWithEmptyContent() throws GitLabApiException {
Project project = gitLabApi.getProjectApi().getProject(TEST_NAMESPACE, TEST_PROJECT_NAME);
assertNotNull(project);
RepositoryFile file = new RepositoryFile();
file.setFilePath(TEST_FILEPATH);
file.setContent("");
RepositoryFile createdFile = gitLabApi.getRepositoryFileApi().createFile(file, project.getId(), TEST_BRANCH_NAME, "Testing createFile().");
assertNotNull(createdFile);
gitLabApi.getRepositoryFileApi().deleteFile(TEST_FILEPATH, project.getId(), TEST_BRANCH_NAME, "Testing deleteFile().");
}
@Test
public void testProtectBranch() throws GitLabApiException {
Project project = gitLabApi.getProjectApi().getProject(TEST_NAMESPACE, TEST_PROJECT_NAME);
assertNotNull(project);
Branch branch = gitLabApi.getRepositoryApi().createBranch(project.getId(), TEST_PROTECT_BRANCH_NAME, "master");
assertNotNull(branch);
Branch protectedBranch = gitLabApi.getRepositoryApi().protectBranch(project.getId(), TEST_PROTECT_BRANCH_NAME);
assertNotNull(protectedBranch);
assertTrue(protectedBranch.getProtected());
Branch unprotectedBranch = gitLabApi.getRepositoryApi().unprotectBranch(project.getId(), TEST_PROTECT_BRANCH_NAME);
assertNotNull(unprotectedBranch);
assertFalse(unprotectedBranch.getProtected());
}
} |
package org.takes.facets.auth;
import java.io.IOException;
import org.hamcrest.MatcherAssert;
import org.hamcrest.Matchers;
import org.junit.Test;
import org.takes.Request;
import org.takes.Take;
import org.takes.Takes;
import org.takes.facets.auth.codecs.CcPlain;
import org.takes.facets.forward.RsForward;
import org.takes.rq.RqFake;
import org.takes.rq.RqWithHeader;
import org.takes.rs.RsEmpty;
import org.takes.tk.TkEmpty;
/**
* Test case for {@link TsSecure}.
* @author Dmitry Zaytsev (dmitry.zaytsev@gmail.com)
* @version $Id$
* @since 0.11
*/
public final class TsSecureTest {
/**
* TsSecure can fail on anonymous access.
* @throws IOException If some problem inside
*/
@Test(expected = RsForward.class)
public void failsOnAnonymous() throws IOException {
new TsSecure(
new Takes() {
@Override
public Take route(final Request request) throws IOException {
return new TkEmpty();
}
}
).route(new RqFake()).act();
}
/**
* TsSecure can pass on registered user.
* @throws IOException If some problem inside
*/
@Test
public void passesOnRegisteredUser() throws IOException {
MatcherAssert.assertThat(
new TsSecure(
new Takes() {
@Override
public Take route(final Request request)
throws IOException {
return new TkEmpty();
}
}
).route(
new RqWithHeader(
new RqFake(),
TsAuth.class.getSimpleName(),
new String(
new CcPlain().encode(new Identity.Simple("urn:test:2"))
)
)
).act(),
Matchers.instanceOf(RsEmpty.class)
);
}
} |
package com.rho.db;
import com.xruby.runtime.builtin.*;
import com.xruby.runtime.lang.*;
import com.rho.*;
import com.rho.file.*;
import java.util.Enumeration;
import java.util.Vector;
import java.util.Hashtable;
public class DBAdapter extends RubyBasic
{
private static final RhoLogger LOG = RhoLogger.RHO_STRIP_LOG ? new RhoEmptyLogger() :
new RhoLogger("DbAdapter");
//private static DBAdapter m_Instance;
private IDBStorage m_dbStorage;
private boolean m_bIsOpen = false;
private String m_strDBPath, m_strDBVerPath;
private String m_strDbPartition;
private DBAttrManager m_attrMgr = new DBAttrManager();
static Hashtable/*Ptr<String,CDBAdapter*>*/ m_mapDBPartitions = new Hashtable();
Mutex m_mxDB = new Mutex();
int m_nTransactionCounter=0;
boolean m_bUIWaitDB = false;
static String USER_PARTITION_NAME(){return "user";}
static Hashtable/*Ptr<String,CDBAdapter*>&*/ getDBPartitions(){ return m_mapDBPartitions; }
String m_strClientInfoInsert = "";
Object[] m_dataClientInfo = null;
DBAdapter(RubyClass c) {
super(c);
try{
m_dbStorage = RhoClassFactory.createDBStorage();
}catch(Exception exc){
LOG.ERROR("createDBStorage failed.", exc);
}
}
/*
public static DBAdapter getInstance(){
if ( m_Instance == null )
m_Instance = new DBAdapter(RubyRuntime.DatabaseClass);
return m_Instance;
}*/
private void setDbPartition(String strPartition)
{
m_strDbPartition = strPartition;
}
public void close()
{
try{
m_dbStorage.close();
m_dbStorage = null;
}catch(Exception exc)
{
LOG.ERROR("DB close failed.", exc);
}
}
public DBAttrManager getAttrMgr()
{
return m_attrMgr;
}
public void executeBatchSQL(String strStatement)throws DBException{
LOG.TRACE("executeBatchSQL: " + strStatement);
m_dbStorage.executeBatchSQL(strStatement);
}
public IDBResult executeSQL(String strStatement, Object[] values)throws DBException{
LOG.TRACE("executeSQL: " + strStatement);
IDBResult res = null;
Lock();
try{
res = m_dbStorage.executeSQL(strStatement,values,false);
}finally
{
Unlock();
}
return res;
}
public IDBResult executeSQL(String strStatement)throws DBException{
return executeSQL(strStatement,null);
}
public IDBResult executeSQL(String strStatement, Object arg1)throws DBException{
Object[] values = {arg1};
return executeSQL(strStatement,values);
}
public IDBResult executeSQL(String strStatement, int arg1)throws DBException{
Object[] values = { new Integer(arg1)};
return executeSQL(strStatement,values);
}
public IDBResult executeSQL(String strStatement, int arg1, int arg2)throws DBException{
Object[] values = { new Integer(arg1), new Integer(arg2)};
return executeSQL(strStatement,values);
}
public IDBResult executeSQL(String strStatement, long arg1)throws DBException{
Object[] values = { new Long(arg1)};
return executeSQL(strStatement,values);
}
public IDBResult executeSQL(String strStatement, Object arg1, Object arg2)throws DBException{
Object[] values = {arg1,arg2};
return executeSQL(strStatement,values);
}
public IDBResult executeSQL(String strStatement, Object arg1, Object arg2, Object arg3)throws DBException{
Object[] values = {arg1,arg2,arg3};
return executeSQL(strStatement,values);
}
public IDBResult executeSQL(String strStatement, Object arg1, Object arg2, Object arg3, Object arg4)throws DBException{
Object[] values = {arg1,arg2,arg3,arg4};
return executeSQL(strStatement,values);
}
public IDBResult executeSQL(String strStatement, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5)throws DBException{
Object[] values = {arg1,arg2,arg3,arg4,arg5};
return executeSQL(strStatement,values);
}
public IDBResult executeSQL(String strStatement, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6)throws DBException{
Object[] values = {arg1,arg2,arg3,arg4,arg5,arg6};
return executeSQL(strStatement,values);
}
public IDBResult executeSQLReportNonUnique(String strStatement, Object arg1, Object arg2, Object arg3, Object arg4)throws DBException{
//LOG.TRACE("executeSQLReportNonUnique: " + strStatement);
Object[] values = {arg1,arg2,arg3,arg4};
IDBResult res = null;
Lock();
try{
res = m_dbStorage.executeSQL(strStatement,values, true);
}finally
{
Unlock();
}
return res;
}
public IDBResult executeSQLReportNonUnique(String strStatement, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7)throws DBException{
//LOG.TRACE("executeSQLReportNonUnique: " + strStatement);
Object[] values = {arg1,arg2,arg3,arg4, arg5, arg6, arg7};
IDBResult res = null;
Lock();
try{
res = m_dbStorage.executeSQL(strStatement,values, true);
}finally
{
Unlock();
}
return res;
}
public IDBResult executeSQLReportNonUniqueEx(String strStatement, Vector vecValues)throws DBException{
//LOG.TRACE("executeSQLReportNonUnique: " + strStatement);
Object[] values = new Object[vecValues.size()];
for (int i = 0; i < vecValues.size(); i++ )
values[i] = vecValues.elementAt(i);
IDBResult res = null;
Lock();
try{
res = m_dbStorage.executeSQL(strStatement,values, true);
}finally
{
Unlock();
}
return res;
}
public IDBResult executeSQLEx(String strStatement, Vector vecValues)throws DBException{
Object[] values = new Object[vecValues.size()];
for (int i = 0; i < vecValues.size(); i++ )
values[i] = vecValues.elementAt(i);
return executeSQL(strStatement,values);
}
public IDBResult executeSQL(String strStatement, Object arg1, Object arg2, Object arg3, Object arg4, Object arg5, Object arg6, Object arg7)throws DBException{
Object[] values = {arg1,arg2,arg3,arg4,arg5,arg6,arg7};
return executeSQL(strStatement,values);
}
public boolean isUIWaitDB(){ return m_bUIWaitDB; }
public void Lock()
{
if ( RhoRuby.isMainRubyThread() )
m_bUIWaitDB = true;
m_mxDB.Lock();
if ( RhoRuby.isMainRubyThread() )
m_bUIWaitDB = false;
}
public void Unlock(){ m_mxDB.Unlock(); }
public boolean isInsideTransaction(){ return m_nTransactionCounter>0; }
//public static IDBResult createResult(){
// return getInstance().m_dbStorage.createResult();
public static String makeBlobFolderName()throws Exception{
String fName = RhoClassFactory.createFile().getDirPath("db/db-files");
return fName;
}
RubyString[] getOrigColNames(IDBResult rows)
{
RubyString[] colNames = new RubyString[rows.getColCount()];
for ( int nCol = 0; nCol < rows.getColCount(); nCol ++ )
colNames[nCol] = ObjectFactory.createString(rows.getOrigColName(nCol));
return colNames;
}
private String getNameNoExt(String strPath){
int nDot = strPath.lastIndexOf('.');
String strDbName = "";
if ( nDot > 0 )
strDbName = strPath.substring(0, nDot);
else
strDbName = strPath;
return strDbName;
}
public String getDBPath(){ return getNameNoExt(m_strDBPath); }
private void initFilePaths(String strDBName)throws Exception
{
if ( strDBName.charAt(0) == '/' || strDBName.charAt(0) == '\\' )
strDBName = strDBName.substring(1);
int nSlash = strDBName.lastIndexOf('/');
if ( nSlash < 0 )
nSlash = strDBName.lastIndexOf('\\');
String strDBDir = "";
if ( nSlash > 0 )
strDBDir = strDBName.substring(0, nSlash);
String strPath = RhoClassFactory.createFile().getDirPath(strDBDir);
m_strDBPath = strPath + strDBName.substring(nSlash+1);
m_strDBVerPath = strPath + getNameNoExt(strDBName.substring(nSlash+1)) + ".version";
}
private String getSqlScript()
{
return RhoFile.readStringFromJarFile("apps/db/syncdb.schema", this);
}
public void startTransaction()throws DBException
{
Lock();
m_nTransactionCounter++;
if (m_nTransactionCounter == 1)
m_dbStorage.startTransaction();
}
public void commit()throws DBException
{
m_nTransactionCounter
if (m_nTransactionCounter == 0)
{
m_dbStorage.onBeforeCommit();
//getAttrMgr().save(this);
m_dbStorage.commit();
}
Unlock();
}
public void rollback()throws DBException
{
m_nTransactionCounter
if (m_nTransactionCounter == 0)
m_dbStorage.rollback();
Unlock();
}
public void endTransaction()throws DBException
{
commit();
}
class DBVersion
{
String m_strRhoVer = "";
String m_strAppVer = "";
DBVersion(){}
DBVersion( String strRhoVer, String strAppVer )
{
m_strRhoVer = strRhoVer;
m_strAppVer = strAppVer;
}
};
/*private void testError()throws Exception
{
throw new net.rim.device.api.io.file.FileIOException(net.rim.device.api.io.file.FileIOException.FILESYSTEM_FULL);
}*/
DBVersion readDBVersion()throws Exception
{
String strFullVer = "";
IRAFile file = null;
try {
file = RhoClassFactory.createRAFile();
try{
file.open(m_strDBVerPath);
}catch(j2me.io.FileNotFoundException exc)
{
//file not exist
return new DBVersion();
}
byte buf[] = new byte[20];
// testError();
int len = file.read(buf, 0, buf.length);
if ( len > 0 )
strFullVer = new String(buf,0,len);
if ( strFullVer.length() == 0 )
return new DBVersion();
int nSep = strFullVer.indexOf(';');
if ( nSep == -1 )
return new DBVersion(strFullVer, "");
return new DBVersion(strFullVer.substring(0,nSep), strFullVer.substring(nSep+1) );
}
catch (Exception e) {
LOG.ERROR("readDBVersion failed.", e);
throw e;
}finally
{
if (file!=null)
try{ file.close(); }catch(Exception exc){}
}
}
void writeDBVersion(DBVersion ver)throws Exception
{
IRAFile file = null;
try{
file = RhoClassFactory.createRAFile();
file.open(m_strDBVerPath, "rw");
String strFullVer = ver.m_strRhoVer + ";" + ver.m_strAppVer;
byte[] buf = strFullVer.getBytes();
file.write(buf, 0, buf.length);
}catch (Exception e) {
LOG.ERROR("writeDBVersion failed.", e);
throw e;
}finally
{
if (file!=null)
try{ file.close(); }catch(Exception exc){}
}
}
boolean migrateDB(DBVersion dbVer, String strRhoDBVer, String strAppDBVer )
{
LOG.INFO( "Try migrate database from " + (dbVer != null ? dbVer.m_strRhoVer:"") + " to " + (strRhoDBVer !=null ? strRhoDBVer:"") );
if ( dbVer != null && strRhoDBVer != null &&
(dbVer.m_strRhoVer.startsWith("1.4")||dbVer.m_strRhoVer.startsWith("1.4")) && (strRhoDBVer.startsWith("1.5")||strRhoDBVer.startsWith("1.4")) )
{
LOG.INFO( "No migration required from " + (dbVer != null ? dbVer.m_strRhoVer:"") + " to " + (strRhoDBVer !=null ? strRhoDBVer:"") );
try{
writeDBVersion( new DBVersion(strRhoDBVer, strAppDBVer) );
}catch(Exception e)
{
LOG.ERROR("migrateDB failed.", e);
}
return true;
}
//1.2.x -> 1.5.x,1.4.x
if ( dbVer != null && strRhoDBVer != null &&
(dbVer.m_strRhoVer.startsWith("1.2")||dbVer.m_strRhoVer.startsWith("1.4")) && (strRhoDBVer.startsWith("1.5")||strRhoDBVer.startsWith("1.4")) )
{
//sources
//priority INTEGER, ADD
//backend_refresh_time int default 0, ADD
LOG.INFO("Migrate database from " + dbVer.m_strRhoVer + " to " + strRhoDBVer);
IDBStorage db = null;
try{
db = RhoClassFactory.createDBStorage();
db.open( m_strDBPath, getSqlScript() );
db.executeSQL( "ALTER TABLE sources ADD priority INTEGER", null, false);
db.executeSQL( "ALTER TABLE sources ADD backend_refresh_time int default 0", null, false);
{
Vector/*<int>*/ vecSrcIds = new Vector();
IDBResult res2 = db.executeSQL( "SELECT source_id FROM sources", null, false );
for ( ; !res2.isEnd(); res2.next() )
vecSrcIds.addElement( new Integer(res2.getIntByIdx(0)) );
for( int i = 0; i < vecSrcIds.size(); i++)
{
Object[] values = {vecSrcIds.elementAt(i), vecSrcIds.elementAt(i)};
db.executeSQL( "UPDATE sources SET priority=? where source_id=?", values, false );
}
}
db.close();
db = null;
writeDBVersion( new DBVersion(strRhoDBVer, strAppDBVer) );
return true;
}catch(Exception e)
{
LOG.ERROR("migrateDB failed.", e);
if (db!=null)
{
try{db.close();}catch(DBException exc)
{
LOG.ERROR("migrateDB : close db after error failed.", e);
}
db = null;
}
}
}
return false;
}
void checkDBVersion()throws Exception
{
String strRhoDBVer = RhoSupport.getRhoDBVersion();
String strAppDBVer = RhoConf.getInstance().getString("app_db_version");
DBVersion dbVer = readDBVersion();
boolean bRhoReset = false;
boolean bAppReset = false;
if ( strRhoDBVer != null && strRhoDBVer.length() > 0 )
{
if ( dbVer == null || dbVer.m_strRhoVer == null || !dbVer.m_strRhoVer.equalsIgnoreCase(strRhoDBVer) )
bRhoReset = true;
}
if ( strAppDBVer != null && strAppDBVer.length() > 0 )
{
if ( dbVer == null || dbVer.m_strAppVer == null || !dbVer.m_strAppVer.equalsIgnoreCase(strAppDBVer) )
bAppReset = true;
}
if ( bRhoReset && !bAppReset )
bRhoReset = !migrateDB(dbVer, strRhoDBVer, strAppDBVer);
else if ( Capabilities.USE_SQLITE )
{
IFileAccess fs = RhoClassFactory.createFileAccess();
String dbName = getNameNoExt(m_strDBPath);
String dbNameScript = dbName + ".script";
String dbNameData = dbName + ".data";
String dbNameJournal = dbName + ".journal";
String dbNameProperties = dbName + ".properties";
if ( fs.exists(dbNameScript) )
{
LOG.INFO("Remove hsqldb and use sqlite for Blackberry>=5.");
fs.delete(dbNameScript);
fs.delete(dbNameData);
fs.delete(dbNameJournal);
fs.delete(dbNameProperties);
bRhoReset = true;
}
}
if ( bRhoReset || bAppReset )
{
IDBStorage db = null;
try
{
db = RhoClassFactory.createDBStorage();
if ( db.isDbFileExists(m_strDBPath) )
{
db.open( m_strDBPath, "" );
IDBResult res = db.executeSQL("SELECT * FROM client_info", null, false);
if ( !res.isOneEnd() )
{
m_strClientInfoInsert = createInsertStatement(res, "client_info");
m_dataClientInfo = res.getCurData();
}
}
}catch(Exception exc)
{
LOG.ERROR("Copy client_info table failed.", exc);
}catch(Throwable e)
{
LOG.ERROR("Copy client_info table crashed.", e);
}finally
{
if (db != null )
try{ db.close(); }catch(Exception e){}
}
m_dbStorage.deleteAllFiles(m_strDBPath);
String fName = makeBlobFolderName();
RhoClassFactory.createFile().delete(fName);
DBAdapter.makeBlobFolderName(); //Create folder back
writeDBVersion(new DBVersion(strRhoDBVer, strAppDBVer) );
if ( RhoConf.getInstance().isExist("bulksync_state") && RhoConf.getInstance().getInt("bulksync_state") != 0)
RhoConf.getInstance().setInt("bulksync_state", 0, true);
}
}
static Vector m_dbAdapters = new Vector();
public static DBAdapter findDBAdapterByBaseName(String strBaseName)
{
for ( int i = 0; i < m_dbAdapters.size(); i++ )
{
DBAdapter item = (DBAdapter)m_dbAdapters.elementAt(i);
FilePath oPath = new FilePath(item.getDBPath());
if ( oPath.getBaseName().compareTo(strBaseName) == 0 )
return item;
}
return null;
}
public static void startAllDBTransaction()throws DBException
{
for ( int i = 0; i < m_dbAdapters.size(); i++ )
{
DBAdapter item = (DBAdapter)m_dbAdapters.elementAt(i);
item.startTransaction();
}
}
public static void commitAllDBTransaction()throws DBException
{
for ( int i = 0; i < m_dbAdapters.size(); i++ )
{
DBAdapter item = (DBAdapter)m_dbAdapters.elementAt(i);
item.commit();
}
}
private void openDB(String strDBName, boolean bTemp)throws Exception
{
if ( m_bIsOpen )
return;
initFilePaths(strDBName);
if ( !bTemp )
checkDBVersion();
m_dbStorage.open(m_strDBPath, getSqlScript() );
//executeSQL("CREATE INDEX by_src ON object_values (source_id)", null);
m_bIsOpen = true;
//getAttrMgr().load(this);
m_dbStorage.setDbCallback(new DBCallback(this));
m_dbAdapters.addElement(this);
//copy client_info table
if ( !bTemp && m_strClientInfoInsert != null && m_strClientInfoInsert.length() > 0 &&
m_dataClientInfo != null )
{
LOG.INFO("Copy client_info table from old database");
m_dbStorage.executeSQL(m_strClientInfoInsert, m_dataClientInfo, false );
IDBResult res = executeSQL( "SELECT client_id FROM client_info" );
if ( !res.isOneEnd() && res.getStringByIdx(0).length() > 0 )
{
LOG.INFO("Set reset=1 in client_info");
executeSQL( "UPDATE client_info SET reset=1" );
}
}
}
private String createInsertStatement(IDBResult res, String tableName)
{
String strInsert = "INSERT INTO ";
strInsert += tableName;
strInsert += "(";
String strQuest = ") VALUES(";
for (int i = 0; i < res.getColCount(); i++ )
{
if ( i > 0 )
{
strInsert += ",";
strQuest += ",";
}
strInsert += res.getColName(i);
strQuest += "?";
}
strInsert += strQuest + ")";
return strInsert;
}
private boolean destroyTableName(String tableName, Vector arIncludeTables, Vector arExcludeTables )
{
int i;
for (i = 0; i < (int)arExcludeTables.size(); i++ )
{
if ( ((String)arExcludeTables.elementAt(i)).equalsIgnoreCase(tableName) )
return false;
}
for (i = 0; i < (int)arIncludeTables.size(); i++ )
{
if ( ((String)arIncludeTables.elementAt(i)).equalsIgnoreCase(tableName) )
return true;
}
return arIncludeTables.size()==0;
}
public boolean isTableExist(String strTableName)throws DBException
{
return m_dbStorage.isTableExists(strTableName);
}
private RubyValue rb_destroy_tables(RubyValue vInclude, RubyValue vExclude)
{
if ( !m_bIsOpen )
return RubyConstant.QNIL;
IDBStorage db = null;
try{
//getAttrMgr().reset(this);
Vector vecIncludes = RhoRuby.makeVectorStringFromArray(vInclude);
Vector vecExcludes = RhoRuby.makeVectorStringFromArray(vExclude);
String dbName = getNameNoExt(m_strDBPath);
String dbNewName = dbName + "new";
IFileAccess fs = RhoClassFactory.createFileAccess();
String dbNameData = dbName + ".data";
String dbNewNameData = dbNewName + ".data";
String dbNameScript = dbName + ".script";
String dbNewNameScript = dbNewName + ".script";
String dbNameJournal = dbName + ".journal";
String dbNameJournal2 = dbName + ".data-journal";
String dbNewNameJournal = dbNewName + ".journal";
String dbNewNameJournal2 = dbNewName + ".data-journal";
String dbNewNameProps = dbNewName + ".properties";
//LOG.TRACE("DBAdapter: " + dbNewNameDate + ": " + (fs.exists(dbNewNameData) ? "" : "not ") + "exists");
fs.delete(dbNewNameData);
//LOG.TRACE("DBAdapter: " + dbNewNameScript + ": " + (fs.exists(dbNewNameScript) ? "" : "not ") + "exists");
fs.delete(dbNewNameScript);
//LOG.TRACE("DBAdapter: " + dbNewNameJournal + ": " + (fs.exists(dbNewNameJournal) ? "" : "not ") + "exists");
fs.delete(dbNewNameJournal);
fs.delete(dbNewNameJournal2);
fs.delete(dbNewNameProps);
LOG.TRACE("1. Size of " + dbNameData + ": " + fs.size(dbNameData));
db = RhoClassFactory.createDBStorage();
db.open( dbNewName, getSqlScript() );
String[] vecTables = m_dbStorage.getAllTableNames();
//IDBResult res;
db.startTransaction();
for ( int i = 0; i< vecTables.length; i++ )
{
String tableName = vecTables[i];
if ( destroyTableName( tableName, vecIncludes, vecExcludes ) )
continue;
copyTable(tableName, this.m_dbStorage, db );
}
db.commit();
db.close();
m_dbStorage.close();
m_dbStorage = null;
m_bIsOpen = false;
LOG.TRACE("2. Size of " + dbNewNameData + ": " + fs.size(dbNewNameData));
fs.delete(dbNewNameProps);
fs.delete(dbNameJournal);
fs.delete(dbNameJournal2);
String fName = makeBlobFolderName();
RhoClassFactory.createFile().delete(fName);
DBAdapter.makeBlobFolderName(); //Create folder back
fs.renameOverwrite(dbNewNameData, dbNameData);
if ( !Capabilities.USE_SQLITE )
fs.renameOverwrite(dbNewNameScript, dbNameScript);
LOG.TRACE("3. Size of " + dbNameData + ": " + fs.size(dbNameData));
m_dbStorage = RhoClassFactory.createDBStorage();
m_dbStorage.open(m_strDBPath, getSqlScript() );
m_bIsOpen = true;
//getAttrMgr().load(this);
m_dbStorage.setDbCallback(new DBCallback(this));
}catch(Exception e)
{
LOG.ERROR("execute failed.", e);
if ( !m_bIsOpen )
{
LOG.ERROR("destroy_table error.Try to open old DB.");
try{
m_dbStorage.open(m_strDBPath, getSqlScript() );
m_bIsOpen = true;
}catch(Exception exc)
{
LOG.ERROR("destroy_table open old table failed.", exc);
}
}
try {
if ( db != null)
db.close();
} catch (DBException e1) {
LOG.ERROR("closing of DB caused exception: " + e1.getMessage());
}
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
return RubyConstant.QNIL;
}
private void copyTable(String tableName, IDBStorage dbFrom, IDBStorage dbTo)throws DBException
{
IDBResult res = dbFrom.executeSQL("SELECT * from " + tableName, null, false);
String strInsert = "";
for ( ; !res.isEnd(); res.next() )
{
if ( strInsert.length() == 0 )
strInsert = createInsertStatement(res, tableName);
dbTo.executeSQL(strInsert, res.getCurData(), false );
}
}
public void updateAllAttribChanges()throws DBException
{
//Check for attrib = object
IDBResult res = executeSQL("SELECT object, source_id, update_type " +
"FROM changed_values where attrib = 'object' and sent=0" );
if ( res.isEnd() )
return;
startTransaction();
Vector/*<String>*/ arObj = new Vector(), arUpdateType = new Vector();
Vector/*<int>*/ arSrcID = new Vector();
for( ; !res.isEnd(); res.next() )
{
arObj.addElement(res.getStringByIdx(0));
arSrcID.addElement(new Integer(res.getIntByIdx(1)));
arUpdateType.addElement(res.getStringByIdx(2));
}
for( int i = 0; i < (int)arObj.size(); i++ )
{
IDBResult resSrc = executeSQL("SELECT name, schema FROM sources where source_id=?", arSrcID.elementAt(i) );
boolean bSchemaSource = false;
String strTableName = "object_values";
if ( !resSrc.isEnd() )
{
bSchemaSource = resSrc.getStringByIdx(1).length() > 0;
if ( bSchemaSource )
strTableName = resSrc.getStringByIdx(0);
}
if (bSchemaSource)
{
IDBResult res2 = executeSQL( "SELECT * FROM " + strTableName + " where object=?", arObj.elementAt(i) );
for( int j = 0; j < res2.getColCount(); j ++)
{
String strAttrib = res2.getColName(j);
String value = res2.getStringByIdx(j);
String attribType = getAttrMgr().isBlobAttr((Integer)arSrcID.elementAt(i), strAttrib) ? "blob.file" : "";
executeSQLReportNonUnique("INSERT INTO changed_values (source_id,object,attrib,value,update_type,attrib_type,sent) VALUES(?,?,?,?,?,?,?)",
arSrcID.elementAt(i), arObj.elementAt(i), strAttrib, value, arUpdateType.elementAt(i), attribType, new Integer(0) );
}
}else
{
IDBResult res2 = executeSQL( "SELECT attrib, value FROM " + strTableName + " where object=? and source_id=?",
arObj.elementAt(i), arSrcID.elementAt(i) );
for( ; !res2.isEnd(); res2.next() )
{
String strAttrib = res2.getStringByIdx(0);
String value = res2.getStringByIdx(1);
String attribType = getAttrMgr().isBlobAttr((Integer)arSrcID.elementAt(i), strAttrib) ? "blob.file" : "";
executeSQLReportNonUnique("INSERT INTO changed_values (source_id,object,attrib,value,update_type,attrib_type,sent) VALUES(?,?,?,?,?,?,?)",
arSrcID.elementAt(i), arObj.elementAt(i), strAttrib, value, arUpdateType.elementAt(i), attribType, new Integer(0) );
}
}
}
executeSQL("DELETE FROM changed_values WHERE attrib='object'");
endTransaction();
}
void copyChangedValues(DBAdapter db)throws DBException
{
updateAllAttribChanges();
copyTable("changed_values", m_dbStorage, db.m_dbStorage );
{
Vector/*<int>*/ arOldSrcs = new Vector();
{
IDBResult resSrc = db.executeSQL( "SELECT DISTINCT(source_id) FROM changed_values" );
for ( ; !resSrc.isEnd(); resSrc.next() )
arOldSrcs.addElement( new Integer(resSrc.getIntByIdx(0)) );
}
for( int i = 0; i < arOldSrcs.size(); i++)
{
int nOldSrcID = ((Integer)arOldSrcs.elementAt(i)).intValue();
IDBResult res = executeSQL("SELECT name from sources WHERE source_id=?", nOldSrcID);
if ( !res.isOneEnd() )
{
String strSrcName = res.getStringByIdx(0);
IDBResult res2 = db.executeSQL("SELECT source_id from sources WHERE name=?", strSrcName );
if ( !res2.isOneEnd() )
{
if ( nOldSrcID != res2.getIntByIdx(0) )
{
db.executeSQL("UPDATE changed_values SET source_id=? WHERE source_id=?", res2.getIntByIdx(0), nOldSrcID);
}
continue;
}
}
//source not exist in new partition, remove this changes
db.executeSQL("DELETE FROM changed_values WHERE source_id=?", nOldSrcID);
}
}
}
public void setBulkSyncDB(String fDbName, String fScriptName)
{
DBAdapter db = null;
try{
db = (DBAdapter)alloc(null);
db.openDB(fDbName, true);
db.m_dbStorage.createTriggers();
db.setDbPartition(m_strDbPartition);
db.startTransaction();
copyTable("client_info", m_dbStorage, db.m_dbStorage );
copyChangedValues(db);
/*
//update User partition
if ( m_strDbPartition.compareTo(USER_PARTITION_NAME()) == 0 )
{
//copy all NOT user sources from current db to bulk db
startTransaction();
executeSQL("DELETE FROM sources WHERE partition=?", m_strDbPartition);
copyTable("sources", m_dbStorage, db.m_dbStorage );
rollback();
}else
{
//remove all m_strDbPartition sources from user db
//copy all sources from bulk db to user db
DBAdapter dbUser = getDB(USER_PARTITION_NAME());
dbUser.startTransaction();
dbUser.executeSQL("DELETE FROM sources WHERE partition=?", m_strDbPartition);
copyTable("sources", db.m_dbStorage, dbUser.m_dbStorage );
dbUser.endTransaction();
}*/
getDBPartitions().put(m_strDbPartition, db);
com.rho.sync.SyncThread.getSyncEngine().applyChangedValues(db);
getDBPartitions().put(m_strDbPartition, this);
db.endTransaction();
db.close();
m_dbStorage.close();
m_dbStorage = null;
m_bIsOpen = false;
String dbName = getNameNoExt(m_strDBPath);
IFileAccess fs = RhoClassFactory.createFileAccess();
String dbNameData = dbName + ".data";
String dbNameScript = dbName + ".script";
String dbNameJournal = dbName + ".journal";
String dbNameJournal2 = dbName + ".data-journal";
String dbNewNameProps = getNameNoExt(fDbName) + ".properties";
fs.delete(dbNameJournal);
fs.delete(dbNameJournal2);
fs.delete(dbNewNameProps);
String fName = makeBlobFolderName();
RhoClassFactory.createFile().delete(fName);
DBAdapter.makeBlobFolderName(); //Create folder back
fs.renameOverwrite(fDbName, dbNameData);
if ( !Capabilities.USE_SQLITE )
fs.renameOverwrite(fScriptName, dbNameScript);
m_dbStorage = RhoClassFactory.createDBStorage();
m_dbStorage.open(m_strDBPath, getSqlScript() );
m_bIsOpen = true;
//getAttrMgr().load(this);
m_dbStorage.setDbCallback(new DBCallback(this));
}catch(Exception e)
{
LOG.ERROR("execute failed.", e);
if ( !m_bIsOpen )
{
LOG.ERROR("destroy_table error.Try to open old DB.");
try{
m_dbStorage.open(m_strDBPath, getSqlScript() );
m_bIsOpen = true;
}catch(Exception exc)
{
LOG.ERROR("destroy_table open old table failed.", exc);
}
}
if ( db != null)
db.close();
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
}
/*
public RubyValue rb_execute(RubyValue v)
{
RubyArray res = new RubyArray();
try{
IDBResult rows = executeSQL(v.toStr(), null);
RubyString[] colNames = getColNames(rows);
for( ; !rows.isEnd(); rows.next() )
{
RubyHash row = ObjectFactory.createHash();
for ( int nCol = 0; nCol < rows.getColCount(); nCol ++ )
row.add( colNames[nCol], rows.getRubyValueByIdx(nCol) );
res.add( row );
}
}catch(Exception e)
{
LOG.ERROR("execute failed.", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
return res;
}*/
public RubyValue rb_execute(RubyValue v, RubyValue batch, RubyValue arg)
{
RubyArray res = new RubyArray();
try{
String strSql = v.toStr();
if ( batch == RubyConstant.QTRUE )
{
//LOG.INFO("batch execute:" + strSql);
executeBatchSQL( strSql );
}
else
{
Object[] values = null;
if ( arg != null )
{
RubyArray args1 = arg.toAry();
RubyArray args = args1;
if ( args.size() > 0 && args.get(0) instanceof RubyArray )
args = (RubyArray)args.get(0);
values = new Object[args.size()];
for ( int i = 0; i < args.size(); i++ )
{
RubyValue val = args.get(i);
if ( val == RubyConstant.QNIL )
values[i] = null;
else if ( val instanceof RubyInteger )
values[i] = new Long( ((RubyInteger)val).toLong() );
else if ( val instanceof RubyFloat )
values[i] = new Double( ((RubyFloat)val).toFloat() );
else if ( val instanceof RubyString )
values[i] = new String( ((RubyString)val).toStr() );
else if ( val == RubyConstant.QTRUE )
values[i] = new String( "true" );
else if ( val == RubyConstant.QFALSE )
values[i] = new String( "false" );
else
values[i] = val.toStr();
}
}
IDBResult rows = executeSQL( strSql, values);
RubyString[] colNames = null;
for( ; !rows.isEnd(); rows.next() )
{
RubyHash row = ObjectFactory.createHash();
for ( int nCol = 0; nCol < rows.getColCount(); nCol ++ )
{
if ( colNames == null )
colNames = getOrigColNames(rows);
row.add( colNames[nCol], rows.getRubyValueByIdx(nCol) );
}
res.add( row );
}
}
}catch(Exception e)
{
LOG.ERROR("execute failed.", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
return res;
}
//@RubyAllocMethod
private static RubyValue alloc(RubyValue receiver) {
return new DBAdapter((RubyClass) receiver);
}
public static void closeAll()
{
Enumeration enumDBs = m_mapDBPartitions.elements();
while (enumDBs.hasMoreElements())
{
DBAdapter db = (DBAdapter)enumDBs.nextElement();
db.close();
}
}
public static void initAttrManager()throws DBException
{
Enumeration enumDBs = m_mapDBPartitions.elements();
while (enumDBs.hasMoreElements())
{
DBAdapter db = (DBAdapter)enumDBs.nextElement();
db.getAttrMgr().loadBlobAttrs(db);
if ( !db.getAttrMgr().hasBlobAttrs() )
db.m_dbStorage.setDbCallback(null);
}
}
public static DBAdapter getUserDB()
{
return (DBAdapter)getDBPartitions().get(USER_PARTITION_NAME());
}
public static DBAdapter getDB(String szPartition)
{
return (DBAdapter)getDBPartitions().get(szPartition);
}
public static Vector/*<String>*/ getDBAllPartitionNames()
{
Vector/*<String>*/ vecNames = new Vector();
Enumeration enumDBs = m_mapDBPartitions.keys();
while (enumDBs.hasMoreElements())
{
vecNames.addElement(enumDBs.nextElement());
}
return vecNames;
}
public static boolean isAnyInsideTransaction()
{
Enumeration enumDBs = m_mapDBPartitions.elements();
while (enumDBs.hasMoreElements())
{
DBAdapter db = (DBAdapter)enumDBs.nextElement();
if ( db.isInsideTransaction() )
return true;
}
return false;
}
public static void initMethods(RubyClass klass) {
klass.defineAllocMethod(new RubyNoArgMethod(){
protected RubyValue run(RubyValue receiver, RubyBlock block ) {
return DBAdapter.alloc(receiver);}
});
klass.defineMethod( "initialize", new RubyTwoArgMethod()
{
protected RubyValue run(RubyValue receiver, RubyValue arg1, RubyValue arg2, RubyBlock block )
{
try
{
String szDbName = arg1.toStr();
String szDbPartition = arg2.toStr();
((DBAdapter)receiver).openDB(szDbName, false);
((DBAdapter)receiver).setDbPartition(szDbPartition);
DBAdapter.getDBPartitions().put(szDbPartition, receiver);
return receiver;
}catch(Exception e)
{
LOG.ERROR("initialize failed.", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
}
});
/*klass.defineMethod( "close", new RubyNoArgMethod(){
protected RubyValue run(RubyValue receiver, RubyBlock block ){
return ((DBAdapter)receiver).rb_close();}
});*/
klass.defineMethod( "execute", new RubyVarArgMethod(){
protected RubyValue run(RubyValue receiver, RubyArray args, RubyBlock block ){
return ((DBAdapter)receiver).rb_execute(args.get(0), args.get(1),
(args.size() > 2 ? args.get(2):null));}
});
klass.defineMethod( "start_transaction", new RubyNoArgMethod(){
protected RubyValue run(RubyValue receiver, RubyBlock block )
{
try{
((DBAdapter)receiver).startTransaction();
return ObjectFactory.createInteger(0);
}catch( Exception e ){
LOG.ERROR("start_transaction failed.", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
}
});
klass.defineMethod( "commit", new RubyNoArgMethod(){
protected RubyValue run(RubyValue receiver, RubyBlock block )
{
try{
((DBAdapter)receiver).commit();
return ObjectFactory.createInteger(0);
}catch( Exception e ){
LOG.ERROR("commit failed.", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
}
});
klass.defineMethod( "rollback", new RubyNoArgMethod(){
protected RubyValue run(RubyValue receiver, RubyBlock block )
{
try{
((DBAdapter)receiver).rollback();
return ObjectFactory.createInteger(0);
}catch( Exception e ){
LOG.ERROR("rollback failed.", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
}
});
klass.defineMethod( "destroy_tables", new RubyTwoArgMethod(){
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyValue arg1, RubyBlock block ){
return ((DBAdapter)receiver).rb_destroy_tables(arg, arg1);}
});
klass.defineMethod("is_ui_waitfordb", new RubyNoArgMethod() {
protected RubyValue run(RubyValue receiver, RubyBlock block)
{
try{
boolean bRes = ((DBAdapter)receiver).isUIWaitDB();
return ObjectFactory.createBoolean(bRes);
}catch(Exception e)
{
LOG.ERROR("is_ui_waitfordb failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
}
});
klass.defineMethod("lock_db",
new RubyNoArgMethod() {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
try{
DBAdapter db = (DBAdapter)receiver;
//db.setUnlockDB(true);
db.Lock();
}catch(Exception e)
{
LOG.ERROR("lock_db failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
return RubyConstant.QNIL;
}
});
klass.defineMethod("unlock_db",
new RubyNoArgMethod() {
protected RubyValue run(RubyValue receiver, RubyBlock block) {
try{
DBAdapter db = (DBAdapter)receiver;
db.Unlock();
}catch(Exception e)
{
LOG.ERROR("unlock_db failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
return RubyConstant.QNIL;
}
});
klass.defineMethod( "table_exist?", new RubyOneArgMethod(){
protected RubyValue run(RubyValue receiver, RubyValue arg, RubyBlock block )
{
try{
DBAdapter db = (DBAdapter)receiver;
boolean bExists = db.isTableExist(arg.toStr());
return ObjectFactory.createBoolean(bExists);
}catch(Exception e)
{
LOG.ERROR("unlock_db failed", e);
throw (e instanceof RubyException ? (RubyException)e : new RubyException(e.getMessage()));
}
}
});
}
public static class DBCallback implements IDBCallback
{
private DBAdapter m_db;
DBCallback(DBAdapter db){ m_db = db; }
/*public void OnDeleteAll() {
OnDeleteAllFromTable("object_values");
}
public void OnDeleteAllFromTable(String tableName) {
if ( !tableName.equals("object_values") )
return;
try{
String fName = DBAdapter.makeBlobFolderName();
RhoClassFactory.createFile().delete(fName);
DBAdapter.makeBlobFolderName(); //Create folder back
}catch(Exception exc){
LOG.ERROR("DBCallback.OnDeleteAllFromTable: Error delete files from table: " + tableName, exc);
}
}*/
/*
public void onAfterInsert(String tableName, IDBResult rows2Insert)
{
try
{
if ( !tableName.equalsIgnoreCase("object_values") )
return;
for( ; !rows2Insert.isEnd(); rows2Insert.next() )
{
//Object[] data = rows2Insert.getCurData();
Integer nSrcID = new Integer(rows2Insert.getIntByIdx(0));
String attrib = rows2Insert.getStringByIdx(1);
m_db.getAttrMgr().add(nSrcID, attrib);
}
}catch(DBException exc)
{
LOG.ERROR("onAfterInsert failed.", exc);
}
}*/
public void onBeforeUpdate(String tableName, IDBResult rows2Delete, int[] cols)
{
try
{
processDelete(tableName, rows2Delete, cols);
}catch(DBException exc)
{
LOG.ERROR("onAfterInsert failed.", exc);
}
}
public void onBeforeDelete(String tableName, IDBResult rows2Delete)
{
try
{
processDelete(tableName, rows2Delete, null);
}catch(DBException exc)
{
LOG.ERROR("onAfterInsert failed.", exc);
}
}
private boolean isChangedCol(int[] cols, int iCol)
{
if (cols==null)
return true;
for ( int i = 0; i < cols.length; i++ )
{
if ( cols[i] == iCol )
return true;
}
return false;
}
private void processDelete(String tableName, IDBResult rows2Delete, int[] cols) throws DBException
{
if ( tableName.equalsIgnoreCase("changed_values") || tableName.equalsIgnoreCase("sources") ||
tableName.equalsIgnoreCase("client_info"))
return;
boolean bProcessTable = tableName.equalsIgnoreCase("object_values");
boolean bSchemaSrc = false;
Integer nSrcID = null;
if ( !bProcessTable )
{
nSrcID = m_db.getAttrMgr().getSrcIDHasBlobsByName(tableName);
bProcessTable = nSrcID != null;
bSchemaSrc = bProcessTable;
}
if ( !bProcessTable)
return;
if ( !bSchemaSrc && !isChangedCol(cols, 3))//value
return;
for( ; !rows2Delete.isEnd(); rows2Delete.next() )
{
if ( !bSchemaSrc )
{
nSrcID = new Integer(rows2Delete.getIntByIdx(0));
String attrib = rows2Delete.getStringByIdx(1);
String value = rows2Delete.getStringByIdx(3);
//if (cols == null) //delete
// m_db.getAttrMgr().remove(nSrcID, attrib);
if ( m_db.getAttrMgr().isBlobAttr(nSrcID, attrib) )
processBlobDelete(nSrcID, attrib, value);
}else
{
Object[] data = rows2Delete.getCurData();
for ( int i = 0; i < rows2Delete.getColCount(); i++ )
{
if (!isChangedCol(cols, i))
continue;
String attrib = rows2Delete.getColName(i);
if ( !(data[i] instanceof String) )
continue;
String value = (String)data[i];
if ( m_db.getAttrMgr().isBlobAttr(nSrcID, attrib) )
processBlobDelete(nSrcID, attrib, value);
}
}
}
}
private void processBlobDelete(Integer nSrcID, String attrib, String value)
{
if ( value == null || value.length() == 0 )
return;
try{
String strFilePath = RhodesApp.getInstance().resolveDBFilesPath(value);
SimpleFile oFile = RhoClassFactory.createFile();
oFile.delete(strFilePath);
}catch(Exception exc){
LOG.ERROR("DBCallback.OnDeleteFromTable: Error delete file: " + value, exc);
}
}
}
} |
// jTDS JDBC Driver for Microsoft SQL Server and Sybase
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package net.sourceforge.jtds.jdbc;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* @author
* Holger Rehn
*/
public class StatementTest extends TestBase
{
public StatementTest( String name )
{
super( name );
}
/**
* Test for bug #544, getMoreResults() does not work with insert triggers.
*/
public void testBug544()
throws Exception
{
dropTrigger( "Bug544T" );
dropTable( "Bug544a" );
dropTable( "Bug544b" );
Statement sta = con.createStatement();
sta.executeUpdate( "create table Bug544a(A int, B int identity(18,1) not null)" );
sta.executeUpdate( "create table Bug544b(A int)" );
// create insert trigger
sta.executeUpdate( "create trigger Bug544T on Bug544a for insert as begin insert into Bug544b values (12) end" );
// insert data to fire the trigger
sta.execute( "insert into Bug544a values( 1 ) select SCOPE_IDENTITY()" );
// dumpAll( sta );
// check update counts
assertEquals( 1, sta.getUpdateCount() ); // original insert
assertFalse( sta.getMoreResults() );
assertEquals( 1, sta.getUpdateCount() ); // insert executed by the trigger
assertTrue( sta.getMoreResults() );
ResultSet res = sta.getResultSet(); // result of SELECT SCOPE_IDENTITY()" );
assertTrue( res.next() );
assertEquals( 18, res.getInt( 1 ) ); // the generated value
assertFalse( res.next() );
// check the target table
res = sta.executeQuery( "select * from Bug544b" );
assertTrue( res.next() );
assertEquals( 12, res.getInt( 1 ) );
assertFalse( res.next() );
}
/**
* Test for bug #500, Statement.execute() raises executeQuery() exception if
* using cursors (useCursors=true) and SHOWPLAN_ALL is set to ON.
*/
public void testBug500()
throws Exception
{
Properties override = new Properties();
override.put( "useCursors", "true" );
Connection connection = getConnection( override );
Statement stmt = connection.createStatement();
stmt.executeUpdate( "create table #Bug500 (A int)" );
for( int i = 0; i < 10; i ++ )
{
stmt.executeUpdate( "insert into #Bug500 values(" + i + ")" );
}
stmt.executeUpdate( "set SHOWPLAN_ALL on" );
// or stmt.execute( "set SHOWPLAN_ALL on" ); - doesn't matters
stmt.execute( "select top 5 * from #Bug500" );
dumpAll( stmt );
// stmt.execute( "select top 5 * from #Bug500" );
// ResultSet rs = stmt.getResultSet();
}
/**
* Regression test for bug #528, ResultSet not getting populated correctly
* with autogenerated keys.
*/
public void testBug528()
throws Exception
{
Statement sta = con.createStatement();
sta.executeUpdate( "create table #Bug528 (A int identity(11,1) not null, B varchar(10))" );
boolean result = sta.execute( "insert into #Bug528(B) values ('test');" + // Update Count: 1
"insert into #Bug528(B) values ('test');" + // Update Count: 1
"select * from #Bug528", // ResultSet: [11, test] [12, test]
Statement.RETURN_GENERATED_KEYS ); // Generated Keys: 12
// dumpAll( sta );
assertFalse( result ); // first is an update count for 1st insert
assertEquals( 1, sta.getUpdateCount() ); // check update count
assertFalse( sta.getMoreResults() ); // next is an update count for 2nd insert
assertEquals( 1, sta.getUpdateCount() ); // check update count
assertTrue( sta.getMoreResults() ); // resultset generated by select (this used to fail)
// get and check resultset
ResultSet res = sta.getResultSet();
assertTrue( res.next() );
assertEquals( 11, res.getInt( 1 ) );
assertEquals( "test", res.getString( 2 ) );
assertTrue( res.next() );
assertEquals( 12, res.getInt( 1 ) );
assertEquals( "test", res.getString( 2 ) );
assertFalse( res.next() );
// now check generated keys
res = sta.getGeneratedKeys();
// FIXME: the driver is not yet able to return generated keys for anything but the last update
// assertTrue( res.next() );
// assertEquals( 11, res.getInt( 1 ) );
assertTrue( res.next() );
assertEquals( 12, res.getInt( 1 ) );
assertFalse( res.next() );
sta.close();
}
/**
* Test for bug #559, unique constraint violation error hidden by an internal
* jTDS error.
*/
public void testBug559()
throws Exception
{
Statement st = con.createStatement();
st.executeUpdate( "create table #Bug559 (A int, unique (A))" );
try
{
st.executeUpdate( "select 1;insert into #Bug559 values( 1 );insert into #Bug559 values( 1 )" );
fail();
}
catch( SQLException e )
{
// expected, executeUpdate() cannot return a resultset
assertTrue( e.getMessage().toLowerCase().contains( "executeupdate" ) );
}
st.close();
}
/**
* Test for bug #609, slow finalization in {@link SharedSocket#closeStream()}
* can block JVM finalizer thread or cause OOM errors.
*/
public void testBug609()
throws Exception
{
final int STATEMENTS = 50000;
final int THREADS = 10;
final Connection connection = con;
final boolean[] running = new boolean[] { true };
List block = new ArrayList( 1000 );
try
{
while( true )
{
block.add( new byte[32*1024*1024] );
System.gc();
}
}
catch( OutOfMemoryError oome )
{
block.remove( block.size() - 1 );
}
System.gc();
System.out.println( "free memory: " + Runtime.getRuntime().freeMemory() / 1024 / 1024 + " MB" );
Statement sta = connection.createStatement();
sta.executeUpdate( "create table #bug609( A int primary key, B varchar(max) )" );
sta.close();
Thread[] threads = new Thread[THREADS];
// start threads that keeps sending data to block VirtualSocket table in SharedSocket as much as possible
for( int t = 0; t < threads.length; t ++ )
{
final int i = t;
threads[t] = new Thread()
{
public void run()
{
try
{
Statement sta = connection.createStatement();
sta.executeUpdate( "insert into #bug609 values( " + i + ", 'nix' )" );
String value = "BIGVAL";
while( value.length() < 64 * 1024 )
{
value += value + "BIGVAL";
}
String sql = "update #bug609 set B = '" + value + "' where A = " + i;
while( running[0] )
{
sta.executeUpdate( sql );
}
sta.close();
}
catch( SQLException s )
{
// test stopped, connection is closed
}
catch( Throwable t )
{
t.printStackTrace();
}
}
};
threads[t].setPriority( Thread.MIN_PRIORITY );
threads[t].start();
}
int stats = 0;
long start = System.currentTimeMillis();
try
{
// buffer some statements that can later be closed together, otherwise
// the connection's TdsCore cache would prevent the TdsCore from being
// closed (and SharedSocket.closeStream to be called) most of the time
Statement[] buffered = new Statement[2500];
for( ; stats < STATEMENTS; stats ++ )
{
int r = stats % buffered.length;
buffered[r] = con.createStatement();
if( r == buffered.length - 1 )
{
for( int c = 0; c < buffered.length; c ++ )
{
buffered[c] = null;
}
System.out.println( stats + 1 );
}
}
}
catch( OutOfMemoryError oome )
{
block = null;
System.gc();
fail( "OOM after " + (System.currentTimeMillis() - start) + " ms, " + stats + " statements created successfully" );
}
long elapsed = System.currentTimeMillis() - start;
System.out.println( "time: " + elapsed + " ms" );
assertTrue( elapsed < 10000 );
// stop threads
running[0] = false;
for( int t = 0; t < threads.length; t ++ )
{
threads[t].join();
}
}
/**
* Test for bug #473, Statement.setMaxRows() also effects INSERT, UPDATE,
* DELETE and SELECT INTO.
*/
public void testBug473()
throws Exception
{
Statement sta = con.createStatement();
// create test table and fill with data
sta.executeUpdate( "create table #Bug473( X int )" );
sta.executeUpdate( "insert into #Bug473 values( 1 )" );
sta.executeUpdate( "insert into #Bug473 values( 2 )" );
// copy all data (maxRows shouldn't have any effect)
sta.setMaxRows( 1 );
sta.executeUpdate( "select * into #copy from #Bug473" );
// ensure all table data has been copied
sta.setMaxRows( 0 );
ResultSet res = sta.executeQuery( "select * from #copy" );
assertTrue ( res.next() );
assertTrue ( res.next() );
assertFalse( res.next() );
res.close();
sta.close();
}
/**
* Test for bug #635, select from a view with order by clause doesn't work if
* correctly if using Statement.setMaxRows().
*/
public void testBug635()
throws Exception
{
final int[] data = new int[] { 1, 3, 5, 7, 9, 2, 4, 6, 8, 10 };
dropTable( "Bug635T" );
dropView ( "Bug635V" );
Statement sta = con.createStatement();
sta.setMaxRows( 7 );
sta.executeUpdate( "create table Bug635T( X int )" );
sta.executeUpdate( "create view Bug635V as select * from Bug635T" );
for( int i = 0; i < data.length; i ++ )
{
sta.executeUpdate( "insert into Bug635T values( " + data[i] + " )" );
}
ResultSet res = sta.executeQuery( "select X from Bug635V order by X" );
for( int i = 1; i <= 7; i ++ )
{
assertTrue( res.next() );
assertEquals( i, res.getInt( 1 ) );
}
res.close();
sta.close();
}
/**
* Test for bug #624, full text search causes connection reset when connected
* to Microsoft SQL Server 2008.
*/
// TODO: test CONTAINSTABLE, FREETEXT, FREETEXTTABLE
public void testFullTextSearch()
throws Exception
{
// cleanup
dropTable( "Bug624" );
dropDatabase( "Bug624DB" );
// create DB
Statement stmt = con.createStatement();
stmt.executeUpdate( "create database Bug624DB" );
stmt.executeUpdate( "use Bug624DB" );
// create table and fulltext index
stmt.executeUpdate( "create fulltext catalog FTS_C as default" );
stmt.executeUpdate( "create table Bug624 ( ID int primary key, A varchar( 100 ) )" );
ResultSet res = stmt.executeQuery( "select name from sysindexes where object_id( 'Bug624' ) = id" );
assertTrue( res.next() );
String pk = res.getString( 1 );
assertFalse( res.next() );
res.close();
stmt.executeUpdate( "create fulltext index on Bug624( A ) key index " + pk );
// insert test data
assertEquals( 1, stmt.executeUpdate( "insert into Bug624 values( 0, 'Strange Axolotl, that!' )" ) );
// wait for the index to be build
for( boolean indexed = false; ! indexed; )
{
res = stmt.executeQuery( "select FULLTEXTCATALOGPROPERTY( 'FTS_C', 'PopulateStatus' )" );
assertTrue( res.next() );
indexed = res.getInt( 1 ) == 0;
res.close();
Thread.sleep( 10 );
}
// query table using CONTAINS
PreparedStatement ps = con.prepareStatement( "select * from Bug624 where contains( A, ? )" );
ps.setString( 1, "Axolotl" );
res = ps.executeQuery();
assertTrue( res.next() );
assertEquals( 0, res.getInt( 1 ) );
assertEquals( "Strange Axolotl, that!", res.getString( 2 ) );
}
/**
* Test for computed results, bug #678.
*/
public void testComputeClause()
throws Exception
{
final int VALUES = 150;
Statement sta = con.createStatement();
sta.executeUpdate( "create table #Bug678( X int, A varchar(10), B int, C bigint )" );
for( int i = 0; i < VALUES; i ++ )
{
sta.executeUpdate( "insert into #Bug678 values( " + i % Math.max( 1, i / 20 ) + ", 'VAL" + i + "'," + ( VALUES - i ) + ", " + (long)i * Integer.MAX_VALUE + " )" );
}
assertTrue( sta.execute( "select * from #Bug678 order by X, A asc compute min( A ), max( A ), min( C ), max( C ), avg( B ), sum( B ), count( A ), count_big( C ) by X" ) );
// expected result groups, each followed by a computed result
int[] expected = new int[] { 72, 32, 20, 13, 8, 4, 1 };
for( int i = 0; i < expected.length; i ++ )
{
ResultSet res = sta.getResultSet();
// consume rows
for( int r = 0; r < expected[i]; r ++ )
{
assertTrue( res.next() );
}
assertFalse( res.next() );
res.close();
// consume computed result
assertTrue( sta.getMoreResults() );
res = sta.getResultSet();
assertTrue( res.next() );
assertEquals( expected[i], res.getInt( 7 ) );
assertFalse( res.next() );
res.close();
// move to next result if any
assertEquals( i == expected.length -1 ? false : true, sta.getMoreResults() );
}
// no update count expected
assertEquals( -1, sta.getUpdateCount() );
sta.close();
}
/**
* <p> Test to ensure that single results generated as result of aggregation
* operations (COMPUTE clause) can be closed individually without affecting
* remaining {@link ResultSet}s. </p>
*/
public void testCloseComputedResult()
throws Exception
{
Statement sta = con.createStatement();
sta.executeUpdate( "create table #Bug678( NAME varchar(10), CREDITS int )" );
sta.executeUpdate( "insert into #Bug678 values( 'Alf' , 10 )" );
sta.executeUpdate( "insert into #Bug678 values( 'Alf' , 20 )" );
sta.executeUpdate( "insert into #Bug678 values( 'Alf' , 30 )" );
sta.executeUpdate( "insert into #Bug678 values( 'Ronny', 5 )" );
sta.executeUpdate( "insert into #Bug678 values( 'Ronny', 10 )" );
assertTrue( sta.execute( "select * from #Bug678 order by NAME compute sum( CREDITS ) by NAME" ) );
ResultSet res = sta.getResultSet();
// check 1st row of 1st ResultSet
assertTrue ( res.next() );
assertEquals( "Alf", res.getString( 1 ) );
assertEquals( 10, res.getInt( 2 ) );
assertTrue ( res.next() );
// close 1st ResultSet
res.close();
// 3 ResultSets should be left
assertTrue( sta.getMoreResults() );
res = sta.getResultSet();
// close 2nd (computed) ResultSet without processing it
res.close();
// 2 ResultSets should be left
assertTrue( sta.getMoreResults() );
res = sta.getResultSet();
// check 1st row of 3rd ResultSet
assertTrue( res.next() );
assertEquals( "Ronny", res.getString( 1 ) );
assertEquals( 5, res.getInt( 2 ) );
// close 3rd ResultSet
res.close();
// 1 ResultSet should be left
assertTrue( sta.getMoreResults() );
res = sta.getResultSet();
// check 1st row of 4th (computed) ResultSet
assertTrue( res.next() );
assertEquals( 15, res.getInt( 1 ) );
assertFalse( res.next() );
// no ResultSets should be left
assertFalse( sta.getMoreResults() );
sta.close();
}
public void testConcurrentClose()
throws Exception
{
final int THREADS = 10;
final int STATEMENTS = 200;
final int RESULTSETS = 100;
final List errors = new ArrayList<>();
final Statement[] stm = new Statement[STATEMENTS];
final ResultSet[] res = new ResultSet[STATEMENTS*RESULTSETS];
Connection con = getConnection();
for( int i = 0; i < STATEMENTS; i ++ )
{
stm[i] = con.createStatement();
for( int r = 0; r < RESULTSETS; r ++ )
{
res[i * RESULTSETS + r] = stm[i].executeQuery( "select 1" );
}
}
Thread[] threads = new Thread[THREADS];
for( int i = 0; i < THREADS; i ++ )
{
threads[i] = new Thread( "closer " + i )
{
public void run()
{
try
{
for( int i = 0; i < STATEMENTS; i ++ )
{
stm[i].close();
}
}
catch( Exception e )
{
synchronized( errors )
{
errors.add( e );
}
}
}
};
}
for( int i = 0; i < THREADS; i ++ )
{
threads[i].start();
}
for( int i = 0; i < THREADS; i ++ )
{
threads[i].join();
}
for( int i = 0; i < errors.size(); i ++ )
{
( (Exception) errors.get( i ) ).printStackTrace();
}
assertTrue( errors.toString(), errors.isEmpty() );
}
/**
* Regression test for bug #677, deadlock in {@link JtdsStatement#close()}.
*/
public void testCloseDeadlock()
throws Exception
{
final int THREADS = 100;
final int STATEMENTS = 1000;
final List errors = new ArrayList<>();
Thread[] threads = new Thread[THREADS];
for( int i = 0; i < THREADS; i ++ )
{
threads[i] = new Thread( "deadlock " + i )
{
public void run()
{
try
{
Connection con = getConnection();
final Statement[] stm = new Statement[STATEMENTS];
for( int i = 0; i < STATEMENTS; i ++ )
{
stm[i] = con.createStatement();
}
new Thread( Thread.currentThread().getName() + " (closer)" )
{
public void run()
{
try
{
for( int i = 0; i < STATEMENTS; i ++ )
{
stm[i].close();
}
}
catch( SQLException e )
{
// statements might already be closed by closing the connection
if( ! "HY010".equals( e.getSQLState() ) )
{
synchronized( errors )
{
errors.add( e );
}
}
}
}
}.start();
Thread.sleep( 1 );
con.close();
}
catch( Exception e )
{
synchronized( errors )
{
errors.add( e );
}
}
}
};
}
for( int i = 0; i < THREADS; i ++ )
{
threads[i].start();
}
System.currentTimeMillis();
int running = THREADS;
while( running != 0 )
{
Thread.sleep( 2500 );
int last = running;
running = THREADS;
for( int i = 0; i < THREADS; i ++ )
{
if( threads[i].getState() == Thread.State.TERMINATED )
{
running
}
}
if( running == last )
{
// for( int i = 0; i < THREADS; i ++ )
// if( threads[i].getState() != Thread.State.TERMINATED )
// Exception e = new Exception();
// e.setStackTrace( threads[i].getStackTrace() );
// e.printStackTrace();
fail( "deadlock detected, none of the remaining connections closed within 2500 ms" );
}
}
// for( int i = 0; i < errors.size(); i ++ )
// ( (Exception) errors.get( i ) ).printStackTrace();
assertTrue( errors.toString(), errors.isEmpty() );
}
/**
* Test for #676, error in multi line comment handling.
*/
public void testMultiLineComment()
throws Exception
{
Statement st = con.createStatement();
st.executeUpdate( "create table /*/ comment '\"?@[*-} /**/*/ #Bug676a (A int) /* */" );
try
{
// SQL server stacks, instead of ignoring 'inner comments'
st.executeUpdate( "create table #Bug676b (A int)" );
}
catch( SQLException e )
{
// thrown by jTDS due to unclosed 'inner comment'
assertEquals( String.valueOf( 22025 ), e.getSQLState() );
}
st.close();
}
/**
* Test for bug #669, no error if violating unique constraint in update.
*/
public void testDuplicateKey()
throws Exception
{
Statement st = con.createStatement();
st.executeUpdate( "create table #Bug669 (A int, unique (A))" );
st.executeUpdate( "insert into #Bug669 values( 1 )" );
try
{
st.executeUpdate( "insert into #Bug669 values( 1 )" );
fail();
}
catch( SQLException e )
{
// expected, unique constraint violation
}
try
{
st.execute( "insert into #Bug669 values( 1 )" );
fail();
}
catch( SQLException e )
{
// expected, unique constraint violation
}
st.close();
}
/**
* <p> Test for bug [1694194], queryTimeout does not work on MSSQL2005 when
* property 'useCursors' is set to 'true'. Furthermore, the test also checks
* timeout with a query that cannot use a cursor. </p>
*
* <p> This test requires property 'queryTimeout' to be set to true. </p>
*/
public void testQueryTimeout() throws Exception
{
Statement st = con.createStatement();
st.setQueryTimeout( 1 );
st.execute( "create procedure #testTimeout as begin waitfor delay '00:00:30'; select 1; end" );
long start = System.currentTimeMillis();
try
{
// this query doesn't use a cursor
st.executeQuery( "exec #testTimeout" );
fail( "query did not time out" );
}
catch( SQLException e )
{
assertEquals( "HYT00", e.getSQLState() );
assertEquals( 1000, System.currentTimeMillis() - start, 50 );
}
st.execute( "create table #dummy1(A varchar(200))" );
st.execute( "create table #dummy2(B varchar(200))" );
st.execute( "create table #dummy3(C varchar(200))" );
// create test data
con.setAutoCommit( false );
for( int i = 0; i < 100; i++ )
{
st.execute( "insert into #dummy1 values('" + i + "')" );
st.execute( "insert into #dummy2 values('" + i + "')" );
st.execute( "insert into #dummy3 values('" + i + "')" );
}
con.commit();
con.setAutoCommit( true );
start = System.currentTimeMillis();
try
{
// this query can use a cursor
st.executeQuery( "select * from #dummy1, #dummy2, #dummy3 order by A desc, B asc, C desc" );
fail( "query did not time out" );
}
catch( SQLException e )
{
assertEquals( "HYT00", e.getSQLState() );
assertEquals( 1000, System.currentTimeMillis() - start, 100 );
}
st.close();
}
} |
package org.inventivetalent.npclib.npc;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.entity.Entity;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Player;
import org.bukkit.event.entity.CreatureSpawnEvent;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.plugin.Plugin;
import org.inventivetalent.boundingbox.BoundingBox;
import org.inventivetalent.nbt.*;
import org.inventivetalent.nbt.annotation.AnnotatedNBTHandler;
import org.inventivetalent.nbt.annotation.NBT;
import org.inventivetalent.npclib.*;
import org.inventivetalent.npclib.ai.AIAbstract;
import org.inventivetalent.npclib.annotation.NPCInfo;
import org.inventivetalent.npclib.entity.NPCEntity;
import org.inventivetalent.npclib.event.*;
import org.inventivetalent.npclib.event.nbt.NBTReadEvent;
import org.inventivetalent.npclib.event.nbt.NBTWriteEvent;
import org.inventivetalent.npclib.registry.NPCRegistry;
import org.inventivetalent.npclib.watcher.AnnotatedMethodWatcher;
import org.inventivetalent.npclib.watcher.Watch;
import org.inventivetalent.reflection.minecraft.Minecraft;
import org.inventivetalent.reflection.resolver.FieldResolver;
import org.inventivetalent.reflection.resolver.MethodResolver;
import org.inventivetalent.reflection.resolver.ResolverQuery;
import org.inventivetalent.reflection.util.AccessUtil;
import org.inventivetalent.vectors.d3.Vector3DDouble;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
public abstract class NPCAbstract<N extends NPCEntity, B extends Entity> {
protected final FieldResolver npcEntityFieldResolver;
protected final MethodResolver npcEntityMethodResolver;
protected final FieldResolver entityFieldResolver = new FieldResolver(Reflection.nmsClassResolver.resolveSilent("Entity"));
protected final MethodResolver entityMethodResolver = new MethodResolver(Reflection.nmsClassResolver.resolveSilent("Entity"));
private final N npcEntity;
private final List<AIAbstract> aiList = new ArrayList<>();
protected String pluginName;
protected AnnotatedNBTHandler nbtHandler;
@NBT(value = { "npclib.pluginData" },
type = TagID.TAG_COMPOUND)
private CompoundTag nbtData = new CompoundTag();
public NPCAbstract(N npcEntity) {
this.npcEntity = npcEntity;
this.npcEntityFieldResolver = new FieldResolver(npcEntity.getClass());
this.npcEntityMethodResolver = new MethodResolver(npcEntity.getClass());
this.npcEntity.setMethodWatcher(new AnnotatedMethodWatcher(this));
this.nbtHandler = new AnnotatedNBTHandler(this);
// postInit();
}
public void postInit(Plugin plugin, Location location) throws Exception {
this.postInit(plugin.getName(), location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch());
}
protected void postInit(String pluginName, double x, double y, double z, float yaw, float pitch) throws Exception {
if (this.pluginName != null) {
this.getPlugin().getLogger().warning("[NPCLib] Attempt to change the NPCs plugin from " + this.pluginName + " to " + pluginName);
} else {
this.pluginName = pluginName;
}
//TODO: Pathfinder
NPCRegistry.getRegistry(getPlugin()).registerNpc(this);
// Reflection.nmsClassResolver.resolve("Entity")
// .getDeclaredMethod("setLocation", double.class, double.class, double.class, float.class, float.class)
// .invoke(getNpcEntity(), location.getX(), location.getY(), location.getZ(), location.getYaw(), location.getPitch());
getNpcEntity().setLocation(x, y, z, yaw, pitch);
}
public CompoundTag getNbtData() {
return nbtData;
}
public UUID getUniqueId() {
return getBukkitEntity().getUniqueId();
}
public void spawn() {
NPCSpawnEvent event = new NPCSpawnEvent(this, CreatureSpawnEvent.SpawnReason.CUSTOM);
Bukkit.getPluginManager().callEvent(event);
getNpcEntity().spawn(event.getSpawnReason());
}
public void despawn() {
NPCDeathEvent event = new NPCDeathEvent(this, null, null);
Bukkit.getPluginManager().callEvent(event);
if (event.isCancelled()) { return; }
getBukkitEntity().remove();
}
public <A extends NPCAbstract<N, B>> boolean registerAI(AIAbstract<A> aiAbstract) {
return aiList.add(aiAbstract);
}
public void tickAI() {
for (Iterator<AIAbstract> iterator = aiList.iterator(); iterator.hasNext(); ) {
AIAbstract next = iterator.next();
next.tick();
if (next.isFinished()) {
iterator.remove();
}
}
}
public BoundingBox getAbsoluteBoundingBox() {
return BoundingBox.fromNMS(getEntityField("boundingBox"));
}
public BoundingBox getBoundingBox() {
return getAbsoluteBoundingBox().translate(new Vector3DDouble(getBukkitEntity().getLocation()).multiply(-1));
}
public void setName(String name) {
getBukkitEntity().setCustomName(name);
}
public void setNameVisible(boolean visible) {
getBukkitEntity().setCustomNameVisible(visible);
}
// NPCInfo
public NPCType getNpcType() {
return NPCType.forEntityType(getNpcEntity().getNpcInfo().getType());
}
public EntityType getEntityType() {
return getNpcEntity().getNpcInfo().getType();
}
// Watched
@Watch("void m()")
public void onBaseTick(SuperSwitch superSwitch) {
tickAI();
}
public void setMotion(double x, double y, double z) {
getNpcEntity().setMotX(x);
getNpcEntity().setMotY(y);
getNpcEntity().setMotZ(z);
}
@Watch("void move(double,double,double)")
public void onMove(ObjectContainer<Double> x, ObjectContainer<Double> y, ObjectContainer<Double> z, SuperSwitch superSwitch) {
}
@Watch("void g(double,double,double)")
public void onMotion(ObjectContainer<Double> x, ObjectContainer<Double> y, ObjectContainer<Double> z, SuperSwitch superSwitch) {
NPCVelocityEvent event = new NPCVelocityEvent(this, x.value, y.value, z.value);
Bukkit.getPluginManager().callEvent(event);
if (event.isCancelled()) {
superSwitch.setCancelled(true);
return;
}
x.value = event.getX();
y.value = event.getY();
z.value = event.getZ();
}
@Watch("void collide(Entity)")
public void onCollide(ObjectContainer<Object> entity) {
Entity bukkitEntity;
try {
bukkitEntity = Minecraft.getBukkitEntity(entity.value);
} catch (ReflectiveOperationException e) {
throw new RuntimeException(e);
}
NPCCollisionEvent event = new NPCCollisionEvent(this, bukkitEntity);
Bukkit.getPluginManager().callEvent(event);
}
@Watch("boolean damageEntity(DamageSource,float)")
public Boolean onDamage(ObjectContainer<Object> damageSource, ObjectContainer<Float> amount, SuperSwitch superSwitch) {
String sourceName = Reflection.getDamageSourceName(damageSource.value);
EntityDamageEvent.DamageCause damageCause = Reflection.damageSourceToCause(sourceName);
Entity damager = Reflection.getEntityFromDamageSource(damageSource.value);
NPCDamageEvent event = new NPCDamageEvent(this, sourceName, damageCause, amount.value, damager);
Bukkit.getPluginManager().callEvent(event);
if (event.isCancelled()) {
superSwitch.setCancelled(true);
return false;
}
amount.value = event.getAmount();
return !event.isCancelled();
}
@Watch("void die()")
public void onDie(SuperSwitch superSwitch) {
NPCDeathEvent event = new NPCDeathEvent(this, null, null);
Bukkit.getPluginManager().callEvent(event);
if (event.isCancelled()) {
superSwitch.setCancelled(true);
}
}
//NBT
@Watch("* e(NBTTagCompound)")
public void onNBTWrite(final ObjectContainer<Object> nbtTagCompound) {
NPCLib.debug("Writing", this.getClass().getName(), "to NBT");
CompoundTag compoundTag = null;
try {
compoundTag = new CompoundTag().fromNMS(nbtTagCompound.value);
writeToNBT(compoundTag);
NBTWriteEvent event = new NBTWriteEvent(this, nbtTagCompound.value, compoundTag);
Bukkit.getPluginManager().callEvent(event);
// Just replacing the nbtTagCompound.value would be easier,
// but that seems to completely mess up the NBT compound and only leaves the 'id' field.
// Merging works fine apparently.
Reflection.mergeNBTCompound(nbtTagCompound.value, compoundTag.toNMS());
} catch (ReflectiveOperationException e) {
NPCLib.debug(nbtTagCompound.value);
NPCLib.debug(compoundTag);
throw new RuntimeException("Failed to convert NBTWrite compound for", e);
}
}
@Watch("void f(NBTTagCompound)")
public void onNBTRead(ObjectContainer<Object> nbtTagCompound) {
NPCLib.debug("Reading", this.getClass().getName(), "from NBT");
CompoundTag compoundTag = null;
try {
compoundTag = new CompoundTag().fromNMS(nbtTagCompound.value);
readFromNBT(compoundTag);
NBTReadEvent event = new NBTReadEvent(this, nbtTagCompound.value, compoundTag);
Bukkit.getPluginManager().callEvent(event);
// ^ See note above
Reflection.mergeNBTCompound(nbtTagCompound.value, compoundTag.toNMS());
} catch (ReflectiveOperationException e) {
NPCLib.debug(nbtTagCompound.value);
NPCLib.debug(compoundTag);
throw new RuntimeException("Failed to convert NBTRead compound for " + nbtTagCompound.value, e);
}
}
public void writeToNBT(CompoundTag compoundTag) {
NPCType npcType = getNpcType();
compoundTag.set("npclib.type", npcType.name());
compoundTag.set("npclib.class", getNpcEntity().getNpcInfo().getNpcClass().getName());
compoundTag.set("npclib.plugin", this.pluginName);
this.nbtHandler.onWrite(compoundTag);
}
public void readFromNBT(CompoundTag compoundTag) {
if (compoundTag.has("npclib.plugin")) {
String pluginName = ((StringTag) compoundTag.get("npclib.plugin")).getValue();
if (this.pluginName != null) {
if (!this.pluginName.equals(pluginName)) {
getPlugin().getLogger().warning("[NPCLib] Tried to load plugin from NBT (" + pluginName + "), but it's already set to " + this.pluginName);
pluginName = null;
}
}
if (pluginName != null) {
String className = compoundTag.getString("npclib.class");
try {
getNpcEntity().setNpcInfo(NPCInfo.of(Class.forName(className)));
} catch (ClassNotFoundException e) {
throw new RuntimeException("Could not find NPCClass " + className + " loaded from NBT", e);
}
ListTag<DoubleTag> posList = compoundTag.getList("Pos", DoubleTag.class);
ListTag<FloatTag> rotationList = compoundTag.getList("Rotation", FloatTag.class);
try {
this.postInit(pluginName, posList.get(0).getValue(), posList.get(1).getValue(), posList.get(2).getValue(), rotationList.get(0).getValue(), rotationList.get(1).getValue());
} catch (Exception e) {
throw new RuntimeException("Failed to postInit " + this.getNpcType() + " from NBT", e);
}
}
}
this.nbtHandler.onRead(compoundTag);
}
public Plugin getPlugin() {
return Bukkit.getPluginManager().getPlugin(this.pluginName);
}
public N getNpcEntity() {
return npcEntity;
}
public B getBukkitEntity() {
return (B) invokeNPCMethod("getBukkitEntity");
}
public Object getNPCField(String field) {
return npcEntityFieldResolver.resolveWrapper(field).get(this.npcEntity);
}
public void setNPCField(String field, Object value) {
npcEntityFieldResolver.resolveWrapper(field).set(this.npcEntity, value);
}
public Object invokeNPCMethod(String method, Class[] types, Object[] args) {
return npcEntityMethodResolver.resolveWrapper(new ResolverQuery(method, types)).invoke(this.npcEntity, args);
}
public Object invokeNPCMethod(String method, Object... args) {
return npcEntityMethodResolver.resolveWrapper(method).invoke(this.npcEntity, args);
}
public Object getEntityField(String field) {
return entityFieldResolver.resolveWrapper(field).get(this.npcEntity);
}
public void setEntityField(String field, Object value) {
entityFieldResolver.resolveWrapper(field).set(this.npcEntity, value);
}
public Object invokeEntityMethod(String method, Class[] types, Object[] args) {
return entityMethodResolver.resolveWrapper(new ResolverQuery(method, types)).invoke(this.npcEntity, args);
}
public Object invokeEntityMethod(String method, Object... args) {
return entityMethodResolver.resolveWrapper(method).invoke(this.npcEntity, args);
}
protected void broadcastGlobalPacket(Object packet) {
for (Player player : Bukkit.getOnlinePlayers()) {
sendPacket(player, packet);
}
}
protected void broadcastPacket(Object packet) {
for (Player player : getBukkitEntity().getWorld().getPlayers()) {
sendPacket(player, packet);
}
}
protected void sendPacket(Player player, Object packet) {
if (player == null || packet == null) { return; }
if (player == this.getNpcEntity() || player == this.getBukkitEntity()) { return; }
if (NPCLib.isNPC(player)) { return; }
try {
Object handle = Minecraft.getHandle(player);
if (handle != null) {
Object connection = AccessUtil.setAccessible(handle.getClass().getDeclaredField("playerConnection")).get(handle);
if (connection != null) {
new MethodResolver(connection.getClass()).resolve("sendPacket").invoke(connection, packet);
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
} |
package edu.vu.isis.ammo.core.provider;
import java.util.EnumMap;
import java.util.Map;
import android.content.ContentResolver;
import android.net.Uri;
import android.provider.BaseColumns;
import edu.vu.isis.ammo.util.BaseDateColumns;
public class DistributorSchema implements BaseColumns, BaseDateColumns {
public static final String AUTHORITY = "edu.vu.isis.ammo.core.provider.distributor";
/**
* The content:// style URL for these tables
* This Uri is a Map containing all table Uris contained in the distributor database.
* The map is indexed by Relations.<TABLE_NAME>.n where n is the
* name of the enum declared in Tables.
*
* e.g.
* final Uri presenceUri = DistributorSchema.CONTENT_URI.get(Relations.PRESENCE);
*/
public static final Map<Relations, Uri> CONTENT_URI;
static {
CONTENT_URI = new EnumMap<Relations, Uri>(Relations.class);
for (Relations table : Relations.values()) {
CONTENT_URI.put(table, Uri.parse("content://"+AUTHORITY+"/"+table.n));
}
}
/**
* Special URI that when queried, returns a cursor to the number of
* queued messages per channel (where each channel is in a separate row)
*/
/**
* The MIME type of {@link #CONTENT_URI} providing a directory
*/
public static final String CONTENT_TYPE =
ContentResolver.CURSOR_DIR_BASE_TYPE+"/vnd.edu.vu.isis.ammo.core.distributor";
/**
* A mime type used for publisher subscriber.
*/
public static final String CONTENT_TOPIC =
"ammo/edu.vu.isis.ammo.core.distributor";
/**
* The MIME type of a {@link #CONTENT_URI} sub-directory of a single media entry.
*/
public static final String CONTENT_ITEM_TYPE =
ContentResolver.CURSOR_ITEM_BASE_TYPE+"/vnd.edu.vu.isis.ammo.core.distributor";
public static final String DEFAULT_SORT_ORDER = ""; //"modified_date DESC";
} |
package com.hubspot.blazar;
import com.google.common.base.Optional;
import com.google.inject.Inject;
import com.hubspot.jackson.jaxrs.PropertyFiltering;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadLocalRandom;
import static com.hubspot.blazar.BuildState.Result.IN_PROGRESS;
@Path("/builds")
@Produces(MediaType.APPLICATION_JSON)
public class BuildResource {
private static final Map<String, ModuleBuildWithState> BUILD_MAP = initialBuilds();
@Inject
public BuildResource() {}
@GET
@PropertyFiltering
public synchronized Collection<ModuleBuildWithState> test() {
updateBuildMap();
return BUILD_MAP.values();
}
private static void updateBuildMap() {
for (Entry<String, ModuleBuildWithState> entry : BUILD_MAP.entrySet()) {
ModuleBuildWithState build = entry.getValue();
do {
build = updateBuild(build);
} while (build.getBuildState().getStartTime() + 120000 < System.currentTimeMillis());
entry.setValue(build);
}
}
private static ModuleBuildWithState updateBuild(ModuleBuildWithState previous) {
if (previous.getBuildState().getResult() == IN_PROGRESS) {
long buildDuration = 15000 + ThreadLocalRandom.current().nextInt(15000);
if (System.currentTimeMillis() > previous.getBuildState().getStartTime() + buildDuration) {
BuildState p = previous.getBuildState();
Optional<Long> endTime = Optional.of(p.getStartTime() + buildDuration);
BuildState newBuildState = new BuildState(p.getBuildNumber(), p.getCommitSha(), randomCompletedResult(), p.getStartTime(), endTime);
return new ModuleBuildWithState(previous.getGitInfo(), previous.getModule(), newBuildState);
} else {
return previous;
}
} else {
long sleepDuration = 15000 + ThreadLocalRandom.current().nextInt(15000);
if (System.currentTimeMillis() > previous.getBuildState().getEndTime().get() + sleepDuration) {
BuildState p = previous.getBuildState();
long startTime = p.getEndTime().get() + sleepDuration;
BuildState newBuildState = new BuildState(p.getBuildNumber() + 1, p.getCommitSha(), IN_PROGRESS, startTime, Optional.<Long>absent());
return new ModuleBuildWithState(previous.getGitInfo(), previous.getModule(), newBuildState);
} else {
return previous;
}
}
}
private static Map<String, ModuleBuildWithState> initialBuilds() {
List<ModuleBuildWithState> builds = new ArrayList<>();
builds.add(build("Contacts", "ContactsHadoop"));
builds.add(build("HubSpotConnect"));
builds.add(build("guice-jdbi"));
builds.add(build("dropwizard-hubspot"));
builds.add(build("Wormhole"));
builds.add(build("Email", "EmailApiClient"));
builds.add(build("TaskService", "TaskServiceWorker"));
builds.add(build("InternalEmail", "InternalEmailJobs"));
builds.add(build("DeployService", "DeployServiceData"));
builds.add(build("HubSpotConfig"));
Map<String, ModuleBuildWithState> buildMap = new ConcurrentHashMap<>();
for (ModuleBuildWithState build : builds) {
buildMap.put(build.getGitInfo().getRepository(), build);
}
return buildMap;
}
private static ModuleBuildWithState build(String repoName) {
return new ModuleBuildWithState(gitInfo(repoName), new Module(repoName, "."), buildState());
}
private static ModuleBuildWithState build(String repoName, String moduleName) {
return new ModuleBuildWithState(gitInfo(repoName), new Module(moduleName, moduleName), buildState());
}
private static GitInfo gitInfo(String repository) {
return new GitInfo("git.hubteam.com", "HubSpot", repository, "master");
}
private static BuildState buildState() {
Random r = ThreadLocalRandom.current();
int buildNumber = r.nextInt(1000) + 1;
long startTime = System.currentTimeMillis() - 30000 - r.nextInt(20000);
BuildState.Result result = BuildState.Result.values()[r.nextInt(BuildState.Result.values().length)];
Optional<Long> endTime = result == IN_PROGRESS ? Optional.<Long>absent() : Optional.of(startTime + r.nextInt(30000));
return new BuildState(buildNumber, "abc", result, startTime, endTime);
}
private static BuildState.Result randomCompletedResult() {
BuildState.Result result = BuildState.Result.values()[ThreadLocalRandom.current().nextInt(BuildState.Result.values().length)];
return result == IN_PROGRESS ? randomCompletedResult() : result;
}
} |
package ca.ualberta.cs.views;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.util.Base64;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import ca.ualberta.cs.controllers.BrowseController;
import ca.ualberta.cs.controllers.ForumEntryController;
import ca.ualberta.cs.f14t07_application.R;
import ca.ualberta.cs.intent_singletons.BrowseRequestSingleton;
import ca.ualberta.cs.intent_singletons.ForumEntrySingleton;
import ca.ualberta.cs.models.Answer;
import ca.ualberta.cs.models.AuthorModel;
import ca.ualberta.cs.models.DataManager;
import ca.ualberta.cs.models.ForumEntry;
import ca.ualberta.cs.models.ForumEntryList;
import ca.ualberta.cs.models.Question;
/**
* This view allows the user to enter a new question or enter and answer to a question. The
* user does not need to differentiate between this. This view will differentiate between asking
* a question or answering a question. Then, it will present the user an appropriate interface for doing
* that.
*
* @author lexie
*/
public class AskActivity extends Activity implements Observer<ForumEntryList>
{
/*
* TODO: Do not let user make a blank question or answer
* TODO: Home screen button
* TODO: Attach a picture
*/
public Intent intent;
public Intent intent2;
public Context ctx;
private AuthorModel authorModel;
private ForumEntryController feController;
private DataManager dm;
private BrowseController browseController;
private ForumEntry forumEntry;
private static final String SUBMIT_ANSWER = "Answer";
private static final String SUBMIT_QUESTION = "Ask";
private static final String TEXT_HINT_ANSWER = "Your Answer";
private static final String TEXT_HINT_QUESTION = "Your Question";
private static final String TITLE_ANSWER = "Answer a Question";
private static final String TITLE_QUESTION = "Ask a Question";
private Uri pictureFile;
public static final int RESULT_GALLERY = 0;
private Bitmap bitmap = null;
private String image;
private byte[] pictureByteArray= new byte[64000];
/**
* lays out the screen and creates onClickListeners
*/
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.ask_activity_screen);
this.authorModel = new AuthorModel();
this.feController = new ForumEntryController(this);
this.browseController = new BrowseController(this);
/*
* Submit Button's on click listener.
*/
Button submitButton = (Button) findViewById(R.id.askButton);
submitButton.setOnClickListener(new View.OnClickListener()
{
/**
* gets necessary info and opens question screen
*/
@Override
public void onClick(View v)
{
/*
* Get an instance of the forum entry singleton so that we can check what ForumEntry it
* is focusing on (look about 9 lines below).
*/
ForumEntrySingleton forumEntryFocus = ForumEntrySingleton.getInstance();
// new edit text boxes
EditText newEntryEdit = (EditText) findViewById(R.id.question);
EditText newSubjectEdit = (EditText) findViewById(R.id.subject);
EditText newAuthorEdit = (EditText) findViewById(R.id.name);
// set strings from edit text boxes
String newEntry = newEntryEdit.getText().toString();
String newSubject = newSubjectEdit.getText().toString();
String newAuthor = newAuthorEdit.getText().toString();
if(!isAlphaNumeric(newAuthor)){
newAuthor = "Anonymous";
}
/*
* If the forumEntrySingleton is focusing on nothing (ie a null ForumEntry) then we are trying to create a
* new question. Do that, then change the focus onto the newly created ForumEntry.
*/
if(forumEntryFocus.getForumEntry() == null)
{
if(isAlphaNumeric(newSubject) && isAlphaNumeric(newEntry)){
/*
* Create an instance of the new ForumEntry then set the ForumEntrySingletons focus on it.
*/
ForumEntry newForumEntry = new ForumEntry(newSubject, newEntry, newAuthor, image);
forumEntryFocus.setForumEntry(newForumEntry);
/*
* Invoke the AddThread to add this new ForumEntry to the remote server by
* calling the controller
*/
// Save to my authored
ArrayList<ForumEntry> fel = new ArrayList<ForumEntry>();
fel = dm.getMyAuthored();
fel.add(newForumEntry);
dm.setMyAuthored(fel);
Thread thread = new AddQuestionThread(newForumEntry);
thread.start();
resetEditText(newEntryEdit, newSubjectEdit, newAuthorEdit);
startQuestionScreen();
}
else{
Toast.makeText(AskActivity.this,
"Invalid Question or Subject",
Toast.LENGTH_SHORT).show();
}
}
/*
* The ForumEntrySingleton is focusing on a ForumEntry. This means we are trying to add an answer to the focused ForumEntry.
*/
else
{
Answer answer = new Answer(newEntry, newAuthor);
/*
* Invoke the AddThread to add this answer to the ForumEntry in the remote server
* by calling controller
*/
Thread thread = new AddAnswerThread(answer);
thread.start();
startQuestionScreen();
}
resetEditText(newEntryEdit, newSubjectEdit, newAuthorEdit);
}
private void resetEditText(EditText newEntryEdit,
EditText newSubjectEdit, EditText newAuthorEdit) {
/*
* Reset the EditText widgets to be blank for the next time the activity starts
*/
newEntryEdit.setText("");
newSubjectEdit.setText("");
newAuthorEdit.setText("");
}
});
// the button the user clicks to attach a file
Button attach_button = (Button) findViewById(R.id.attachButton);
attach_button.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
GetPictureThread getpic = new GetPictureThread();
getpic.start();
}
});
}
public void startQuestionScreen(){
/*
* Start the question activity to view the new question or appended answer.
*/
intent = new Intent(AskActivity.this, QuestionActivity.class);
intent2 = intent;
/*
* This destroys the activity. Basically, this means after a user asks a question or answers one,
* they cannot come back to this activity. The back button will not bring them here.
*/
finish();
startActivity(intent);
}
public Boolean isAlphaNumeric(String s){
String checkS = s;
if(checkS.trim().length() == 0){
return false;
}
return true;
}
@Override
protected void onStart()
{
super.onStart();
ctx = this.getApplicationContext();
dm = new DataManager();
/*
* Tell the controller what ForumEntry the singleton is focusing on.
*/
this.feController.setView(ForumEntrySingleton.getInstance().getForumEntry());
/*
* Set the name of the author in the view to be the sessionAuthor in the authorModel
*/
EditText newAuthorEdit = (EditText) findViewById(R.id.name);
newAuthorEdit.setText(this.authorModel.getSessionAuthor());
/*
* If the focus of the ForumEntrySingleton is not null then we are answering a
* question, not creating one. Therefore, we need to remove the subject text element
* and change the dialog of the submit button.
*/
EditText newSubjectEdit = (EditText) findViewById(R.id.subject);
EditText textBody = (EditText) findViewById(R.id.question);
TextView titleText = (TextView) findViewById(R.id.askTitle);
Button submitButton = (Button) findViewById(R.id.askButton);
if(ForumEntrySingleton.getInstance().getForumEntry() != null)
{
newSubjectEdit.setVisibility(EditText.INVISIBLE);
submitButton.setText(AskActivity.SUBMIT_ANSWER);
textBody.setHint(AskActivity.TEXT_HINT_ANSWER);
titleText.setText(AskActivity.TITLE_ANSWER);
}
/*
* Otherwise, we are creating a question and we do want the subject text element visible.
*/
else
{
newSubjectEdit.setVisibility(EditText.VISIBLE);
submitButton.setText(AskActivity.SUBMIT_QUESTION);
textBody.setHint(AskActivity.TEXT_HINT_QUESTION);
titleText.setText(AskActivity.TITLE_QUESTION);
}
}
public void getPicture(){
Intent galleryIntent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent , RESULT_GALLERY );
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_GALLERY){
if (null != data) {
pictureFile = data.getData();
decodeUri();
bitmap =BitmapFactory.decodeFile(image);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
pictureByteArray = stream.toByteArray();
Bitmap newbitmap = BitmapFactory.decodeByteArray(pictureByteArray , 0, pictureByteArray.length);
ImageView iv = (ImageView) findViewById(R.id.picture);
iv.setImageBitmap(newbitmap);
}
}
}
public void decodeUri(){
String [] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(pictureFile, filePath, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePath[0]);
String picturePath = cursor.getString(columnIndex);
//ImageView iv = (ImageView) findViewById(R.id.picture);
//iv.setImageBitmap(BitmapFactory.decodeFile(picturePath));
image=picturePath;
}
class AddQuestionThread extends Thread
{
private ForumEntry forumEntry;
public AddQuestionThread(ForumEntry forumEntry)
{
this.forumEntry = forumEntry;
}
@Override
public void run()
{
feController.addNewQuestion(this.forumEntry);
}
}
class AddAnswerThread extends Thread
{
private Answer answer;
public AddAnswerThread(Answer answer)
{
this.answer = answer;
}
@Override
public void run()
{
feController.addAnswer(this.answer);
}
}
class GetPictureThread extends Thread
{
@Override
public void run()
{
getPicture();
}
}
@Override
public void update(ForumEntryList model)
{
// TODO Auto-generated method stub
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.ask, menu);
return true;
}
/**
* Allows user to navigate through some screens using the menu bar
*/
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
Intent intent;
intent = new Intent(this, BrowseActivity.class);
BrowseRequestSingleton.getInstance().setSearchToken(BrowseRequestSingleton.SEARCH_EVERYTHING);
switch (id)
{
case R.id.switchToMyQuestions:
/*
* Set the search and view tokens in the BrowseRequestSingleton, this way, the browse activity
* knows what to search for and what view to present when starting up.
*/
BrowseRequestSingleton.getInstance().setViewToken(BrowseRequestSingleton.MY_AUTHORED_VIEW);
startActivity(intent);
return true;
case R.id.switchToReadLaters:
/*
* Set the search and view tokens in the BrowseRequestSingleton, this way, the browse activity
* knows what to search for and what view to present when starting up.
*/
BrowseRequestSingleton.getInstance().setViewToken(BrowseRequestSingleton.READ_LATER_VIEW);
startActivity(intent);
return true;
case R.id.switchToFavourites:
/*
* Set the search and view tokens in the BrowseRequestSingleton, this way, the browse activity
* knows what to search for and what view to present when starting up.
*/
BrowseRequestSingleton.getInstance().setViewToken(BrowseRequestSingleton.FAVOURITES_VIEW);
startActivity(intent);
return true;
case R.id.switchToHome:
Intent homeIntent = new Intent(this, MainScreenActivity.class);
homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
homeIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(homeIntent);
return true;
case R.id.help:
ForumEntrySingleton forumEntryFocus = ForumEntrySingleton.getInstance();
if(forumEntryFocus.getForumEntry() == null)
{
String helpText = "This is where you can post a question to our system.\n\n" +
"To ask a question, simply fill out the Author, Subject, and Question fields. " +
"You may leave the Author field blank if you wish to remain anonymous, but we " +
"must insist that you fill in the Subject and Question fields. Please include as much " +
"relevent information as possible in your question so people are more able to comprehend " +
"and answer it. \n\n" +
"If you would like to attach an image to your question, you can click the Paperclip" +
" button to the bottom right of the Question field. This will prompt you to choose" +
" whether to get the picture from your phone's album, or take a new picture. Choose " +
"whichever best suits you.\n\n" +
"When you feel your question is complete, press the Ask button at the bottom of the screen. \n\n" +
"You can navigate to other screens either by clicking the " +
"back button, or by using the menu found by clicking the ellipsis in the corner.";
Intent helpIntent = new Intent(AskActivity.this, HelpActivity.class);
helpIntent.putExtra("HELP_TEXT", helpText);
startActivity(helpIntent);
return true;
}
else
{
String helpText = "This is where you can answer a question.\n\n" +
"To post your answer, simply fill out the Author and Answer fields. " +
"You may leave the Author field blank if you wish to remain anonymous, but we " +
"must insist that you fill in the Answer field. \n\n" +
"If you would like to attach an image to your answer, you can click the Paperclip" +
" button to the bottom right of the Answer field. This will prompt you to choose" +
" whether to get the picture from your phone's album, or take a new picture. Choose " +
"whichever best suits you.\n\n" +
"When you feel your answer is complete, press the Answer button at the bottom of the screen. \n\n" +
"You can navigate to other screens either by clicking the " +
"back button, or by using the menu found by clicking the ellipsis in the corner.";
Intent helpIntent = new Intent(AskActivity.this, HelpActivity.class);
helpIntent.putExtra("HELP_TEXT", helpText);
startActivity(helpIntent);
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
} |
package ca.ualberta.cs.views;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import ca.ualberta.cs.controllers.BrowseController;
import ca.ualberta.cs.controllers.ForumEntryController;
import ca.ualberta.cs.f14t07_application.R;
import ca.ualberta.cs.intent_singletons.BrowseRequestSingleton;
import ca.ualberta.cs.intent_singletons.ForumEntrySingleton;
import ca.ualberta.cs.models.Answer;
import ca.ualberta.cs.models.AuthorModel;
import ca.ualberta.cs.models.DataManager;
import ca.ualberta.cs.models.ForumEntry;
import ca.ualberta.cs.models.ForumEntryList;
import ca.ualberta.cs.models.Question;
/**
* This view allows the user to enter a new question or enter and answer to a question. The
* user does not need to differentiate between this. This view will differentiate between asking
* a question or answering a question. Then, it will present the user an appropriate interface for doing
* that.
*
* @author lexie
*/
public class AskActivity extends Activity implements Observer<ForumEntryList>
{
/*
* TODO: Do not let user make a blank question or answer
* TODO: Home screen button
* TODO: Attach a picture
*/
public Intent intent;
public Intent intent2;
public Context ctx;
private AuthorModel authorModel;
private ForumEntryController feController;
private DataManager dm;
private BrowseController browseController;
private ForumEntry forumEntry;
private static final String SUBMIT_ANSWER = "Answer";
private static final String SUBMIT_QUESTION = "Ask";
private static final String TEXT_HINT_ANSWER = "Your Answer";
private static final String TEXT_HINT_QUESTION = "Your Question";
private static final String TITLE_ANSWER = "Answer a Question";
private static final String TITLE_QUESTION = "Ask a Question";
private Uri pictureFile;
public static final int RESULT_GALLERY = 0;
private Bitmap bitmap = null;
private String image=null;
private byte[] pictureByteArray= new byte[64000];
/**
* lays out the screen and creates onClickListeners
*/
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.ask_activity_screen);
this.authorModel = new AuthorModel();
this.feController = new ForumEntryController(this);
this.browseController = new BrowseController(this);
/*
* Submit Button's on click listener.
*/
Button submitButton = (Button) findViewById(R.id.askButton);
submitButton.setOnClickListener(new View.OnClickListener()
{
/**
* gets necessary info and opens question screen
*/
@Override
public void onClick(View v)
{
/*
* Get an instance of the forum entry singleton so that we can check what ForumEntry it
* is focusing on (look about 9 lines below).
*/
ForumEntrySingleton forumEntryFocus = ForumEntrySingleton.getInstance();
// new edit text boxes
EditText newEntryEdit = (EditText) findViewById(R.id.question);
EditText newSubjectEdit = (EditText) findViewById(R.id.subject);
EditText newAuthorEdit = (EditText) findViewById(R.id.name);
// set strings from edit text boxes
String newEntry = newEntryEdit.getText().toString();
String newSubject = newSubjectEdit.getText().toString();
String newAuthor = newAuthorEdit.getText().toString();
if(!isAlphaNumeric(newAuthor)){
newAuthor = "Anonymous";
}
/*
* If the forumEntrySingleton is focusing on nothing (ie a null ForumEntry) then we are trying to create a
* new question. Do that, then change the focus onto the newly created ForumEntry.
*/
if(forumEntryFocus.getForumEntry() == null)
{
if(isAlphaNumeric(newSubject) && isAlphaNumeric(newEntry)){
/*
* Create an instance of the new ForumEntry then set the ForumEntrySingletons focus on it.
*/
ForumEntry newForumEntry = new ForumEntry(newSubject, newEntry, newAuthor, image);
forumEntryFocus.setForumEntry(newForumEntry);
/*
* Invoke the AddThread to add this new ForumEntry to the remote server by
* calling the controller
*/
// Save to my authored
ArrayList<ForumEntry> fel = new ArrayList<ForumEntry>();
fel = dm.getMyAuthored();
fel.add(newForumEntry);
dm.setMyAuthored(fel);
Thread thread = new AddQuestionThread(newForumEntry);
thread.start();
resetEditText(newEntryEdit, newSubjectEdit, newAuthorEdit);
startQuestionScreen();
}
else{
Toast.makeText(AskActivity.this,
"Invalid Question or Subject",
Toast.LENGTH_SHORT).show();
}
}
/*
* The ForumEntrySingleton is focusing on a ForumEntry. This means we are trying to add an answer to the focused ForumEntry.
*/
else
{
Answer answer = new Answer(newEntry, newAuthor);
/*
* Invoke the AddThread to add this answer to the ForumEntry in the remote server
* by calling controller
*/
Thread thread = new AddAnswerThread(answer);
thread.start();
startQuestionScreen();
}
resetEditText(newEntryEdit, newSubjectEdit, newAuthorEdit);
}
private void resetEditText(EditText newEntryEdit,
EditText newSubjectEdit, EditText newAuthorEdit) {
/*
* Reset the EditText widgets to be blank for the next time the activity starts
*/
newEntryEdit.setText("");
newSubjectEdit.setText("");
newAuthorEdit.setText("");
}
});
// the button the user clicks to attach a file
Button attach_button = (Button) findViewById(R.id.attachButton);
attach_button.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
GetPictureThread getpic = new GetPictureThread();
getpic.start();
}
});
}
public void startQuestionScreen(){
/*
* Start the question activity to view the new question or appended answer.
*/
intent = new Intent(AskActivity.this, QuestionActivity.class);
intent2 = intent;
/*
* This destroys the activity. Basically, this means after a user asks a question or answers one,
* they cannot come back to this activity. The back button will not bring them here.
*/
finish();
startActivity(intent);
}
public Boolean isAlphaNumeric(String s){
String checkS = s;
if(checkS.trim().length() == 0){
return false;
}
return true;
}
@Override
protected void onStart()
{
super.onStart();
ctx = this.getApplicationContext();
dm = new DataManager();
/*
* Tell the controller what ForumEntry the singleton is focusing on.
*/
this.feController.setView(ForumEntrySingleton.getInstance().getForumEntry());
/*
* Set the name of the author in the view to be the sessionAuthor in the authorModel
*/
EditText newAuthorEdit = (EditText) findViewById(R.id.name);
newAuthorEdit.setText(this.authorModel.getSessionAuthor());
/*
* If the focus of the ForumEntrySingleton is not null then we are answering a
* question, not creating one. Therefore, we need to remove the subject text element
* and change the dialog of the submit button.
*/
EditText newSubjectEdit = (EditText) findViewById(R.id.subject);
EditText textBody = (EditText) findViewById(R.id.question);
TextView titleText = (TextView) findViewById(R.id.askTitle);
Button submitButton = (Button) findViewById(R.id.askButton);
if(ForumEntrySingleton.getInstance().getForumEntry() != null)
{
newSubjectEdit.setVisibility(EditText.INVISIBLE);
submitButton.setText(AskActivity.SUBMIT_ANSWER);
textBody.setHint(AskActivity.TEXT_HINT_ANSWER);
titleText.setText(AskActivity.TITLE_ANSWER);
}
/*
* Otherwise, we are creating a question and we do want the subject text element visible.
*/
else
{
newSubjectEdit.setVisibility(EditText.VISIBLE);
submitButton.setText(AskActivity.SUBMIT_QUESTION);
textBody.setHint(AskActivity.TEXT_HINT_QUESTION);
titleText.setText(AskActivity.TITLE_QUESTION);
}
}
public void getPicture(){
Intent galleryIntent = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(galleryIntent , RESULT_GALLERY );
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RESULT_GALLERY){
if (null != data) {
pictureFile = data.getData();
decodeUri();
bitmap =BitmapFactory.decodeFile(image);
if ((bitmap.getRowBytes() * bitmap.getHeight()) > 64000){
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG,100, stream);
byte [] b=stream.toByteArray();
String temp=Base64.encodeToString(b, Base64.DEFAULT);
Bitmap newbitmap=null;
try {
byte [] encodeByte=Base64.decode(temp,Base64.DEFAULT);
newbitmap=BitmapFactory.decodeByteArray(encodeByte, 0, encodeByte.length);
} catch(Exception e) {
e.getMessage();
}
ImageView iv = (ImageView) findViewById(R.id.picture);
iv.setImageBitmap(newbitmap);
}
else{
Toast.makeText(AskActivity.this,"Image too big",Toast.LENGTH_SHORT).show();
image=null;
}
}
}
}
public void decodeUri(){
String [] filePath = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(pictureFile, filePath, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePath[0]);
String picturePath = cursor.getString(columnIndex);
//ImageView iv = (ImageView) findViewById(R.id.picture);
//iv.setImageBitmap(BitmapFactory.decodeFile(picturePath));
image=picturePath;
}
class AddQuestionThread extends Thread
{
private ForumEntry forumEntry;
public AddQuestionThread(ForumEntry forumEntry)
{
this.forumEntry = forumEntry;
}
@Override
public void run()
{
feController.addNewQuestion(this.forumEntry);
}
}
class AddAnswerThread extends Thread
{
private Answer answer;
public AddAnswerThread(Answer answer)
{
this.answer = answer;
}
@Override
public void run()
{
feController.addAnswer(this.answer);
}
}
class GetPictureThread extends Thread
{
@Override
public void run()
{
getPicture();
}
}
@Override
public void update(ForumEntryList model)
{
// TODO Auto-generated method stub
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.ask, menu);
return true;
}
/**
* Allows user to navigate through some screens using the menu bar
*/
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
Intent intent;
intent = new Intent(this, BrowseActivity.class);
BrowseRequestSingleton.getInstance().setSearchToken(BrowseRequestSingleton.SEARCH_EVERYTHING);
switch (id)
{
case R.id.switchToMyQuestions:
/*
* Set the search and view tokens in the BrowseRequestSingleton, this way, the browse activity
* knows what to search for and what view to present when starting up.
*/
BrowseRequestSingleton.getInstance().setViewToken(BrowseRequestSingleton.MY_AUTHORED_VIEW);
startActivity(intent);
return true;
case R.id.switchToReadLaters:
/*
* Set the search and view tokens in the BrowseRequestSingleton, this way, the browse activity
* knows what to search for and what view to present when starting up.
*/
BrowseRequestSingleton.getInstance().setViewToken(BrowseRequestSingleton.READ_LATER_VIEW);
startActivity(intent);
return true;
case R.id.switchToFavourites:
/*
* Set the search and view tokens in the BrowseRequestSingleton, this way, the browse activity
* knows what to search for and what view to present when starting up.
*/
BrowseRequestSingleton.getInstance().setViewToken(BrowseRequestSingleton.FAVOURITES_VIEW);
startActivity(intent);
return true;
case R.id.switchToHome:
Intent homeIntent = new Intent(this, MainScreenActivity.class);
homeIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
homeIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(homeIntent);
return true;
case R.id.help:
ForumEntrySingleton forumEntryFocus = ForumEntrySingleton.getInstance();
if(forumEntryFocus.getForumEntry() == null)
{
String helpText = "This is where you can post a question to our system.\n\n" +
"To ask a question, simply fill out the Author, Subject, and Question fields. " +
"You may leave the Author field blank if you wish to remain anonymous, but we " +
"must insist that you fill in the Subject and Question fields. Please include as much " +
"relevent information as possible in your question so people are more able to comprehend " +
"and answer it. \n\n" +
"If you would like to attach an image to your question, you can click the Paperclip" +
" button to the bottom right of the Question field. This will prompt you to choose" +
" whether to get the picture from your phone's album, or take a new picture. Choose " +
"whichever best suits you.\n\n" +
"When you feel your question is complete, press the Ask button at the bottom of the screen. \n\n" +
"You can navigate to other screens either by clicking the " +
"back button, or by using the menu found by clicking the ellipsis in the corner.";
Intent helpIntent = new Intent(AskActivity.this, HelpActivity.class);
helpIntent.putExtra("HELP_TEXT", helpText);
startActivity(helpIntent);
return true;
}
else
{
String helpText = "This is where you can answer a question.\n\n" +
"To post your answer, simply fill out the Author and Answer fields. " +
"You may leave the Author field blank if you wish to remain anonymous, but we " +
"must insist that you fill in the Answer field. \n\n" +
"If you would like to attach an image to your answer, you can click the Paperclip" +
" button to the bottom right of the Answer field. This will prompt you to choose" +
" whether to get the picture from your phone's album, or take a new picture. Choose " +
"whichever best suits you.\n\n" +
"When you feel your answer is complete, press the Answer button at the bottom of the screen. \n\n" +
"You can navigate to other screens either by clicking the " +
"back button, or by using the menu found by clicking the ellipsis in the corner.";
Intent helpIntent = new Intent(AskActivity.this, HelpActivity.class);
helpIntent.putExtra("HELP_TEXT", helpText);
startActivity(helpIntent);
return true;
}
default:
return super.onOptionsItemSelected(item);
}
}
public Context getContext() {
// TODO Auto-generated method stub
return this;
}
} |
package org.waterforpeople.mapping.dataexport;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.swing.JApplet;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.app.VelocityEngine;
import org.waterforpeople.mapping.app.gwt.client.location.PlacemarkDto;
import org.waterforpeople.mapping.app.gwt.client.location.PlacemarkDtoResponse;
import org.waterforpeople.mapping.dataexport.service.BulkDataServiceClient;
public class KMLApplet extends JApplet implements Runnable {
private static final long serialVersionUID = -450706177231338054L;
private JLabel statusLabel;
private String serverBase;
private VelocityEngine engine;
@Override
public void run() {
try {
SwingUtilities.invokeLater(new StatusUpdater("Prompting for File"));
String filePath = promptForFile();
if (filePath != null) {
System.out.println(filePath);
SwingUtilities.invokeLater(new StatusUpdater("Running export"));
executeExport(filePath);
SwingUtilities
.invokeLater(new StatusUpdater("Export Complete"));
} else {
SwingUtilities.invokeLater(new StatusUpdater("Cancelled"));
}
} catch (Exception e) {
SwingUtilities
.invokeLater(new StatusUpdater("Backout Failed: " + e));
}
}
ClassLoader cl = null;
public void init() {
cl = this.getClass().getClassLoader();
engine = new VelocityEngine();
engine.setProperty("runtime.log.logsystem.class",
"org.apache.velocity.runtime.log.NullLogChute");
try {
engine.init();
} catch (Exception e) {
System.out.println("Could not initialize velocity" + e);
}
statusLabel = new JLabel();
getContentPane().add(statusLabel);
if (getParameter("serverOverride") != null
&& getParameter("serverOverride").trim().length() > 0) {
serverBase = getParameter("serverOverride").trim();
} else {
serverBase = getCodeBase().toString();
}
if (serverBase.trim().endsWith("/")) {
serverBase = serverBase.trim().substring(0,
serverBase.lastIndexOf("/"));
}
System.out.println("ServerBase: " + serverBase);
Thread worker = new Thread(this);
worker.start();
}
private void executeExport(String path) {
try {
System.out.println("File to save to: " + path);
ArrayList<String> countryList = new ArrayList<String>();
countryList.add("BF");
countryList.add("MW");
countryList.add("RW");
countryList.add("BO");
countryList.add("PE");
countryList.add("GT");
countryList.add("IN");
countryList.add("NI");
countryList.add("SV");
countryList.add("LR");
countryList.add("HT");
countryList.add("ID");
countryList.add("SD");
countryList.add("NG");
countryList.add("NP");
countryList.add("EC");
countryList.add("GN");
countryList.add("CI");
countryList.add("CM");
countryList.add("NG");
countryList.add("SL");
countryList.add("DO");
countryList.add("GH");
countryList.add("UG");
processFile(path, countryList);
} catch (Exception e1) {
e1.printStackTrace();
}
}
private void processFile(String fileName, ArrayList<String> countryList)
throws Exception {
System.out.println("Calling GenerateDocument");
VelocityContext context = new VelocityContext();
File f = new File(fileName);
if (!f.exists()) {
f.createNewFile();
}
ZipOutputStream zipOut = null;
try {
zipOut = new ZipOutputStream(new FileOutputStream(fileName));
zipOut.setLevel(ZipOutputStream.DEFLATED);
ZipEntry entry = new ZipEntry("ap.kml");
zipOut.putNextEntry(entry);
zipOut.write(mergeContext(context, "template/DocumentHead.vm")
.getBytes("UTF-8"));
for (String countryCode : countryList) {
int i = 0;
String cursor = null;
PlacemarkDtoResponse pdr = BulkDataServiceClient
.fetchPlacemarks(countryCode, serverBase, cursor);
if (pdr != null) {
cursor = pdr.getCursor();
List<PlacemarkDto> placemarkDtoList = pdr.getDtoList();
SwingUtilities.invokeLater(new StatusUpdater(
"Staring to processes " + countryCode));
writePlacemark(placemarkDtoList, zipOut);
SwingUtilities.invokeLater(new StatusUpdater(
"Processing complete for " + countryCode));
while (cursor != null) {
pdr = BulkDataServiceClient.fetchPlacemarks(
countryCode, serverBase, cursor);
if (pdr != null) {
if (pdr.getCursor() != null)
cursor = pdr.getCursor();
else
cursor = null;
placemarkDtoList = pdr.getDtoList();
System.out.println("Starting to process: "
+ countryCode);
writePlacemark(placemarkDtoList, zipOut);
System.out
.println("Fetching next set of records for: "
+ countryCode + " : " + i++);
} else {
break;
}
}
}
}
zipOut.write(mergeContext(context, "template/DocumentFooter.vm")
.getBytes("UTF-8"));
zipOut.closeEntry();
zipOut.close();
} catch (Exception ex) {
System.out.println(ex + " " + ex.getMessage() + " ");
ex.printStackTrace(System.out);
}
}
private void writePlacemark(List<PlacemarkDto> placemarkDtoList,
ZipOutputStream zipOut) throws Exception {
if (placemarkDtoList != null) {
for (PlacemarkDto pm : placemarkDtoList) {
if (pm != null) {
if (pm.getCollectionDate() != null
&& pm.getLatitude() != null
&& pm.getLatitude() != 0
&& pm.getLongitude() != null
&& pm.getLongitude() != 0) {
VelocityContext vc = new VelocityContext();
String timestamp = DateFormatUtils.formatUTC(
pm.getCollectionDate(),
DateFormatUtils.ISO_DATE_FORMAT.getPattern());
vc.put("timestamp", timestamp);
vc.put("pinStyle", pm.getPinStyle());
vc.put("balloon", pm.getPlacemarkContents());
vc.put("longitude", pm.getLongitude());
vc.put("latitude", pm.getLatitude());
vc.put("altitude", pm.getAltitude());
vc.put("communityCode", pm.getCommunityCode());
vc.put("communityName", pm.getCommunityCode());
String placemark = mergeContext(vc,
"template/PlacemarksNewLook.vm");
zipOut.write(placemark.getBytes("UTF-8"));
}
}
}
}
}
private String promptForFile() {
JFileChooser fc = new JFileChooser();
int returnVal = fc.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
return fc.getSelectedFile().getAbsolutePath();
} else {
return null;
}
}
/**
* merges a hydrated context with a template identified by the templateName
* passed in.
*
* @param context
* @param templateName
* @return
* @throws Exception
*/
private String mergeContext(VelocityContext context, String templateName)
throws Exception {
String templateContents = loadResourceAsString(templateName);
StringWriter writer = new StringWriter();
Velocity.evaluate(context, writer, "mystring", templateContents);
return writer.toString();
}
private String loadResourceAsString(String resourceName) throws Exception {
InputStream in = cl.getResourceAsStream(resourceName);
String resourceContents = readInputStreamAsString(in);
return resourceContents;
}
public static String readInputStreamAsString(InputStream in)
throws IOException {
BufferedInputStream bis = new BufferedInputStream(in);
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int result = bis.read();
while (result != -1) {
byte b = (byte) result;
buf.write(b);
result = bis.read();
}
return buf.toString();
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
}
/**
* Private class to handle updating of the UI thread from our worker thread
*/
private class StatusUpdater implements Runnable {
private String status;
public StatusUpdater(String val) {
status = val;
}
public void run() {
statusLabel.setText(status);
}
}
} |
package com.rgi.geopackage.tiles;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import utility.DatabaseUtility;
import com.rgi.common.BoundingBox;
import com.rgi.common.coordinate.Coordinate;
import com.rgi.common.coordinate.CoordinateReferenceSystem;
import com.rgi.common.coordinate.CrsCoordinate;
import com.rgi.common.coordinate.referencesystem.profile.Utility;
import com.rgi.common.tile.TileOrigin;
import com.rgi.common.util.jdbc.ResultSetStream;
import com.rgi.geopackage.core.GeoPackageCore;
import com.rgi.geopackage.core.SpatialReferenceSystem;
import com.rgi.geopackage.verification.FailedRequirement;
/**
* @author Luke Lambert
*
*/
public class GeoPackageTiles
{
/**
* Constructor
*
* @param databaseConnection
* The open connection to the database that contains a GeoPackage
* @param core
* Access to GeoPackage's "core" methods
*/
public GeoPackageTiles(final Connection databaseConnection, final GeoPackageCore core)
{
this.databaseConnection = databaseConnection;
this.core = core;
}
/**
* Requirements this GeoPackage failed to meet
*
* @return The tile GeoPackage requirements this GeoPackage fails to conform to
* @throws SQLException throws if {@link TilesVerifier#TilesVerifier(Connection) Verifier Constructor} throws
*/
public Collection<FailedRequirement> getFailedRequirements() throws SQLException
{
return new TilesVerifier(this.databaseConnection).getFailedRequirements();
}
/**
* Creates a user defined tiles table, and adds a corresponding entry to the
* content table
*
* @param tableName
* The name of the tiles table. The table name must begin with a
* letter (A..Z, a..z) or an underscore (_) and may only be
* followed by letters, underscores, or numbers, and may not
* begin with the prefix "gpkg_"
* @param identifier
* A human-readable identifier (e.g. short name) for the
* tableName content
* @param description
* A human-readable description for the tableName content
* @param boundingBox
* Bounding box for all content in tableName
* @param spatialReferenceSystem
* Spatial Reference System (SRS)
* @return Returns a newly created user defined tiles table
* @throws SQLException
* throws if the method {@link #getTileSet(String) getTileSet}
* or the method
* {@link DatabaseUtility#tableOrViewExists(Connection, String)
* tableOrViewExists} or if the database cannot rollback the
* changes after a different exception throws will throw an SQLException
*
*/
public TileSet addTileSet(final String tableName,
final String identifier,
final String description,
final BoundingBox boundingBox,
final SpatialReferenceSystem spatialReferenceSystem) throws SQLException
{
if(tableName == null || tableName.isEmpty())
{
throw new IllegalArgumentException("Tile set name may not be null");
}
if(!tableName.matches("^[_a-zA-Z]\\w*"))
{
throw new IllegalArgumentException("The tile set's table name must begin with a letter (A..Z, a..z) or an underscore (_) and may only be followed by letters, underscores, or numbers");
}
if(tableName.startsWith("gpkg_"))
{
throw new IllegalArgumentException("The tile set's name may not start with the reserved prefix 'gpkg_'");
}
if(boundingBox == null)
{
throw new IllegalArgumentException("Bounding box cannot be mull.");
}
final TileSet existingContent = this.getTileSet(tableName);
if(existingContent != null)
{
if(existingContent.equals(tableName,
TileSet.TileContentType,
identifier,
description,
boundingBox,
spatialReferenceSystem.getOrganizationSrsId()))
{
return existingContent;
}
throw new IllegalArgumentException("An entry in the content table already exists with this table name, but has different values for its other fields");
}
if(DatabaseUtility.tableOrViewExists(this.databaseConnection, tableName))
{
throw new IllegalArgumentException("A table already exists with this tile set's table name");
}
try
{
this.createTilesTablesNoCommit(); // Create the tile metadata tables
// Create the tile set table
try(Statement statement = this.databaseConnection.createStatement())
{
statement.executeUpdate(this.getTileSetCreationSql(tableName));
}
// Add tile set to the content table
this.core.addContent(tableName,
TileSet.TileContentType,
identifier,
description,
boundingBox,
spatialReferenceSystem);
this.addTileMatrixSetNoCommit(tableName,
boundingBox,
spatialReferenceSystem); // Add tile matrix set metadata
this.databaseConnection.commit();
return this.getTileSet(tableName);
}
catch(final Exception ex)
{
this.databaseConnection.rollback();
throw ex;
}
}
/**
* The zoom levels that a tile set has values for
*
* @param tileSet
* A handle to a set of tiles
* @return Returns all of the zoom levels that apply for tileSet
* @throws SQLException
* SQLException thrown by automatic close() invocation on preparedStatement or various other SQLExceptions
*/
public Set<Integer> getTileZoomLevels(final TileSet tileSet) throws SQLException
{
if(tileSet == null)
{
throw new IllegalArgumentException("Tile set cannot be null");
}
final String zoomLevelQuerySql = String.format("SELECT zoom_level FROM %s WHERE table_name = ?;",
GeoPackageTiles.MatrixTableName);
try(PreparedStatement preparedStatement = this.databaseConnection.prepareStatement(zoomLevelQuerySql))
{
preparedStatement.setString(1, tileSet.getTableName());
try(ResultSet results = preparedStatement.executeQuery())
{
final Set<Integer> zoomLevels = new HashSet<>();
while(results.next())
{
zoomLevels.add(results.getInt(1));
}
return zoomLevels;
}
}
}
/**
* Gets all entries in the GeoPackage's contents table with the "tiles"
* data_type
*
* @return Returns a collection of {@link TileSet}s
* @throws SQLException
* throws if the method
* {@link #getTileSets(SpatialReferenceSystem) getTileSets}
* throws
*/
public Collection<TileSet> getTileSets() throws SQLException
{
return this.getTileSets(null);
}
/**
* Gets all entries in the GeoPackage's contents table with the "tiles"
* data_type that also match the supplied spatial reference system
*
* @param matchingSpatialReferenceSystem
* Spatial reference system that returned {@link TileSet}s much
* refer to
* @return Returns a collection of {@link TileSet}s
* @throws SQLException
* throws if the method
* {@link GeoPackageCore#getContent(String, com.rgi.geopackage.core.ContentFactory, SpatialReferenceSystem)
* getContent} throws
*/
public Collection<TileSet> getTileSets(final SpatialReferenceSystem matchingSpatialReferenceSystem) throws SQLException
{
return this.core.getContent(TileSet.TileContentType,
(tableName, dataType, identifier, description, lastChange, boundingBox, spatialReferenceSystem) -> new TileSet(tableName, identifier, description, lastChange, boundingBox, spatialReferenceSystem),
matchingSpatialReferenceSystem);
}
/**
* Adds a tile matrix
*
* @param tileSet
* A handle to a tile set
* @param zoomLevel
* The zoom level of the associated tile set (0 <= zoomLevel <=
* max_level)
* @param matrixWidth
* The number of columns (>= 1) for this tile at this zoom level
* @param matrixHeight
* The number of rows (>= 1) for this tile at this zoom level
* @param tileWidth
* The tile width in pixels (>= 1) at this zoom level
* @param tileHeight
* The tile height in pixels (>= 1) at this zoom level
* @param pixelXSize
* The width of the associated tile set's spatial reference
* system or default meters for an undefined geographic
* coordinate reference system (SRS id 0) (> 0)
* @param pixelYSize
* The height of the associated tile set's spatial reference
* system or default meters for an undefined geographic
* coordinate reference system (SRS id 0) (> 0)
* @return Returns the newly added tile matrix
* @throws SQLException
* throws when the method {@link #getTileMatrix(TileSet, int)
* getTileMatrix(TileSet, int)} or the method
* {@link #getTileMatrixSet(TileSet) getTileMatrixSet} or the
* database cannot roll back the changes after a different
* exception is thrown, an SQLException is thrown
*/
public TileMatrix addTileMatrix(final TileSet tileSet,
final int zoomLevel,
final int matrixWidth,
final int matrixHeight,
final int tileWidth,
final int tileHeight,
final double pixelXSize,
final double pixelYSize) throws SQLException
{
if(tileSet == null)
{
throw new IllegalArgumentException("The tile set may not be null");
}
if(zoomLevel < 0)
{
throw new IllegalArgumentException("Zoom level must be greater than or equal to 0");
}
if(matrixWidth <= 0)
{
throw new IllegalArgumentException("Matrix width must be greater than 0");
}
if(matrixHeight <= 0)
{
throw new IllegalArgumentException("Matrix height must be greater than 0");
}
if(tileWidth <= 0)
{
throw new IllegalArgumentException("Tile width must be greater than 0");
}
if(tileHeight <= 0)
{
throw new IllegalArgumentException("Matrix height must be greater than 0");
}
if(pixelXSize <= 0.0)
{
throw new IllegalArgumentException("Pixel X size must be greater than 0.0");
}
if(pixelYSize <= 0.0)
{
throw new IllegalArgumentException("Pixel Y size must be greater than 0.0");
}
final TileMatrix tileMatrix = this.getTileMatrix(tileSet, zoomLevel);
if(tileMatrix != null)
{
if(!tileMatrix.equals(tileSet.getTableName(),
zoomLevel,
matrixWidth,
matrixHeight,
tileWidth,
tileHeight,
pixelXSize,
pixelYSize))
{
throw new IllegalArgumentException("An entry in the content table already exists with this table name, but has different values for its other fields");
}
return tileMatrix;
}
final TileMatrixSet tileMatrixSet = this.getTileMatrixSet(tileSet);
if(tileMatrixSet == null)
{
throw new IllegalArgumentException("Cannot add a tile matrix to a tile set with no tile matrix set."); // TODO do we need to expose addTileMatrixSet() to help avoid ever getting here? a tile matrix set is created automatically by this API on tile set creation, and the verifier insures that there's one for every tile set.
}
if(matrixHeight * tileHeight * pixelYSize != tileMatrixSet.getBoundingBox().getHeight()) // TODO instead of testing for equality, test with an EPSILON tolerance ?
{
throw new IllegalArgumentException("The geographic height of the tile matrix [matrix height * tile height (pixels) * pixel y size (srs units per pixel)] differs from the minimum bounds for this tile set specified by the tile matrix set");
}
if(matrixWidth * tileWidth * pixelXSize != tileMatrixSet.getBoundingBox().getWidth()) // TODO instead of testing for equality, test with an EPSILON tolerance ?
{
throw new IllegalArgumentException("The geographic width of the tile matrix [matrix width * tile width (pixels) * pixel x size (srs units per pixel)] differs from the minimum bounds for this tile set specified by the tile matrix set");
}
try
{
final String insertTileMatrix = String.format("INSERT INTO %s (%s, %s, %s, %s, %s, %s, %s, %s) VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
GeoPackageTiles.MatrixTableName,
"table_name",
"zoom_level",
"matrix_width",
"matrix_height",
"tile_width",
"tile_height",
"pixel_x_size",
"pixel_y_size");
try(PreparedStatement preparedStatement = this.databaseConnection.prepareStatement(insertTileMatrix))
{
preparedStatement.setString(1, tileSet.getTableName());
preparedStatement.setInt (2, zoomLevel);
preparedStatement.setInt (3, matrixWidth);
preparedStatement.setInt (4, matrixHeight);
preparedStatement.setInt (5, tileWidth);
preparedStatement.setInt (6, tileHeight);
preparedStatement.setDouble(7, pixelXSize);
preparedStatement.setDouble(8, pixelYSize);
preparedStatement.executeUpdate();
}
this.databaseConnection.commit();
return new TileMatrix(tileSet.getTableName(),
zoomLevel,
matrixWidth,
matrixHeight,
tileWidth,
tileHeight,
pixelXSize,
pixelYSize);
}
catch(final SQLException ex)
{
this.databaseConnection.rollback();
throw ex;
}
}
/**
* Add a tile to the GeoPackage
*
* @param tileSet
* Tile set that which the tiles and tile metadata are associated
* @param tileMatrix
* Tile matrix associated with the tile set at the corresponding
* zoom level
* @param coordinate
* The coordinate of the tile, relative to the tile set
* @param imageData
* The bytes of the image file
* @return The Tile added to the GeoPackage with the properties of the
* parameters
* @throws SQLException
* SQLException thrown by automatic close() invocation on
* preparedStatement or if the Database is unable to commit the
* changes or if the method
* {@link #getTile(TileSet, RelativeTileCoordinate) getTile}
* throws an SQLException or other various SQLExceptions
*/
public Tile addTile(final TileSet tileSet,
final TileMatrix tileMatrix,
final RelativeTileCoordinate coordinate,
final byte[] imageData) throws SQLException
{
if(tileSet == null)
{
throw new IllegalArgumentException("Tile set may not be null");
}
if(tileMatrix == null)
{
throw new IllegalArgumentException("Tile matrix may not be null");
}
if(coordinate == null)
{
throw new IllegalArgumentException("Coordinate may not be null");
}
if(imageData == null || imageData.length == 0) // TODO the standard restricts the image types to image/jpeg, image/png and image/x-webp (by extension only: http://www.geopackage.org/spec/#extension_tiles_webp)
// TODO It'd be desirable to check the height/width of the image against the values described by the tile matrix, but this is difficult to do with a string of bytes. One solution would be to changed to a java BufferedImage rather than raw bytes, but this *might* unnecessarily confine extension writers to to formats that fit into Java.ImageIO
{
throw new IllegalArgumentException("Image data may not be null or empty");
}
if(coordinate.getZoomLevel() != tileMatrix.getZoomLevel())
{
throw new IllegalArgumentException("The zoom level of the tile coordinate must match the zoom level of the tile matrix");
}
final int row = coordinate.getRow();
final int column = coordinate.getColumn();
// Verify row and column are within the tile metadata's range
if(row < 0 || row >= tileMatrix.getMatrixHeight())
{
throw new IllegalArgumentException(String.format("Tile row %d is outside of the valid row range [0, %d] (0 to tile matrix metadata's matrix height - 1)",
row,
tileMatrix.getMatrixHeight()-1));
}
if(column < 0 || column >= tileMatrix.getMatrixWidth())
{
throw new IllegalArgumentException(String.format("Tile column %d is outside of the valid column range [0, %d] (0 to tile matrix metadata's matrix width - 1)",
column,
tileMatrix.getMatrixWidth()-1));
}
final String insertTileSql = String.format("INSERT INTO %s (%s, %s, %s, %s) VALUES (?, ?, ?, ?)",
tileSet.getTableName(),
"zoom_level",
"tile_column",
"tile_row",
"tile_data");
try(final PreparedStatement preparedStatement = this.databaseConnection.prepareStatement(insertTileSql))
{
preparedStatement.setInt (1, coordinate.getZoomLevel());
preparedStatement.setInt (2, coordinate.getColumn());
preparedStatement.setInt (3, coordinate.getRow());
preparedStatement.setBytes(4, imageData);
preparedStatement.executeUpdate();
}
this.databaseConnection.commit();
return this.getTile(tileSet, coordinate);
}
/**
* Add a tile to the GeoPackage
*
* @param tileSet
* Tile set that which the tiles and tile metadata are associated
* @param tileMatrix
* Tile matrix associated with the tile set at the corresponding
* zoom level
* @param coordinate
* The coordinate of the tile in units of the tile set's spatial
* reference system
* @param precision
* Specifies a tolerance for coordinate value testings to a number of decimal places
* @param zoomLevel
* Zoom level
* @param imageData
* The bytes of the image file
* @return returns a Tile added to the GeoPackage with the properties of the
* parameters
* @throws SQLException
* is thrown if the following methods throw
* {@link #crsToRelativeTileCoordinate(TileSet, CrsCoordinate, int, int)
* crsToRelativeTileCoordinate} or
* {@link #addTile(TileSet, TileMatrix, RelativeTileCoordinate, byte[])
* addTile} throws an SQLException
*/
public Tile addTile(final TileSet tileSet,
final TileMatrix tileMatrix,
final CrsCoordinate coordinate,
final int precision,
final int zoomLevel,
final byte[] imageData) throws SQLException
{
final RelativeTileCoordinate relativeCoordinate = this.crsToRelativeTileCoordinate(tileSet,
coordinate,
precision,
zoomLevel);
return relativeCoordinate != null ? this.addTile(tileSet,
tileMatrix,
relativeCoordinate,
imageData)
: null;
}
// public Tile updateTile(final TileSet tileSet,
// final Tile tile,
// final byte[] imageData) throws SQLException
// if(tileSet == null)
// if(tile == null)
// if(imageData == null)
// final String updateTileSql = String.format("UPDATE %s SET %s = ? WHERE %s = ? AND %s = ? AND %s = ?",
// tileSet.getTableName(),
// "tile_data",
// "zoom_level",
// "tile_column",
// "tile_row");
// try(final PreparedStatement preparedStatement = this.databaseConnection.prepareStatement(updateTileSql))
// preparedStatement.setInt (2, tile.getZoomLevel());
// preparedStatement.setInt (3, tile.getColumn());
// preparedStatement.setInt (4, tile.getRow());
// preparedStatement.executeUpdate();
// this.databaseConnection.commit();
// return new Tile(tile.getIdentifier(),
// tile.getZoomLevel(),
// tile.getRow(),
// tile.getColumn(),
// imageData);
/**
* Gets tile coordinates for every tile in a tile set. A tile set need not
* have an entry for every possible position in its respective tile
* matrices.
*
* @param tileSet
* Handle to the tile set that the requested tiles should belong
* @return Returns a {@link Stream} of {@link RelativeTileCoordinate}s
* representing every tile that the specific tile set contains.
* @throws SQLException
* when SQLException thrown by automatic close() invocation on
* preparedStatement or if other SQLExceptions occur
*/
public Stream<RelativeTileCoordinate> getTiles(final TileSet tileSet) throws SQLException
{
if(tileSet == null)
{
throw new IllegalArgumentException("Tile set cannot be null");
}
final String tileQuery = String.format("SELECT %s, %s, %s FROM %s;",
"zoom_level",
"tile_column",
"tile_row",
tileSet.getTableName());
try(final PreparedStatement preparedStatement = this.databaseConnection.prepareStatement(tileQuery))
{
return ResultSetStream.getStream(preparedStatement.executeQuery(),
resultSet -> { try
{
return new RelativeTileCoordinate(resultSet.getInt(3), resultSet.getInt(2), resultSet.getInt(1));
}
catch(final Exception ex)
{
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toList()) // By collecting here, we prevent the resultSet from being closed by the parent prepared statement being closed
.stream();
}
}
/**
* Gets a stream of every tile in the tile store for a given zoom level.
* The zoom level need not have an entry for every possible position in
* its respective tile matrices. If there are no tiles at this zoom level,
* an empty stream will be returned.
*
* @param tileSet
* Handle to the tile set that the requested tiles should belong
* @param zoomLevel
* The zoom level of the requested tiles
* @return Returns a {@link Stream} of {@link RelativeTileCoordinate}s
* representing every tile that the specific tile set contains.
* @throws SQLException
* when SQLException thrown by automatic close() invocation on
* preparedStatement or if other SQLExceptions occur
*/
public Stream<RelativeTileCoordinate> getTiles(final TileSet tileSet, final int zoomLevel) throws SQLException
{
if(tileSet == null)
{
throw new IllegalArgumentException("Tile set cannot be null");
}
final String tileQuery = String.format("SELECT %s, %s FROM %s WHERE zoom_level = ?;",
"tile_column",
"tile_row",
tileSet.getTableName());
try(final PreparedStatement preparedStatement = this.databaseConnection.prepareStatement(tileQuery))
{
preparedStatement.setInt(1, zoomLevel);
return ResultSetStream.getStream(preparedStatement.executeQuery(),
resultSet -> { try
{
return new RelativeTileCoordinate(resultSet.getInt(2), resultSet.getInt(1), zoomLevel);
}
catch(final Exception ex)
{
return null;
}
})
.filter(Objects::nonNull)
.collect(Collectors.toList()) // By collecting here, we prevent the resultSet from being closed by the parent prepared statement being closed
.stream();
}
}
/**
* Gets a tile
*
* @param tileSet
* Handle to the tile set that the requested tile should belong
* @param coordinate
* Coordinate relative to the tile set, of the requested tile
* @return Returns the requested tile, or null if it's not found
* @throws SQLException
* SQLException thrown by automatic close() invocation on
* preparedStatement or if other SQLExceptions occur when adding
* the Tile data to the database
*/
public Tile getTile(final TileSet tileSet,
final RelativeTileCoordinate coordinate) throws SQLException
{
if(tileSet == null)
{
throw new IllegalArgumentException("Tile set cannot be null");
}
if(coordinate == null)
{
throw new IllegalArgumentException("Requested tile cannot be null");
}
final String tileQuery = String.format("SELECT %s, %s, %s, %s, %s FROM %s WHERE zoom_level = ? AND tile_column = ? AND tile_row = ?;",
"id",
"zoom_level",
"tile_column",
"tile_row",
"tile_data",
tileSet.getTableName());
try(PreparedStatement preparedStatement = this.databaseConnection.prepareStatement(tileQuery))
{
preparedStatement.setInt(1, coordinate.getZoomLevel());
preparedStatement.setInt(2, coordinate.getColumn());
preparedStatement.setInt(3, coordinate.getRow());
try(ResultSet tileResult = preparedStatement.executeQuery())
{
if(tileResult.isBeforeFirst())
{
return new Tile(tileResult.getInt(1),
tileResult.getInt(2), // zoom level
tileResult.getInt(4), // row
tileResult.getInt(3), // column
tileResult.getBytes(5)); // data
}
return null; // No tile exists for this coordinate and zoom level
}
}
}
/**
* Gets a tile
*
* @param tileSet
* Handle to the tile set that the requested tile should belong
* @param coordinate
* Coordinate, in the units of the tile set's spatial reference
* system, of the requested tile
* @param precision
* Specifies a tolerance for coordinate value testings to a number of decimal places
* @param zoomLevel
* Zoom level
* @return Returns the requested tile, or null if it's not found
* @throws SQLException
* throws when the method
* {@link #crsToRelativeTileCoordinate(TileSet, CrsCoordinate, int, int)
* crsToRelativeTileCoordinate} or the method
* {@link #getTile(TileSet, RelativeTileCoordinate)} throws an
* SQLException
*/
public Tile getTile(final TileSet tileSet,
final CrsCoordinate coordinate,
final int precision,
final int zoomLevel) throws SQLException
{
final RelativeTileCoordinate relativeCoordiante = this.crsToRelativeTileCoordinate(tileSet,
coordinate,
precision,
zoomLevel);
return relativeCoordiante != null ? this.getTile(tileSet, relativeCoordiante)
: null;
}
/**
* Gets a tile set's tile matrix
*
* @param tileSet
* A handle to a set of tiles
* @return Returns a tile set's tile matrix set
* @throws SQLException
* SQLException thrown by automatic close() invocation on
* preparedStatement or if the method
* {@link DatabaseUtility#tableOrViewExists(Connection, String)}
* throws or other SQLExceptions occur when retrieving
* information from the database
*/
public TileMatrixSet getTileMatrixSet(final TileSet tileSet) throws SQLException
{
if(tileSet == null)
{
throw new IllegalArgumentException("Tile set cannot be null");
}
if(!DatabaseUtility.tableOrViewExists(this.databaseConnection, GeoPackageTiles.MatrixTableName))
{
return null;
}
final String querySql = String.format("SELECT %s, %s, %s, %s, %s, %s FROM %s WHERE table_name = ?;",
"table_name",
"srs_id",
"min_x",
"min_y",
"max_x",
"max_y",
GeoPackageTiles.MatrixSetTableName);
try(PreparedStatement preparedStatement = this.databaseConnection.prepareStatement(querySql))
{
preparedStatement.setString(1, tileSet.getTableName());
try(ResultSet result = preparedStatement.executeQuery())
{
return new TileMatrixSet(result.getString(1), // table name
this.core.getSpatialReferenceSystem(result.getInt(2)), // srs id
new BoundingBox(result.getDouble(4), // min y
result.getDouble(3), // min x
result.getDouble(6), // max y
result.getDouble(5))); // max x
}
}
}
/**
* Gets a tile set object based on its table name
*
* @param tileSetTableName
* Name of a tile set table
* @return Returns a TileSet or null if there isn't with the supplied table
* name
* @throws SQLException
* throws if the method
* {@link GeoPackageCore#getContent(String, com.rgi.geopackage.core.ContentFactory, SpatialReferenceSystem)}
* throws an SQLException
*/
public TileSet getTileSet(final String tileSetTableName) throws SQLException
{
return this.core.getContent(tileSetTableName,
(tableName, dataType, identifier, description, lastChange, boundingBox, spatialReferenceSystem) -> new TileSet(tableName, identifier, description, lastChange, boundingBox, spatialReferenceSystem));
}
/**
* Adds a tile matrix associated with a tile set <br>
* <br>
* <b>**WARNING**</b> this does not do a database commit. It is expected
* that this transaction will always be paired with others that need to be
* committed or roll back as a single transaction.
*
* @param tableName
* Name of the tile set
* @param boundingBox
* Bounding box of the tile matrix set
* @param spatialReferenceSystem
* Spatial reference system of the tile matrix set
* @throws SQLException
* thrown by automatic close() invocation on preparedStatement
*/
private void addTileMatrixSetNoCommit(final String tableName,
final BoundingBox boundingBox,
final SpatialReferenceSystem spatialReferenceSystem) throws SQLException
{
if(tableName == null || tableName.isEmpty())
{
throw new IllegalArgumentException("Table name cannot null or empty");
}
if(spatialReferenceSystem == null)
{
throw new IllegalArgumentException("Spatial reference system cannot be null");
}
if(boundingBox == null)
{
throw new IllegalArgumentException("Bounding box cannot be null");
}
final String insertTileMatrixSetSql = String.format("INSERT INTO %s (%s, %s, %s, %s, %s, %s) VALUES (?, ?, ?, ?, ?, ?)",
GeoPackageTiles.MatrixSetTableName,
"table_name",
"srs_id",
"min_x",
"min_y",
"max_x",
"max_y");
try(PreparedStatement preparedStatement = this.databaseConnection.prepareStatement(insertTileMatrixSetSql))
{
preparedStatement.setString(1, tableName);
preparedStatement.setInt (2, spatialReferenceSystem.getIdentifier());
preparedStatement.setDouble(3, boundingBox.getMinX());
preparedStatement.setDouble(4, boundingBox.getMinY());
preparedStatement.setDouble(5, boundingBox.getMaxX());
preparedStatement.setDouble(6, boundingBox.getMaxY());
preparedStatement.executeUpdate();
}
}
/**
* Get a tile set's tile matrix
*
* @param tileSet
* A handle to a set of tiles
* @param zoomLevel
* Zoom level of the tile matrix
* @return Returns a tile set's tile matrix that corresponds to the input
* level, or null if one doesn't exist
* @throws SQLException
* SQLException thrown by automatic close() invocation on
* preparedStatement or when an SQLException occurs retrieving
* information from the database
*/
public TileMatrix getTileMatrix(final TileSet tileSet, final int zoomLevel) throws SQLException
{
if(tileSet == null)
{
throw new IllegalArgumentException("Tile set cannot be null");
}
final String tileQuery = String.format("SELECT %s, %s, %s, %s, %s, %s FROM %s WHERE table_name = ? AND zoom_level = ?;",
"matrix_width",
"matrix_height",
"tile_width",
"tile_height",
"pixel_x_size",
"pixel_y_size",
GeoPackageTiles.MatrixTableName);
try(PreparedStatement preparedStatement = this.databaseConnection.prepareStatement(tileQuery))
{
preparedStatement.setString(1, tileSet.getTableName());
preparedStatement.setInt (2, zoomLevel);
try(ResultSet result = preparedStatement.executeQuery())
{
if(result.isBeforeFirst())
{
return new TileMatrix(tileSet.getTableName(),
zoomLevel,
result.getInt (1), // matrix width
result.getInt (2), // matrix height
result.getInt (3), // tile width
result.getInt (4), // tile height
result.getDouble(5), // pixel x size
result.getDouble(6)); // pizel y size
}
return null; // No matrix exists for this table name and zoom level
}
}
}
/**
* Gets the tile matrices associated with a tile set
*
* @param tileSet
* A handle to a set of tiles
* @return Returns every tile matrix associated with a tile set in ascending
* order by zoom level
* @throws SQLException
* SQLException thrown by automatic close() invocation on
* preparedStatement or when an SQLException occurs retrieving
* information from the database
*/
public List<TileMatrix> getTileMatrices(final TileSet tileSet) throws SQLException
{
if(tileSet == null)
{
throw new IllegalArgumentException("Tile set cannot be null");
}
final String tileQuery = String.format("SELECT %s, %s, %s, %s, %s, %s, %s FROM %s WHERE table_name = ? ORDER BY %1$s ASC;",
"zoom_level",
"matrix_width",
"matrix_height",
"tile_width",
"tile_height",
"pixel_x_size",
"pixel_y_size",
GeoPackageTiles.MatrixTableName);
try(PreparedStatement preparedStatement = this.databaseConnection.prepareStatement(tileQuery))
{
preparedStatement.setString(1, tileSet.getTableName());
try(ResultSet results = preparedStatement.executeQuery())
{
final List<TileMatrix> tileMatrices = new ArrayList<>();
while(results.next())
{
tileMatrices.add(new TileMatrix(tileSet.getTableName(),
results.getInt (1), // zoom level
results.getInt (2), // matrix width
results.getInt (3), // matrix height
results.getInt (4), // tile width
results.getInt (5), // tile height
results.getDouble(6), // pixel x size
results.getDouble(7))); // pizel y size
}
return tileMatrices;
}
}
}
/**
* Convert a CRS coordinate to a tile coordinate relative to a tile set
*
* @param tileSet
* A handle to a set of tiles
* @param crsCoordinate
* A coordinate with a specified coordinate reference system
* @param precision
* Specifies a tolerance for coordinate value testings to a number of decimal places
* @param zoomLevel
* Zoom level
* @return Returns a tile coordinate relative and specific to the input tile
* set. The input CRS coordinate would be contained in the the
* associated tile bounds.
* @throws SQLException
* throws if the method {@link #getTileMatrix(TileSet, int)
* getTileMatrix} or the method
* {@link GeoPackageCore#getSpatialReferenceSystem(int)
* getSpatialReferenceSystem} or the method
* {@link #getTileMatrixSet(TileSet) getTileMatrixSet} throws
*/
public RelativeTileCoordinate crsToRelativeTileCoordinate(final TileSet tileSet,
final CrsCoordinate crsCoordinate,
final int precision,
final int zoomLevel) throws SQLException
{
if(tileSet == null)
{
throw new IllegalArgumentException("Tile set may not be null");
}
if(crsCoordinate == null)
{
throw new IllegalArgumentException("CRS coordinate may not be null");
}
final CoordinateReferenceSystem crs = crsCoordinate.getCoordinateReferenceSystem();
final SpatialReferenceSystem srs = this.core.getSpatialReferenceSystem(tileSet.getSpatialReferenceSystemIdentifier());
if(!crs.getAuthority().equalsIgnoreCase(srs.getOrganization()) ||
crs.getIdentifier() != srs.getOrganizationSrsId())
{
throw new IllegalArgumentException("Coordinate transformation is not currently supported. The incoming spatial reference system must match that of the tile set's");
}
final TileMatrix tileMatrix = this.getTileMatrix(tileSet, zoomLevel);
if(tileMatrix == null)
{
return null; // No tile matrix for the requested zoom level
}
final TileMatrixSet tileMatrixSet = this.getTileMatrixSet(tileSet);
final BoundingBox tileSetBounds = tileMatrixSet.getBoundingBox();
if(!Utility.contains(roundBounds(tileSetBounds, precision), crsCoordinate, GeoPackageTiles.Origin))
{
return null; // The requested SRS coordinate is outside the bounds of our data
}
final Coordinate<Double> boundsCorner = Utility.boundsCorner(roundBounds(tileSetBounds, precision), GeoPackageTiles.Origin);
final double tileHeightInSrs = tileMatrix.getPixelYSize() * tileMatrix.getTileHeight();
final double tileWidthInSrs = tileMatrix.getPixelXSize() * tileMatrix.getTileWidth();
final double normalizedSrsTileCoordinateY = Math.abs(crsCoordinate.getY() - boundsCorner.getY());
final double normalizedSrsTileCoordinateX = Math.abs(crsCoordinate.getX() - boundsCorner.getX());
final int tileY = (int)Math.floor(normalizedSrsTileCoordinateY / tileHeightInSrs);
final int tileX = (int)Math.floor(normalizedSrsTileCoordinateX / tileWidthInSrs);
return new RelativeTileCoordinate(tileY,
tileX,
zoomLevel);
}
/**
* Creates the tables required for storing tiles
* <br>
* <br>
* <b>**WARNING**</b> this does not do a database commit. It is expected
* that this transaction will always be paired with others that need to be
* committed or roll back as a single transaction.
*
* @throws SQLException
*/
protected void createTilesTablesNoCommit() throws SQLException
{
// Create the tile matrix set table or view
if(!DatabaseUtility.tableOrViewExists(this.databaseConnection, GeoPackageTiles.MatrixSetTableName))
{
try(Statement statement = this.databaseConnection.createStatement())
{
statement.executeUpdate(this.getTileMatrixSetCreationSql());
}
}
// Create the tile matrix table or view
if(!DatabaseUtility.tableOrViewExists(this.databaseConnection, GeoPackageTiles.MatrixTableName))
{
try(Statement statement = this.databaseConnection.createStatement())
{
statement.executeUpdate(this.getTileMatrixCreationSql());
}
}
}
@SuppressWarnings("static-method")
protected String getTileMatrixSetCreationSql()
{
// http://www.geopackage.org/spec/#gpkg_tile_matrix_set_sql
// http://www.geopackage.org/spec/#_tile_matrix_set
return "CREATE TABLE " + GeoPackageTiles.MatrixSetTableName + "\n" +
"(table_name TEXT NOT NULL PRIMARY KEY, -- Tile Pyramid User Data Table Name\n" +
" srs_id INTEGER NOT NULL, -- Spatial Reference System ID: gpkg_spatial_ref_sys.srs_id\n" +
" min_x DOUBLE NOT NULL, -- Bounding box minimum easting or longitude for all content in table_name\n" +
" min_y DOUBLE NOT NULL, -- Bounding box minimum northing or latitude for all content in table_name\n" +
" max_x DOUBLE NOT NULL, -- Bounding box maximum easting or longitude for all content in table_name\n" +
" max_y DOUBLE NOT NULL, -- Bounding box maximum northing or latitude for all content in table_name\n" +
" CONSTRAINT fk_gtms_table_name FOREIGN KEY (table_name) REFERENCES gpkg_contents(table_name)," +
" CONSTRAINT fk_gtms_srs FOREIGN KEY (srs_id) REFERENCES gpkg_spatial_ref_sys (srs_id));";
}
@SuppressWarnings("static-method")
protected String getTileMatrixCreationSql()
{
// http://www.geopackage.org/spec/#tile_matrix
// http://www.geopackage.org/spec/#gpkg_tile_matrix_sql
return "CREATE TABLE " + GeoPackageTiles.MatrixTableName + "\n" +
"(table_name TEXT NOT NULL, -- Tile Pyramid User Data Table Name\n" +
" zoom_level INTEGER NOT NULL, -- 0 <= zoom_level <= max_level for table_name\n" +
" matrix_width INTEGER NOT NULL, -- Number of columns (>= 1) in tile matrix at this zoom level\n" +
" matrix_height INTEGER NOT NULL, -- Number of rows (>= 1) in tile matrix at this zoom level\n" +
" tile_width INTEGER NOT NULL, -- Tile width in pixels (>= 1) for this zoom level\n" +
" tile_height INTEGER NOT NULL, -- Tile height in pixels (>= 1) for this zoom level\n" +
" pixel_x_size DOUBLE NOT NULL, -- In t_table_name srid units or default meters for srid 0 (>0)\n" +
" pixel_y_size DOUBLE NOT NULL, -- In t_table_name srid units or default meters for srid 0 (>0)\n" +
" CONSTRAINT pk_ttm PRIMARY KEY (table_name, zoom_level)," +
" CONSTRAINT fk_tmm_table_name FOREIGN KEY (table_name) REFERENCES gpkg_contents(table_name));";
}
@SuppressWarnings("static-method")
protected String getTileSetCreationSql(final String tileTableName)
{
// http://www.geopackage.org/spec/#tiles_user_tables
// http://www.geopackage.org/spec/#_sample_tile_pyramid_informative
return "CREATE TABLE " + tileTableName + "\n" +
"(id INTEGER PRIMARY KEY AUTOINCREMENT, -- Autoincrement primary key\n" +
" zoom_level INTEGER NOT NULL, -- min(zoom_level) <= zoom_level <= max(zoom_level) for t_table_name\n" +
" tile_column INTEGER NOT NULL, -- 0 to tile_matrix matrix_width - 1\n" +
" tile_row INTEGER NOT NULL, -- 0 to tile_matrix matrix_height - 1\n" +
" tile_data BLOB NOT NULL, -- Of an image MIME type specified in clauses Tile Encoding PNG, Tile Encoding JPEG, Tile Encoding WEBP\n" +
" UNIQUE (zoom_level, tile_column, tile_row));";
}
/**
* Rounds the bounds to the appropriate level of accuracy
* (2 decimal places for meters, 7 decimal places for degrees)
* @param bounds
* A {@link BoundingBox} that needs to be rounded
* @param precision
* The Coordinate Reference System of the bounds (to determine level of precision)
* @return A {@link BoundingBox} with the minimum values rounded down, and the maximum values rounded up to the specified level of precision
*/
private static BoundingBox roundBounds(final BoundingBox bounds, final int precision)
{
final double divisor = Math.pow(10, precision);
return new BoundingBox(Math.floor(bounds.getMinY()*divisor) / divisor,
Math.floor(bounds.getMinX()*divisor) / divisor,
Math.ceil (bounds.getMaxY()*divisor) / divisor,
Math.ceil (bounds.getMaxX()*divisor) / divisor);
}
private final GeoPackageCore core;
private final Connection databaseConnection;
public final static TileOrigin Origin = TileOrigin.UpperLeft; // http://www.geopackage.org/spec/#clause_tile_matrix_table_data_values
public final static String MatrixSetTableName = "gpkg_tile_matrix_set";
public final static String MatrixTableName = "gpkg_tile_matrix";
} |
package com.kaeruct.glxy.actor;
import java.util.Iterator;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.Texture.TextureWrap;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer;
import com.badlogic.gdx.graphics.glutils.ShapeRenderer.ShapeType;
import com.badlogic.gdx.input.GestureDetector;
import com.badlogic.gdx.input.GestureDetector.GestureListener;
import com.badlogic.gdx.math.Circle;
import com.badlogic.gdx.math.Matrix4;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener.ChangeEvent;
import com.badlogic.gdx.utils.Array;
import com.kaeruct.glxy.data.ImageCache;
import com.kaeruct.glxy.model.Particle;
import com.kaeruct.glxy.model.Settings;
import com.kaeruct.glxy.model.Settings.Setting;
public class Universe extends Actor {
final OrthographicCamera camera;
final ShapeRenderer sr;
final Particle protoParticle;
final Array<Particle> particles;
TrailParticleManager trailParticles;
final Vector3 initPos, touchPos, cinitPos, ctouchPos;
final CameraController controller;
public final GestureDetector gestureDetector;
private Particle followedParticle;
public Settings settings;
boolean addedParticle;
public boolean panning;
public boolean inMenu;
public final float minRadius = 5;
public final float maxRadius = 80;
public final float minZoom = 0.1f;
public final float maxZoom = 16;
final float G = 0.1f; // gravity constant
final float sG = G * 0.5f; // multiplier for slingshot
final int maxTrails = 500; // max trails for all particles
private Rectangle bottomBar = null;
private Texture texture;
private Texture bg;
private Matrix4 m4;
class CameraController implements GestureListener {
float initialScale = 1;
float px, py;
public boolean touchDown(float x, float y, int pointer, int button) {
initialScale = camera.zoom;
return false;
}
private Particle getTouchedParticle(float x, float y) {
Circle tapCircle = new Circle();
for (Particle p : particles) {
// check a slightly bigger area to allow for finger inaccuracy
tapCircle.set(p.x, p.y, p.radius * 1.4f * camera.zoom);
if (tapCircle.contains(x, y)) {
return p;
}
}
return null;
}
private void singleTap(float tapX, float tapY) {
if (touchBottomBar(tapX, tapY))
return;
touchPos.set(tapX, tapY, 0);
initPos.set(0, 0, 0); // just to avoid instantiating a new vector
camera.unproject(touchPos);
protoParticle.dragged = false;
protoParticle.vel(initPos);
protoParticle.position(touchPos);
addParticle();
}
@Override
public boolean tap(float x, float y, int count, int button) {
touchPos.set(x, y, 0);
camera.unproject(touchPos);
if (count == 1 && Gdx.input.isButtonJustPressed(1)) { // single tap
if (followedParticle == null
|| getTouchedParticle(touchPos.x, touchPos.y) == null) {
// single tap that wasn't either on another particle or the
// one already being followed
singleTap(x, y);
return true;
}
} else if (count >= 2) { // multiple taps
Particle p = getTouchedParticle(touchPos.x, touchPos.y);
if (p == followedParticle) {
// stop following the followed particle if it was tapped
followedParticle = null;
} else if (p != null) {
// follow a new particle
followedParticle = p;
}
}
return true;
}
@Override
public boolean longPress(float x, float y) {
return false;
}
@Override
public boolean fling(float velocityX, float velocityY, int button) {
return false;
}
@Override
public boolean pan(float x, float y, float deltaX, float deltaY) {
if (panning) {
camera.position.add(-deltaX * camera.zoom, -deltaY
* camera.zoom, 0);
}
return false;
}
@Override
public boolean panStop(float v, float v1, int i, int i1) {
return false;
}
@Override
public boolean zoom(float originalDistance, float currentDistance) {
float ratio = originalDistance / currentDistance;
float z = initialScale * ratio;
if (z <= maxZoom && z >= minZoom) {
float zx = (px - getWidth() / 2) * (camera.zoom - z), zy = (py - getHeight() / 2)
* (camera.zoom - z);
camera.translate(zx, zy);
px = zx;
py = zy;
camera.zoom = z;
}
return false;
}
@Override
public boolean pinch(Vector2 initialFirstPointer,
Vector2 initialSecondPointer, Vector2 firstPointer,
Vector2 secondPointer) {
px = (initialFirstPointer.x + initialSecondPointer.x) / 2;
py = (initialFirstPointer.y + initialSecondPointer.y) / 2;
return false;
}
@Override
public void pinchStop() {
}
public void update() {
if (followedParticle != null) {
camera.position.set(followedParticle.x, followedParticle.y, 0);
}
}
}
public Universe() {
addedParticle = true;
panning = false;
particles = new Array<>();
sr = new ShapeRenderer();
touchPos = new Vector3();
initPos = new Vector3();
ctouchPos = new Vector3();
cinitPos = new Vector3();
protoParticle = (new Particle()).radius(minRadius);
camera = new OrthographicCamera();
controller = new CameraController();
gestureDetector = new GestureDetector(20, 0.5f, 0.5f, 0.15f, controller);
bottomBar = new Rectangle();
settings = new Settings();
resize();
}
public void setBottomBar(float w, float h) {
bottomBar.set(0, 0, w, h);
}
public void resize() {
float w = Gdx.graphics.getWidth(), h = Gdx.graphics.getHeight();
camera.setToOrtho(true, w, h);
camera.position.set(w / 2f, h / 2f, 0);
ImageCache.load();
texture = ImageCache.getTexture("circle").getTexture();
texture.setFilter(TextureFilter.Nearest, TextureFilter.Nearest);
trailParticles = new TrailParticleManager(maxTrails, texture);
bg = new Texture(Gdx.files.internal("data/bg.png"));
bg.setWrap(TextureWrap.MirroredRepeat, TextureWrap.MirroredRepeat);
}
public void setParticleRadius(float r) {
protoParticle.radius = r;
}
@Override
public void act(float delta) {
manageInput();
if (!settings.get(Setting.PAUSED)) {
updateParticles();
}
}
@Override
public void draw(Batch batch, float parentAlpha) {
controller.update();
camera.update();
if (m4 == null) {
m4 = batch.getProjectionMatrix().cpy();
}
// draw background
// batch.draw(bg, 0, getY(), getWidth(), getHeight());
// draw particles and trails
batch.setProjectionMatrix(camera.combined);
renderParticles(batch);
batch.end();
// draw black bar on the bottom
Gdx.gl.glEnable(GL20.GL_BLEND);
Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
sr.begin(ShapeType.Filled);
sr.setColor(0f, 0f, 0f, 0.6f);
sr.rect(0, 0, bottomBar.width, bottomBar.height);
sr.end();
Gdx.gl.glDisable(GL20.GL_BLEND);
if (!panning && protoParticle.dragged) {
// draw "slingshot" line
// TODO: i think stage.setViewport broke this
// i can't get consistent placement on different screen sizes
sr.begin(ShapeType.Line);
sr.setColor(Color.LIGHT_GRAY);
float yoff = getTop();
sr.line(cinitPos.x,
yoff - cinitPos.y,
ctouchPos.x,
yoff - ctouchPos.y);
sr.end();
}
batch.setProjectionMatrix(m4);
batch.begin();
}
public void manageInput() {
if (panning || inMenu)
return;
if (Gdx.input.isTouched(0) && !Gdx.input.isTouched(1)
&& !Gdx.input.justTouched() && // only one finger is touching
!touchBottomBar(Gdx.input.getX(0), Gdx.input.getY(0))) {
touchPos.set(Gdx.input.getX(0), Gdx.input.getY(0), 0);
ctouchPos.set(touchPos);
// I have no idea what this was for
// if (null == hit(touchPos.x, touchPos.y, false)) {
// addedParticle = true;
// protoParticle.dragged = false;
// return;
camera.unproject(touchPos);
addedParticle = false;
if (!protoParticle.dragged) {
protoParticle.stop();
protoParticle.dragged = true;
initPos.set(touchPos);
cinitPos.set(ctouchPos);
}
protoParticle.position(touchPos);
} else if (!addedParticle) {
protoParticle.dragged = false;
protoParticle.vel(initPos.sub(touchPos).scl(sG));
protoParticle.position(touchPos);
addParticle();
}
}
private boolean touchBottomBar(float x, float y) {
return bottomBar.contains(x, Gdx.graphics.getHeight() - y);
}
private void updateParticles() {
Iterator<Particle> it;
for (int i = 0; i < particles.size; i++) {
Particle p = particles.get(i);
if (p.dead)
continue;
for (int j = 0; j < particles.size; j++) {
Particle p2 = particles.get(j);
if (p2.dead || i == j)
continue;
float dx = p2.x - p.x;
float dy = p2.y - p.y;
float d = (float) Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
if (d == 0)
d = (float) 0.001;
if (p.collidesWith(p2)) {
if (settings.get(Setting.COLLISION)) {
// collision
float mtd = 2 * (p.radius + p2.radius - d) / d;
p2.inc(dx * mtd / p2.radius, dy * mtd / p2.radius);
p.inc(-dx * mtd / p.radius, -dy * mtd / p.radius);
p2.dx += dx * mtd / p2.mass;
p2.dy += dy * mtd / p2.mass;
p.dx -= dx * mtd / p.mass;
p.dy -= dy * mtd / p.mass;
} else {
Particle bigger = p.radius >= p2.radius ? p : p2, smaller = p.radius < p2.radius ? p
: p2;
bigger.radius((float) (p2.radius + Math
.sqrt(p.radius / 2)));
smaller.kill();
if (smaller == followedParticle) {
followedParticle = bigger;
}
if (p2 == smaller)
break;
}
} else {
// "gravity"
float force = (float) (G * p.mass * p2.mass / Math
.pow(d, 2));
float fscale = force / d;
p.dx += fscale * dx / p.mass;
p.dy += fscale * dy / p.mass;
}
}
}
it = particles.iterator();
while (it.hasNext()) {
Particle p = it.next();
if (!p.update()) {
it.remove();
fire(new ChangeEvent());
}
}
}
private void renderParticles(Batch batch) {
if (followedParticle != null && !followedParticle.dead) {
batch.setColor(0.9f, 0.2f, 0.2f, 1);
batch.draw(texture, followedParticle.x - followedParticle.radius
* 1.05f, followedParticle.y - followedParticle.radius
* 1.05f, followedParticle.radius * 2.1f,
followedParticle.radius * 2.1f);
}
for (Particle p : particles) {
Color c = p.color;
if (settings.get(Setting.TRAILS) && !settings.get(Setting.PAUSED)) {
if (Math.abs(p.x - p.oldx) > 0.2
|| Math.abs(p.y - p.oldy) > 0.2) {
trailParticles.add(p.x, p.y, p.radius, c);
}
}
batch.setColor(c);
batch.draw(texture, p.x - p.radius, p.y - p.radius, p.radius * 2,
p.radius * 2);
}
if (settings.get(Setting.TRAILS)) {
trailParticles.render(batch, settings.get(Setting.PAUSED));
}
}
private void addParticle() {
Particle p = new Particle(protoParticle);
particles.add(p);
addedParticle = true;
fire(new ChangeEvent());
}
public void clearParticles() {
particles.clear();
clearTrails();
followedParticle = null;
fire(new ChangeEvent());
}
public void clearTrails() {
trailParticles.clear();
}
public int getParticleCount() {
return particles.size;
}
public void dispose() {
sr.dispose();
}
public void resetZoom() {
camera.zoom = 1;
}
} |
package com.tcg.missit.managers;
import java.util.HashMap;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.audio.Music;
import com.badlogic.gdx.audio.Sound;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.GlyphLayout;
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator;
public class Content {
private HashMap<String, Music> music;
private HashMap<String, Sound> sound;
private HashMap<String, BitmapFont> font;
private GlyphLayout gl;
public Content() {
music = new HashMap<String, Music>();
sound = new HashMap<String, Sound>();
font = new HashMap<String, BitmapFont>();
gl = new GlyphLayout();
}
/*
* Music
*/
public void loadMusic(String folder, String path, String key, boolean looping) {
Music m = Gdx.audio.newMusic(Gdx.files.internal(folder + "/" + path));
m.setLooping(looping);
music.put(key, m);
}
public Music getMusic(String key) {
return music.get(key);
}
public void setVolumeAll(float vol) {
for(Object o : music.values()) {
Music music = (Music) o;
music.setVolume(vol);
}
}
/*
* Sound
*/
public void loadSound(String folder, String path, String key) {
Sound s = Gdx.audio.newSound(Gdx.files.internal(folder + "/" + path));
sound.put(key, s);
}
public Sound getSound(String key) {
return sound.get(key);
}
/*
* Bitmap Font
*/
@SuppressWarnings("deprecation")
public void loadBitmapFont(String folder, String path, String key, int size, Color color) {
FreeTypeFontGenerator gen = new FreeTypeFontGenerator(Gdx.files.internal(folder + "/" + path));
FreeTypeFontGenerator.FreeTypeFontParameter parameter = new FreeTypeFontGenerator.FreeTypeFontParameter();
parameter.color = color;
parameter.size = size;
BitmapFont bmf = gen.generateFont(parameter);
font.put(key, bmf);
gen.dispose();
}
public BitmapFont getFont(String key) {
return font.get(key);
}
public float getWidth(String key, String s) {
gl.setText(font.get(key), s);
return gl.width;
}
public float getHeight(String key, String s) {
gl.setText(font.get(key), s);
return gl.height - font.get(key).getDescent();
}
/*
* Other
*/
public void removeAll() {
for(Object o : music.values()) {
Music m = (Music) o;
m.dispose();
}
for(Object o : sound.values()) {
Sound s = (Sound) o;
s.dispose();
}
for(Object o : font.values()) {
BitmapFont bmf = (BitmapFont) o;
bmf.dispose();
}
}
public void stopSound() {
for(Object o : sound.values()) {
Sound s = (Sound) o;
s.stop();
}
}
public void stopMusic() {
for(Object o : music.values()) {
Music m = (Music) o;
m.stop();
}
}
public void stopAllSound() {
stopSound();
stopMusic();
}
} |
package hudson.model;
import hudson.Util;
import hudson.model.Queue.*;
import hudson.FilePath;
import hudson.util.TimeUnit2;
import hudson.util.InterceptingProxy;
import hudson.security.ACL;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.export.Exported;
import org.acegisecurity.context.SecurityContextHolder;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.lang.reflect.Method;
/**
* Thread that executes builds.
*
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public class Executor extends Thread implements ModelObject {
protected final Computer owner;
private final Queue queue;
private long startTime;
/**
* Used to track when a job was last executed.
*/
private long finishTime;
/**
* Executor number that identifies it among other executors for the same {@link Computer}.
*/
private int number;
/**
* {@link Queue.Executable} being executed right now, or null if the executor is idle.
*/
private volatile Queue.Executable executable;
private Throwable causeOfDeath;
public Executor(Computer owner, int n) {
super("Executor #"+n+" for "+owner.getDisplayName());
this.owner = owner;
this.queue = Hudson.getInstance().getQueue();
this.number = n;
}
@Override
public void run() {
// run as the system user. see ACL.SYSTEM for more discussion about why this is somewhat broken
SecurityContextHolder.getContext().setAuthentication(ACL.SYSTEM);
try {
finishTime = System.currentTimeMillis();
while(shouldRun()) {
executable = null;
synchronized(owner) {
if(owner.getNumExecutors()<owner.getExecutors().size()) {
// we've got too many executors.
owner.removeExecutor(this);
return;
}
}
// clear the interrupt flag as a precaution.
// sometime an interrupt aborts a build but without clearing the flag.
// see issue #1583
if (Thread.interrupted()) continue;
Queue.Item queueItem;
Queue.Task task;
try {
synchronized (queue) {// perform this state change as an atomic operation wrt other queue operations
queueItem = grabJob();
task = queueItem.task;
startTime = System.currentTimeMillis();
executable = task.createExecutable();
}
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Executor throw an exception unexpectedly", e);
continue;
} catch (InterruptedException e) {
continue;
}
Throwable problems = null;
final String threadName = getName();
try {
owner.taskAccepted(this, task);
if (executable instanceof Actionable) {
for (Action action: queueItem.getActions()) {
((Actionable) executable).addAction(action);
}
}
setName(threadName+" : executing "+executable.toString());
queue.execute(executable, task);
} catch (Throwable e) {
// for some reason the executor died. this is really
// a bug in the code, but we don't want the executor to die,
// so just leave some info and go on to build other things
LOGGER.log(Level.SEVERE, "Executor throw an exception unexpectedly", e);
problems = e;
} finally {
setName(threadName);
finishTime = System.currentTimeMillis();
if (problems == null) {
queueItem.future.set(executable);
owner.taskCompleted(this, task, finishTime - startTime);
} else {
queueItem.future.set(problems);
owner.taskCompletedWithProblems(this, task, finishTime - startTime, problems);
}
}
}
} catch(RuntimeException e) {
causeOfDeath = e;
throw e;
} catch (Error e) {
causeOfDeath = e;
throw e;
}
}
/**
* Returns true if we should keep going.
*/
protected boolean shouldRun() {
return Hudson.getInstance() != null && !Hudson.getInstance().isTerminating();
}
protected Queue.Item grabJob() throws InterruptedException {
return queue.pop();
}
/**
* Returns the current {@link Queue.Task} this executor is running.
*
* @return
* null if the executor is idle.
*/
@Exported
public Queue.Executable getCurrentExecutable() {
return executable;
}
/**
* If {@linkplain #getCurrentExecutable() current executable} is {@link AbstractBuild},
* return the workspace that this executor is using, or null if the build hasn't gotten
* to that point yet.
*/
public FilePath getCurrentWorkspace() {
Executable e = executable;
if(e==null) return null;
if (e instanceof AbstractBuild) {
AbstractBuild ab = (AbstractBuild) e;
return ab.getWorkspace();
}
return null;
}
/**
* Same as {@link #getName()}.
*/
public String getDisplayName() {
return "Executor #"+getNumber();
}
/**
* Gets the executor number that uniquely identifies it among
* other {@link Executor}s for the same computer.
*
* @return
* a sequential number starting from 0.
*/
@Exported
public int getNumber() {
return number;
}
/**
* Returns true if this {@link Executor} is ready for action.
*/
@Exported
public boolean isIdle() {
return executable==null;
}
/**
* The opposite of {@link #isIdle()} — the executor is doing some work.
*/
public boolean isBusy() {
return executable!=null;
}
/**
* If this thread dies unexpectedly, obtain the cause of the failure.
*
* @return null if the death is expected death or the thread is {@link #isAlive() still alive}.
* @since 1.142
*/
public Throwable getCauseOfDeath() {
return causeOfDeath;
}
/**
* Returns the progress of the current build in the number between 0-100.
*
* @return -1
* if it's impossible to estimate the progress.
*/
@Exported
public int getProgress() {
Queue.Executable e = executable;
if(e==null) return -1;
long d = e.getParent().getEstimatedDuration();
if(d<0) return -1;
int num = (int)(getElapsedTime()*100/d);
if(num>=100) num=99;
return num;
}
/**
* Returns true if the current build is likely stuck.
*
* <p>
* This is a heuristics based approach, but if the build is suspiciously taking for a long time,
* this method returns true.
*/
@Exported
public boolean isLikelyStuck() {
Queue.Executable e = executable;
if(e==null) return false;
long elapsed = getElapsedTime();
long d = e.getParent().getEstimatedDuration();
if(d>=0) {
// if it's taking 10 times longer than ETA, consider it stuck
return d*10 < elapsed;
} else {
// if no ETA is available, a build taking longer than a day is considered stuck
return TimeUnit2.MILLISECONDS.toHours(elapsed)>24;
}
}
public long getElapsedTime() {
return System.currentTimeMillis() - startTime;
}
/**
* Gets the string that says how long since this build has started.
*
* @return
* string like "3 minutes" "1 day" etc.
*/
public String getTimestampString() {
return Util.getPastTimeString(getElapsedTime());
}
/**
* Computes a human-readable text that shows the expected remaining time
* until the build completes.
*/
public String getEstimatedRemainingTime() {
Queue.Executable e = executable;
if(e==null) return Messages.Executor_NotAvailable();
long d = e.getParent().getEstimatedDuration();
if(d<0) return Messages.Executor_NotAvailable();
long eta = d-getElapsedTime();
if(eta<=0) return Messages.Executor_NotAvailable();
return Util.getTimeSpanString(eta);
}
/**
* The same as {@link #getEstimatedRemainingTime()} but return
* it as a number of milli-seconds.
*/
public long getEstimatedRemainingTimeMillis() {
Queue.Executable e = executable;
if(e==null) return -1;
long d = e.getParent().getEstimatedDuration();
if(d<0) return -1;
long eta = d-getElapsedTime();
if(eta<=0) return -1;
return eta;
}
/**
* Stops the current build.
*/
public void doStop( StaplerRequest req, StaplerResponse rsp ) throws IOException, ServletException {
Queue.Executable e = executable;
if(e!=null) {
e.getParent().checkAbortPermission();
interrupt();
}
rsp.forwardToPreviousPage(req);
}
public boolean hasStopPermission() {
Queue.Executable e = executable;
return e!=null && e.getParent().hasAbortPermission();
}
public Computer getOwner() {
return owner;
}
/**
* Returns when this executor started or should start being idle.
*/
public long getIdleStartMilliseconds() {
if (isIdle())
return Math.max(finishTime, owner.getConnectTime());
else {
return Math.max(startTime + Math.max(0, executable.getParent().getEstimatedDuration()),
System.currentTimeMillis() + 15000);
}
}
/**
* Exposes the executor to the remote API.
*/
public Api getApi() {
return new Api(this);
}
/**
* Creates a proxy object that executes the callee in the context that impersonates
* this executor. Useful to export an object to a remote channel.
*/
public <T> T newImpersonatingProxy(Class<T> type, T core) {
return new InterceptingProxy() {
protected Object call(Object o, Method m, Object[] args) throws Throwable {
final Executor old = IMPERSONATION.get();
IMPERSONATION.set(Executor.this);
try {
return m.invoke(o,args);
} finally {
IMPERSONATION.set(old);
}
}
}.wrap(type,core);
}
/**
* Returns the executor of the current thread or null if current thread is not an executor.
*/
public static Executor currentExecutor() {
Thread t = Thread.currentThread();
if (t instanceof Executor) return (Executor) t;
return IMPERSONATION.get();
}
/**
* Mechanism to allow threads (in particular the channel request handling threads) to
* run on behalf of {@link Executor}.
*/
private static final ThreadLocal<Executor> IMPERSONATION = new ThreadLocal<Executor>();
private static final Logger LOGGER = Logger.getLogger(Executor.class.getName());
} |
package org.simmetrics.utils;
import static java.lang.Math.max;
import static java.lang.Math.min;
/**
* The class {@code Math} contains methods for performing usefull functions.
*/
public final class Math {
private Math() {
// Utility class
}
/**
* Returns the greater of three {@code float} values. That is, the result is
* the argument closer to positive infinity. If the arguments have the same
* value, the result is that same value. If any value is {@code NaN}, then
* the result is {@code NaN}. Unlike the numerical comparison operators,
* this method considers negative zero to be strictly smaller than positive
* zero.
*
* @param a
* an argument
* @param b
* an other argument
* @param c
* an other argument
* @return the larger of {@code a}, {@code b} and {@code c}.
*/
public static float max3(float a, float b, float c) {
return max(a, max(b, c));
}
/**
* Returns the greater of three {@code int} values. That is, the result is
* the argument closer to the value of {@link Integer#MAX_VALUE}. If the
* arguments have the same value, the result is that same value.
*
* @param a
* an argument
* @param b
* an other argument
* @param c
* an other argument
* @return the larger of {@code a}, {@code b} and {@code c}.
*/
public static int max3(final int a, final int b, final int c) {
return max(a, max(b, c));
}
/**
* Returns the greater of four {@code float} values. That is, the result is
* the argument closer to positive infinity. If the arguments have the same
* value, the result is that same value. If any value is {@code NaN}, then
* the result is {@code NaN}. Unlike the numerical comparison operators,
* this method considers negative zero to be strictly smaller than positive
* zero.
*
* @param a
* an argument
* @param b
* an other argument
* @param c
* an other argument
* @param d
* an other argument
* @return the larger of {@code a}, {@code b}, {@code c} and {@code d}.
*/
public static float max4(float a, float b, float c, float d) {
return max(max(d, a), max(b, c));
}
/**
* Returns the greater of four {@code int} values. That is, the result is
* the argument closer to the value of {@link Integer#MAX_VALUE}. If the
* arguments have the same value, the result is that same value.
*
* @param a
* an argument
* @param b
* an other argument
* @param c
* an other argument
* @param d
* an other argument
* @return the larger of {@code a}, {@code b}, {@code c} and {@code d}.
*/
public static int max4(final int d, final int a, final int b, final int c) {
return max(max(d, a), max(b, c));
}
/**
* Returns the smaller of three {@code float} values. That is, the result is
* the value closer to negative infinity. If the arguments have the same
* value, the result is that same value. If any value is NaN, then the
* result is NaN. Unlike the numerical comparison operators, this method
* considers negative zero to be strictly smaller than positive zero.
*
* @param a
* an argument
* @param b
* an other argument
* @param c
* an other argument
*
* @return the smaller of {@code a}, {@code b} and {@code c}.
*/
public static float min3(float a, float b, float c) {
return min(a, min(b, c));
}
/**
* Returns the smaller of three {@code int} values. That is, the result the
* argument closer to the value of {@link Integer#MIN_VALUE}. If the
* arguments have the same value, the result is that same value.
*
* @param a
* an argument
* @param b
* an other argument
* @param c
* an other argument
*
* @return the smaller of {@code a}, {@code b} and {@code c}.
*/
public static int min3(final int a, final int b, final int c) {
return min(a, min(b, c));
}
/**
* Returns the smaller of four {@code float} values. That is, the result is
* the value closer to negative infinity. If the arguments have the same
* value, the result is that same value. If any value is NaN, then the
* result is NaN. Unlike the numerical comparison operators, this method
* considers negative zero to be strictly smaller than positive zero.
*
* @param a
* an argument
* @param b
* an other argument
* @param c
* an other argument
* @param d
* an other argument
* @return the smaller of {@code a}, {@code b}, {@code c} and {@code d}.
*/
public static float min4(final float a, final float b, final float c,
final float d) {
return min(min(d, a), min(b, c));
}
/**
* Returns the smaller of four {@code int} values. That is, the result the
* argument closer to the value of {@link Integer#MIN_VALUE}. If the
* arguments have the same value, the result is that same value.
*
* @param a
* an argument
* @param b
* an other argument
* @param c
* an other argument
* @param d
* an other argument
* @return the smaller of {@code a}, {@code b} and {@code c}.
*/
public static int min4(final int a, final int b, final int c, final int d) {
return min(min(d, a), min(b, c));
}
/**
* Clamps an {@code int} value between the upper and lower bounds. The
* returned value will be no lower then the lower bound and no higher then
* the upper bound. If the value falls between the upper and lower bound the
* value is returned.
*
*
* @param lower
* lower bound
* @param a
* an argument
* @param upper
* upper bound
* @return a value clamped between the upper and lower bounds.
*/
public static int clamp(int lower, int a, int upper) {
return min(max(lower, a), upper);
}
} |
package abra.cadabra;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import abra.CompareToReference2;
import abra.ReadAdjuster;
import net.sf.samtools.Cigar;
import net.sf.samtools.CigarElement;
import net.sf.samtools.CigarOperator;
import net.sf.samtools.SAMRecord;
import net.sf.samtools.TextCigarCodec;
public class Cadabra {
private static final int MIN_SUPPORTING_READS = 2;
private static final int MIN_DISTANCE_FROM_READ_END = 3;
private ReadLocusReader normal;
private ReadLocusReader tumor;
private CompareToReference2 c2r;
public void callSomatic(String reference, String normal, String tumor) throws IOException {
c2r = new CompareToReference2();
c2r.init(reference);
this.normal = new ReadLocusReader(normal);
this.tumor = new ReadLocusReader(tumor);
outputHeader();
process();
}
private void outputHeader() {
System.out.println("##fileformat=VCFv4.1");
System.out.println("#CHROM POS ID REF ALT QUAL FILTER INFO FORMAT NORMAL TUMOR");
}
private void process() {
Iterator<ReadsAtLocus> normalIter = normal.iterator();
Iterator<ReadsAtLocus> tumorIter = tumor.iterator();
ReadsAtLocus normalReads = null;
ReadsAtLocus tumorReads = null;
int count = 0;
while (normalIter.hasNext() && tumorIter.hasNext()) {
if (normalReads != null && tumorReads != null) {
int compare = normalReads.compareLoci(tumorReads, normal.getSamHeader().getSequenceDictionary());
if (compare < 0) {
normalReads = normalIter.next();
} else if (compare > 0) {
tumorReads = tumorIter.next();
} else {
processLocus(normalReads, tumorReads);
normalReads = normalIter.next();
tumorReads = tumorIter.next();
}
if ((count % 1000000) == 0) {
System.err.println("Position: " + normalReads.getChromosome() + ":" + normalReads.getPosition());
}
count += 1;
} else {
normalReads = normalIter.next();
tumorReads = tumorIter.next();
}
}
}
private void processLocus(ReadsAtLocus normalReads, ReadsAtLocus tumorReads) {
String chromosome = normalReads.getChromosome();
int position = normalReads.getPosition();
CigarElement tumorIndel = null;
int tumorCount = 0;
int mismatch0Count = 0;
int mismatch1Count = 0;
int totalMismatchCount = 0;
boolean hasSufficientDistanceFromReadEnd = false;
int maxContigMapq = 0;
Map<String, Integer> insertBasesMap = new HashMap<String, Integer>();
for (SAMRecord read : tumorReads.getReads()) {
IndelInfo readElement = checkForIndelAtLocus(read, position);
if (readElement != null) {
Integer ymInt = (Integer) read.getAttribute(ReadAdjuster.MISMATCHES_TO_CONTIG_TAG);
if (ymInt != null) {
int ym = ymInt;
if (ym == 0) {
mismatch0Count++;
}
if (ym <= 1) {
mismatch1Count++;
}
totalMismatchCount += ym;
}
}
if (tumorIndel == null && readElement != null) {
tumorIndel = readElement.getCigarElement();
tumorCount = 1;
maxContigMapq = Math.max(maxContigMapq, read.getIntegerAttribute(ReadAdjuster.CONTIG_QUALITY_TAG));
if (readElement.getInsertBases() != null) {
updateInsertBases(insertBasesMap, readElement.getInsertBases());
}
} else if (tumorIndel != null && readElement != null) {
if (tumorIndel.equals(readElement.getCigarElement())) {
// Increment tumor indel support count
tumorCount += 1;
maxContigMapq = Math.max(maxContigMapq, read.getIntegerAttribute(ReadAdjuster.CONTIG_QUALITY_TAG));
if (readElement.getInsertBases() != null) {
updateInsertBases(insertBasesMap, readElement.getInsertBases());
}
} else {
// We will not deal with multiple indels at a single locus for now.
tumorIndel = null;
tumorCount = 0;
break;
}
}
if (!hasSufficientDistanceFromReadEnd && tumorIndel != null && readElement != null && readElement.getCigarElement().equals(tumorIndel)) {
hasSufficientDistanceFromReadEnd = sufficientDistanceFromReadEnd(read, readElement.getReadIndex());
}
}
if (tumorCount >= MIN_SUPPORTING_READS && hasSufficientDistanceFromReadEnd) {
int normalCount = 0;
for (SAMRecord read : normalReads.getReads()) {
IndelInfo normalInfo = checkForIndelAtLocus(read.getAlignmentStart(), read.getCigar(), position);
if (normalInfo != null && sufficientDistanceFromReadEnd(read, normalInfo.getReadIndex())) {
normalCount += 1;
if (normalCount >= MIN_SUPPORTING_READS) {
// Don't allow call if normal indels exists at this position.
tumorIndel = null;
tumorCount = 0;
break;
}
}
}
if (tumorIndel != null && !isNormalCountOK(normalCount, normalReads.getReads().size(), tumorCount)) {
tumorIndel = null;
tumorCount = 0;
}
}
if (tumorCount >= MIN_SUPPORTING_READS && hasSufficientDistanceFromReadEnd) {
String insertBases = null;
if (tumorIndel.getOperator() == CigarOperator.I) {
insertBases = getInsertBaseConsensus(insertBasesMap, tumorIndel.getLength());
}
outputRecord(chromosome, position, normalReads, tumorReads, tumorIndel,
tumorCount, insertBases, maxContigMapq, mismatch0Count, mismatch1Count, totalMismatchCount);
}
}
private void updateInsertBases(Map<String, Integer> insertBases, String bases) {
if (insertBases.containsKey(bases)) {
insertBases.put(bases, insertBases.get(bases) + 1);
} else {
insertBases.put(bases, 1);
}
}
private String getInsertBaseConsensus(Map<String, Integer> insertBases, int length) {
int maxCount = -1;
String maxBases = null;
for (String bases : insertBases.keySet()) {
int count = insertBases.get(bases);
if (count > maxCount) {
maxCount = count;
maxBases = bases;
}
}
if (maxBases == null) {
StringBuffer buf = new StringBuffer(length);
for (int i=0; i<length; i++) {
buf.append('N');
}
maxBases = buf.toString();
}
return maxBases;
}
private boolean isNormalCountOK(int normalObs, int numNormalReads, int tumorObs) {
// Magic numbers here.
// Allow a single normal observation if >= 20 tumor observations and >= 20 normal reads
return normalObs == 0 || (tumorObs >= 20 && numNormalReads >= 20);
}
private boolean sufficientDistanceFromReadEnd(SAMRecord read, int readIdx) {
boolean ret = false;
if (readIdx >= MIN_DISTANCE_FROM_READ_END &&
readIdx <= read.getReadLength()-MIN_DISTANCE_FROM_READ_END-1) {
ret = true;
}
return ret;
}
private String getDelRefField(String chromosome, int position, int length) {
return c2r.getSequence(chromosome, position, length+1);
}
private String getInsRefField(String chromosome, int position) {
return c2r.getSequence(chromosome, position, 1);
}
private void outputRecord(String chromosome, int position,
ReadsAtLocus normalReads, ReadsAtLocus tumorReads, CigarElement indel,
int tumorObs, String insertBases, int maxContigMapq, int ym0, int ym1, int totalYm) {
int normalDepth = normalReads.getReads().size();
int tumorDepth = tumorReads.getReads().size();
String context = c2r.getSequence(chromosome, position-10, 20);
StringBuffer buf = new StringBuffer();
buf.append(chromosome);
buf.append('\t');
buf.append(position);
buf.append("\t.\t");
String ref = ".";
String alt = ".";
if (indel.getOperator() == CigarOperator.D) {
ref = getDelRefField(chromosome, position, indel.getLength());
alt = ref.substring(0, 1);
} else if (indel.getOperator() == CigarOperator.I) {
ref = getInsRefField(chromosome, position);
alt = ref + insertBases;
}
buf.append(ref);
buf.append('\t');
buf.append(alt);
buf.append("\t.\tPASS\t");
buf.append("SOMATIC;CMQ=" + maxContigMapq + ";CTX=" + context);
buf.append("\tDP:YM0:YM1:YM:OBS\t");
buf.append(normalDepth);
buf.append(":0:0:0:0");
buf.append('\t');
buf.append(tumorDepth);
buf.append(':');
buf.append(ym0);
buf.append(':');
buf.append(ym1);
buf.append(':');
buf.append(totalYm);
buf.append(':');
buf.append(tumorObs);
System.out.println(buf.toString());
}
private IndelInfo checkForIndelAtLocus(SAMRecord read, int refPos) {
IndelInfo elem = null;
String contigInfo = read.getStringAttribute("YA");
if (contigInfo != null) {
// Get assembled contig info.
String[] fields = contigInfo.split(":");
int contigPos = Integer.parseInt(fields[1]);
Cigar contigCigar = TextCigarCodec.getSingleton().decode(fields[2]);
// Check to see if contig contains indel at current locus
elem = checkForIndelAtLocus(contigPos, contigCigar, refPos);
if (elem != null) {
// Now check to see if this read supports the indel
IndelInfo readElem = checkForIndelAtLocus(read.getAlignmentStart(),
read.getCigar(), refPos);
// Allow partially overlapping indels to support contig
// (Should only matter for inserts)
if (readElem == null || readElem.getCigarElement().getOperator() != elem.getCigarElement().getOperator()) {
// Read element doesn't match contig indel
elem = null;
} else {
elem.setReadIndex(readElem.getReadIndex());
// If this read overlaps the entire insert, capture the bases.
if (elem.getCigarElement().getOperator() == CigarOperator.I &&
elem.getCigarElement().getLength() == readElem.getCigarElement().getLength()) {
String insertBases = read.getReadString().substring(readElem.getReadIndex(), readElem.getReadIndex()+readElem.getCigarElement().getLength());
elem.setInsertBases(insertBases);
}
}
}
}
return elem;
}
private IndelInfo checkForIndelAtLocus(int alignmentStart, Cigar cigar, int refPos) {
IndelInfo ret = null;
int readIdx = 0;
int currRefPos = alignmentStart;
for (CigarElement element : cigar.getCigarElements()) {
if (element.getOperator() == CigarOperator.M) {
readIdx += element.getLength();
currRefPos += element.getLength();
} else if (element.getOperator() == CigarOperator.I) {
if (currRefPos == refPos+1) {
ret = new IndelInfo(element, readIdx);
break;
}
readIdx += element.getLength();
} else if (element.getOperator() == CigarOperator.D) {
if (currRefPos == refPos+1) {
ret = new IndelInfo(element, readIdx);
break;
}
currRefPos += element.getLength();
} else if (element.getOperator() == CigarOperator.S) {
readIdx += element.getLength();
}
}
return ret;
}
private char getReadBase(SAMRecord read, int index) {
return (char) read.getReadBases()[index];
}
public static void main(String[] args) throws Exception {
// String normal = "/home/lmose/dev/abra/cadabra/normal_test2.bam";
// String tumor = "/home/lmose/dev/abra/cadabra/tumor_test2.bam";
// String normal = "/home/lmose/dev/abra/cadabra/normal.abra4.sort.bam";
// String tumor = "/home/lmose/dev/abra/cadabra/tumor.abra4.sort.bam";
// String reference = "/home/lmose/reference/chr1/chr1.fa";
// String normal = "/home/lmose/dev/abra/cadabra/t2/ntest.bam";
// String tumor = "/home/lmose/dev/abra/cadabra/t2/ttest.bam";
// String reference = "/home/lmose/reference/chr1/chr1.fa";
// String normal = "/home/lmose/dev/abra/cadabra/ins/ntest.bam";
// String tumor = "/home/lmose/dev/abra/cadabra/ins/ttest.bam";
String reference = args[0];
String normal = args[1];
String tumor = args[2];
new Cadabra().callSomatic(reference, normal, tumor);
}
} |
package alma.acs.util;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class IsoDateFormat extends SimpleDateFormat
{
private static final IsoDateFormat instance = new IsoDateFormat();
public static final String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS";
public IsoDateFormat() {
super(pattern);
}
/**
* Convenience method that works with a shared instance of this class.
* @see DateFormat#format(Date)
*/
public static String formatDate(Date date) {
synchronized (instance) { // see sync comment for java.text.DataFormat
return instance.format(date);
}
}
/**
* Convenience method that works with a shared instance of this class.
*/
public static String formatCurrentDate() {
return formatDate(new Date());
}
} |
package apoc.trigger;
import apoc.ApocConfiguration;
import apoc.Description;
import apoc.coll.SetBackedList;
import apoc.util.Util;
import org.neo4j.graphdb.*;
import org.neo4j.graphdb.event.LabelEntry;
import org.neo4j.graphdb.event.PropertyEntry;
import org.neo4j.graphdb.event.TransactionData;
import org.neo4j.graphdb.event.TransactionEventHandler;
import org.neo4j.helpers.collection.Iterators;
import org.neo4j.kernel.impl.core.GraphProperties;
import org.neo4j.kernel.impl.core.NodeManager;
import org.neo4j.kernel.internal.GraphDatabaseAPI;
//import org.neo4j.procedure.Mode;
import org.neo4j.logging.Log;
import org.neo4j.procedure.*;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Stream;
import static apoc.util.Util.map;
/**
* @author mh
* @since 20.09.16
*/
public class Trigger {
public static class TriggerInfo {
public String name;
public String query;
public Map<String,Object> selector;
public boolean installed;
public TriggerInfo(String name, String query, Map<String, Object> selector, boolean installed) {
this.name = name;
this.query = query;
this.selector = selector;
this.installed = installed;
}
}
@UserFunction
@Description("function to filter labelEntries by label, to be used within a trigger statement with {assignedLabels}, {removedLabels}, {assigned/removedNodeProperties}")
public List<Node> nodesByLabel(@Name("labelEntries") Object entries, @Name("label") String labelString) {
if (!(entries instanceof Iterable)) return Collections.emptyList();
Iterable iterable = (Iterable) entries;
Iterator it = iterable.iterator();
if (!it.hasNext()) return Collections.emptyList();
Object value = it.next();
List<Node> nodes = null;
if (value instanceof LabelEntry) {
for (LabelEntry labelEntry : (Iterable<LabelEntry>) entries) {
if (labelString == null || labelEntry.label().name().equals(labelString)) {
if (nodes==null) nodes = new ArrayList<>(100);
nodes.add(labelEntry.node());
}
}
}
if (value instanceof PropertyEntry) {
Set<Node> nodeSet = null;
Label label = labelString == null ? null : Label.label(labelString);
for (PropertyEntry<Node> entry : (Iterable<PropertyEntry<Node>>) entries) {
if (label == null || entry.entity().hasLabel(label)) {
if (nodeSet==null) nodeSet = new HashSet<>(100);
nodeSet.add(entry.entity());
}
}
if (nodeSet!=null && !nodeSet.isEmpty()) nodes = new SetBackedList<>(nodeSet);
}
return nodes == null ? Collections.emptyList() : nodes;
}
@UserFunction
@Description("function to filter propertyEntries by property-key, to be used within a trigger statement with {assignedNode/RelationshipProperties} and {removedNode/RelationshipProperties}. Returns [{old,new,key,node,relationship}]")
public List<Map<String,Object>> propertiesByKey(@Name("propertyEntries") Object propertyEntries, @Name("key") String key) {
if (!(propertyEntries instanceof Iterable)) return Collections.emptyList();
List<Map<String,Object>> result = null;
for (PropertyEntry<?> entry : (Iterable<PropertyEntry<?>>) propertyEntries) {
if (entry.key().equals(key)) {
if (result==null) result = new ArrayList<>(100);
PropertyContainer entity = entry.entity();
Map<String, Object> map = map("old", entry.previouslyCommitedValue(), "new", entry.value(), "key", key, (entity instanceof Node ? "node" : "relationship"), entity);
result.add(map);
}
}
return result;
}
@Procedure(mode = Mode.WRITE)
@Description("add a trigger statement under a name, in the statement you can use {createdNodes}, {deletedNodes} etc., the selector is {phase:'before/after/rollback'} returns previous and new trigger information")
public Stream<TriggerInfo> add(@Name("name") String name, @Name("statement") String statement, @Name(value = "selector"/*, defaultValue = "{}"*/) Map<String,Object> selector) {
Map<String, Object> removed = TriggerHandler.add(name, statement, selector);
if (removed != null) {
return Stream.of(
new TriggerInfo(name,(String)removed.get("statement"), (Map<String, Object>) removed.get("selector"),false),
new TriggerInfo(name,statement,selector,true));
}
return Stream.of(new TriggerInfo(name,statement,selector,true));
}
@Procedure(mode = Mode.WRITE)
@Description("remove previously added trigger, returns trigger information")
public Stream<TriggerInfo> remove(@Name("name")String name) {
Map<String, Object> removed = TriggerHandler.remove(name);
if (removed == null) {
Stream.of(new TriggerInfo(name, null, null, false));
}
return Stream.of(new TriggerInfo(name,(String)removed.get("statement"), (Map<String, Object>) removed.get("selector"),false));
}
@PerformsWrites
@Procedure
@Description("list all installed triggers")
public Stream<TriggerInfo> list() {
return TriggerHandler.list().entrySet().stream()
.map( (e) -> new TriggerInfo(e.getKey(),(String)e.getValue().get("statement"),(Map<String,Object>)e.getValue().get("selector"),true));
}
public static class TriggerHandler implements TransactionEventHandler {
public static final String APOC_TRIGGER = "apoc.trigger";
static ConcurrentHashMap<String,Map<String,Object>> triggers = new ConcurrentHashMap(map("",map()));
private static GraphProperties properties;
private final Log log;
public TriggerHandler(GraphDatabaseAPI api, Log log) {
properties = api.getDependencyResolver().resolveDependency(NodeManager.class).newGraphProperties();
// Pools.SCHEDULED.submit(() -> updateTriggers(null,null));
this.log = log;
}
public static Map<String, Object> add(String name, String statement, Map<String,Object> selector) {
return updateTriggers(name, map("statement", statement, "selector", selector));
}
public synchronized static Map<String, Object> remove(String name) {
return updateTriggers(name,null);
}
private synchronized static Map<String, Object> updateTriggers(String name, Map<String, Object> value) {
try (Transaction tx = properties.getGraphDatabase().beginTx()) {
triggers.clear();
String triggerProperty = (String) properties.getProperty(APOC_TRIGGER, "{}");
triggers.putAll(Util.fromJson(triggerProperty,Map.class));
Map<String,Object> previous = null;
if (name != null) {
previous = (value == null) ? triggers.remove(name) : triggers.put(name, value);
if (value != null || previous != null) {
properties.setProperty(APOC_TRIGGER, Util.toJson(triggers));
}
}
tx.success();
return previous;
}
}
public static Map<String,Map<String,Object>> list() {
updateTriggers(null,null);
return triggers;
}
@Override
public Object beforeCommit(TransactionData txData) throws Exception {
executeTriggers(txData, "before");
return null;
}
private void executeTriggers(TransactionData txData, String phase) {
Map<String, Object> params = map(
"transactionId", phase.equals("after") ? txData.getTransactionId() : -1,
"commitTime", phase.equals("after") ? txData.getCommitTime() : -1,
"createdNodes", txData.createdNodes(),
"createdRelationships", txData.createdRelationships(),
"deletedNodes", txData.deletedNodes(),
"deletedRelationships", txData.deletedRelationships(),
"removedLabels", txData.removedLabels(),
"removedNodeProperties", txData.removedNodeProperties(),
"removedRelationshipProperties", txData.removedRelationshipProperties(),
"assignedLabels",txData.assignedLabels(),
"assignedNodeProperties",txData.assignedNodeProperties(),
"assignedRelationshipProperties",txData.assignedRelationshipProperties());
if (triggers.containsKey("")) updateTriggers(null,null);
GraphDatabaseService db = properties.getGraphDatabase();
Map<String,String> exceptions = new LinkedHashMap<>();
triggers.forEach((name, data) -> {
try (Transaction tx = db.beginTx()) {
Map<String,Object> selector = (Map<String, Object>) data.get("selector");
if (when(selector, phase)) {
params.put("trigger", name);
Result result = db.execute((String) data.get("statement"), params);
Iterators.count(result);
result.close();
}
tx.success();
} catch(Exception e) {
log.warn("Error executing trigger "+name+" in phase "+phase,e);
exceptions.put(name, e.getMessage());
}
});
if (!exceptions.isEmpty()) {
throw new RuntimeException("Error executing triggers "+exceptions.toString());
}
}
private boolean when(Map<String, Object> selector, String phase) {
if (selector == null) return (phase.equals("before"));
return selector.getOrDefault("phase", "before").equals(phase);
}
@Override
public void afterCommit(TransactionData txData, Object state) {
executeTriggers(txData, "after");
}
@Override
public void afterRollback(TransactionData txData, Object state) {
executeTriggers(txData, "rollback");
}
}
public static class LifeCycle {
private final GraphDatabaseAPI db;
private final Log log;
private TriggerHandler triggerHandler;
public LifeCycle(GraphDatabaseAPI db, Log log) {
this.db = db;
this.log = log;
}
public void start() {
boolean enabled = Util.toBoolean(ApocConfiguration.get("trigger.enabled", null));
if (!enabled) return;
triggerHandler = new Trigger.TriggerHandler(db,log);
db.registerTransactionEventHandler(triggerHandler);
}
public void stop() {
if (triggerHandler == null) return;
db.unregisterTransactionEventHandler(triggerHandler);
}
}
} |
package com.brackeen.app;
import com.brackeen.app.view.Scene;
import com.brackeen.app.view.View;
import java.applet.Applet;
import java.awt.AlphaComposite;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.WindowEvent;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.WindowConstants;
/**
* The App class sets up the animation loop and provides methods to load images and set the
* current scene.
*/
@SuppressWarnings("unused")
public abstract class App extends Applet implements MouseListener, MouseMotionListener,
KeyListener, FocusListener {
private static final InheritableThreadLocal<App> APP = new InheritableThreadLocal<>();
public static App getApp() {
return APP.get();
}
private static final int MAX_LOG_LINES = 1000;
public static void log(String statement) {
log(statement, false);
}
public static void logError(String statement) {
log(statement, true);
}
private static void log(String statement, boolean toSystemOut) {
if (toSystemOut) {
System.out.println(statement);
}
List<String> log = App.getApp().getLog();
// Split on newlines
int index = 0;
while (true) {
int newIndex = statement.indexOf('\n', index);
if (newIndex == -1) {
log.add(statement.substring(index));
break;
}
log.add(statement.substring(index, newIndex));
index = newIndex + 1;
}
while (log.size() > MAX_LOG_LINES) {
log.remove(0);
}
}
private JFrame frame;
private String appName = "App";
private final float frameRate = 60;
private final Timer timer = new Timer(1, new ActionListener() {
// Using Swing's Timer because it executes on the EDT, so there will be no threading issues.
public void actionPerformed(ActionEvent ae) {
tick();
}
});
private long lastTime = 0;
private double remainingTime = 0;
private long lastTickTime = 0;
private float actualFrameRate = 0;
private long actualFrameRateLastTime = 0;
private long actualFrameRateTickCount = 0;
private int pixelScale = 1;
private boolean autoPixelScale = false;
private int autoPixelScaleBaseWidth = 320;
private int autoPixelScaleBaseHeight = 240;
private BufferedImage pixelScaleBufferedImage;
private final List<String> log = new ArrayList<>();
private final HashMap<String, WeakReference<BufferedImage>> imageCache = new HashMap<>();
private final HashMap<String, BufferedAudio> loadedAudio = new HashMap<>();
private final Stack<Scene> sceneStack = new Stack<>();
private List<View> prevViewsWithTouchInside = new ArrayList<>();
private List<View> currViewsWithTouchInside = new ArrayList<>();
private BufferStrategy bufferStrategy;
private Canvas canvas;
private int mouseX = -1;
private int mouseY = -1;
public App() {
APP.set(this);
setBackground(Color.BLACK);
}
public List<String> getLog() {
return log;
}
// Applet callbacks
@Override
public synchronized void init() {
}
@Override
public synchronized void start() {
lastTime = System.nanoTime();
remainingTime = 0;
actualFrameRate = 0;
actualFrameRateLastTime = 0;
actualFrameRateTickCount = 0;
timer.start();
}
@Override
public synchronized void stop() {
timer.stop();
}
@Override
public synchronized void destroy() {
while (canPopScene()) {
popScene();
}
if (bufferStrategy != null) {
bufferStrategy.dispose();
bufferStrategy = null;
}
for (BufferedAudio audio : loadedAudio.values()) {
audio.dispose();
}
loadedAudio.clear();
imageCache.clear();
prevViewsWithTouchInside.clear();
currViewsWithTouchInside.clear();
log.clear();
canvas = null;
removeAll();
}
protected void initFrame(int width, int height) {
// Create frame
frame = new JFrame(appName);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
enableOSXFullscreen(frame);
// Add applet to contentPane
setSize(width, height);
final Container contentPane = frame.getContentPane();
contentPane.setBackground(Color.BLACK);
contentPane.setPreferredSize(new Dimension(width, height));
contentPane.setLayout(null);
contentPane.add(this);
// Show frame
frame.pack();
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation(Math.max(0, (dim.width - frame.getWidth()) / 2),
Math.max(0, (dim.height - frame.getHeight()) / 2));
frame.setVisible(true);
// Start
init();
start();
// Resize applet on frame resize
frame.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
setBounds(contentPane.getBounds());
}
});
}
private static void enableOSXFullscreen(Window window) {
try {
Class util = Class.forName("com.apple.eawt.FullScreenUtilities");
Class params[] = new Class[]{Window.class, Boolean.TYPE};
Method method = util.getMethod("setWindowCanFullScreen", params);
method.invoke(util, window, true);
} catch (NoSuchMethodException | SecurityException | IllegalAccessException |
IllegalArgumentException | InvocationTargetException | ClassNotFoundException ex) {
// Ignore
}
}
public synchronized boolean dispose() {
if (frame != null) {
final JFrame thisFrame = frame;
frame = null;
stop();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
thisFrame.dispatchEvent(new WindowEvent(thisFrame, WindowEvent.WINDOW_CLOSING));
}
});
return true;
} else {
return false;
}
}
private void setPixelScale() {
if (autoPixelScale) {
float area = getWidth() * getHeight();
float areaFactor = area / (autoPixelScaleBaseWidth * autoPixelScaleBaseHeight);
float scale = (float) (Math.log(areaFactor) / Math.log(2));
int pixelScale;
if (scale < 2.0) {
pixelScale = Math.max(1, (int) Math.ceil(scale));
} else if (scale < 4.0) {
pixelScale = Math.round(scale);
} else {
pixelScale = (int) Math.floor(scale);
}
setPixelScale(pixelScale);
} else {
setPixelScale(1);
}
}
private synchronized void tick() {
long tickTime = System.nanoTime();
if (tickTime - lastTickTime < 1000000000 / frameRate - 750000) {
return;
} else {
lastTickTime = tickTime;
}
boolean needsResize = false;
if (App.getApp() == null) {
// For appletviewer
APP.set(this);
}
int oldPixelScale = pixelScale;
setPixelScale();
if (oldPixelScale != pixelScale && bufferStrategy != null) {
bufferStrategy.dispose();
bufferStrategy = null;
needsResize = true;
}
if (bufferStrategy != null && canvas != null &&
(canvas.getWidth() != getWidth() || canvas.getHeight() != getHeight())) {
bufferStrategy.dispose();
bufferStrategy = null;
needsResize = true;
}
if (bufferStrategy == null) {
removeAll();
canvas = new Canvas();
canvas.setSize(getWidth(), getHeight());
canvas.setLocation(0, 0);
setLayout(null);
add(canvas);
try {
canvas.createBufferStrategy(2);
bufferStrategy = canvas.getBufferStrategy();
} catch (Exception ex) {
// Do nothing
}
if (bufferStrategy == null) {
canvas = null;
} else {
canvas.addMouseListener(this);
canvas.addMouseMotionListener(this);
canvas.addKeyListener(this);
canvas.addFocusListener(this);
canvas.setFocusTraversalKeysEnabled(false);
canvas.requestFocus();
lastTime = System.nanoTime();
remainingTime = 0;
}
}
if (bufferStrategy != null) {
// Resize
if (needsResize) {
for (Scene scene : sceneStack) {
scene.notifySuperviewDirty();
scene.setSize(getWidthForScene(), getHeightForScene());
}
}
// Tick
double elapsedTime = (System.nanoTime() - lastTime) / 1000000000.0 + remainingTime;
int ticks = (int) (frameRate * elapsedTime);
if (ticks > 0) {
if (ticks > 4) {
ticks = 4;
remainingTime = 0;
} else {
remainingTime = Math.max(0, elapsedTime - ticks / frameRate);
}
for (int i = 0; i < ticks; i++) {
if (sceneStack.size() == 0) {
pushScene(createFirstScene());
}
View scene = sceneStack.peek();
scene.tick();
}
lastTime = System.nanoTime();
}
View scene = null;
if (!sceneStack.isEmpty()) {
scene = sceneStack.peek();
}
// Set cursor
Cursor cursor = Cursor.getDefaultCursor();
if (scene != null) {
View pick = scene.pick(mouseX, mouseY);
while (pick != null) {
Cursor pickCursor = pick.getCursor();
if (pickCursor != null) {
cursor = pickCursor;
break;
}
pick = pick.getSuperview();
}
}
if (getCursor() != cursor) {
setCursor(cursor);
}
// Draw
Graphics2D g = (Graphics2D) bufferStrategy.getDrawGraphics();
if (scene == null) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());
} else if (pixelScale > 1) {
if (pixelScaleBufferedImage == null ||
pixelScaleBufferedImage.getWidth() != getWidthForScene() ||
pixelScaleBufferedImage.getHeight() != getHeightForScene()) {
pixelScaleBufferedImage = new BufferedImage(getWidthForScene(),
getHeightForScene(),
BufferedImage.TYPE_INT_RGB);
}
scene.draw(pixelScaleBufferedImage.createGraphics());
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
g.setTransform(AffineTransform.getScaleInstance(pixelScale, pixelScale));
g.setComposite(AlphaComposite.Src);
g.drawImage(pixelScaleBufferedImage, 0, 0, null);
} else {
pixelScaleBufferedImage = null;
g.setComposite(AlphaComposite.SrcOver);
scene.draw(g);
}
g.dispose();
bufferStrategy.show();
// Frame rate
actualFrameRateTickCount++;
if (lastTime - actualFrameRateLastTime >= 500000000) {
float duration = (lastTime - actualFrameRateLastTime) / 1000000000.0f;
if (actualFrameRateLastTime == 0) {
actualFrameRate = 0;
} else {
actualFrameRate = actualFrameRateTickCount / duration;
}
actualFrameRateTickCount = 0;
actualFrameRateLastTime = lastTime;
}
}
}
public String getAppName() {
return appName;
}
public void setAppName(String appName) {
this.appName = appName;
}
public float getActualFrameRate() {
return actualFrameRate;
}
public int getPixelScale() {
return pixelScale;
}
public void setPixelScale(int pixelScale) {
this.pixelScale = pixelScale;
}
public boolean isAutoPixelScale() {
return autoPixelScale;
}
public void setAutoPixelScale(boolean autoPixelScale) {
this.autoPixelScale = autoPixelScale;
}
public void setAutoPixelScaleBaseSize(int w, int h) {
this.autoPixelScaleBaseWidth = w;
this.autoPixelScaleBaseHeight = h;
}
// Resources
private static URL getResourceFromLocalSource(String name) {
// For developers running from an IDE. Tested in Android Studio
try {
File file = new File(System.getProperty("user.dir") + "/src/main/resources/" + name);
return file.toURI().toURL();
} catch (IOException ex) {
return null;
}
}
public static URL getResource(String name) {
URL url = App.class.getResource(name);
if (url == null) {
url = getResourceFromLocalSource(name);
}
return url;
}
public static InputStream getResourceAsStream(String name) {
InputStream is = App.class.getResourceAsStream(name);
if (is == null) {
URL url = getResourceFromLocalSource(name);
if (url != null) {
try {
return url.openStream();
} catch (IOException ex) {
return null;
}
}
}
return is;
}
/**
* Get an audio file. The first time the audio is loaded, the maxSimultaneousStreams param
* sets how many times the audio file can be played at the same time. If the audio file was
* previously loaded, the maxSimultaneousStreams is ignored.
*/
public BufferedAudio getAudio(String audioName, int maxSimultaneousStreams) {
BufferedAudio audio = loadedAudio.get(audioName);
if (audio == null && audioName != null) {
try {
URL url = getResource(audioName);
if (url != null) {
audio = BufferedAudio.read(url, maxSimultaneousStreams);
if (audio != null) {
loadedAudio.put(audioName, audio);
}
}
} catch (IOException ex) {
// Do nothing
}
}
if (audio == null) {
logError("Could not load audio: " + audioName);
audio = BufferedAudio.DUMMY_AUDIO;
}
return audio;
}
public void unloadAudio(String audioName) {
BufferedAudio audio = loadedAudio.get(audioName);
if (audio != null) {
loadedAudio.remove(audioName);
audio.dispose();
}
}
/**
* Gets an image. Returns a previously-loaded cached image if available.
*/
public BufferedImage getImage(String imageName) {
BufferedImage image = null;
WeakReference<BufferedImage> cachedImage = imageCache.get(imageName);
if (cachedImage != null) {
image = cachedImage.get();
}
if (image == null && imageName != null) {
try {
URL url = getResource(imageName);
if (url != null) {
image = ImageIO.read(url);
if (image != null) {
imageCache.put(imageName, new WeakReference<>(image));
}
}
} catch (IOException ex) {
// Do nothing
}
}
if (image == null) {
logError("Could not load image: " + imageName);
}
return image;
}
// Scene
public abstract Scene createFirstScene();
public boolean canPopScene() {
return sceneStack.size() > 0;
}
public void popScene() {
View scene = sceneStack.pop();
scene.unload();
}
public void pushScene(Scene scene) {
scene.setSize(getWidthForScene(), getHeightForScene());
scene.load();
sceneStack.push(scene);
}
public void setScene(Scene scene) {
View oldScene;
if (sceneStack.size() > 0) {
oldScene = sceneStack.pop();
oldScene.unload();
}
pushScene(scene);
}
private int getWidthForScene() {
return (int) Math.ceil((float) getWidth() / pixelScale);
}
private int getHeightForScene() {
return (int) Math.ceil((float) getHeight() / pixelScale);
}
// Input
private KeyListener getFocusedViewKeyListener() {
if (sceneStack.size() == 0) {
return null;
} else {
Scene scene = sceneStack.peek();
View focusedView = scene.getFocusedView();
if (focusedView == null) {
// No focusedView
return null;
} else if (focusedView.getRoot() != scene) {
// The focusedView not in current scene graph
return null;
} else {
return focusedView.getKeyListener();
}
}
}
private FocusListener getFocusedViewFocusListener() {
if (sceneStack.size() == 0) {
return null;
} else {
Scene scene = sceneStack.peek();
View focusedView = scene.getFocusedView();
if (focusedView == null) {
// No focusedView
return null;
} else if (focusedView.getRoot() != scene) {
// The focusedView not in current scene graph
return null;
} else {
return focusedView.getFocusListener();
}
}
}
private View getMousePick(MouseEvent e) {
View pick = null;
mouseX = e.getX();
mouseY = e.getY();
if (sceneStack.size() > 0) {
pick = sceneStack.peek().pick(e.getX(), e.getY());
}
return pick;
}
private void dispatchEnterEvents(View view, MouseEvent e) {
while (view != null) {
currViewsWithTouchInside.add(view);
MouseListener l = view.getMouseListener();
if (l != null && !prevViewsWithTouchInside.contains(view)) {
l.mouseEntered(e);
}
view = view.getSuperview();
}
}
private void dispatchExitEvents(MouseEvent e) {
for (View oldView : prevViewsWithTouchInside) {
MouseListener l = oldView.getMouseListener();
if (l != null && !currViewsWithTouchInside.contains(oldView)) {
l.mouseExited(e);
}
}
// Swap
List<View> temp = prevViewsWithTouchInside;
prevViewsWithTouchInside = currViewsWithTouchInside;
currViewsWithTouchInside = temp;
currViewsWithTouchInside.clear();
}
// Propagate mouse events until it is consumed.
public void mouseClicked(MouseEvent e) {
View view = getMousePick(e);
while (view != null) {
if (view.isEnabled()) {
MouseListener l = view.getMouseListener();
if (l != null) {
l.mouseClicked(e);
if (e.isConsumed()) {
return;
}
}
}
view = view.getSuperview();
}
}
public void mousePressed(MouseEvent e) {
if (canvas != null && !canvas.isFocusOwner()) {
canvas.requestFocus();
}
View view = getMousePick(e);
while (view != null) {
if (view.isEnabled()) {
MouseListener l = view.getMouseListener();
if (l != null) {
l.mousePressed(e);
if (e.isConsumed()) {
return;
}
}
}
view = view.getSuperview();
}
}
public void mouseReleased(MouseEvent e) {
View view = getMousePick(e);
while (view != null) {
if (view.isEnabled()) {
MouseListener l = view.getMouseListener();
if (l != null) {
l.mouseReleased(e);
if (e.isConsumed()) {
return;
}
}
}
view = view.getSuperview();
}
}
public void mouseMoved(MouseEvent e) {
View view = getMousePick(e);
dispatchEnterEvents(view, e);
while (view != null) {
if (view.isEnabled()) {
MouseMotionListener l = view.getMouseMotionListener();
if (l != null) {
l.mouseMoved(e);
if (e.isConsumed()) {
return;
}
}
}
view = view.getSuperview();
}
dispatchExitEvents(e);
}
public void mouseEntered(MouseEvent e) {
mouseMoved(e);
}
public void mouseExited(MouseEvent e) {
mouseMoved(e);
}
public void mouseDragged(MouseEvent e) {
mouseMoved(e);
}
public void keyPressed(KeyEvent e) {
KeyListener keyListener = getFocusedViewKeyListener();
if (keyListener != null) {
keyListener.keyPressed(e);
}
}
public void keyReleased(KeyEvent e) {
KeyListener keyListener = getFocusedViewKeyListener();
if (keyListener != null) {
keyListener.keyReleased(e);
}
}
public void keyTyped(KeyEvent e) {
KeyListener keyListener = getFocusedViewKeyListener();
if (keyListener != null) {
keyListener.keyTyped(e);
}
}
public void focusGained(FocusEvent e) {
FocusListener focusListener = getFocusedViewFocusListener();
if (focusListener != null) {
focusListener.focusGained(e);
}
}
public void focusLost(FocusEvent e) {
FocusListener focusListener = getFocusedViewFocusListener();
if (focusListener != null) {
focusListener.focusLost(e);
}
}
} |
package tud.ke.ml.project.classifier;
import java.io.Serializable;
import java.util.*;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
import tud.ke.ml.project.util.Pair;
/**
* This implementation assumes the class attribute is always available (but probably not set).
*/
public class NearestNeighbor extends INearestNeighbor implements Serializable {
private static final long serialVersionUID = 1L;
private List<List<Object>> model;
protected double[] scaling;
protected double[] translation;
@Override
public String getMatrikelNumbers() {
return "2879718,2594213,2753711";
}
@Override
protected void learnModel(List<List<Object>> data) {
this.model = data;
}
@Override
protected Map<Object, Double> getUnweightedVotes(List<Pair<List<Object>, Double>> subset) {
Map<Object, Double> unweightedVotes = new HashMap<>();
//initialize unweightedVotes with all possible class attributes
for (Pair<List<Object>, Double> nearestN : subset) {
unweightedVotes.put(nearestN.getA().get(this.getClassAttribute()), 0.0D);
}
//Count the number of each class attribute in the nearestN
for (Pair<List<Object>, Double> nearestN : subset) {
double count = unweightedVotes.get(nearestN.getA().get(this.getClassAttribute()));
count++;
unweightedVotes.put(nearestN.getA().get(this.getClassAttribute()), count);
}
return unweightedVotes;
}
@Override
protected Map<Object, Double> getWeightedVotes(List<Pair<List<Object>, Double>> subset) {
Map<Object, Double> weightedVotes = new HashMap<>();
//initialize weightedVotes with all possible class attributes
for (Pair<List<Object>, Double> nearestN : subset) {
weightedVotes.put(nearestN.getA().get(this.getClassAttribute()), 0.0D);
}
//Count the number of each class attribute in the nearestN
for (Pair<List<Object>, Double> nearestN : subset) {
double count = weightedVotes.get(nearestN.getA().get(this.getClassAttribute()));
//Votes are the sum of the inverted distances
count = count + (1/nearestN.getB());
weightedVotes.put(nearestN.getA().get(this.getClassAttribute()), count);
}
return weightedVotes;
}
@Override
protected Object getWinner(Map<Object, Double> votes) {
double max = Double.MIN_VALUE;
for (Double d : votes.values()) {
if (max < d)
max = d;
}
for (Object okey : votes.keySet()) {
if ( votes.get(okey) == max )
return okey;
}
return null;
}
@Override
protected Object vote(List<Pair<List<Object>, Double>> subset) {
return this.isInverseWeighting() ? this.getWinner(this.getWeightedVotes(subset)) :
this.getWinner(this.getUnweightedVotes(subset));
}
@Override
protected List<Pair<List<Object>, Double>> getNearest(List<Object> data) {
ArrayList<Pair<List<Object>, Double>> distances = new ArrayList<>();
for (List<Object> instance : this.model) {
if(this.getMetric() == 0)
distances.add(new Pair<>(instance, this.determineManhattanDistance(instance, data)));
else
distances.add(new Pair<>(instance, this.determineEuclideanDistance(instance, data)));
}
distances.sort((x, y) -> (int) (x.getB() * 10 - y.getB() * 10));
return distances.subList(0, super.getkNearest());
}
@Override
protected double determineManhattanDistance(List<Object> instance1, List<Object> instance2) {
throw new NotImplementedException();
}
@Override
protected double determineEuclideanDistance(List<Object> instance1, List<Object> instance2) {
throw new NotImplementedException();
}
@Override
protected double[][] normalizationScaling() {
throw new NotImplementedException();
}
} |
package com.jajja.jorm;
import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* The implementation for generating SQL statements and mapping parameters to statements for records and transactions.
*
* <h3>Grammar</h3>
* <p>
* Processes and appends the specified sql string.<br>
* <br>
* Format placeholder syntax: #(modifier)[argno](:[label])#<br>
* <br>
* Modifiers: (none) value is quoted, (!) value is NOT quoted, (:) value is quoted as an SQL identifier<br>
* <br>
* When a label is specified, the referenced argument must either a Record (the label refers to a column name),
* or a java.util.Map (the label refers to a key contained by the Map).<br>
* <br>
* If the referenced argument is a Collection, each entry in the collection is processed separately,
* then finally concatenated together using a colon as a separator.<br>
* <br>
* If the referenced argument is a Table, it is properly quoted (e.g "the_schema"."the_table"), regardless of modifier.<br>
* <br>
* If the referenced argument is a QueryBuilder, it is processed as if appended by append(). The modifier is ignored.<br>
* <br>
* </p>
*
* @see Record
* @see Transaction
* @author Andreas Allerdahl <andreas.allerdahl@jajja.com>
* @author Martin Korinth <martin.korinth@jajja.com>
* @since 1.0.0
*/
public class Query {
public static final char MODIFIER_NONE = 0;
public static final char MODIFIER_UNQUOTED = '!';
public static final char MODIFIER_IDENTIFIER = ':';
public static final char MODIFIER_RAW = '?';
private static final String ALL_MODIFIERS = "!:?";
private Dialect dialect;
private StringBuilder sql = new StringBuilder(64);
private List<Object> params;
Query(Dialect dialect) {
this.dialect = dialect;
params = new LinkedList<Object>();
}
Query(Dialect dialect, String sql) {
this(dialect);
append(sql);
}
Query(Dialect dialect, String sql, Object... params) {
this(dialect);
append(sql, params);
}
public Query(Transaction transaction) {
this(transaction.getDialect());
}
public Query(Transaction transaction, String sql) {
this(transaction.getDialect(), sql);
}
public Query(Transaction transaction, String sql, Object ... params) {
this(transaction.getDialect(), sql, params);
}
@SuppressWarnings("rawtypes")
private void append(char modifier, Object param, String label) {
// TODO: refactor
if (param instanceof Map) {
if (label == null) throw new IllegalArgumentException("Cannot append map without a label! (e.g. #1:map_key#)");
param = ((Map)param).get(label);
} else if (param instanceof Record) {
if (label == null) throw new IllegalArgumentException("Cannot append record field without a label! (e.g. #1:foo_column#)");
param = ((Record)param).get(label);
}
if (param instanceof Table) {
Table table = (Table)param;
if (table.getSchema() != null) {
sql.append(dialect.quoteIdentifier(table.getSchema()));
sql.append('.');
}
sql.append(dialect.quoteIdentifier(table.getTable()));
return;
} else if (param instanceof Symbol) {
param = ((Symbol)param).getName();
modifier = MODIFIER_IDENTIFIER;
} else if (param instanceof Query) {
append((Query)param);
return;
}
// parse modifier
switch (modifier) {
case MODIFIER_UNQUOTED:
// Raw string
sql.append(param != null ? param.toString() : "NULL");
break;
case MODIFIER_IDENTIFIER:
// Quoted SQL identifier (table, column name, etc)
sql.append(dialect.quoteIdentifier(param.toString()));
break;
case MODIFIER_NONE:
sql.append("?");
this.params.add(param);
break;
default:
throw new IllegalStateException("Unknown modifier '" + modifier + "'");
}
}
@SuppressWarnings("rawtypes")
private void processPlaceholder(String string, Object ... params) {
if (string.isEmpty()) {
// UNREACHABLE
throw new IllegalStateException("Placeholder is empty");
}
char modifier = string.charAt(0);
if (ALL_MODIFIERS.indexOf(modifier) != -1) {
string = string.substring(1);
if (string.isEmpty()) {
throw new IllegalStateException("Missing value after modifier");
}
} else {
modifier = MODIFIER_NONE;
}
Object param;
String label = null;
int index = string.indexOf(':');
if (index >= 0) {
label = string.substring(index + 1);
string = string.substring(0, index);
}
int i = Integer.decode(string);
param = params[i-1];
if (modifier == MODIFIER_RAW) {
sql.append("?");
this.params.add(param);
return;
}
if (param != null && param.getClass().isArray() && !param.getClass().getComponentType().isPrimitive()) {
param = Arrays.asList((Object[])param);
}
if (param instanceof Collection) {
boolean isFirst = true;
for (Object o : (Collection)param) {
if (isFirst) {
isFirst = false;
} else {
this.sql.append(", ");
}
append(modifier, o, label);
}
} else {
append(modifier, param, label);
}
}
public Query append(String sql, Object... params) {
int hashStart = -1;
boolean inHash = false;
for (int i = 0; i < sql.length(); i++) {
char ch = sql.charAt(i);
if (inHash) {
if (ch == '
processPlaceholder(sql.substring(hashStart + 1, i), params);
inHash = false;
hashStart = -1;
}
} else if (hashStart >= 0) {
if (ch == '
hashStart = -1;
this.sql.append('
continue;
}
inHash = true;
} else if (ch == '
hashStart = i;
} else {
this.sql.append(ch);
}
}
if (hashStart >= 0) {
throw new IllegalStateException("Malformed placeholder: " + sql);
}
return this;
}
public Query append(String sql) {
this.sql.append(sql);
return this;
}
public Query append(Query query) {
sql.append(query.getSql());
params.addAll(query.getParams());
return this;
}
public String getSql() {
return sql.toString();
}
public List<Object> getParams() {
return params;
}
} |
package com.temp.tool;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Scanner;
import java.util.UUID;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
public class TagGen {
public static String getPinYin(String inputString) {
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
char[] input = inputString.trim().toCharArray();
StringBuffer output = new StringBuffer("");
try {
for (int i = 0; i < input.length; i++) {
if (Character.toString(input[i]).matches("[\u4E00-\u9FA5]+")) {
String[] temp = PinyinHelper.toHanyuPinyinStringArray(input[i], format);
output.append(temp[0].substring(0, 1));
} else
output.append(Character.toString(input[i]));
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
return output.toString();
}
private static String uuid() {
return UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
}
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static List<String> list = new ArrayList<String>();
private static void printSql(String ... alias) {
String now = sdf.format(new Date());
StringBuffer py = new StringBuffer();
StringBuffer name = new StringBuffer();
boolean flag = true;
for(String str : alias) {
if(!flag) {
py.append("-");
name.append("-");
}
py.append(getPinYin(str));
name.append(str);
flag = false;
}
String sql = "INSERT INTO `trc_acl_db`.`access_tag_tb` (`id`, `access_tag`, `access_tag_alias`, `create_time`, `update_time`) VALUES (";
String out = String.format(sql + "'%s','%s','%s','%s','%s');", uuid(), py.toString(), name.toString(), now, now);
System.out.println(out);
list.add(out);
}
public static void main(String[] args) {
@SuppressWarnings("resource")
Scanner scanner = new Scanner(System.in);
while(true) {
System.out.println("Input the the first class(Enter 'q' to exit):");
String first = scanner.nextLine();
if("q".equals(first)) break;
printSql(first);
while(true) {
System.out.println("Input the the second class(Enter 'q' to exit):");
String second = scanner.nextLine();
if("q".equals(second)) break;
printSql(first, second);
while(true) {
System.out.println("Input the the third class(Enter 'q' to exit):");
String third = scanner.nextLine();
if("q".equals(third)) break;
printSql(first, second, third);
}
}
}
System.out.println("All SQL:");
for(String str : list) {
System.out.println(str);
}
}
} |
package main.java.edugit;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ListView;
import javafx.scene.control.SelectionMode;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import org.controlsfx.control.CheckListView;
import org.controlsfx.control.ListSelectionView;
import org.controlsfx.control.NotificationPane;
import org.controlsfx.control.action.Action;
import org.eclipse.jgit.api.CreateBranchCommand;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.errors.*;
import org.eclipse.jgit.lib.BranchTrackingStatus;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.transport.RefSpec;
import java.io.IOException;
import java.rmi.Remote;
import java.util.ArrayList;
import java.util.List;
public class BranchManager {
public ListView<RemoteBranchHelper> remoteListView;
public ListView<LocalBranchHelper> localListView;
private Repository repo;
private NotificationPane notificationPane;
private TextField newBranchNameField;
public BranchManager(ArrayList<LocalBranchHelper> localBranches, ArrayList<RemoteBranchHelper> remoteBranches, Repository repo) throws IOException {
this.repo = repo;
this.remoteListView = new ListView<>(FXCollections.observableArrayList(remoteBranches));
this.localListView = new ListView<>(FXCollections.observableArrayList(localBranches));
this.remoteListView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
this.localListView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
this.newBranchNameField = new TextField();
this.newBranchNameField.setPromptText("Branch name");
}
public void showBranchChooserWindow() throws IOException {
int PADDING = 10;
GridPane root = new GridPane();
root.setHgap(PADDING);
root.setVgap(PADDING);
root.setPadding(new Insets(PADDING));
root.add(this.remoteListView, 0, 0); // col, row
root.add(this.localListView, 1, 0);
Button trackRemoteBranchButton = new Button("Track branch locally");
trackRemoteBranchButton.setOnAction(e -> {
try {
this.trackSelectedBranchLocally();
} catch (GitAPIException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
});
Button deleteLocalBranchButton = new Button("Delete local branch");
deleteLocalBranchButton.setOnAction(e -> this.deleteSelectedLocalBranch());
HBox hButtons = new HBox(trackRemoteBranchButton, deleteLocalBranchButton);
hButtons.setAlignment(Pos.CENTER);
hButtons.setSpacing(PADDING);
hButtons.setPrefWidth(this.localListView.getPrefWidth()+PADDING+this.remoteListView.getPrefWidth());
root.add(hButtons, 0, 1, 2, 1);
root.add(new Text(String.format("Branch off from %s:", this.repo.getBranch())), 0, 2, 2, 1); // colspan = 2
root.add(this.newBranchNameField, 0, 3);
Button newBranchButton = new Button("Create branch");
newBranchButton.setOnAction(e -> {
try {
LocalBranchHelper newLocalBranch = this.createNewLocalBranch(this.newBranchNameField.getText());
this.localListView.getItems().add(newLocalBranch);
}catch (InvalidRefNameException e1) {
this.showInvalidBranchNameNotification();
e1.printStackTrace();
} catch (GitAPIException e1) {
this.showGenericGitError();
e1.printStackTrace();
} catch (IOException e1) {
this.showGenericError();
e1.printStackTrace();
}
});
root.add(newBranchButton, 1, 3);
Stage stage = new Stage();
stage.setTitle("Branch Manager");
this.notificationPane = new NotificationPane(root);
this.notificationPane.getStylesheets().add("/main/resources/edugit/css/BaseStyle.css");
stage.setScene(new Scene(this.notificationPane, 450, 450));
stage.show();
}
private LocalBranchHelper createLocalTrackingBranchForRemote(RemoteBranchHelper remoteBranchHelper) throws GitAPIException, IOException {
Ref trackingBranchRef = new Git(this.repo).branchCreate().
setName(remoteBranchHelper.getBranchName()).
setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK).
setStartPoint(remoteBranchHelper.getRefPathString()).
call();
LocalBranchHelper trackingBranch = new LocalBranchHelper(trackingBranchRef, this.repo);
return trackingBranch;
}
public List<LocalBranchHelper> getLocalBranches() {
return this.localListView.getItems();
}
public void trackSelectedBranchLocally() throws GitAPIException, IOException {
RemoteBranchHelper selectedRemoteBranch = this.remoteListView.getSelectionModel().getSelectedItem();
try {
if (selectedRemoteBranch != null) {
LocalBranchHelper tracker = this.createLocalTrackingBranchForRemote(selectedRemoteBranch);
this.localListView.getItems().add(tracker);
}
} catch (RefAlreadyExistsException e) {
this.showRefAlreadyExistsNotification();
}
}
public void deleteSelectedLocalBranch() {
LocalBranchHelper selectedBranch = this.localListView.getSelectionModel().getSelectedItem();
Git git = new Git(this.repo);
try {
if (selectedBranch != null) {
// Local delete:
git.branchDelete().setBranchNames(selectedBranch.getRefPathString()).call();
this.localListView.getItems().remove(selectedBranch);
}
} catch (NotMergedException e) {
this.showNotMergedNotification();
e.printStackTrace();
} catch (CannotDeleteCurrentBranchException e) {
this.showCannotDeleteBranchNotification();
e.printStackTrace();
} catch (GitAPIException e) {
this.showGenericGitError();
e.printStackTrace();
}
// TODO: add optional delete from remote, too.
}
private LocalBranchHelper createNewLocalBranch(String branchName) throws GitAPIException, IOException {
Git git = new Git(this.repo);
Ref newBranch = git.branchCreate().setName(branchName).call();
LocalBranchHelper newLocalBranchHelper = new LocalBranchHelper(newBranch, this.repo);
return newLocalBranchHelper;
}
private void forceDeleteSelectedLocalBranch() {
LocalBranchHelper selectedBranch = this.localListView.getSelectionModel().getSelectedItem();
Git git = new Git(this.repo);
try {
if (selectedBranch != null) {
// Local delete:
git.branchDelete().setForce(true).setBranchNames(selectedBranch.getRefPathString()).call();
this.localListView.getItems().remove(selectedBranch);
}
} catch (NotMergedException e) {
this.showNotMergedNotification();
e.printStackTrace();
} catch (CannotDeleteCurrentBranchException e) {
this.showCannotDeleteBranchNotification();
e.printStackTrace();
} catch (GitAPIException e) {
this.showGenericGitError();
e.printStackTrace();
}
}
private void showGenericGitError() {
this.notificationPane.setText("Sorry, there was a git error.");
this.notificationPane.getActions().clear();
this.notificationPane.show();
}
private void showGenericError() {
this.notificationPane.setText("Sorry, there was an error.");
this.notificationPane.getActions().clear();
this.notificationPane.show();
}
private void showNotMergedNotification() {
this.notificationPane.setText("That branch has to be merged before you can do that.");
Action forceDeleteAction = new Action("Force delete", e -> {
this.forceDeleteSelectedLocalBranch();
this.notificationPane.hide();
});
this.notificationPane.getActions().clear();
this.notificationPane.getActions().setAll(forceDeleteAction);
this.notificationPane.show();
}
private void showCannotDeleteBranchNotification() {
this.notificationPane.setText("Sorry, that branch can't be deleted right now. Try checking out a different branch first.");
// probably because it's checked out
this.notificationPane.getActions().clear();
this.notificationPane.show();
}
private void showRefAlreadyExistsNotification() {
this.notificationPane.setText("Looks like that branch already exists locally!");
this.notificationPane.getActions().clear();
this.notificationPane.show();
}
private void showInvalidBranchNameNotification() {
this.notificationPane.setText("That branch name is invalid.");
this.notificationPane.getActions().clear();
this.notificationPane.show();
}
} |
package ev3dev.actuators;
import ev3dev.hardware.EV3DevDevice;
import ev3dev.hardware.EV3DevPlatform;
import ev3dev.hardware.EV3DevScreenInfo;
import ev3dev.hardware.EV3DevPlatforms;
import ev3dev.utils.Sysfs;
import lejos.hardware.lcd.GraphicsLCD;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.awt.*;
import java.awt.image.*;
import java.awt.color.*;
import java.io.RandomAccessFile;
import java.io.IOException;
import java.nio.*;
import java.nio.file.*;
import java.nio.channels.FileChannel;
import java.util.Objects;
public class LCD extends EV3DevDevice implements GraphicsLCD {
private static final Logger log = LoggerFactory.getLogger(LCD.class);
public static final String EV3DEV_LCD_KEY = "EV3DEV_LCD_KEY";
public static final String EV3DEV_LCD_MODE_KEY = "EV3DEV_LCD_MODE_KEY";
private EV3DevScreenInfo info;
private BufferedImage image;
private Graphics2D g2d;
private static GraphicsLCD instance;
private int bufferSize;
/**
* Return a Instance of Sound.
*
* @return A Sound instance
*/
public static GraphicsLCD getInstance() {
if (instance == null) {
instance = new LCD();
}
return instance;
}
// Prevent duplicate objects
private LCD() {
EV3DevPlatforms conf = new EV3DevPlatforms();
if(conf.getPlatform() == EV3DevPlatform.EV3BRICK){
init(conf.getFramebufferInfo());
} else {
log.error("This actuator was only tested for: {}", EV3DevPlatform.EV3BRICK);
throw new RuntimeException("This actuator was only tested for: " + EV3DevPlatform.EV3BRICK);
}
}
private void identifyMode() {
String alternative = System.getProperty(EV3DEV_LCD_MODE_KEY);
if (alternative == null) {
int bits = Sysfs.readInteger(Paths.get(info.getSysfsPath(), "bits_per_pixel").toString());
if (bits == 32) {
this.info.setKernelMode(EV3DevScreenInfo.Mode.XRGB);
} else {
this.info.setKernelMode(EV3DevScreenInfo.Mode.BITPLANE);
}
} else {
if (alternative == "xrgb") {
this.info.setKernelMode(EV3DevScreenInfo.Mode.XRGB);
} else if (alternative == "bitplane") {
this.info.setKernelMode(EV3DevScreenInfo.Mode.BITPLANE);
} else {
throw new RuntimeException("Invalid fake lcd mode.");
}
}
}
private void initFramebuffer() throws IOException {
String alternative = System.getProperty(EV3DEV_LCD_KEY);
if (alternative != null) {
this.info.setKernelPath(alternative);
}
if (Files.notExists(Paths.get(info.getKernelPath()))) {
throw new RuntimeException("Device path not found: " + info.getKernelPath());
}
if (info.getKernelMode() == EV3DevScreenInfo.Mode.BITPLANE) {
bufferSize = info.getBitModeStride() * info.getHeight();
} else {
bufferSize = 4 * info.getWidth() * info.getHeight();
}
}
private BufferedImage initBitplane() {
// initialize backing store
byte[] data = new byte[bufferSize];
DataBuffer db = new DataBufferByte(data, data.length);
// initialize buffer <-> sample mapping
MultiPixelPackedSampleModel packing =
new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE,
info.getWidth(), info.getHeight(),
1, info.getBitModeStride(), 0);
// initialize raster
WritableRaster wr = Raster.createWritableRaster(packing, db, null);
// initialize color interpreter
byte[] mapPixels = new byte[]{ (byte)0xFF, (byte)0x00 };
IndexColorModel cm = new IndexColorModel(1, mapPixels.length, mapPixels, mapPixels, mapPixels);
// glue everything together
return new BufferedImage(cm, wr, false, null);
}
private BufferedImage initXrgb() {
// data masks
final int maskAlpha = 0xFF000000;
final int maskRed = 0x00FF0000;
final int maskGreen = 0x0000FF00;
final int maskBlue = 0x000000FF;
final int maskNone = 0x00000000;
// initialize backing store
int[] data = new int[bufferSize / 4];
DataBuffer db = new DataBufferInt(data, data.length);
// initialize raster
WritableRaster wr = Raster.createPackedRaster(db, info.getWidth(), info.getHeight(), info.getWidth(),
new int[]{ maskRed, maskGreen, maskBlue, maskAlpha }, null);
// initialize color interpreter
DirectColorModel cm = new DirectColorModel(32, maskRed, maskGreen, maskBlue, maskAlpha);
// glue everything together
return new BufferedImage(cm, wr, false, null);
}
private void init(EV3DevScreenInfo inInfo) {
this.info = inInfo;
identifyMode();
try {
initFramebuffer();
} catch (IOException e) {
throw new RuntimeException("Unable to map the framebuffer", e);
}
this.image = info.getKernelMode() == EV3DevScreenInfo.Mode.BITPLANE ? initBitplane() : initXrgb();
this.g2d = (Graphics2D) image.getGraphics();
g2d.setColor(Color.WHITE);
g2d.fillRect(0, 0, image.getWidth(), image.getHeight());
this.refresh();
}
public BufferedImage getImage(){
return image;
}
/**
* Write LCD with current context
*/
public void flush() {
WritableRaster rst = image.getRaster();
DataBuffer buf = rst.getDataBuffer();
if (buf instanceof DataBufferByte) {
byte[] data = ((DataBufferByte) buf).getData();
Sysfs.writeBytes(info.getKernelPath(), data);
} else if (buf instanceof DataBufferInt) {
int[] data = ((DataBufferInt) buf).getData();
ByteBuffer bytes = ByteBuffer.allocate(data.length * 4);
IntBuffer wrap = IntBuffer.wrap(data);
IntBuffer dest = bytes.asIntBuffer();
dest.put(wrap);
Sysfs.writeBytes(info.getKernelPath(), bytes.array());
}
}
//Graphics LCD
@Override
public void translate(int x, int y) {
g2d.translate(x, y);
}
@Override
public Font getFont() {
return g2d.getFont();
}
@Override
public void setFont(Font font) {
g2d.setFont(font);
}
@Override
public int getTranslateX() {
return 0;
}
@Override
public int getTranslateY() {
return 0;
}
/**
* Use in combination with possible values from
* lejos.robotics.Color
*
* @param color
*/
@Override
public void setColor(int color) {
if(color == lejos.robotics.Color.WHITE){
g2d.setColor(Color.WHITE);
}else if(color == lejos.robotics.Color.BLACK){
g2d.setColor(Color.BLACK);
}else{
throw new IllegalArgumentException("Bad color configured");
}
}
@Override
public void setColor(int i, int i1, int i2) {
log.debug("Feature not implemented");
}
@Override
public void setPixel(int i, int i1, int i2) {
log.debug("Feature not implemented");
}
@Override
public int getPixel(int i, int i1) {
log.debug("Feature not implemented");
return -1;
}
@Override
public void drawString(String s, int i, int i1, int i2, boolean b) {
log.debug("Feature not implemented");
}
@Override
public void drawString(String s, int i, int i1, int i2) {
g2d.drawString(s, i, i1);
}
@Override
public void drawSubstring(String s, int i, int i1, int i2, int i3, int i4) {
log.debug("Feature not implemented");
}
@Override
public void drawChar(char c, int i, int i1, int i2) {
log.debug("Feature not implemented");
}
@Override
public void drawChars(char[] chars, int i, int i1, int i2, int i3, int i4) {
log.debug("Feature not implemented");
}
//TODO Review LeJOS Javadocs
@Override
public int getStrokeStyle() {
log.debug("Feature not implemented");
return -1;
}
//TODO Review LeJOS Javadocs
@Override
public void setStrokeStyle(int i) {
log.debug("Feature not implemented");
}
@Override
public void drawRegionRop(Image image, int i, int i1, int i2, int i3, int i4, int i5, int i6, int i7) {
log.debug("Feature not implemented");
}
@Override
public void drawRegionRop(Image image, int i, int i1, int i2, int i3, int i4, int i5, int i6, int i7, int i8) {
log.debug("Feature not implemented");
}
@Override
public void drawRegion(Image image, int i, int i1, int i2, int i3, int i4, int i5, int i6, int i7) {
log.debug("Feature not implemented");
}
@Override
public void drawImage(Image image, int i, int i1, int i2) {
g2d.drawImage(image,i, i1, null);
}
@Override
public void drawLine(int x1, int y1, int x2, int y2) {
g2d.drawLine(x1, y1, x2, y2);
}
@Override
public void fillRect(int x, int y, int width, int height) {
g2d.fillRect(x, y, width, height);
}
@Override
public void copyArea(int i, int i1, int i2, int i3, int i4, int i5, int i6) {
log.debug("Feature not implemented");
}
@Override
public void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) {
g2d.drawRoundRect(x, y, width, height, arcWidth, arcHeight);
}
@Override
public void drawRect(int x, int y, int width, int height) {
g2d.drawRect(x, y, width, height);
}
@Override
public void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) {
g2d.drawArc(x, y, width, height, startAngle, arcAngle);
}
@Override
public void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) {
g2d.fillArc(x, y, width, height, startAngle, arcAngle);
}
// CommonLCD
@Override
public void refresh() {
flush();
}
@Override
public void clear() {
g2d.setColor(Color.WHITE);
g2d.fillRect(0,0, info.getWidth(), info.getHeight());
flush();
}
@Override
public int getWidth() {
return info.getWidth();
}
@Override
public int getHeight() {
return info.getHeight();
}
@Override
public byte[] getDisplay() {
log.debug("Feature not implemented");
return null;
}
@Override
public byte[] getHWDisplay() {
log.debug("Feature not implemented");
return null;
}
@Override
public void setContrast(int i) {
log.debug("Feature not implemented");
}
@Override
public void bitBlt(byte[] bytes, int i, int i1, int i2, int i3, int i4, int i5, int i6, int i7, int i8) {
log.debug("Feature not implemented");
}
@Override
public void bitBlt(byte[] bytes, int i, int i1, int i2, int i3, byte[] bytes1, int i4, int i5, int i6, int i7, int i8, int i9, int i10) {
log.debug("Feature not implemented");
}
@Override
public void setAutoRefresh(boolean b) {
log.debug("Feature not implemented");
}
@Override
public int setAutoRefreshPeriod(int i) {
log.debug("Feature not implemented");
return -1;
}
} |
package i5.las2peer.p2p;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.Serializable;
import java.lang.management.ManagementFactory;
import java.lang.reflect.InvocationTargetException;
import java.security.KeyPair;
import java.security.PublicKey;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Vector;
import com.sun.management.OperatingSystemMXBean;
import i5.las2peer.api.Service;
import i5.las2peer.communication.Message;
import i5.las2peer.communication.MessageException;
import i5.las2peer.communication.RMIExceptionContent;
import i5.las2peer.communication.RMIResultContent;
import i5.las2peer.communication.RMIUnlockContent;
import i5.las2peer.execution.L2pServiceException;
import i5.las2peer.execution.L2pThread;
import i5.las2peer.execution.NoSuchServiceException;
import i5.las2peer.execution.NotFinishedException;
import i5.las2peer.execution.RMITask;
import i5.las2peer.execution.ServiceInvocationException;
import i5.las2peer.execution.UnlockNeededException;
import i5.las2peer.logging.NodeObserver;
import i5.las2peer.logging.NodeObserver.Event;
import i5.las2peer.logging.NodeStreamLogger;
import i5.las2peer.logging.monitoring.MonitoringObserver;
import i5.las2peer.p2p.pastry.PastryStorageException;
import i5.las2peer.persistency.DecodingFailedException;
import i5.las2peer.persistency.EncodingFailedException;
import i5.las2peer.persistency.Envelope;
import i5.las2peer.persistency.EnvelopeException;
import i5.las2peer.security.Agent;
import i5.las2peer.security.AgentException;
import i5.las2peer.security.AgentStorage;
import i5.las2peer.security.Context;
import i5.las2peer.security.DuplicateEmailException;
import i5.las2peer.security.DuplicateLoginNameException;
import i5.las2peer.security.GroupAgent;
import i5.las2peer.security.L2pSecurityException;
import i5.las2peer.security.Mediator;
import i5.las2peer.security.MessageReceiver;
import i5.las2peer.security.MonitoringAgent;
import i5.las2peer.security.ServiceAgent;
import i5.las2peer.security.ServiceInfoAgent;
import i5.las2peer.security.UserAgent;
import i5.las2peer.security.UserAgentList;
import i5.las2peer.testing.MockAgentFactory;
import i5.las2peer.tools.CryptoException;
import i5.las2peer.tools.CryptoTools;
import i5.las2peer.tools.SerializationException;
import rice.pastry.NodeHandle;
/**
* Base class for nodes in the LAS2peer environment.
*
* A Node represents one enclosed unit in the network hosting an arbitrary number of
* agents willing to participate in the P2P networking.
*/
public abstract class Node implements AgentStorage {
private static final String MAINLIST_ID = "mainlist";
/**
* The Sending mode for outgoing messages.
*/
public enum SendMode {
ANYCAST, BROADCAST
};
/**
* Enum with the possible states of a node.
*/
public enum NodeStatus {
UNCONFIGURED,
CONFIGURED,
STARTING,
RUNNING,
CLOSING,
CLOSED
}
/**
* For performance measurement (load balance)
*/
private OperatingSystemMXBean osBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
public static final float CPU_LOAD_TRESHOLD = 0.5f;//arbitrary value TODO: make it configurable
private NodeServiceCache nodeServiceCache;
private int nodeServiceCacheLifetime = 10; //10s before cached node info becomes invalidated
/**
* observers to be notified of all occurring events
*/
private HashSet<NodeObserver> observers = new HashSet<NodeObserver>();
/**
* contexts for local method invocation
*/
private Hashtable<Long, Context> htLocalExecutionContexts = new Hashtable<Long, Context>();
/**
* status of this node
*/
private NodeStatus status = NodeStatus.UNCONFIGURED;
/**
* hashtable with all {@link i5.las2peer.security.MessageReceiver}s registered at this node
*/
private Hashtable<Long, MessageReceiver> htRegisteredReceivers = new Hashtable<Long, MessageReceiver>();
private ClassLoader baseClassLoader = null;
private Hashtable<Long, MessageResultListener> htAnswerListeners = new Hashtable<Long, MessageResultListener>();
private String sLogFilePrefix;
private final static String DEFAULT_INFORMATION_FILE = "etc/nodeInfo.xml";
private String sInformationFileName = DEFAULT_INFORMATION_FILE;
private KeyPair nodeKeyPair;
/**
* the list of users containing email an login name tables
*/
private Envelope activeUserList = null;
/**
* a set of updates on user Agents to perform, if an update storage of {@link activeUserList} fails
*/
private HashSet<UserAgent> hsUserUpdates = new HashSet<UserAgent>();
/**
* Creates a new node, if the standardObserver flag is true, an observer logging all events to a
* simple plain text log file will be generated.
* If not, no observer will be used at startup.
*
* @param standardObserver
*/
public Node(boolean standardObserver) {
this(null, standardObserver);
}
/**
* Creates a new node with a standard plain text log file observer.
*/
public Node() {
this(true);
}
/**
* @param baseClassLoader
*/
public Node(ClassLoader baseClassLoader) {
this(baseClassLoader, true);
}
/**
* @param baseClassLoader
* @param standardObserver
*/
public Node(ClassLoader baseClassLoader, boolean standardObserver) {
this(baseClassLoader, standardObserver, false);
}
/**
* Generates a new Node with the given baseClassLoader.
* The Observer-flags determine, which observers will be registered at startup.
*
* @param baseClassLoader
* @param standardObserver
* @param monitoringObserver
*/
public Node(ClassLoader baseClassLoader, boolean standardObserver, boolean monitoringObserver) {
if (standardObserver) {
initStandardLogfile();
}
if (monitoringObserver) {
addObserver(new MonitoringObserver(50, this));
}
this.baseClassLoader = baseClassLoader;
if (baseClassLoader == null)
this.baseClassLoader = this.getClass().getClassLoader();
nodeKeyPair = CryptoTools.generateKeyPair();
nodeServiceCache = new NodeServiceCache(this, nodeServiceCacheLifetime);//TODO make time as setting
}
/**
* Gets the public key of this node.
*
* @return a public key
*/
public PublicKey getPublicNodeKey() {
return nodeKeyPair.getPublic();
}
/**
* Creates an observer for a standard log-file.
* The name of the log-file will contain the id of the node to prevent conflicts if
* running multiple nodes on the same machine.
*/
private void initStandardLogfile() {
try {
new File("log").mkdir();
if (this instanceof LocalNode)
addObserver(new NodeStreamLogger("log/l2p_local_" + ((LocalNode) this).getNodeId() + ".log"));
else if (this instanceof PastryNodeImpl)
addObserver(new NodeStreamLogger());
else
addObserver(new NodeStreamLogger("log/l2p_node.log"));
} catch (FileNotFoundException e) {
System.err.println("Error opening standard node log: " + e + "\n\n\n");
addObserver(new NodeStreamLogger(System.out));
}
}
/**
* Handles a request from the (p2p) net to unlock the private key of a remote Agent.
*
* @throws L2pSecurityException
* @throws AgentNotKnownException
* @throws CryptoException
* @throws SerializationException
*/
public void unlockRemoteAgent(long agentId, byte[] enctryptedPass) throws L2pSecurityException,
AgentNotKnownException, SerializationException, CryptoException {
String passphrase = (String) CryptoTools.decryptAsymmetric(enctryptedPass, nodeKeyPair.getPrivate());
Context context = getAgentContext(agentId);
if (!context.getMainAgent().isLocked())
return;
context.unlockMainAgent(passphrase);
observerNotice(Event.AGENT_UNLOCKED, this.getNodeId(), agentId, null, (Long) null, "");
}
/**
* Sends a request to unlock the agent's private key to the target node.
*
* @param agentId
* @param passphrase
* @param targetNode
* @param nodeEncryptionKey
* @throws L2pSecurityException
*/
public abstract void sendUnlockRequest(long agentId, String passphrase, Object targetNode,
PublicKey nodeEncryptionKey) throws L2pSecurityException;
/**
* Adds an observer to this node.
*
* @param observer
*/
public void addObserver(NodeObserver observer) {
observers.add(observer);
}
/**
* Removes an observer from this node.
*
* @param observer
*/
public void removeObserver(NodeObserver observer) {
observers.remove(observer);
}
/**
* Enables the service monitoring for the requested Service.
*
* @param service
*/
public void setServiceMonitoring(ServiceAgent service) {
for (NodeObserver ob : observers)
ob.logEvent(Event.SERVICE_ADD_TO_MONITORING, this.getNodeId(), service.getId(),
service.getServiceClassName());
}
/**
* Logs an event to all observers.
*
* @param event
* @param remarks
*/
public void observerNotice(Event event, String remarks) {
for (NodeObserver ob : observers)
ob.logEvent(event, remarks);
}
/**
* Logs an event to all observers.
*
* @param event
* @param sourceNode
* @param remarks
*/
public void observerNotice(Event event, Object sourceNode, String remarks) {
for (NodeObserver ob : observers)
ob.logEvent(event, sourceNode, remarks);
}
/**
* Logs an event to all observers.
*
* @param event
* @param sourceNode
* @param sourceAgentId
* @param remarks
*/
public void observerNotice(Event event, Object sourceNode, long sourceAgentId, String remarks) {
for (NodeObserver ob : observers)
ob.logEvent(event, sourceNode, sourceAgentId, remarks);
}
/**
* Logs an event to all observers.
*
* @param event
* @param sourceNode
* @param sourceAgent
* @param remarks
*/
public void observerNotice(Event event, Object sourceNode, MessageReceiver sourceAgent, String remarks) {
Long sourceAgentId = null;
if (sourceAgent != null)
sourceAgentId = sourceAgent.getResponsibleForAgentId();
for (NodeObserver ob : observers)
ob.logEvent(event, sourceNode, sourceAgentId, remarks);
}
/**
* Logs an event to all observers.
*
* @param event
* @param sourceNode
* @param sourceAgent
* @param destinationNode
* @param destinationAgent
* @param remarks
*/
public void observerNotice(Event event, Object sourceNode, Agent sourceAgent, Object destinationNode,
Agent destinationAgent, String remarks) {
Long sourceAgentId = null;
if (sourceAgent != null)
sourceAgentId = sourceAgent.getId();
Long destinationAgentId = null;
if (destinationAgent != null)
destinationAgentId = destinationAgent.getId();
for (NodeObserver ob : observers)
ob.logEvent(event, sourceNode, sourceAgentId, destinationNode, destinationAgentId, remarks);
}
/**
* Logs an event to all observers.
*
* @param event
* @param sourceNode
* @param sourceAgentId
* @param destinationNode
* @param destinationAgentId
* @param remarks
*/
public void observerNotice(Event event, Object sourceNode, Long sourceAgentId, Object destinationNode,
Long destinationAgentId, String remarks) {
for (NodeObserver ob : observers)
ob.logEvent(event, sourceNode, sourceAgentId, destinationNode, destinationAgentId, remarks);
}
/**
* Gets the status of this node.
*
* @return status of this node
*/
public NodeStatus getStatus() {
return status;
};
/**
* Gets some kind of node identifier.
*
* @return id of this node
*/
public abstract Serializable getNodeId();
/**
* Gets the class loader, this node is bound to.
* In a <i>real</i> LAS2peer environment, this should refer to a
* {@link i5.las2peer.classLoaders.L2pClassLoader}
*
* Otherwise, the class loader of this Node class is used.
*
* @return a class loader
*/
public ClassLoader getBaseClassLoader() {
return baseClassLoader;
}
/**
* Sets the status of this node.
*
* @param newstatus
*/
protected void setStatus(NodeStatus newstatus) {
if (newstatus == NodeStatus.RUNNING && this instanceof PastryNodeImpl) {
observerNotice(Event.NODE_STATUS_CHANGE, this.getNodeId(), "" + newstatus);
for (NodeObserver observer : observers) {
if (observer instanceof NodeStreamLogger) {
try {
DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
NodeHandle nh = (NodeHandle) getNodeId();
String filename = sLogFilePrefix + "_pastry_" + fmt.format(new Date()) + "_"
+ nh.getNodeId().toStringFull();
filename += ".log";
System.out.println("set logfile to " + filename);
((NodeStreamLogger) observer).setOutputFile(filename);
} catch (Exception e) {
System.out.println("error setting logfile: " + e);
}
}
}
}
else if (newstatus == NodeStatus.CLOSING) {
observerNotice(Event.NODE_STATUS_CHANGE, this.getNodeId(), "" + newstatus);
}
else {
observerNotice(Event.NODE_STATUS_CHANGE, "" + newstatus);
}
status = newstatus;
}
/**
* Sets a prefix for a log file, if the node has not been started yet.
*
* @param prefix
*/
public void setLogfilePrefix(String prefix) {
if (getStatus() != NodeStatus.UNCONFIGURED && getStatus() != NodeStatus.CONFIGURED)
throw new IllegalStateException("You can set a logfile prefix only before startup!");
sLogFilePrefix = prefix;
}
/**
* Gets the filename of the current information file for this node.
* The file should be an XML file representation of a {@link NodeInformation}.
*
* @return filename
*/
public String getInformationFilename() {
return sInformationFileName;
}
/**
* Sets the nodes information filename.
*
* @param filename
*/
public void setInformationFilename(String filename) {
if (new File(filename).exists())
sInformationFileName = filename;
}
/**
* Gets information about this node including all registered service classes.
*
* @return node information
* @throws CryptoException
*/
public NodeInformation getNodeInformation() throws CryptoException {
NodeInformation result = new NodeInformation(getRegisteredServices());
try {
if (sInformationFileName != null && new File(sInformationFileName).exists())
result = NodeInformation.createFromXmlFile(sInformationFileName, getRegisteredServices());
} catch (Exception e) {
e.printStackTrace();
}
result.setNodeHandle(getNodeId());
result.setNodeKey(nodeKeyPair.getPublic());
result.setSignature(CryptoTools.signContent(result.getSignatureContent(), nodeKeyPair.getPrivate()));
return result;
}
/**
* Gets information about a distant node.
*
* @param nodeId
*
* @return information about the node
* @throws NodeNotFoundException
*/
public abstract NodeInformation getNodeInformation(Object nodeId) throws NodeNotFoundException;
/**
* Gets an array with identifiers of other (locally known) nodes in this network.
*
* @return array with handles of other (known) p2p network nodes
*/
public abstract Object[] getOtherKnownNodes();
/**
* Starts this node.
*/
public abstract void launch() throws NodeException;
/**
* Stops the node.
*/
public void shutDown() {
for (Long id : htRegisteredReceivers.keySet())
htRegisteredReceivers.get(id).notifyUnregister();
observerNotice(Event.NODE_SHUTDOWN, this.getNodeId(), null);
for (NodeObserver observer : observers) {
if (observer instanceof MonitoringObserver) {
try {
System.out.println("Wait a little to give the observer time to send its last message...");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
}
}
htRegisteredReceivers = new Hashtable<Long, MessageReceiver>();
}
/**
* Registers a (local) Agent for usage through this node.
* The Agent has to be unlocked before registration.
*
* @param receiver
*
* @return true, if new entry was added, false if entry already existed
* @throws AgentAlreadyRegisteredException the given agent is already registered to this node
* @throws L2pSecurityException the agent is not unlocked
* @throws AgentException any problem with the agent itself (probably on calling {@link i5.las2peer.security.Agent#notifyRegistrationTo}
* @throws PastryStorageException
*/
public void registerReceiver(MessageReceiver receiver) throws AgentAlreadyRegisteredException,
L2pSecurityException, AgentException {
if (getStatus() != NodeStatus.RUNNING)
throw new IllegalStateException("You can register agents only to running nodes!");
if (htRegisteredReceivers.get(receiver.getResponsibleForAgentId()) != null)
{
//throw new AgentAlreadyRegisteredException ("This agent is already running here!");
//why throw an exception here?
return;
}
if ((receiver instanceof Agent)) {
// we have an agent
Agent agent = (Agent) receiver;
if (agent.isLocked())
throw new L2pSecurityException("An agent has to be unlocked for registering at a node");
if (!knowsAgentLocally(agent.getId()))
try {
storeAgent(agent);
} catch (AgentAlreadyRegisteredException e) {
System.out
.println("Just for notice - not an error: tried to store an already known agent before registering");
// nothing to do
}
try {
// ensure (unlocked) context
getAgentContext((Agent) receiver);
} catch (Exception e) {
}
if (agent instanceof UserAgent) {
observerNotice(Event.AGENT_REGISTERED, this.getNodeId(), agent, "UserAgent");
}
else if (agent instanceof ServiceAgent) {
observerNotice(Event.AGENT_REGISTERED, this.getNodeId(), agent, "ServiceAgent");
}
else if (agent instanceof GroupAgent) {
observerNotice(Event.AGENT_REGISTERED, this.getNodeId(), agent, "GroupAgent");
}
else if (agent instanceof MonitoringAgent) {
observerNotice(Event.AGENT_REGISTERED, this.getNodeId(), agent, "MonitoringAgent");
}
else if (agent instanceof ServiceInfoAgent) {
observerNotice(Event.AGENT_REGISTERED, this.getNodeId(), agent, "ServiceInfoAgent");
}
} else {
// ok, we have a mediator
observerNotice(Event.AGENT_REGISTERED, this.getNodeId(), receiver, "Mediator");
}
htRegisteredReceivers.put(receiver.getResponsibleForAgentId(), receiver);
try {
receiver.notifyRegistrationTo(this);
} catch (AgentException e) {
observerNotice(Event.AGENT_LOAD_FAILED, this, receiver, e.toString());
htRegisteredReceivers.remove(receiver.getResponsibleForAgentId());
throw e;
} catch (Exception e) {
observerNotice(Event.AGENT_LOAD_FAILED, this, receiver, e.toString());
htRegisteredReceivers.remove(receiver.getResponsibleForAgentId());
throw new AgentException("problems notifying agent of registration", e);
}
}
/**
* Unregisters an agent from this node.
*
* @param agent
* @throws AgentNotKnownException the agent is not registered to this node
*/
public void unregisterAgent(Agent agent) throws AgentNotKnownException {
unregisterAgent(agent.getId());
}
/**
* Is an instance of the given agent running at this node?
*
* @param agentId
*/
public void unregisterAgent(long agentId) throws AgentNotKnownException {
if (htRegisteredReceivers.get(agentId) == null)
throw new AgentNotKnownException(agentId);
observerNotice(Event.AGENT_REMOVED, this.getNodeId(), getAgent(agentId), "");
htRegisteredReceivers.get(agentId).notifyUnregister();
htRegisteredReceivers.remove(agentId);
}
/**
* Is an instance of the given agent running at this node?
*
* @param agent
* @return true, if the given agent is running at this node
*/
public boolean hasLocalAgent(Agent agent) {
return hasLocalAgent(agent.getId());
}
/**
* Is an instance of the given agent running at this node?
*
* @param agentId
* @return true, if the given agent is registered here
*/
public boolean hasLocalAgent(long agentId) {
return htRegisteredReceivers.get(agentId) != null;
}
/**
* Sends a message, recipient and sender are stated in the message.
* The node tries to find a node hosting the recipient
* and sends the message there.
*
* @param message the message to send
* @param listener a listener for getting the result separately
*/
public void sendMessage(Message message, MessageResultListener listener) {
sendMessage(message, listener, SendMode.ANYCAST);
}
/**
* Sends a message, recipient and sender are stated in the message.
* Depending on the mode, either all nodes running the given agent
* will be notified of this message, or only a random one.
*
* NOTE: Pastry nodes will always use broadcast at the moment!
*
* @param message the message to send
* @param listener a listener for getting the result separately
* @param mode is it a broadcast or an any-cast message?
*/
public abstract void sendMessage(Message message, MessageResultListener listener, SendMode mode);
/**
* Sends a message to the agent residing at the given node.
*
* @param message
* @param atNodeId
* @param listener a listener for getting the result separately
*
* @throws AgentNotKnownException
* @throws NodeNotFoundException
* @throws L2pSecurityException
*/
public abstract void sendMessage(Message message, Object atNodeId, MessageResultListener listener)
throws AgentNotKnownException, NodeNotFoundException, L2pSecurityException;
/**
* Sends the given response message to the given node.
*
* @param message
* @param atNodeId
*
* @throws AgentNotKnownException
* @throws NodeNotFoundException
* @throws L2pSecurityException
*/
public void sendResponse(Message message, Object atNodeId) throws AgentNotKnownException, NodeNotFoundException,
L2pSecurityException {
sendMessage(message, atNodeId, null);
}
/**
* For <i>external</i> access to this node. Will be called by the (P2P) network library, when
* a new message has been received via the network and could not be handled otherwise.
*
* Make sure, that the {@link #baseClassLoader} method is used for answer messages.
*
* @param message
*
* @throws AgentNotKnownException the designated recipient is not known at this node
* @throws MessageException
* @throws L2pSecurityException
*/
public void receiveMessage(Message message) throws AgentNotKnownException, MessageException, L2pSecurityException {
if (message.isResponse())
if (handoverAnswer(message))
return;
//Since this field is not always available
if (message.getSendingNodeId() != null) {
observerNotice(Event.MESSAGE_RECEIVED, message.getSendingNodeId(), message.getSenderId(), this.getNodeId(),
message.getRecipientId(), message.getId() + "");
}
else {
observerNotice(Event.MESSAGE_RECEIVED, null, message.getSenderId(), this.getNodeId(),
message.getRecipientId(), message.getId() + "");
}
MessageReceiver receiver = htRegisteredReceivers.get(message.getRecipientId());
if (receiver == null)
throw new AgentNotKnownException(message.getRecipientId());
receiver.receiveMessage(message, getAgentContext(message.getSenderId()));
}
/**
* Gets an artifact from the p2p storage.
*
* @param id
*
* @return the envelope containing the requested artifact
*
* @throws ArtifactNotFoundException
* @throws StorageException
*/
public abstract Envelope fetchArtifact(long id) throws ArtifactNotFoundException, StorageException;
/**
* Stores an artifact to the p2p storage.
*
* @param envelope
* @throws StorageException
* @throws L2pSecurityException
*
*/
public abstract void storeArtifact(Envelope envelope) throws StorageException, L2pSecurityException;
/**
* Removes an artifact from the p2p storage.
* <i>NOTE: This is not possible with a FreePastry backend!</i>
*
* @param id
* @param signature
*
* @throws ArtifactNotFoundException
* @throws StorageException
*/
public abstract void removeArtifact(long id, byte[] signature) throws ArtifactNotFoundException, StorageException;
/**
* Searches the nodes for registered Versions of the given Agent.
* Returns an array of objects identifying the nodes the given agent is registered to.
*
* @param agentId id of the agent to look for
* @param hintOfExpectedCount a hint for the expected number of results (e.g. to wait for)
* @return array with the IDs of nodes, where the given agent is registered
*
* @throws AgentNotKnownException
*/
public abstract Object[] findRegisteredAgent(long agentId, int hintOfExpectedCount) throws AgentNotKnownException;
/**
* Search the nodes for registered versions of the given agent.
* Returns an array of objects identifying the nodes the given agent is registered to.
*
* @param agent
* @return array with the IDs of nodes, where the given agent is registered
* @throws AgentNotKnownException
*/
public Object[] findRegisteredAgent(Agent agent) throws AgentNotKnownException {
return findRegisteredAgent(agent.getId());
}
/**
* Searches the nodes for registered versions of the given agentId.
* Returns an array of objects identifying the nodes the given agent is registered to.
*
* @param agentId id of the agent to look for
* @return array with the IDs of nodes, where the given agent is registered
* @throws AgentNotKnownException
*/
public Object[] findRegisteredAgent(long agentId) throws AgentNotKnownException {
return findRegisteredAgent(agentId, 1);
}
/**
* searches the nodes for registered versions of the given agent.
* Returns an array of objects identifying the nodes the given agent is registered to.
*
* @param agent
* @param hintOfExpectedCount a hint for the expected number of results (e.g. to wait for)
* @return array with the IDs of nodes, where the given agent is registered
* @throws AgentNotKnownException
*/
public Object[] findRegisteredAgent(Agent agent, int hintOfExpectedCount) throws AgentNotKnownException {
return findRegisteredAgent(agent.getId(), hintOfExpectedCount);
}
/**
* Gets an agent description from the net.
*
* make sure, always to return fresh versions of the requested agent, so that no thread can unlock the private key
* for another one!
*
* @param id
*
* @return the requested agent
*
* @throws AgentNotKnownException
*/
public abstract Agent getAgent(long id) throws AgentNotKnownException;
/**
* Does this node know an agent with the given id?
*
* from {@link i5.las2peer.security.AgentStorage}
*
* @param id
* @return true, if this node knows the given agent
*/
@Override
public boolean hasAgent(long id) {
// Since an request for this agent is probable after this check, it makes sense
// to try to load it into this node and decide afterwards
try {
getAgent(id);
return true;
} catch (AgentNotKnownException e) {
return false;
}
}
/**
* Checks, if an agent of the given id is known locally.
*
* @param agentId
* @return true, if this agent is (already) known here at this node
*/
public abstract boolean knowsAgentLocally(long agentId);
/**
* Gets a local registered agent by its id.
*
* @param id
*
* @return the agent registered to this node
* @throws AgentNotKnownException
*/
public Agent getLocalAgent(long id) throws AgentNotKnownException {
MessageReceiver result = htRegisteredReceivers.get(id);
if (result == null)
throw new AgentNotKnownException("The given agent agent is not registered to this node");
if (result instanceof Agent)
return (Agent) result;
else
throw new AgentNotKnownException("The requested Agent is only known as a Mediator here!");
}
/**
* Gets an array with all {@link i5.las2peer.security.UserAgent}s registered at this node.
*
* @return all local registered UserAgents
*/
public UserAgent[] getRegisteredAgents() {
Vector<UserAgent> result = new Vector<UserAgent>();
for (MessageReceiver rec : htRegisteredReceivers.values()) {
if (rec instanceof UserAgent)
result.add((UserAgent) rec);
}
return result.toArray(new UserAgent[0]);
}
/**
* Gets an array with all {@link i5.las2peer.security.ServiceAgent}s registered at this node.
*
* @return all local registered ServiceAgents
*/
public ServiceAgent[] getRegisteredServices() {
Vector<ServiceAgent> result = new Vector<ServiceAgent>();
for (MessageReceiver rec : htRegisteredReceivers.values()) {
if (rec instanceof ServiceAgent)
result.add((ServiceAgent) rec);
}
return result.toArray(new ServiceAgent[0]);
}
/**
* Gets a local registered mediator for the given agent id.
* If no mediator exists, registers a new one to this node.
*
* @param agent
*
* @return the mediator for the given agent
*
* @throws AgentNotKnownException
* @throws L2pSecurityException
* @throws AgentException
* @throws AgentAlreadyRegisteredException
*/
public Mediator getOrRegisterLocalMediator(Agent agent) throws AgentNotKnownException, L2pSecurityException,
AgentAlreadyRegisteredException, AgentException {
if (agent.isLocked())
throw new L2pSecurityException("you need to unlock the agent for mediation!");
MessageReceiver result = htRegisteredReceivers.get(agent.getId());
if (result != null && !(result instanceof Mediator))
throw new AgentNotKnownException("The requested Agent is registered directly at this node!");
if (result == null) {
getAgentContext(agent);
result = new Mediator(agent);
registerReceiver(result);
}
return (Mediator) result;
}
/**
* Stores a new Agent to the network.
*
* @param agent
*
* @throws AgentAlreadyRegisteredException
* @throws L2pSecurityException
* @throws PastryStorageException
*/
public abstract void storeAgent(Agent agent) throws AgentAlreadyRegisteredException, L2pSecurityException,
AgentException;
/**
* Updates an existing agent of the network.
*
* @param agent
*
* @throws L2pSecurityException
* @throws PastryStorageException
* @throws AgentException
*/
public abstract void updateAgent(Agent agent) throws AgentException, L2pSecurityException, PastryStorageException;
private Agent anonymousAgent = null;
/**
* get an agent to use, if no <i>real</i> agent is available
* @return a generic anonymous agent
*/
public Agent getAnonymous() {
if (anonymousAgent == null) {
try {
anonymousAgent = getAgent(MockAgentFactory.getAnonymous().getId());
} catch (Exception e) {
try {
anonymousAgent = MockAgentFactory.getAnonymous();
((UserAgent) anonymousAgent).unlockPrivateKey("anonymous");
storeAgent(anonymousAgent);
} catch (Exception e1) {
throw new RuntimeException("No anonymous agent could be initialized!?!", e1);
}
}
}
Agent result;
try {
result = anonymousAgent.cloneLocked();
((UserAgent) result).unlockPrivateKey("anonymous");
} catch (Exception e) {
throw new RuntimeException("Strange - should not happen...");
}
return result;
}
/**
* Loads the central user list from the backend.
*/
private void loadUserList() {
Agent owner = getAnonymous();
boolean bLoadedOrCreated = false;
try {
try {
activeUserList = fetchArtifact(Envelope.getClassEnvelopeId(UserAgentList.class, MAINLIST_ID));
activeUserList.open(owner);
bLoadedOrCreated = true;
} catch (Exception e) {
if (activeUserList == null) {
activeUserList = Envelope.createClassIdEnvelope(new UserAgentList(), MAINLIST_ID, owner);
activeUserList.open(owner);
activeUserList.setOverWriteBlindly(false);
activeUserList.lockContent();
bLoadedOrCreated = true;
}
}
if (bLoadedOrCreated && hsUserUpdates.size() > 0) {
for (UserAgent agent : hsUserUpdates)
activeUserList.getContent(UserAgentList.class).updateUser(agent);
doStoreUserList();
}
} catch (Exception e) {
observerNotice(Event.NODE_ERROR, "Error updating the user registration list: " + e.toString());
e.printStackTrace();
}
}
/**
* Stores the current list. If the storage fails e.g. due to a failed up-to-date-check of the current
* user list, the storage is attempted a second time.
*/
private void storeUserList() {
synchronized (hsUserUpdates) {
try {
doStoreUserList();
loadUserList();
} catch (Exception e) {
e.printStackTrace();
// one retry because of actuality problems:
loadUserList();
try {
doStoreUserList();
loadUserList();
} catch (Exception e1) {
observerNotice(Event.NODE_ERROR, "Error storing new User List: " + e.toString());
}
}
}
}
/**
* The actual backend storage procedure.
*
* @throws EncodingFailedException
* @throws StorageException
* @throws L2pSecurityException
* @throws DecodingFailedException
*/
private void doStoreUserList() throws EncodingFailedException, StorageException, L2pSecurityException,
DecodingFailedException {
Agent anon = getAnonymous();
activeUserList.open(anon);
activeUserList.addSignature(anon);
activeUserList.close();
storeArtifact(activeUserList);
activeUserList.open(anon);
// ok, all changes are stored
hsUserUpdates.clear();
}
/**
* Forces the node to publish all changes on the userlist.
*/
public void forceUserListUpdate() {
if (hsUserUpdates.size() > 0)
storeUserList();
}
/**
* Update the registry of login and mail addresses of known / stored user agents on
* an {@link #updateAgent(Agent)} or {@link #storeAgent(Agent)} action.
*
* @param agent
* @throws DuplicateEmailException
* @throws DuplicateLoginNameException
*/
protected void updateUserAgentList(UserAgent agent) throws DuplicateEmailException, DuplicateLoginNameException {
synchronized (hsUserUpdates) {
if (activeUserList == null)
loadUserList();
try {
activeUserList.getContent(UserAgentList.class).updateUser(agent);
} catch (EnvelopeException e) {
observerNotice(Event.NODE_ERROR, "Envelope error while updating user list: " + e);
}
synchronized (hsUserUpdates) {
hsUserUpdates.add(agent);
if (hsUserUpdates.size() > 10) {
storeUserList();
}
}
}
}
/**
* Gets an id for the user for the given login name.
*
* @param login
* @return agent id
* @throws AgentNotKnownException
*/
public long getAgentIdForLogin(String login) throws AgentNotKnownException {
if (activeUserList == null) {
loadUserList();
}
if (activeUserList == null)
throw new AgentNotKnownException("No agents known!");
try {
return activeUserList.getContent(UserAgentList.class).getLoginId(login);
} catch (AgentNotKnownException e) {
// retry once
loadUserList();
try {
return activeUserList.getContent(UserAgentList.class).getLoginId(login);
} catch (EnvelopeException e1) {
throw e;
}
} catch (EnvelopeException e) {
throw new AgentNotKnownException("Envelope Problems with user list!", e);
}
}
/**
* Gets an id for the user for the given email address.
*
* @param email
* @return agent id
* @throws AgentNotKnownException
*/
public long getAgentIdForEmail(String email) throws AgentNotKnownException {
if (activeUserList == null)
loadUserList();
if (activeUserList == null)
throw new AgentNotKnownException("No agents known!");
try {
return activeUserList.getContent(UserAgentList.class).getLoginId(email);
} catch (AgentNotKnownException e) {
throw e;
} catch (EnvelopeException e) {
throw new AgentNotKnownException("Evelope Problems with user list!", e);
}
}
/**
* Gets the agent representing the given service class.
*
* prefer using a locally registered agent
*
* @param serviceClass
* @return the ServiceAgent responsible for the given service class
* @throws AgentNotKnownException
*/
public ServiceAgent getServiceAgent(String serviceClass) throws AgentNotKnownException {
long agentId = ServiceAgent.serviceClass2Id(serviceClass);
Agent result;
try {
result = getLocalAgent(agentId);
} catch (AgentNotKnownException e) {
result = getAgent(agentId);
}
if (result == null || !(result instanceof ServiceAgent)) {
throw new AgentNotKnownException("The corresponding agent is not a ServiceAgent!?");
}
return (ServiceAgent) result;
}
/**
* Invokes a service method of a local running service agent.
*
* @param executingAgentId
* @param serviceClass
* @param method
* @param parameters
*
* @return result of the method invocation
*
* @throws AgentNotKnownException cannot find the executing agent
* @throws L2pSecurityException
* @throws InterruptedException
* @throws L2pServiceException
*/
public Serializable invokeLocally(long executingAgentId, String serviceClass, String method,
Serializable[] parameters) throws L2pSecurityException, AgentNotKnownException, InterruptedException,
L2pServiceException {
if (getStatus() != NodeStatus.RUNNING)
throw new IllegalStateException("You can invoke methods only on a running node!");
long serviceAgentId = ServiceAgent.serviceClass2Id(serviceClass);
if (!hasLocalAgent(serviceAgentId))
throw new NoSuchServiceException("Service not known locally!");
ServiceAgent serviceAgent;
try {
serviceAgent = getServiceAgent(serviceClass);
} catch (AgentNotKnownException e1) {
throw new NoSuchServiceException(serviceClass, e1);
}
RMITask task = new RMITask(serviceClass, method, parameters);
Context context = getAgentContext(executingAgentId);
L2pThread thread = new L2pThread(serviceAgent, task, context);
thread.start();
thread.join();
if (thread.hasException()) {
Exception e = thread.getException();
if (e instanceof ServiceInvocationException)
throw (ServiceInvocationException) e;
else
throw new ServiceInvocationException("Internal exception in service", thread.getException());
}
try {
return thread.getResult();
} catch (NotFinishedException e) {
// should not occur, since we joined before
throw new L2pServiceException("Interrupted service execution?!", e);
}
}
/**
* Tries to get an instance of the given class as a registered service of this node.
*
* @param classname
* @return the instance of the given service class running at this node
* @throws NoSuchServiceException
*/
public Service getLocalServiceInstance(String classname) throws NoSuchServiceException {
try {
ServiceAgent agent = (ServiceAgent) getLocalAgent(ServiceAgent.serviceClass2Id(classname));
return agent.getServiceInstance();
} catch (Exception e) {
throw new NoSuchServiceException(classname);
}
}
/**
* Tries to get an instance of the given class as a registered service of this node.
* @param cls
* @return the (typed) instance of the given service class running at this node
* @throws NoSuchServiceException
*/
@SuppressWarnings("unchecked")
public <ServiceType extends Service> ServiceType getLocalServiceInstance(Class<ServiceType> cls)
throws NoSuchServiceException {
try {
return (ServiceType) getLocalServiceInstance(cls.getName());
} catch (ClassCastException e) {
throw new NoSuchServiceException(cls.getName());
}
}
private int invocationDistributerIndex = 0;
/**
* Invokes a service method of the network.
*
* @param executing
* @param serviceClass
* @param serviceMethod
* @param parameters
*
* @return result of the method invocation
*
* @throws L2pSecurityException
* @throws ServiceInvocationException several reasons -- see subclasses
* @throws InterruptedException
* @throws TimeoutException
* @throws UnlockNeededException
*/
public Serializable invokeGlobally(Agent executing, String serviceClass, String serviceMethod,
Serializable[] parameters) throws L2pSecurityException, ServiceInvocationException, InterruptedException,
TimeoutException, UnlockNeededException {
if (getStatus() != NodeStatus.RUNNING)
throw new IllegalStateException("you can invoke methods only on a running node!");
this.observerNotice(Event.RMI_SENT, this.getNodeId(), executing, null); //Do not log service class name (privacy..)
/*if (executing.isLocked()){
System.out.println( "The executing agent has to be unlocked to call a RMI");
throw new L2pSecurityException("The executing agent has to be unlocked to call a RMI");
}*/
try {
//Agent target = getServiceAgent(serviceClass);
Agent target = null;
target = nodeServiceCache.getServiceAgent(serviceClass, "1.0");
if (target == null)
target = getServiceAgent(serviceClass);
Message rmiMessage = new Message(executing, target, new RMITask(serviceClass, serviceMethod, parameters));
if (this instanceof LocalNode)
rmiMessage.setSendingNodeId((Long) getNodeId());
else
rmiMessage.setSendingNodeId((NodeHandle) getNodeId());
Message resultMessage;
NodeHandle targetNode = null;//=nodeServiceCache.getRandomServiceNode(serviceClass,"1.0");
ArrayList<NodeHandle> targetNodes = nodeServiceCache.getServiceNodes(serviceClass, "1.0");
if (targetNodes != null && targetNodes.size() > 0)
{
invocationDistributerIndex %= targetNodes.size();
targetNode = targetNodes.get(invocationDistributerIndex);
invocationDistributerIndex++;
if (invocationDistributerIndex >= targetNodes.size())
invocationDistributerIndex = 0;
}
//System.out.println( "### nodecount: "+nodeServiceCache.getServiceNodes(serviceClass,"1.0").size());
if (targetNode != null)
{
try
{
resultMessage = sendMessageAndWaitForAnswer(rmiMessage, targetNode);
} catch (NodeNotFoundException nex)
{
nodeServiceCache.removeEntryNode(serviceClass, "1.0", targetNode);//remove so unavailable nodes will not be tries again
resultMessage = sendMessageAndWaitForAnswer(rmiMessage);
}
}
else
resultMessage = sendMessageAndWaitForAnswer(rmiMessage);
resultMessage.open(executing, this);
Object resultContent = resultMessage.getContent();
if (resultContent instanceof RMIUnlockContent) {
// service method needed to unlock some envelope(s)
this.observerNotice(Event.RMI_FAILED, this.getNodeId(), executing, "mediator needed at the target node"); //Do not log service class name (privacy..)
throw new UnlockNeededException(
"mediator needed at the target node",
resultMessage.getSendingNodeId(),
((RMIUnlockContent) resultContent).getNodeKey());
} else if (resultContent instanceof RMIExceptionContent) {
Exception thrown = ((RMIExceptionContent) resultContent).getException();
this.observerNotice(Event.RMI_FAILED, this.getNodeId(), executing, thrown.toString()); //Do not log service class name (privacy..)
if (thrown instanceof ServiceInvocationException)
throw (ServiceInvocationException) thrown;
else if ((thrown instanceof InvocationTargetException)
&& (thrown.getCause() instanceof L2pSecurityException)) {
// internal L2pSecurityException (like internal method access or unauthorizes object access)
throw new L2pSecurityException("internal securityException!", thrown.getCause());
} else
throw new ServiceInvocationException("remote exception at target node", thrown);
} else if (resultContent instanceof RMIResultContent) {
this.observerNotice(Event.RMI_SUCCESSFUL, this.getNodeId(), executing, null); //Do not log service class name (privacy..)
return ((RMIResultContent) resultContent).getContent();
}
else {
this.observerNotice(Event.RMI_FAILED, this.getNodeId(), executing, "Unknown RMI response type: "
+ resultContent.getClass().getCanonicalName()); //Do not log service class name (privacy..)
throw new ServiceInvocationException("Unknown RMI response type: "
+ resultContent.getClass().getCanonicalName());
}
} catch (AgentNotKnownException e) {
this.observerNotice(Event.RMI_FAILED, this.getNodeId(), executing, e.toString()); //Do not log service class name (privacy..)
throw new NoSuchServiceException(serviceClass, e);
} catch (EncodingFailedException e) {
this.observerNotice(Event.RMI_FAILED, this.getNodeId(), executing, e.toString()); //Do not log service class name (privacy..)
throw new ServiceInvocationException("message problems!", e);
} catch (SerializationException e) {
this.observerNotice(Event.RMI_FAILED, this.getNodeId(), executing, e.toString()); //Do not log service class name (privacy..)
throw new ServiceInvocationException("message problems!", e);
}
}
/**
* Registers a MessageResultListener for collecting answers.
*
* @param messageId
* @param listener
*/
public void registerAnswerListener(long messageId, MessageResultListener listener) {
if (listener == null)
return;
htAnswerListeners.put(messageId, listener);
}
/**
* Hands over an answer message to the corresponding listener.
*
* @param answer
*
* @return true, if a listener for this answer was notified
*/
public boolean handoverAnswer(Message answer) {
if (!answer.isResponse())
return false;
observerNotice(Event.MESSAGE_RECEIVED_ANSWER, answer.getSendingNodeId(), answer.getSenderId(),
this.getNodeId(), answer.getRecipientId(), "" + answer.getResponseToId());
MessageResultListener listener = htAnswerListeners.get(answer.getResponseToId());
if (listener == null) {
System.out.println("Did not find corresponding observer!");
return false;
}
listener.collectAnswer(answer);
return true;
}
/**
* Sends a message and wait for one answer message.
*
* @param m
*
* @return a (possible) response message
*
* @throws InterruptedException
* @throws TimeoutException
*/
public Message sendMessageAndWaitForAnswer(Message m) throws InterruptedException, TimeoutException {
long timeout = m.getTimeoutTs() - new Date().getTime();
MessageResultListener listener = new MessageResultListener(timeout);
sendMessage(m, listener);
listener.waitForOneAnswer();
if (listener.isSuccess())
return listener.getResults()[0];
else
throw new TimeoutException();
}
/**
* Sends a message to the given id and wait for one answer message.
*
* @param m
* @param atNodeId
*
* @return a response message
*
* @throws AgentNotKnownException
* @throws NodeNotFoundException
* @throws L2pSecurityException
* @throws InterruptedException
*/
public Message sendMessageAndWaitForAnswer(Message m, Object atNodeId) throws AgentNotKnownException,
NodeNotFoundException, L2pSecurityException, InterruptedException {
long timeout = m.getTimeoutTs() - new Date().getTime();
MessageResultListener listener = new MessageResultListener(timeout);
sendMessage(m, atNodeId, listener);
listener.waitForOneAnswer();
// TODO what happens if the answers timeouts? Throw TimeoutException?
return listener.getResults()[0];
}
/**
* Gets the local execution context of an agent.
* If there is currently none, a new one will be created and stored for later use.
*
* @param agentId
*
* @return the context for the given agent
*
* @throws L2pSecurityException
* @throws AgentNotKnownException
*/
protected Context getAgentContext(long agentId) throws L2pSecurityException, AgentNotKnownException {
Context result = htLocalExecutionContexts.get(agentId);
if (result == null) {
Agent agent = getAgent(agentId);
result = new Context(this, agent);
htLocalExecutionContexts.put(agentId, result);
}
return result;
}
/**
* Gets a (possibly fresh) context for the given agent.
*
* @param agent
*
* @return a context
*/
protected Context getAgentContext(Agent agent) {
Context result = htLocalExecutionContexts.get(agent.getId());
if (result == null || (result.getMainAgent().isLocked() && !agent.isLocked())) {
try {
result = new Context(this, agent);
} catch (L2pSecurityException e) {
}
htLocalExecutionContexts.put(agent.getId(), result);
}
return result;
}
/**
* Checks, if the given service class is running at this node.
*
* @param serviceClass
* @return true, if this node as an instance of the given service running
*/
public boolean hasService(String serviceClass) {
return hasAgent(ServiceAgent.serviceClass2Id(serviceClass));
}
/**
* Gets the approximate CPU load of the JVM the Node is running on.
* Correct value only available a few seconds after the start of the Node.
* @return value between 0 and 1: CPU load of the JVM process * #cores
*/
public float getNodeCpuLoad() {
// TODO maybe this should be a division instead?
float load = (float) osBean.getProcessCpuLoad() * Runtime.getRuntime().availableProcessors();
if (load < 0.0f) {
load = 0f;
} else if (load > 1f) {
load = 1.0f;
}
return load;
}
public boolean isBusy() {
return (getNodeCpuLoad() > CPU_LOAD_TRESHOLD);
}
} |
package io.iron.ironmq;
import java.io.IOException;
import java.io.Reader;
import java.io.Serializable;
import java.util.ArrayList;
import com.google.gson.Gson;
/**
* The Queue class represents a specific IronMQ queue bound to a client.
*/
public class Queue {
final private Client client;
final private String name;
public Queue(Client client, String name) {
this.client = client;
this.name = name;
}
/**
* Retrieves a Message from the queue. If there are no items on the queue, an
* EmptyQueueException is thrown.
*
* @throws EmptyQueueException If the queue is empty.
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public Message get() throws IOException {
Messages msgs = get(1);
Message msg;
try {
msg = msgs.getMessage(0);
} catch (IndexOutOfBoundsException e) {
throw new EmptyQueueException();
}
return msg;
}
/**
* Retrieves Messages from the queue. If there are no items on the queue, an
* EmptyQueueException is thrown.
* @param numberOfMessages The number of messages to receive. Max. is 100.
* @throws EmptyQueueException If the queue is empty.
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public Messages get(int numberOfMessages) throws IOException {
return get(numberOfMessages, -1);
}
/**
* Retrieves Messages from the queue. If there are no items on the queue, an
* EmptyQueueException is thrown.
* @param numberOfMessages The number of messages to receive. Max. is 100.
* @param timeout timeout in seconds.
* @throws EmptyQueueException If the queue is empty.
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public Messages get(int numberOfMessages, int timeout) throws IOException {
if (numberOfMessages < 1 || numberOfMessages > 100) {
throw new IllegalArgumentException("numberOfMessages has to be within 1..100");
}
String url = "queues/" + name + "/messages?n=" + numberOfMessages;
if (timeout > -1) {
url += "&timeout=" + timeout;
}
Reader reader = client.get(url);
Gson gson = new Gson();
Messages messages = gson.fromJson(reader, Messages.class);
reader.close();
return messages;
}
/**
* Peeking at a queue returns the next messages on the queue, but it does not reserve them.
* If there are no items on the queue, an EmptyQueueException is thrown.
*
* @throws EmptyQueueException If the queue is empty.
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public Message peek() throws IOException {
Messages msgs = peek(1);
Message msg;
try {
msg = msgs.getMessage(0);
} catch (IndexOutOfBoundsException e) {
throw new EmptyQueueException();
}
return msg;
}
/**
* Peeking at a queue returns the next messages on the queue, but it does not reserve them.
*
* @param numberOfMessages The number of messages to receive. Max. is 100.
* @throws EmptyQueueException If the queue is empty.
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public Messages peek(int numberOfMessages) throws IOException {
if (numberOfMessages < 1 || numberOfMessages > 100) {
throw new IllegalArgumentException("numberOfMessages has to be within 1..100");
}
Reader reader = client.get("queues/" + name + "/messages/peek?n="+numberOfMessages);
try{
return new Gson().fromJson(reader, Messages.class);
}finally{
reader.close();
}
}
/**
* Touching a reserved message extends its timeout to the duration specified when the message was created.
*
* @param id The ID of the message to delete.
*
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public void touchMessage(String id) throws IOException {
client.post("queues/" + name + "/messages/" + id + "/touch", "");
}
/**
* Deletes a Message from the queue.
*
* @param id The ID of the message to delete.
*
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public void deleteMessage(String id) throws IOException {
client.delete("queues/" + name + "/messages/" + id);
}
/**
* Deletes multiple messages from the queue.
*
* @param ids The IDs of the messages to delete.
*
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public void deleteMessages(Ids ids) throws IOException {
Gson gson = new Gson();
String jsonMessages = gson.toJson(ids);
Reader reader = client.delete("queues/" + name + "/messages", jsonMessages);
reader.close();
}
/**
* Destroy the queue.
*
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public void destroy() throws IOException {
client.delete("queues/" + name);
}
/**
* Deletes a Message from the queue.
*
* @param msg The message to delete.
*
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public void deleteMessage(Message msg) throws IOException {
deleteMessage(msg.getId());
}
/**
* Pushes a message onto the queue.
*
* @param msg The body of the message to push.
* @return The new message's ID
*
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public String push(String msg) throws IOException {
return push(msg, 0);
}
/**
* Pushes a messages onto the queue.
*
* @param msg The array of the messages to push.
* @return The IDs of new messages
*
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public Ids pushMessages(String[] msg) throws IOException {
return pushMessages(msg, 0);
}
/**
* Pushes a message onto the queue.
*
* @param msg The body of the message to push.
* @param timeout The message's timeout in seconds.
* @return The new message's ID
*
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public String push(String msg, long timeout) throws IOException {
return push(msg, timeout, 0);
}
/**
* Pushes a messages onto the queue.
*
* @param msg The array of the messages to push.
* @param timeout The message's timeout in seconds.
* @return The IDs of new messages
*
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public Ids pushMessages(String msg[], long timeout) throws IOException {
return pushMessages(msg, timeout, 0);
}
/**
* Pushes a message onto the queue.
*
* @param msg The body of the message to push.
* @param timeout The message's timeout in seconds.
* @param delay The message's delay in seconds.
* @return The new message's ID
*
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public String push(String msg, long timeout, long delay) throws IOException {
return push(msg, timeout, delay, 0);
}
/**
* Pushes a messages onto the queue.
*
* @param msg The array of the messages to push.
* @param timeout The message's timeout in seconds.
* @param delay The message's delay in seconds.
* @return The IDs of new messages
*
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public Ids pushMessages(String[] msg, long timeout, long delay) throws IOException {
return pushMessages(msg, timeout, delay, 0);
}
/**
* Pushes a message onto the queue.
*
* @param msg The body of the message to push.
* @param timeout The message's timeout in seconds.
* @param delay The message's delay in seconds.
* @param expiresIn The message's expiration offset in seconds.
* @return The new message's ID
*
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public String push(String msg, long timeout, long delay, long expiresIn) throws IOException {
ArrayList<Message> messages = new ArrayList<Message>();
Message message = new Message();
message.setBody(msg);
message.setTimeout(timeout);
message.setDelay(delay);
message.setExpiresIn(expiresIn);
messages.add(message);
Messages msgs = new Messages(messages);
Gson gson = new Gson();
String body = gson.toJson(msgs);
Reader reader = client.post("queues/" + name + "/messages", body);
Ids ids = gson.fromJson(reader, Ids.class);
reader.close();
return ids.getId(0);
}
/**
* Pushes a messages onto the queue.
*
* @param msg The array of the messages to push.
* @param timeout The message's timeout in seconds.
* @param delay The message's delay in seconds.
* @param expiresIn The message's expiration offset in seconds.
* @return The IDs of new messages
*
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public Ids pushMessages(String[] msg, long timeout, long delay, long expiresIn) throws IOException {
ArrayList<Message> messages = new ArrayList<Message>();
for (String messageName: msg){
Message message = new Message();
message.setBody(messageName);
message.setTimeout(timeout);
message.setDelay(delay);
message.setExpiresIn(expiresIn);
messages.add(message);
}
Messages msgs = new Messages(messages);
Gson gson = new Gson();
String jsonMessages = gson.toJson(msgs);
Reader reader = client.post("queues/" + name + "/messages", jsonMessages);
Ids ids = gson.fromJson(reader, Ids.class);
reader.close();
return ids;
}
/**
* Clears the queue off all messages
* @throws IOException
*/
public void clear() throws IOException {
client.post("queues/"+name+"/clear", "").close();
}
/**
* @return the name of this queue
*/
public String getName() {
return name;
}
/**
* Retrieves Info about queue. If there is no queue, an EmptyQueueException is thrown.
* @throws EmptyQueueException If there is no queue.
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public QueueModel getInfoAboutQueue() throws IOException {
Reader reader = client.get("queues/" + name);
Gson gson = new Gson();
QueueModel message = gson.fromJson(reader, QueueModel.class);
reader.close();
return message;
}
/**
* Retrieves Message from the queue by message id. If there are no items on the queue, an
* EmptyQueueException is thrown.
* @param id The ID of the message to get.
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public Message getMessageById(String id) throws IOException {
String url = "queues/" + name + "/messages/" + id;
Reader reader = client.get(url);
Gson gson = new Gson();
Message message = gson.fromJson(reader, Message.class);
reader.close();
return message;
}
static class Delay {
private int delay;
public Delay(int delay) {
this.delay = delay;
}
}
/**
* Release locked message after specified time. If there is no message with such id on the queue, an
* EmptyQueueException is thrown.
* @param id The ID of the message to release.
* @param delay The time after which the message will be released.
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public void releaseMessage(String id, int delay) throws IOException {
String url = "queues/" + name + "/messages/" + id + "/release";
Gson gson = new Gson();
Delay delayClass = new Delay(delay);
String jsonMessages = gson.toJson(delayClass);
Reader reader = client.post(url, jsonMessages);
reader.close();
}
/**
* Add subscribers to Queue. If there is no queue, an EmptyQueueException is thrown.
* @param subscribersList The array list of subscribers.
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public void addSubscribersToQueue(ArrayList<Subscriber> subscribersList) throws IOException {
String url = "queues/" + name + "/subscribers";
Subscribers subscribers = new Subscribers(subscribersList);
Gson gson = new Gson();
String jsonMessages = gson.toJson(subscribers);
Reader reader = client.post(url, jsonMessages);
reader.close();
}
/**
* Remove subscribers from Queue. If there is no queue, an EmptyQueueException is thrown.
* @param subscribersList The array list of subscribers.
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public void removeSubscribersFromQueue(ArrayList<Subscriber> subscribersList) throws IOException {
String url = "queues/" + name + "/subscribers";
Subscribers subscribers = new Subscribers(subscribersList);
Gson gson = new Gson();
String jsonMessages = gson.toJson(subscribers);
Reader reader = client.delete(url, jsonMessages);
reader.close();
}
/**
* Get push info of message by message id. If there is no message, an EmptyQueueException is thrown.
* @param messageId The Message ID.
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public SubscribersInfo getPushStatusForMessage(String messageId) throws IOException {
String url = "queues/" + name + "/messages/" + messageId + "/subscribers";
Reader reader = client.get(url);
Gson gson = new Gson();
SubscribersInfo subscribersInfo = gson.fromJson(reader, SubscribersInfo.class);
reader.close();
return subscribersInfo;
}
/**
* Delete push message for subscriber by subscriber ID and message ID. If there is no message or subscriber,
* an EmptyQueueException is thrown.
* @param subscriberId The Subscriber ID.
* @param messageId The Message ID.
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public void deletePushMessageForSubscriber(String messageId, String subscriberId) throws IOException {
client.delete("queues/" + name + "/messages/" + messageId + "/subscribers/" + subscriberId);
}
static class UpdateQueue {
private String pushType;
private int retries;
private int retriesDelay;
private ArrayList<Subscriber> subscribers;
private ArrayList<Alert> alerts;
public UpdateQueue(ArrayList<Subscriber> subscribers, ArrayList<Alert> alerts, String pushType, int retries, int retriesDelay) {
this.subscribers = subscribers;
this.alerts = alerts;
this.pushType = pushType;
this.retries = retries;
this.retriesDelay = retriesDelay;
}
}
/**
* Update queue. If there is no queue, an EmptyQueueException is thrown.
* @param subscribersList The subscribers list.
* @param alertsList The alerts list.
* @param pushType The push type - multicast or unicast.
* @param retries The retries.
* @param retriesDelay The retries delay.
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public QueueModel updateQueue(ArrayList<Subscriber> subscribersList, ArrayList<Alert> alertsList, String pushType, int retries, int retriesDelay) throws IOException {
String url = "queues/" + name;
UpdateQueue updateQueue = new UpdateQueue(subscribersList, alertsList, pushType, retries, retriesDelay);
Gson gson = new Gson();
String jsonMessages = gson.toJson(updateQueue);
Reader reader = client.post(url, jsonMessages);
QueueModel message = gson.fromJson(reader, QueueModel.class);
reader.close();
return message;
}
/**
* Add alerts to a queue. If there is no queue, an EmptyQueueException is thrown.
* @param alerts The array list of alerts.
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public void addAlertsToQueue(ArrayList<Alert> alerts) throws IOException {
String url = "queues/" + name + "/alerts";
Alerts alert = new Alerts(alerts);
Gson gson = new Gson();
String jsonMessages = gson.toJson(alert);
Reader reader = client.post(url, jsonMessages);
reader.close();
}
/**
* Replace current queue alerts with a given list of alerts. If there is no queue, an EmptyQueueException is thrown.
* @param alerts The array list of alerts.
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public void updateAlertsToQueue(ArrayList<Alert> alerts) throws IOException {
String url = "queues/" + name + "/alerts";
Alerts alert = new Alerts(alerts);
Gson gson = new Gson();
String jsonMessages = gson.toJson(alert);
Reader reader = client.put(url, jsonMessages);
reader.close();
}
/**
* Delete alerts from a queue. If there is no queue, an EmptyQueueException is thrown.
* @param alert_ids The array list of alert ids.
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public void deleteAlertsFromQueue(ArrayList<Alert> alert_ids) throws IOException {
String url = "queues/" + name + "/alerts";
Alerts alert = new Alerts(alert_ids);
Gson gson = new Gson();
String jsonMessages = gson.toJson(alert);
Reader reader = client.delete(url, jsonMessages);
reader.close();
}
/**
* Delete alert from a queue by alert id. If there is no queue, an EmptyQueueException is thrown.
* @param alert_id The alert id.
* @throws HTTPException If the IronMQ service returns a status other than 200 OK.
* @throws IOException If there is an error accessing the IronMQ server.
*/
public void deleteAlertFromQueueById(String alert_id) throws IOException {
String url = "queues/" + name + "/alerts/" + alert_id;
client.delete(url);
}
} |
package is.ru.hugb;
/**
* @author Arnar
*/
public class TicTacToe {
/**
* A 3x3 array of characters that keeps track of the state of the board.
*/
private char[][] gameBoard;
/**
* The length of the game board.
*/
private final int BOARDSIZE = 3;
/**
* A constant to indicate the game is still ongoing.
*/
private final int GAMENOTOVER = 0;
/**
* A constant to indicate the game has ended in a tie.
*/
private final int GAMETIED = 3;
/**
* A constant to represent player one.
*/
private final int PLAYERONE = 1;
/**
* A constant to represent player two.
*/
private final int PLAYERTWO = 2;
/**
* A constant to represent player one's symbol.
*/
private final char PLAYERONESYMBOL = 'x';
/**
* A constant to represent player two's symbol.
*/
private final char PLAYERTWOSYMBOL = 'o';
/**
* A Tic Tac Toe Game
*/
public TicTacToe() {
gameBoard = new char[BOARDSIZE][BOARDSIZE];
initializeGameboard();
}
public static void main(String[] args) {
}
/**
* Initialize the game board.
* <p>
* Initialze the game board by setting each char in the
* array to the number that position represents
*/
public void initializeGameboard() {
for (int row = 0; row < BOARDSIZE; row++) {
for (int col = 0; col < BOARDSIZE; col++) {
gameBoard[row][col] = Character.forDigit(row * 3 + col, 10);
}
}
}
/**
* Output a string representation of the game board.
* @return A String representation of the board.
*/
public String toString() {
StringBuilder builder = new StringBuilder();
for (int row = 0; row < BOARDSIZE; row++) {
for (int col = 0; col < BOARDSIZE; col++) {
builder.append(gameBoard[row][col]);
}
builder.append("\n");
}
return builder.toString();
}
/**
* Converts a onedimensional position to a two dimensional one.
*
* @param position integer from 1-9 to convert to a gameBoard position.
* @return Returns a BoardCoords that contains a gameBoard position.
*/
private BoardCoords convertBoardPosition(int position) {
int row = position / BOARDSIZE;
int col = position % BOARDSIZE;
return new BoardCoords(row, col);
}
/**
* Validates that a position is between 1 and 9.
* <p>
* Longer description. If there were any, it would be
* here.
* <p>
* And even more explanations to follow in consecutive
* paragraphs separated by HTML paragraph breaks.
*
* @param position Description text text text.
* @return Returns true if 1 <= position <= 9.
*/
private boolean validatePosition(int position) {
if (position > 9 || position < 1) {
return false;
}
return true;
}
/**
* Function that checks if the game is over
* <p>
* Function that checks either plays has 3 symbols in a row or the game
* board is full
*
* @return Returns 0 if the game is still going, 1 if player one won,
* 2 if player two won or 3 if the game is tied.
*/
public int isGameOver() {
for (int i = 0; i < BOARDSIZE; i++) {
if (gameBoard[i][0] == gameBoard[i][1] && gameBoard[i][0] == gameBoard[i][2]) {
return getPlayerFromSymbol(gameBoard[i][0]);
}
}
for (int i = 0; i < BOARDSIZE; i++) {
if (gameBoard[0][i] == gameBoard[1][i] && gameBoard[0][i] == gameBoard[2][i]) {
return getPlayerFromSymbol(gameBoard[0][i]);
}
}
if (gameBoard[0][0] == gameBoard[1][1] && gameBoard[0][0] == gameBoard[2][2]) {
return getPlayerFromSymbol(gameBoard[0][0]);
}
if (gameBoard[0][2] == gameBoard[1][1] && gameBoard[0][2] == gameBoard[2][0]) {
return getPlayerFromSymbol(gameBoard[0][2]);
}
int symbolCounter = 0;
for (int i = 0; i < BOARDSIZE; i++) {
for (int j = 0; j < BOARDSIZE; j++) {
if (gameBoard[i][j] == PLAYERONESYMBOL || gameBoard[i][j] == PLAYERTWOSYMBOL) {
symbolCounter++;
}
}
}
if (symbolCounter == 9) {
return GAMETIED;
}
return GAMENOTOVER;
}
/**
* Function that returns the players symbol.
* @param symbol the symbol of the player.
* @return Returns 1 if symbol is player ones symbol, 2 otherwise.
*/
private int getPlayerFromSymbol(char symbol) {
if (symbol == PLAYERONESYMBOL) {
return PLAYERONE;
}
return PLAYERTWO;
}
/**
* Inserts a players symbol into the gameboard.
* @param position the board position to place the symbol
* @param player theplayer whoes turn it is.
* @return returns true if the symbol is placed, false otherwise.
*/
public boolean insertSymbol(int player, int position) {
if (validatePosition(position)) {
BoardCoords coords = convertBoardPosition(position - 1);
if (gameBoard[coords.row][coords.col] != PLAYERONESYMBOL
&& gameBoard[coords.row][coords.col] != PLAYERTWOSYMBOL) {
if (player == PLAYERTWO) {
gameBoard[coords.row][coords.col] = PLAYERTWOSYMBOL;
}
else {
gameBoard[coords.row][coords.col] = PLAYERONESYMBOL;
}
return true;
}
}
return false;
}
private class BoardCoords {
private int row;
private int col;
BoardCoords(int row, int col) {
this.row = row;
this.col = col;
}
}
} |
package leetcode;
import java.util.List;
public class Problem1096 {
public List<String> braceExpansionII(String expression) {
// TODO
return null;
}
public static void main(String[] args) {
Problem1096 prob = new Problem1096();
System.out.println(prob.braceExpansionII("a{b,c}")); // ["ab","ac"]
System.out.println(prob.braceExpansionII("{c{d,e}f}")); // ["cdf","cef"]
// System.out.println(prob.braceExpansionII("{a,b}{c{d,e}}")); // ["acd","ace","bcd","bce"]
// System.out.println(prob.braceExpansionII("{{a,z},a{b,c},{ab,z}}")); // ["a","ab","ac","z"]
// System.out.println(prob.braceExpansionII("{a,b,c}")); // ["a","b","c"]
// System.out.println(prob.braceExpansionII("{{a,b},{b,c}}")); // ["a","b","c"]
// System.out.println(prob.braceExpansionII("{a,b}{c,d}")); // ["ac","ad","bc","bd"]
// System.out.println(prob.braceExpansionII("{a{b,c}}{{d,e}f{g,h}}")); // ["abdfg", "abdfh", "abefg", "abefh", "acdfg", "acdfh", "acefg", "acefh"]
}
} |
package leetcode;
import java.util.ArrayList;
import java.util.List;
public class Problem1313 {
public int[] decompressRLElist(int[] nums) {
List<Integer> decompresssed = new ArrayList<>();
for (int i = 0; i < nums.length; i += 2) {
int a = nums[i];
int b = nums[i + 1];
for (int j = 0; j < a; j++) {
decompresssed.add(b);
}
}
int[] answer = new int[decompresssed.size()];
for (int i = 0; i < answer.length; i++) {
answer[i] = decompresssed.get(i);
}
return answer;
}
} |
package leetcode;
public class Problem1325 {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public TreeNode removeLeafNodes(TreeNode root, int target) {
// TODO
return null;
}
public static void main(String[] args) {
Problem1325 prob = new Problem1325();
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.left.left = new TreeNode(2);
root.right = new TreeNode(3);
root.right.left = new TreeNode(2);
root.right.right = new TreeNode(4);
System.out.println(prob.removeLeafNodes(root, 2));
}
} |
package leetcode;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;
public class Problem1370 {
public String sortString(String s) {
TreeMap<Character, Integer> map = new TreeMap<>();
for (int i = 0; i < s.length(); i++) {
map.put(s.charAt(i), map.getOrDefault(s.charAt(i), 0) + 1);
}
String answer = "";
boolean asc = true;
while (map.size() > 0) {
List<Character> keys = asc ?
new ArrayList<>(map.keySet()) : new ArrayList<>(map.descendingKeySet());
for (char key : keys) {
answer += key;
int c = map.get(key) - 1;
if (c == 0) {
map.remove(key);
} else {
map.put(key, c);
}
}
asc = !asc;
}
return answer;
}
} |
package leetcode;
public class Problem1379 {
public static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) {
val = x;
}
}
public final TreeNode getTargetCopy(final TreeNode original, final TreeNode cloned, final TreeNode target) {
if (original == null) {
return null;
}
if (original == target) {
return cloned;
}
TreeNode left = getTargetCopy(original.left, cloned.left, target);
if (left != null) {
return left;
}
return getTargetCopy(original.right, cloned.right, target);
}
} |
package leetcode;
public class Problem1423 {
public int maxScore(int[] cardPoints, int k) {
int[] prefixSum = new int[cardPoints.length];
for (int i = 0; i < cardPoints.length; i++) {
if (i == 0) {
prefixSum[i] = cardPoints[i];
} else {
prefixSum[i] = prefixSum[i - 1] + cardPoints[i];
}
}
int answer = 0;
for (int i = k - 1; i >= 0; i
if (i - k + 1 == 0) {
answer = Math.max(answer, prefixSum[i]);
} else {
int sum = prefixSum[i] + getSuffixSum(prefixSum, cardPoints.length + i - k + 1);
answer = Math.max(answer, sum);
}
}
return Math.max(answer, getSuffixSum(prefixSum, cardPoints.length - k));
}
private static int getSuffixSum(int[] prefixSum, int index) {
return prefixSum[prefixSum.length - 1] - (index - 1 < 0 ? 0 : prefixSum[index - 1]);
}
} |
// Package Declaration
package me.iffa.bspace;
// Java Imports
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
// Pail Imports
import me.escapeNT.pail.Pail;
// PluginStats Imports
import com.randomappdev.pluginstats.Ping;
// bSpace Imports
import me.iffa.bspace.api.SpaceConfigHandler;
import me.iffa.bspace.api.SpaceLangHandler;
import me.iffa.bspace.api.SpaceMessageHandler;
import me.iffa.bspace.api.schematic.SpaceSchematicHandler;
import me.iffa.bspace.api.SpaceWorldHandler;
import me.iffa.bspace.commands.SpaceCommandHandler;
import me.iffa.bspace.config.SpaceConfig;
import me.iffa.bspace.config.SpaceConfigUpdater;
import me.iffa.bspace.economy.Economy;
import me.iffa.bspace.gui.PailInterface;
import me.iffa.bspace.listeners.SpaceEntityListener;
import me.iffa.bspace.listeners.SpacePlayerListener;
import me.iffa.bspace.listeners.SpaceSuffocationListener;
import me.iffa.bspace.listeners.misc.BlackHoleScannerListener;
import me.iffa.bspace.listeners.misc.SpaceWeatherListener;
import me.iffa.bspace.listeners.misc.SpaceWorldListener;
import me.iffa.bspace.listeners.spout.SpaceSpoutAreaListener;
import me.iffa.bspace.listeners.spout.SpaceSpoutCraftListener;
import me.iffa.bspace.listeners.spout.SpaceSpoutEntityListener;
import me.iffa.bspace.listeners.spout.SpaceSpoutKeyListener;
import me.iffa.bspace.listeners.spout.SpaceSpoutPlayerListener;
import me.iffa.bspace.runnables.SpoutBlackHoleAreaRunnable;
import me.iffa.bspace.wgen.planets.PlanetsChunkGenerator;
// Bukkit Imports
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.generator.ChunkGenerator;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
/**
* Main class of bSpace.
*
* @author iffa
* @author kitskub
* @author HACKhalo2
*/
public class Space extends JavaPlugin {
// Variables
// And here goes all public statics!
private static String prefix;
private static String version;
private static SpaceWorldHandler worldHandler;
private static PailInterface pailInterface;
private static Map<Player, Location> locCache = null;
private static boolean jumpPressed = false;
private PluginManager pm;
private SpaceCommandHandler sce = null;
private Economy economy;
private final SpaceWeatherListener weatherListener = new SpaceWeatherListener();
private final SpaceEntityListener entityListener = new SpaceEntityListener();
private final SpaceWorldListener worldListener = new SpaceWorldListener();
private final SpacePlayerListener playerListener = new SpacePlayerListener();
/**
* Called when the plugin is disabled.
*/
@Override
public void onDisable() {
Bukkit.getScheduler().cancelTasks(this);
// Finishing up disablation.
SpaceMessageHandler.print(Level.INFO, SpaceLangHandler.getDisabledMessage());
}
/**
* Called when the plugin is enabled.
*/
@Override
public void onEnable() {
// Initializing variables.
initVariables();
SpaceMessageHandler.debugPrint(Level.INFO, "Initialized startup variables.");
// Loading configuration files.
SpaceConfig.loadConfigs();
SpaceMessageHandler.debugPrint(Level.INFO, "Loaded configuration files, now checking if they need to be updated...");
// Updating configuration files (if needed).
SpaceConfigUpdater.updateConfigs();
// Registering events.
registerEvents();
// Loading schematic files.
SpaceSchematicHandler.loadSchematics();
// Loading space worlds (startup).
worldHandler.loadSpaceWorlds();
// Initializing the CommandExecutor for /space.
sce = new SpaceCommandHandler(this);
getCommand("space").setExecutor(sce);
SpaceMessageHandler.debugPrint(Level.INFO, "Initialized CommandExecutors.");
// Checking if it should always be night in space worlds.
for (World world : worldHandler.getSpaceWorlds()) {
if (SpaceConfigHandler.forceNight(world)) {
worldHandler.startForceNightTask(world);
SpaceMessageHandler.debugPrint(Level.INFO, "Started night forcing task for world '" + world.getName() + "'.");
}
}
// Checking if Economy is ok.
if (economy == null && getServer().getPluginManager().getPlugin("Register") != null) {
if (Economy.checkEconomy()) {
economy = new Economy();
}
}
// Initializing the Pail tab.
if (pm.getPlugin("Pail") != null) {
SpaceMessageHandler.debugPrint(Level.INFO, "Starting up the Pail tab.");
pailInterface = new PailInterface(this);
((Pail) pm.getPlugin("Pail")).loadInterfaceComponent("bSpace", pailInterface);
}
// Initializing black hole stuff.
if (pm.getPlugin("Spout") != null) {
Bukkit.getScheduler().scheduleSyncRepeatingTask(this, new SpoutBlackHoleAreaRunnable(), 1, 5);
}
// Finishing up enablation.
SpaceMessageHandler.print(Level.INFO, SpaceLangHandler.getUsageStatsMessage());
Ping.init(this);
SpaceMessageHandler.print(Level.INFO, SpaceLangHandler.getEnabledMessage());
}
/**
* Initializes variables (used on startup).
*/
private void initVariables() {
pm = getServer().getPluginManager();
version = getDescription().getVersion();
prefix = "[" + getDescription().getName() + "]";
worldHandler = new SpaceWorldHandler(this);
if (pm.getPlugin("Spout") != null && SpaceConfigHandler.isUsingSpout()) {
locCache = new HashMap<Player, Location>();
}
}
/**
* Registers events for bSpace.
*/
private void registerEvents() {
// Registering other events.
pm.registerEvent(Event.Type.WEATHER_CHANGE, weatherListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.WORLD_LOAD, worldListener, Event.Priority.Normal, this);
SpaceMessageHandler.debugPrint(Level.INFO, "Registered events (other).");
// Registering entity & player events.
pm.registerEvent(Event.Type.ENTITY_DAMAGE, entityListener, Event.Priority.High, this);
pm.registerEvent(Event.Type.ENTITY_DEATH, entityListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.CREATURE_SPAWN, entityListener, Event.Priority.Highest, this);
pm.registerEvent(Event.Type.PLAYER_TELEPORT, playerListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_MOVE, playerListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_RESPAWN, playerListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_QUIT, playerListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.PLAYER_JOIN, playerListener, Event.Priority.Normal, this);
pm.registerEvent(Event.Type.CUSTOM_EVENT, new SpaceSuffocationListener(), Event.Priority.Monitor, this); //Suffocation Listener
SpaceMessageHandler.debugPrint(Level.INFO, "Registered events (entity & player).");
// Registering events for Spout.
if (pm.getPlugin("Spout") != null && SpaceConfigHandler.isUsingSpout()) {
pm.registerEvent(Event.Type.PLAYER_TELEPORT, new SpaceSpoutPlayerListener(this), Event.Priority.Normal, this); //Player listener
pm.registerEvent(Event.Type.PLAYER_RESPAWN, new SpaceSpoutPlayerListener(this), Event.Priority.Normal, this); // Player listener
//pm.registerEvent(Event.Type.PLAYER_JOIN, spListener, Event.Priority.Normal, this); //moved this into a Custom Listener
pm.registerEvent(Event.Type.ENTITY_DAMAGE, new SpaceSpoutEntityListener(), Event.Priority.Normal, this); //Entity Listener
//pm.registerEvent(Event.Type.CREATURE_SPAWN, speListener, Event.Priority.Normal, this); //Disabled until Limitations in Spout is fixed
pm.registerEvent(Event.Type.CUSTOM_EVENT, new SpaceSpoutCraftListener(), Event.Priority.Normal, this); //SpoutCraft Listener
pm.registerEvent(Event.Type.CUSTOM_EVENT, new SpaceSpoutAreaListener(), Event.Priority.Normal, this); //Area Listener
pm.registerEvent(Event.Type.CUSTOM_EVENT, new SpaceSpoutKeyListener(), Event.Priority.Normal, this); //Key Listener
pm.registerEvent(Event.Type.CHUNK_LOAD, new BlackHoleScannerListener(), Event.Priority.Normal, this); // Black hole scanner
SpaceMessageHandler.debugPrint(Level.INFO, "Registered events (Spout).");
}
}
/**
* Gets the default world generator of the plugin.
*
* @param worldName World name
* @param id ID (cow, fish etc)
*
* @return ChunkGenerator to use
*/
@Override
public ChunkGenerator getDefaultWorldGenerator(String worldName, String id) {
boolean realID=true;
if(id == null || id.isEmpty() || id.length() == 0){
realID=false;
}
if(realID){
SpaceMessageHandler.debugPrint(Level.INFO, "Getting generator for '" + worldName + "' using id: '" + id + "'");
}else{
SpaceMessageHandler.debugPrint(Level.INFO, "Getting generator for '" + worldName + "' using default id,planets.");
}
SpaceWorldHandler.checkWorld(worldName);
if (!realID) {
return new PlanetsChunkGenerator("planets", false);
}
return new PlanetsChunkGenerator(id);
}
/* Some API methods */
/**
* Gets the SpaceWorldHandler.
*
* @return SpaceWorldHandler
*/
public static SpaceWorldHandler getWorldHandler() {
return worldHandler;
}
/**
* Gets the jump pressed value. (ie = wtf is this)
*
* @return Jump pressed
*/
public static boolean getJumpPressed() {
return jumpPressed;
}
/**
* Sets the jump pressed value. (ie = wtf is this ??)
*
* @param newJumpPressed New jump pressed value
*/
public static void setJumpPressed(boolean newJumpPressed) {
jumpPressed = newJumpPressed;
}
/**
* Gets the location cache.
*
* @return Location cach
*/
public static Map<Player, Location> getLocCache() {
return locCache;
}
/**
* Gets the plugin's prefix.
*
* @return Prefix
*/
public static String getPrefix() {
return prefix;
}
/**
* Gets the plugin's version.
*
* @return Version
*/
public static String getVersion() {
return version;
}
/**
* Gets the Economy-class.
*
* @return Economy
*/
public Economy getEconomy() {
return economy;
}
} |
package mytown.entities;
import myessentials.teleport.Teleport;
import myessentials.utils.PlayerUtils;
import mypermissions.api.entities.PermissionLevel;
import mypermissions.proxies.PermissionProxy;
import mytown.api.container.*;
import mytown.config.Config;
import mytown.entities.flag.FlagType;
import mytown.proxies.LocalizationProxy;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.util.EnumChatFormatting;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* Defines a Town. A Town is made up of Residents, Ranks, Blocks, and Plots.
*/
public class Town implements Comparable<Town> {
private String name, oldName = null;
protected int extraBlocks = 0;
protected int maxFarClaims = Config.maxFarClaims;
private Nation nation;
private Teleport spawn;
public final ResidentRankMap residentsMap = new ResidentRankMap();
public final RanksContainer ranksContainer = new RanksContainer();
public final PlotsContainer plotsContainer = new PlotsContainer(Config.defaultMaxPlots);
public final FlagsContainer flagsContainer = new FlagsContainer();
public final TownBlocksContainer townBlocksContainer = new TownBlocksContainer();
public final BlockWhitelistsContainer blockWhitelistsContainer = new BlockWhitelistsContainer();
public final Bank bank = new Bank(this);
public Town(String name) {
this.name = name;
}
public void notifyResidentJoin(Resident res) {
for (Resident toRes : residentsMap.keySet()) {
toRes.sendMessage(LocalizationProxy.getLocalization().getLocalization("mytown.notification.town.joined", res.getPlayerName(), getName()));
}
}
/**
* Notifies every resident in this town sending a message.
*/
public void notifyEveryone(String message) {
for (Resident r : residentsMap.keySet()) {
r.sendMessage(message);
}
}
/**
* Checks if the Resident is allowed to do the action specified by the FlagType at the coordinates given.
* This method will go through all the plots and prioritize the plot's flags over town flags.
*/
@SuppressWarnings("unchecked")
public boolean hasPermission(Resident res, FlagType flagType, Object denialValue, int dim, int x, int y, int z) {
Plot plot = plotsContainer.get(dim, x, y, z);
if (plot == null) {
return hasPermission(res, flagType, denialValue);
} else {
return plot.hasPermission(res, flagType, denialValue);
}
}
/**
* Checks if the Resident is allowed to do the action specified by the FlagType in this town.
*/
public boolean hasPermission(Resident res, FlagType flagType, Object denialValue) {
if(PlayerUtils.isOp(res.getUUID())) {
return true;
}
if(!flagsContainer.getValue(flagType).equals(denialValue)) {
return true;
}
boolean rankBypass;
boolean permissionBypass;
if(residentsMap.containsKey(res)) {
if((Boolean) flagsContainer.getValue(FlagType.RESTRICTIONS)) {
rankBypass = hasPermission(res, FlagType.RESTRICTIONS.getBypassPermission());
permissionBypass = PermissionProxy.getPermissionManager().hasPermission(res.getUUID(), FlagType.RESTRICTIONS.getBypassPermission());
if(!rankBypass && !permissionBypass) {
return false;
}
}
rankBypass = hasPermission(res, flagType.getBypassPermission());
permissionBypass = PermissionProxy.getPermissionManager().hasPermission(res.getUUID(), flagType.getBypassPermission());
if(!rankBypass && !permissionBypass) {
return false;
}
} else {
permissionBypass = PermissionProxy.getPermissionManager().hasPermission(res.getUUID(), flagType.getBypassPermission());
if(!permissionBypass) {
return false;
}
}
return true;
}
public boolean hasPermission(Resident res, String permission) {
if(!residentsMap.containsKey(res)) {
return false;
}
Rank rank = residentsMap.get(res);
return rank.permissionsContainer.hasPermission(permission) == PermissionLevel.ALLOWED;
}
public Object getValueAtCoords(int dim, int x, int y, int z, FlagType flagType) {
Plot plot = plotsContainer.get(dim, x, y, z);
if(plot == null || flagType.isTownOnly()) {
return flagsContainer.getValue(flagType);
} else {
return plot.flagsContainer.getValue(flagType);
}
}
/**
* Used to get the owners of a plot (or a town) at the position given
* Returns null if position is not in town
*/
public List<Resident> getOwnersAtPosition(int dim, int x, int y, int z) {
List<Resident> list = new ArrayList<Resident>();
Plot plot = plotsContainer.get(dim, x, y, z);
if (plot == null) {
if (isPointInTown(dim, x, z) && !(this instanceof AdminTown) && !residentsMap.isEmpty()) {
Resident mayor = residentsMap.getMayor();
if (mayor != null) {
list.add(mayor);
}
}
} else {
for (Resident res : plot.ownersContainer) {
list.add(res);
}
}
return list;
}
public void sendToSpawn(Resident res) {
EntityPlayer pl = res.getPlayer();
if (pl != null) {
PlayerUtils.teleport((EntityPlayerMP)pl, spawn.getDim(), spawn.getX(), spawn.getY(), spawn.getZ());
res.setTeleportCooldown(Config.teleportCooldown);
}
}
public void calculateMaxBlocks() {
int mayorBlocks = Config.blocksMayor;
int residentsBlocks = Config.blocksResident * (residentsMap.size() - 1);
int residentsExtra = 0;
for(Resident res : residentsMap.keySet()) {
residentsBlocks += res.getExtraBlocks();
}
int townExtra = townBlocksContainer.getExtraBlocks();
townBlocksContainer.setMaxBlocks(mayorBlocks + residentsBlocks + residentsExtra + townExtra);
}
public String formatOwners(int dim, int x, int y, int z) {
List<Resident> residents = getOwnersAtPosition(dim, x, y, z);
String formattedList = "";
for (Resident r : residents) {
if (formattedList.equals("")) {
formattedList = r.getPlayerName();
} else {
formattedList += ", " + r.getPlayerName();
}
}
if(formattedList.equals("")) {
formattedList = EnumChatFormatting.RED + "SERVER ADMINS";
}
return formattedList;
}
@Override
public int compareTo(Town t) { // TODO Flesh this out more for ranking towns?
int thisNumberOfResidents = residentsMap.size(),
thatNumberOfResidents = t.residentsMap.size();
if (thisNumberOfResidents > thatNumberOfResidents)
return -1;
else if (thisNumberOfResidents == thatNumberOfResidents)
return 0;
else if (thisNumberOfResidents < thatNumberOfResidents)
return 1;
return -1;
}
public String getName() {
return name;
}
public String getOldName() {
return oldName;
}
/**
* Renames this current Town setting oldName to the previous name. You MUST set oldName to null after saving it in the Datasource
*/
public void rename(String newName) {
oldName = name;
name = newName;
}
/**
* Resets the oldName to null. You MUST call this after a name change in the Datasource!
*/
public void resetOldName() {
oldName = null;
}
public Nation getNation() {
return nation;
}
public void setNation(Nation nation) {
this.nation = nation;
}
public boolean hasSpawn() {
return spawn != null;
}
public Teleport getSpawn() {
return spawn;
}
public void setSpawn(Teleport spawn) {
this.spawn = spawn;
}
/**
* Checks if the given block in non-chunk coordinates is in this Town
*/
public boolean isPointInTown(int dim, int x, int z) {
return isChunkInTown(dim, x >> 4, z >> 4);
}
public boolean isChunkInTown(int dim, int chunkX, int chunkZ) {
return townBlocksContainer.contains(dim, chunkX, chunkZ);
}
} |
package org.oakgp.util;
import static java.util.Collections.unmodifiableList;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import org.oakgp.Type;
import org.oakgp.node.Node;
/** Utility methods that support the functionality provided by the rest of the framework. */
public final class Utils {
/** Private constructor as all methods are static. */
private Utils() {
// do nothing
}
public static <T extends Node> Map<Type, List<T>> groupNodesByType(T[] nodes) {
return groupValuesByKey(nodes, Node::getType);
}
public static <K, V> Map<K, List<V>> groupValuesByKey(V[] values, Function<V, K> valueToKey) {
Map<K, List<V>> nodesByType = new HashMap<>();
for (V v : values) {
addToListOfMap(nodesByType, valueToKey.apply(v), v);
}
makeValuesImmutable(nodesByType);
return nodesByType;
}
private static <K, V> void addToListOfMap(Map<K, List<V>> map, K key, V value) {
List<V> list = map.get(key);
if (list == null) {
list = new ArrayList<>();
map.put(key, list);
}
list.add(value);
}
private static <K, V> void makeValuesImmutable(Map<K, List<V>> map) {
for (Map.Entry<K, List<V>> e : map.entrySet()) {
map.put(e.getKey(), unmodifiableList(e.getValue()));
}
}
} |
package org.owasp.esapi;
import java.io.Serializable;
import java.security.Principal;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.http.HttpSession;
import org.owasp.esapi.errors.AuthenticationException;
import org.owasp.esapi.errors.EncryptionException;
public interface User extends Principal, Serializable {
/**
* Adds a role to this user's account.
*
* @param role
* the role to add
*
* @throws AuthenticationException
* the authentication exception
*/
void addRole(String role) throws AuthenticationException;
/**
* Adds a set of roles to this user's account.
*
* @param newRoles
* the new roles to add
*
* @throws AuthenticationException
* the authentication exception
*/
void addRoles(Set newRoles) throws AuthenticationException;
/**
* Sets the user's password, performing a verification of the user's old password, the equality of the two new
* passwords, and the strength of the new password.
*
* @param oldPassword
* the old password
* @param newPassword1
* the new password
* @param newPassword2
* the new password - used to verify that the new password was typed correctly
*
* @throws AuthenticationException
* if newPassword1 does not match newPassword2, if oldPassword does not match the stored old password, or if the new password does not meet complexity requirements
* @throws EncryptionException
*/
void changePassword(String oldPassword, String newPassword1, String newPassword2) throws AuthenticationException, EncryptionException;
/**
* Disable this user's account.
*/
void disable();
/**
* Enable this user's account.
*/
void enable();
/**
* Gets this user's account id number.
*
* @return the account id
*/
long getAccountId();
/**
* Gets this user's account name.
*
* @return the account name
*/
String getAccountName();
/**
* Gets the CSRF token for this user's current sessions.
*
* @return the CSRF token
*/
String getCSRFToken();
/**
* Returns the date that this user's account will expire.
*
* @return Date representing the account expiration time.
*/
Date getExpirationTime();
/**
* Returns the number of failed login attempts since the last successful login for an account. This method is
* intended to be used as a part of the account lockout feature, to help protect against brute force attacks.
* However, the implementor should be aware that lockouts can be used to prevent access to an application by a
* legitimate user, and should consider the risk of denial of service.
*
* @return the number of failed login attempts since the last successful login
*/
int getFailedLoginCount();
/**
* Returns the last host address used by the user. This will be used in any log messages generated by the processing
* of this request.
*
* @return the last host address used by the user
*/
String getLastHostAddress();
/**
* Returns the date of the last failed login time for a user. This date should be used in a message to users after a
* successful login, to notify them of potential attack activity on their account.
*
* @return date of the last failed login
*
* @throws AuthenticationException
* the authentication exception
*/
Date getLastFailedLoginTime() throws AuthenticationException;
/**
* Returns the date of the last successful login time for a user. This date should be used in a message to users
* after a successful login, to notify them of potential attack activity on their account.
*
* @return date of the last successful login
*/
Date getLastLoginTime();
/**
* Gets the date of user's last password change.
*
* @return the date of last password change
*/
Date getLastPasswordChangeTime();
/**
* Gets the roles assigned to a particular account.
*
* @return an immutable set of roles
*/
Set getRoles();
/**
* Gets the screen name (alias) for the current user.
*
* @return the screen name
*/
String getScreenName();
/**
* Adds a session for this User.
*
* @param s
* The session to associate with this user.
*/
void addSession( HttpSession s );
/**
* Removes a session for this User.
*
* @param s
* The session to remove from being associated with this user.
*/
void removeSession( HttpSession s );
/**
* Returns the list of sessions associated with this User.
* @return
*/
Set getSessions();
/**
* Increment failed login count.
*/
void incrementFailedLoginCount();
/**
* Checks if user is anonymous.
*
* @return true, if user is anonymous
*/
boolean isAnonymous();
/**
* Checks if this user's account is currently enabled.
*
* @return true, if account is enabled
*/
boolean isEnabled();
/**
* Checks if this user's account is expired.
*
* @return true, if account is expired
*/
boolean isExpired();
/**
* Checks if this user's account is assigned a particular role.
*
* @param role
* the role for which to check
*
* @return true, if role has been assigned to user
*/
boolean isInRole(String role);
/**
* Checks if this user's account is locked.
*
* @return true, if account is locked
*/
boolean isLocked();
/**
* Tests to see if the user is currently logged in.
*
* @return true, if the user is logged in
*/
boolean isLoggedIn();
/**
* Tests to see if this user's session has exceeded the absolute time out based
* on ESAPI's configuration settings.
*
* @return true, if user's session has exceeded the absolute time out
*/
boolean isSessionAbsoluteTimeout();
/**
* Tests to see if the user's session has timed out from inactivity based
* on ESAPI's configuration settings.
*
* A session may timeout prior to ESAPI's configuration setting due to
* the servlet container setting for session-timeout in web.xml. The
* following is an example of a web.xml session-timeout set for one hour.
*
* <session-config>
* <session-timeout>60</session-timeout>
* </session-config>
*
* @return true, if user's session has timed out from inactivity based
* on ESAPI configuration
*/
boolean isSessionTimeout();
/**
* Lock this user's account.
*/
void lock();
/**
* Login with password.
*
* @param password
* the password
* @throws AuthenticationException
* if login fails
*/
void loginWithPassword(String password) throws AuthenticationException;
/**
* Logout this user.
*/
void logout();
/**
* Removes a role from this user's account.
*
* @param role
* the role to remove
* @throws AuthenticationException
* the authentication exception
*/
void removeRole(String role) throws AuthenticationException;
/**
* Returns a token to be used as a prevention against CSRF attacks. This token should be added to all links and
* forms. The application should verify that all requests contain the token, or they may have been generated by a
* CSRF attack. It is generally best to perform the check in a centralized location, either a filter or controller.
* See the verifyCSRFToken method.
*
* @return the new CSRF token
*
* @throws AuthenticationException
* the authentication exception
*/
String resetCSRFToken() throws AuthenticationException;
/**
* Sets this user's account name.
*
* @param accountName the new account name
*/
void setAccountName(String accountName);
/**
* Sets the date and time when this user's account will expire.
*
* @param expirationTime the new expiration time
*/
void setExpirationTime(Date expirationTime);
/**
* Sets the roles for this account.
*
* @param roles
* the new roles
*
* @throws AuthenticationException
* the authentication exception
*/
void setRoles(Set roles) throws AuthenticationException;
/**
* Sets the screen name (username alias) for this user.
*
* @param screenName the new screen name
*/
void setScreenName(String screenName);
/**
* Unlock this user's account.
*/
void unlock();
/**
* Verify that the supplied password matches the password for this user. This method
* is typically used for "reauthentication" for the most sensitive functions, such
* as transactions, changing email address, and changing other account information.
*
* @param password
* the password that the user entered
*
* @return true, if the password passed in matches the account's password
*
* @throws EncryptionException
*/
public boolean verifyPassword(String password) throws EncryptionException;
/**
* Set the time of the last failed login for this user.
*
* @param lastFailedLoginTime the date and time when the user just failed to login correctly.
*/
void setLastFailedLoginTime(Date lastFailedLoginTime);
/**
* Set the last remote host address used by this user.
*
* @param remoteHost The address of the user's current source host.
*/
void setLastHostAddress(String remoteHost);
/**
* Set the time of the last successful login for this user.
*
* @param lastLoginTime the date and time when the user just successfully logged in.
*/
void setLastLoginTime(Date lastLoginTime);
/**
* Set the time of the last password change for this user.
*
* @param lastPasswordChangeTime the date and time when the user just successfully changed his/her password.
*/
void setLastPasswordChangeTime(Date lastPasswordChangeTime);
/**
* The ANONYMOUS user is used to represent an unidentified user. Since there is
* always a real user, the ANONYMOUS user is better than using null to represent
* this.
*/
public final User ANONYMOUS = new User() {
private String csrfToken = "";
private Set sessions = new HashSet();
/**
* {@inheritDoc}
*/
public void addRole(String role) throws AuthenticationException {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/**
* {@inheritDoc}
*/
public void addRoles(Set newRoles) throws AuthenticationException {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/**
* {@inheritDoc}
*/
public void changePassword(String oldPassword, String newPassword1,
String newPassword2) throws AuthenticationException,
EncryptionException {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/**
* {@inheritDoc}
*/
public void disable() {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/**
* {@inheritDoc}
*/
public void enable() {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/**
* {@inheritDoc}
*/
public long getAccountId() {
return 0;
}
/**
* {@inheritDoc}
*/
public String getAccountName() {
return "Anonymous";
}
/**
* Alias method that is equivalent to getAccountName()
*
* @return the name of the current user's account
*/
public String getName() {
return getAccountName();
}
/**
* {@inheritDoc}
*/
public String getCSRFToken() {
return csrfToken;
}
/**
* {@inheritDoc}
*/
public Date getExpirationTime() {
return null;
}
/**
* {@inheritDoc}
*/
public int getFailedLoginCount() {
return 0;
}
/**
* {@inheritDoc}
*/
public Date getLastFailedLoginTime() throws AuthenticationException {
return null;
}
/**
* {@inheritDoc}
*/
public String getLastHostAddress() {
return "unknown";
}
/**
* {@inheritDoc}
*/
public Date getLastLoginTime() {
return null;
}
/**
* {@inheritDoc}
*/
public Date getLastPasswordChangeTime() {
return null;
}
/**
* {@inheritDoc}
*/
public Set getRoles() {
return new HashSet();
}
/**
* {@inheritDoc}
*/
public String getScreenName() {
return "Anonymous";
}
/**
* {@inheritDoc}
*/
public void addSession(HttpSession s) {
}
/**
* {@inheritDoc}
*/
public void removeSession(HttpSession s) {
}
/**
* {@inheritDoc}
*/
public Set getSessions() {
return sessions;
}
/**
* {@inheritDoc}
*/
public void incrementFailedLoginCount() {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/**
* {@inheritDoc}
*/
public boolean isAnonymous() {
return true;
}
/**
* {@inheritDoc}
*/
public boolean isEnabled() {
return false;
}
/**
* {@inheritDoc}
*/
public boolean isExpired() {
return false;
}
/**
* {@inheritDoc}
*/
public boolean isInRole(String role) {
return false;
}
/**
* {@inheritDoc}
*/
public boolean isLocked() {
return false;
}
/**
* {@inheritDoc}
*/
public boolean isLoggedIn() {
return false;
}
/**
* {@inheritDoc}
*/
public boolean isSessionAbsoluteTimeout() {
return false;
}
/**
* {@inheritDoc}
*/
public boolean isSessionTimeout() {
return false;
}
/**
* {@inheritDoc}
*/
public void lock() {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/**
* {@inheritDoc}
*/
public void loginWithPassword(String password)
throws AuthenticationException {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/**
* {@inheritDoc}
*/
public void logout() {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/**
* {@inheritDoc}
*/
public void removeRole(String role) throws AuthenticationException {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/**
* {@inheritDoc}
*/
public String resetCSRFToken() throws AuthenticationException {
csrfToken = ESAPI.randomizer().getRandomString(8, Encoder.CHAR_ALPHANUMERICS);
return csrfToken;
}
/**
* {@inheritDoc}
*/
public void setAccountName(String accountName) {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/**
* {@inheritDoc}
*/
public void setExpirationTime(Date expirationTime) {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/**
* {@inheritDoc}
*/
public void setRoles(Set roles) throws AuthenticationException {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/**
* {@inheritDoc}
*/
public void setScreenName(String screenName) {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/**
* {@inheritDoc}
*/
public void unlock() {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/**
* {@inheritDoc}
*/
public boolean verifyPassword(String password) throws EncryptionException {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/**
* {@inheritDoc}
*/
public void setLastFailedLoginTime(Date lastFailedLoginTime) {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/**
* {@inheritDoc}
*/
public void setLastLoginTime(Date lastLoginTime) {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/**
* {@inheritDoc}
*/
public void setLastHostAddress(String remoteHost) {
throw new RuntimeException("Invalid operation for the anonymous user");
}
/**
* {@inheritDoc}
*/
public void setLastPasswordChangeTime(Date lastPasswordChangeTime) {
throw new RuntimeException("Invalid operation for the anonymous user");
}
};
} |
package org.takes.tk;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import lombok.EqualsAndHashCode;
import lombok.ToString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.takes.Request;
import org.takes.Response;
import org.takes.Take;
import org.takes.rq.RqHref;
import org.takes.rq.RqMethod;
/**
* Logs Take.act() calls.
*
* <p>The class is immutable and thread-safe.
*
* @since 0.11.2
*/
@ToString(of = { "origin", "target" })
@EqualsAndHashCode
public final class TkSlf4j implements Take {
/**
* Original take.
*/
private final Take origin;
/**
* Log target.
*/
private final String target;
/**
* Ctor.
* @param take Original
*/
public TkSlf4j(final Take take) {
this(take, TkSlf4j.class);
}
/**
* Ctor.
* @param take Original
* @param tgt Log target
*/
public TkSlf4j(final Take take, final Class<?> tgt) {
this(take, tgt.getCanonicalName());
}
/**
* Ctor.
* @param take Original
* @param tgt Log target
*/
public TkSlf4j(final Take take, final String tgt) {
this.target = tgt;
this.origin = take;
}
@Override
@SuppressWarnings("PMD.AvoidCatchingGenericException")
public Response act(final Request req) throws Exception {
final long start = System.currentTimeMillis();
TkPatternLog log = new TkRqPatternLog(this.target, req, start);
try {
final Response rsp = this.origin.act(req);
log.append("returned \"{}\"", rsp.head().iterator().next());
return rsp;
} catch (final IOException ex) {
log.append("thrown {}(\"{}\")",
ex.getClass().getCanonicalName(),
ex.getLocalizedMessage());
throw ex;
} catch (final RuntimeException ex) {
log.append("thrown runtime {}(\"{}\")",
ex.getClass().getCanonicalName(),
ex.getLocalizedMessage());
throw ex;
}
}
private interface TkPatternLog {
void append(String pattern, Object... objects);
}
private static class TkRqPatternLog implements TkPatternLog {
private final Logger logger;
private final String rqMethod;
private final String rqHref;
private final long ms;
public TkRqPatternLog(String target, Request request, long start) throws IOException {
this.logger = LoggerFactory.getLogger(target);
this.rqMethod = new RqMethod.Base(request).method();
this.rqHref = new RqHref.Base(request).href().toString();
this.ms = System.currentTimeMillis() - start;
}
@Override
public void append(String pattern, Object... objects) {
if (logger.isInfoEnabled()) {
final List<Object> objectList = new ArrayList<>(2 + objects.length + 1);
objectList.add(this.rqMethod);
objectList.add(this.rqHref);
objectList.addAll(Arrays.asList(objects));
objectList.add(this.ms);
logger.info("[{} {}] " + pattern + " in {} ms", objectList.toArray());
}
}
}
} |
package picard.sam;
import htsjdk.samtools.BAMRecordCodec;
import htsjdk.samtools.SAMFileHeader;
import htsjdk.samtools.SAMFileHeader.SortOrder;
import htsjdk.samtools.SAMFileWriter;
import htsjdk.samtools.SAMFileWriterFactory;
import htsjdk.samtools.SAMReadGroupRecord;
import htsjdk.samtools.SAMRecord;
import htsjdk.samtools.SAMRecordQueryNameComparator;
import htsjdk.samtools.SAMTag;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import htsjdk.samtools.ValidationStringency;
import htsjdk.samtools.filter.FilteringSamIterator;
import htsjdk.samtools.filter.SamRecordFilter;
import htsjdk.samtools.util.CloserUtil;
import htsjdk.samtools.util.FastqQualityFormat;
import htsjdk.samtools.util.IOUtil;
import htsjdk.samtools.util.Log;
import htsjdk.samtools.util.PeekableIterator;
import htsjdk.samtools.util.ProgressLogger;
import htsjdk.samtools.util.QualityEncodingDetector;
import htsjdk.samtools.util.RuntimeIOException;
import htsjdk.samtools.util.SolexaQualityConverter;
import htsjdk.samtools.util.SortingCollection;
import org.broadinstitute.barclay.argparser.Argument;
import org.broadinstitute.barclay.argparser.CommandLineParser;
import org.broadinstitute.barclay.argparser.CommandLineProgramProperties;
import org.broadinstitute.barclay.help.DocumentedFeature;
import picard.PicardException;
import picard.cmdline.CommandLineProgram;
import picard.cmdline.StandardOptionDefinitions;
import picard.cmdline.programgroups.ReadDataManipulationProgramGroup;
import picard.util.TabbedTextFileWithHeaderParser;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
/**
* Reverts a SAM file by optionally restoring original quality scores and by removing
* all alignment information.
* <p>
* <p>
* This tool removes or restores certain properties of the SAM records, including alignment information.
* It can be used to produce an unmapped BAM (uBAM) from a previously aligned BAM. It is also capable of
* restoring the original quality scores of a BAM file that has already undergone base quality score recalibration
* (BQSR) if the original qualities were retained during the calibration (in the OQ tag).
* <p>
* <h3>Usage Examples</h3>
* <h4>Output to a single file</h4>
* <pre>
* java -jar picard.jar RevertSam \\
* I=input.bam \\
* O=reverted.bam
* </pre>
* <p>
* <h4>Output by read group into multiple files with sample map</h4>
* <pre>
* java -jar picard.jar RevertSam \\
* I=input.bam \\
* OUTPUT_BY_READGROUP=true \\
* OUTPUT_MAP=reverted_bam_paths.tsv
* </pre>
* <p>
* <h4>Output by read group with no output map</h4>
* <pre>
* java -jar picard.jar RevertSam \\
* I=input.bam \\
* OUTPUT_BY_READGROUP=true \\
* O=/write/reverted/read/group/bams/in/this/dir
* </pre>
* This will output a BAM (Can be overridden with OUTPUT_BY_READGROUP_FILE_FORMAT option.)
* <br/>
* Note: If the program fails due to a SAM validation error, consider setting the VALIDATION_STRINGENCY option to
* LENIENT or SILENT if the failures are expected to be obviated by the reversion process
* (e.g. invalid alignment information will be obviated when the REMOVE_ALIGNMENT_INFORMATION option is used).
*/
@CommandLineProgramProperties(
summary = RevertSam.USAGE_SUMMARY + RevertSam.USAGE_DETAILS,
oneLineSummary = RevertSam.USAGE_SUMMARY,
programGroup = ReadDataManipulationProgramGroup.class)
@DocumentedFeature
public class RevertSam extends CommandLineProgram {
static final String USAGE_SUMMARY = "Reverts SAM or BAM files to a previous state. ";
static final String USAGE_DETAILS = "This tool removes or restores certain properties of the SAM records, including alignment " +
"information, which can be used to produce an unmapped BAM (uBAM) from a previously aligned BAM. It is also capable of " +
"restoring the original quality scores of a BAM file that has already undergone base quality score recalibration (BQSR) if the" +
"original qualities were retained.\n" +
"<h3>Examples</h3>\n" +
"<h4>Example with single output:</h4>\n" +
"java -jar picard.jar RevertSam \\\n" +
" I=input.bam \\\n" +
" O=reverted.bam\n" +
"\n" +
"<h4>Example outputting by read group with output map:</h4>\n" +
"java -jar picard.jar RevertSam \\\n" +
" I=input.bam \\\n" +
" OUTPUT_BY_READGROUP=true \\\n" +
" OUTPUT_MAP=reverted_bam_paths.tsv\n" +
"\n" +
"Will output a BAM/SAM file per read group.\n" +
"<h4>Example outputting by read group without output map:</h4>\n" +
"java -jar picard.jar RevertSam \\\n" +
" I=input.bam \\\n" +
" OUTPUT_BY_READGROUP=true \\\n" +
" O=/write/reverted/read/group/bams/in/this/dir\n" +
"\n" +
"Will output a BAM file per read group." +
" Output format can be overridden with the OUTPUT_BY_READGROUP_FILE_FORMAT option.\n" +
"Note: If the program fails due to a SAM validation error, consider setting the VALIDATION_STRINGENCY option to " +
"LENIENT or SILENT if the failures are expected to be obviated by the reversion process " +
"(e.g. invalid alignment information will be obviated when the REMOVE_ALIGNMENT_INFORMATION option is used).\n" +
"";
@Argument(shortName = StandardOptionDefinitions.INPUT_SHORT_NAME, doc = "The input SAM/BAM file to revert the state of.")
public File INPUT;
@Argument(mutex = {"OUTPUT_MAP"}, shortName = StandardOptionDefinitions.OUTPUT_SHORT_NAME, doc = "The output SAM/BAM file to create, or an output directory if OUTPUT_BY_READGROUP is true.")
public File OUTPUT;
@Argument(mutex = {"OUTPUT"}, shortName = "OM", doc = "Tab separated file with two columns, READ_GROUP_ID and OUTPUT, providing file mapping only used if OUTPUT_BY_READGROUP is true.")
public File OUTPUT_MAP;
@Argument(shortName = "OBR", doc = "When true, outputs each read group in a separate file.")
public boolean OUTPUT_BY_READGROUP = false;
public static enum FileType implements CommandLineParser.ClpEnum {
sam("Generate SAM files."),
bam("Generate BAM files."),
cram("Generate CRAM files."),
dynamic("Generate files based on the extention of INPUT.");
final String description;
FileType(String descrition) {
this.description = descrition;
}
@Override
public String getHelpDoc() {
return description;
}
}
@Argument(shortName = "OBRFF", doc = "When using OUTPUT_BY_READGROUP, the output file format can be set to a certain format.")
public FileType OUTPUT_BY_READGROUP_FILE_FORMAT = FileType.dynamic;
@Argument(shortName = "SO", doc = "The sort order to create the reverted output file with.")
public SortOrder SORT_ORDER = SortOrder.queryname;
@Argument(shortName = StandardOptionDefinitions.USE_ORIGINAL_QUALITIES_SHORT_NAME, doc = "True to restore original qualities from the OQ field to the QUAL field if available.")
public boolean RESTORE_ORIGINAL_QUALITIES = true;
@Argument(doc = "Remove duplicate read flags from all reads. Note that if this is false and REMOVE_ALIGNMENT_INFORMATION==true, " +
" the output may have the unusual but sometimes desirable trait of having unmapped reads that are marked as duplicates.")
public boolean REMOVE_DUPLICATE_INFORMATION = true;
@Argument(doc = "Remove all alignment information from the file.")
public boolean REMOVE_ALIGNMENT_INFORMATION = true;
@Argument(doc = "When removing alignment information, the set of optional tags to remove.")
public List<String> ATTRIBUTE_TO_CLEAR = new ArrayList<String>() {{
add(SAMTag.NM.name());
add(SAMTag.UQ.name());
add(SAMTag.PG.name());
add(SAMTag.MD.name());
add(SAMTag.MQ.name());
add(SAMTag.SA.name()); // Supplementary alignment metadata
add(SAMTag.MC.name()); // Mate Cigar
add(SAMTag.AS.name());
}};
@Argument(doc = "WARNING: This option is potentially destructive. If enabled will discard reads in order to produce " +
"a consistent output BAM. Reads discarded include (but are not limited to) paired reads with missing " +
"mates, duplicated records, records with mismatches in length of bases and qualities. This option can " +
"only be enabled if the output sort order is queryname and will always cause sorting to occur.")
public boolean SANITIZE = false;
@Argument(doc = "If SANITIZE=true and higher than MAX_DISCARD_FRACTION reads are discarded due to sanitization then" +
"the program will exit with an Exception instead of exiting cleanly. Output BAM will still be valid.")
public double MAX_DISCARD_FRACTION = 0.01;
@Argument(doc = "If SANITIZE=true keep the first record when we find more than one record with the same name for R1/R2/unpaired reads respectively. " +
"For paired end reads, keeps only the first R1 and R2 found respectively, and discards all unpaired reads. " +
"Duplicates do not refer to the duplicate flag in the FLAG field, but instead reads with the same name.")
public boolean KEEP_FIRST_DUPLICATE = false;
@Argument(doc = "The sample alias to use in the reverted output file. This will override the existing " +
"sample alias in the file and is used only if all the read groups in the input file have the " +
"same sample alias.", shortName = StandardOptionDefinitions.SAMPLE_ALIAS_SHORT_NAME, optional = true)
public String SAMPLE_ALIAS;
@Argument(doc = "The library name to use in the reverted output file. This will override the existing " +
"sample alias in the file and is used only if all the read groups in the input file have the " +
"same library name.", shortName = StandardOptionDefinitions.LIBRARY_NAME_SHORT_NAME, optional = true)
public String LIBRARY_NAME;
private final static Log log = Log.getInstance(RevertSam.class);
/**
* Enforce that output ordering is queryname when sanitization is turned on since it requires a queryname sort.
*/
@Override
protected String[] customCommandLineValidation() {
final List<String> errors = new ArrayList<>();
ValidationUtil.validateSanitizeSortOrder(SANITIZE, SORT_ORDER, errors);
ValidationUtil.validateOutputParams(OUTPUT_BY_READGROUP, OUTPUT, OUTPUT_MAP, errors);
if (!SANITIZE && KEEP_FIRST_DUPLICATE) errors.add("KEEP_FIRST_DUPLICATE cannot be used without SANITIZE");
if (!errors.isEmpty()) {
return errors.toArray(new String[errors.size()]);
}
return null;
}
protected int doWork() {
IOUtil.assertFileIsReadable(INPUT);
ValidationUtil.assertWritable(OUTPUT, OUTPUT_BY_READGROUP);
final boolean sanitizing = SANITIZE;
final SamReader in = SamReaderFactory.makeDefault().referenceSequence(REFERENCE_SEQUENCE).validationStringency(VALIDATION_STRINGENCY).open(INPUT);
final SAMFileHeader inHeader = in.getFileHeader();
ValidationUtil.validateHeaderOverrides(inHeader, SAMPLE_ALIAS, LIBRARY_NAME);
// Build the output writer with an appropriate header based on the options
final boolean presorted = isPresorted(inHeader, SORT_ORDER, sanitizing);
if (SAMPLE_ALIAS != null) overwriteSample(inHeader.getReadGroups(), SAMPLE_ALIAS);
if (LIBRARY_NAME != null) overwriteLibrary(inHeader.getReadGroups(), LIBRARY_NAME);
final SAMFileHeader singleOutHeader = createOutHeader(inHeader, SORT_ORDER, REMOVE_ALIGNMENT_INFORMATION);
inHeader.getReadGroups().forEach(readGroup -> singleOutHeader.addReadGroup(readGroup));
final Map<String, File> outputMap;
final Map<String, SAMFileHeader> headerMap;
if (OUTPUT_BY_READGROUP) {
if (inHeader.getReadGroups().isEmpty()) {
throw new PicardException(INPUT + " does not contain Read Groups");
}
final String defaultExtension;
if (OUTPUT_BY_READGROUP_FILE_FORMAT == FileType.dynamic) {
defaultExtension = getDefaultExtension(INPUT.toString());
} else {
defaultExtension = "." + OUTPUT_BY_READGROUP_FILE_FORMAT.toString();
}
outputMap = createOutputMap(OUTPUT_MAP, OUTPUT, defaultExtension, inHeader.getReadGroups());
ValidationUtil.assertAllReadGroupsMapped(outputMap, inHeader.getReadGroups());
headerMap = createHeaderMap(inHeader, SORT_ORDER, REMOVE_ALIGNMENT_INFORMATION);
} else {
outputMap = null;
headerMap = null;
}
final SAMFileWriterFactory factory = new SAMFileWriterFactory();
final RevertSamWriter out = new RevertSamWriter(OUTPUT_BY_READGROUP, headerMap, outputMap, singleOutHeader, OUTPUT, presorted, factory, REFERENCE_SEQUENCE);
// Build a sorting collection to use if we are sanitizing
final RevertSamSorter sorter;
if (sanitizing)
sorter = new RevertSamSorter(OUTPUT_BY_READGROUP, headerMap, singleOutHeader, MAX_RECORDS_IN_RAM);
else sorter = null;
final ProgressLogger progress = new ProgressLogger(log, 1000000, "Reverted");
for (final SAMRecord rec : in) {
// Weed out non-primary and supplemental read as we don't want duplicates in the reverted file!
if (rec.isSecondaryOrSupplementary()) continue;
// log the progress before you revert because otherwise the "last read position" might not be accurate
progress.record(rec);
// Actually do the reverting of the remaining records
revertSamRecord(rec);
if (sanitizing) sorter.add(rec);
else out.addAlignment(rec);
}
CloserUtil.close(in);
// Now if we're sanitizing, clean up the records and write them to the output
if (!sanitizing) {
out.close();
} else {
final Map<SAMReadGroupRecord, FastqQualityFormat> readGroupToFormat;
try {
readGroupToFormat = createReadGroupFormatMap(inHeader, REFERENCE_SEQUENCE, VALIDATION_STRINGENCY, INPUT, RESTORE_ORIGINAL_QUALITIES);
} catch (final PicardException e) {
log.error(e.getMessage());
return -1;
}
final long[] sanitizeResults = sanitize(readGroupToFormat, sorter, out);
final long discarded = sanitizeResults[0];
final long total = sanitizeResults[1];
out.close();
final double discardRate = discarded / (double) total;
final NumberFormat fmt = new DecimalFormat("0.000%");
log.info("Discarded " + discarded + " out of " + total + " (" + fmt.format(discardRate) + ") reads in order to sanitize output.");
if (discardRate > MAX_DISCARD_FRACTION) {
throw new PicardException("Discarded " + fmt.format(discardRate) + " which is above MAX_DISCARD_FRACTION of " + fmt.format(MAX_DISCARD_FRACTION));
}
}
return 0;
}
static String getDefaultExtension(final String input) {
if (input.endsWith(".sam")) {
return ".sam";
}
if (input.endsWith(".cram")) {
return ".cram";
}
return ".bam";
}
private boolean isPresorted(final SAMFileHeader inHeader, final SortOrder sortOrder, final boolean sanitizing) {
return (inHeader.getSortOrder() == sortOrder) || (sortOrder == SortOrder.queryname && sanitizing);
}
/**
* Takes an individual SAMRecord and applies the set of changes/reversions to it that
* have been requested by program level options.
*/
public void revertSamRecord(final SAMRecord rec) {
if (RESTORE_ORIGINAL_QUALITIES) {
final byte[] oq = rec.getOriginalBaseQualities();
if (oq != null) {
rec.setBaseQualities(oq);
rec.setOriginalBaseQualities(null);
}
}
if (REMOVE_DUPLICATE_INFORMATION) {
rec.setDuplicateReadFlag(false);
}
if (REMOVE_ALIGNMENT_INFORMATION) {
if (rec.getReadNegativeStrandFlag()) {
rec.reverseComplement(true);
rec.setReadNegativeStrandFlag(false);
}
// Remove all alignment based information about the read itself
rec.setReferenceIndex(SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX);
rec.setAlignmentStart(SAMRecord.NO_ALIGNMENT_START);
rec.setCigarString(SAMRecord.NO_ALIGNMENT_CIGAR);
rec.setMappingQuality(SAMRecord.NO_MAPPING_QUALITY);
rec.setInferredInsertSize(0);
rec.setNotPrimaryAlignmentFlag(false);
rec.setProperPairFlag(false);
rec.setReadUnmappedFlag(true);
// Then remove any mate flags and info related to alignment
rec.setMateAlignmentStart(SAMRecord.NO_ALIGNMENT_START);
rec.setMateNegativeStrandFlag(false);
rec.setMateReferenceIndex(SAMRecord.NO_ALIGNMENT_REFERENCE_INDEX);
rec.setMateUnmappedFlag(rec.getReadPairedFlag());
// And then remove any tags that are calculated from the alignment
ATTRIBUTE_TO_CLEAR.forEach(tag -> rec.setAttribute(tag, null));
}
}
private long[] sanitize(final Map<SAMReadGroupRecord, FastqQualityFormat> readGroupToFormat, final RevertSamSorter sorter, final RevertSamWriter out) {
long total = 0, discarded = 0;
final ProgressLogger sanitizerProgress = new ProgressLogger(log, 1000000, "Sanitized");
final List<PeekableIterator<SAMRecord>> iterators = sorter.iterators();
for (final PeekableIterator<SAMRecord> iterator : iterators) {
readNameLoop:
while (iterator.hasNext()) {
List<SAMRecord> recs = fetchByReadName(iterator);
total += recs.size();
// Check that all the reads have bases and qualities of the same length
for (final SAMRecord rec : recs) {
if (rec.getReadBases().length != rec.getBaseQualities().length) {
log.debug("Discarding ", recs.size(), " reads with name ", rec.getReadName(), " for mismatching bases and quals length.");
discarded += recs.size();
continue readNameLoop;
}
}
// Get the number of R1s, R2s, and unpaired reads respectively.
int firsts = 0, seconds = 0, unpaired = 0;
SAMRecord firstRecord = null, secondRecord = null, unpairedRecord = null;
for (final SAMRecord rec : recs) {
if (!rec.getReadPairedFlag()) {
if (unpairedRecord == null) {
unpairedRecord = rec;
}
++unpaired;
} else {
if (rec.getFirstOfPairFlag()) {
if (firstRecord == null) {
firstRecord = rec;
}
++firsts;
}
if (rec.getSecondOfPairFlag()) {
if (secondRecord == null) {
secondRecord = rec;
}
++seconds;
}
}
}
// If we have paired reads, then check that there is exactly one first of pair and one second of pair.
// Otherwise, check that we have only one unpaired read.
if (firsts > 0 || seconds > 0) { // if we have any paired reads
if (firsts != 1 || seconds != 1) { // if we do not have exactly one R1 and one R2
if (KEEP_FIRST_DUPLICATE && firsts >= 1 && seconds >= 1) { // if we have at least one R1 and one R2, we can discard all but the first encountered
discarded += recs.size() - 2;
recs = Arrays.asList(firstRecord, secondRecord);
} else {
log.debug("Discarding ", recs.size(), " reads with name ", recs.get(0).getReadName(), " because we found ", firsts, " R1s ", seconds, " R2s and ", unpaired, " unpaired reads.");
discarded += recs.size();
continue readNameLoop;
}
}
}
else if (unpaired > 1) { // only unpaired reads, and we have too many
if (KEEP_FIRST_DUPLICATE) {
discarded += recs.size() - 1;
recs = Collections.singletonList(unpairedRecord);
}
else {
log.debug("Discarding ", recs.size(), " reads with name ", recs.get(0).getReadName(), " because we found ", unpaired, " unpaired reads.");
discarded += recs.size();
continue readNameLoop;
}
}
// If we've made it this far spit the records into the output!
for (final SAMRecord rec : recs) {
// The only valid quality score encoding scheme is standard; if it's not standard, change it.
final FastqQualityFormat recordFormat = readGroupToFormat.get(rec.getReadGroup());
if (recordFormat != null && !recordFormat.equals(FastqQualityFormat.Standard)) {
final byte[] quals = rec.getBaseQualities();
for (int i = 0; i < quals.length; i++) {
quals[i] -= SolexaQualityConverter.ILLUMINA_TO_PHRED_SUBTRAHEND;
}
rec.setBaseQualities(quals);
}
out.addAlignment(rec);
sanitizerProgress.record(rec);
}
}
}
return new long[]{discarded, total};
}
/**
* Generates a list by consuming from the iterator in order starting with the first available
* read and continuing while subsequent reads share the same read name. If there are no reads
* remaining returns an empty list.
*/
private List<SAMRecord> fetchByReadName(final PeekableIterator<SAMRecord> iterator) {
final List<SAMRecord> out = new ArrayList<>();
if (iterator.hasNext()) {
final SAMRecord first = iterator.next();
out.add(first);
while (iterator.hasNext() && iterator.peek().getReadName().equals(first.getReadName())) {
out.add(iterator.next());
}
}
return out;
}
private void overwriteSample(final List<SAMReadGroupRecord> readGroups, final String sampleAlias) {
readGroups.forEach(rg -> rg.setSample(sampleAlias));
}
private void overwriteLibrary(final List<SAMReadGroupRecord> readGroups, final String libraryName) {
readGroups.forEach(rg -> rg.setLibrary(libraryName));
}
static Map<String, File> createOutputMap(
final File outputMapFile,
final File outputDir,
final String defaultExtension,
final List<SAMReadGroupRecord> readGroups) {
final Map<String, File> outputMap;
if (outputMapFile != null) {
outputMap = createOutputMapFromFile(outputMapFile);
} else {
outputMap = createOutputMap(readGroups, outputDir, defaultExtension);
}
return outputMap;
}
private static Map<String, File> createOutputMapFromFile(final File outputMapFile) {
final Map<String, File> outputMap = new HashMap<>();
final TabbedTextFileWithHeaderParser parser = new TabbedTextFileWithHeaderParser(outputMapFile);
for (final TabbedTextFileWithHeaderParser.Row row : parser) {
final String id = row.getField("READ_GROUP_ID");
final String output = row.getField("OUTPUT");
final File outputPath = new File(output);
outputMap.put(id, outputPath);
}
CloserUtil.close(parser);
return outputMap;
}
private static Map<String, File> createOutputMap(final List<SAMReadGroupRecord> readGroups, final File outputDir, final String extension) {
final Map<String, File> outputMap = new HashMap<>();
for (final SAMReadGroupRecord readGroup : readGroups) {
final String id = readGroup.getId();
final String fileName = id + extension;
final Path outputPath = Paths.get(outputDir.toString(), fileName);
outputMap.put(id, outputPath.toFile());
}
return outputMap;
}
private Map<String, SAMFileHeader> createHeaderMap(
final SAMFileHeader inHeader,
final SortOrder sortOrder,
final boolean removeAlignmentInformation) {
final Map<String, SAMFileHeader> headerMap = new HashMap<>();
for (final SAMReadGroupRecord readGroup : inHeader.getReadGroups()) {
final SAMFileHeader header = createOutHeader(inHeader, sortOrder, removeAlignmentInformation);
header.addReadGroup(readGroup);
headerMap.put(readGroup.getId(), header);
}
return headerMap;
}
private SAMFileHeader createOutHeader(
final SAMFileHeader inHeader,
final SAMFileHeader.SortOrder sortOrder,
final boolean removeAlignmentInformation) {
final SAMFileHeader outHeader = new SAMFileHeader();
outHeader.setSortOrder(sortOrder);
if (!removeAlignmentInformation) {
outHeader.setSequenceDictionary(inHeader.getSequenceDictionary());
outHeader.setProgramRecords(inHeader.getProgramRecords());
}
return outHeader;
}
private Map<SAMReadGroupRecord, FastqQualityFormat> createReadGroupFormatMap(
final SAMFileHeader inHeader,
final File referenceSequence,
final ValidationStringency validationStringency,
final File input,
final boolean restoreOriginalQualities) {
final Map<SAMReadGroupRecord, FastqQualityFormat> readGroupToFormat = new HashMap<>();
final SamReaderFactory readerFactory =
SamReaderFactory.makeDefault().referenceSequence(referenceSequence).validationStringency(validationStringency);
// Figure out the quality score encoding scheme for each read group.
for (final SAMReadGroupRecord rg : inHeader.getReadGroups()) {
final SamRecordFilter filter = new SamRecordFilter() {
public boolean filterOut(final SAMRecord rec) {
return !rec.getReadGroup().getId().equals(rg.getId());
}
public boolean filterOut(final SAMRecord first, final SAMRecord second) {
throw new UnsupportedOperationException();
}
};
try (final SamReader reader = readerFactory.open(input)) {
final FilteringSamIterator filterIterator = new FilteringSamIterator(reader.iterator(), filter);
if (filterIterator.hasNext()) {
readGroupToFormat.put(rg, QualityEncodingDetector.detect(
QualityEncodingDetector.DEFAULT_MAX_RECORDS_TO_ITERATE, filterIterator, restoreOriginalQualities));
} else {
log.warn("Skipping read group " + rg.getReadGroupId() + " with no reads");
}
} catch (IOException e) {
throw new RuntimeIOException(e);
}
}
for (final SAMReadGroupRecord r : readGroupToFormat.keySet()) {
log.info("Detected quality format for " + r.getReadGroupId() + ": " + readGroupToFormat.get(r));
}
if (readGroupToFormat.values().contains(FastqQualityFormat.Solexa)) {
throw new PicardException("No quality score encoding conversion implemented for " + FastqQualityFormat.Solexa);
}
return readGroupToFormat;
}
/**
* Contains a map of writers used when OUTPUT_BY_READGROUP=true
* and a single writer used when OUTPUT_BY_READGROUP=false.
*/
private static class RevertSamWriter {
private final Map<String, SAMFileWriter> writerMap = new HashMap<>();
private final SAMFileWriter singleWriter;
private final boolean outputByReadGroup;
RevertSamWriter(
final boolean outputByReadGroup,
final Map<String, SAMFileHeader> headerMap,
final Map<String, File> outputMap,
final SAMFileHeader singleOutHeader,
final File singleOutput,
final boolean presorted,
final SAMFileWriterFactory factory,
final File referenceFasta) {
this.outputByReadGroup = outputByReadGroup;
if (outputByReadGroup) {
singleWriter = null;
for (final Map.Entry<String, File> outputMapEntry : outputMap.entrySet()) {
final String readGroupId = outputMapEntry.getKey();
final File output = outputMapEntry.getValue();
final SAMFileHeader header = headerMap.get(readGroupId);
final SAMFileWriter writer = factory.makeWriter(header, presorted, output, referenceFasta);
writerMap.put(readGroupId, writer);
}
} else {
singleWriter = factory.makeWriter(singleOutHeader, presorted, singleOutput, referenceFasta);
}
}
void addAlignment(final SAMRecord rec) {
final SAMFileWriter writer;
if (outputByReadGroup) {
writer = writerMap.get(rec.getReadGroup().getId());
} else {
writer = singleWriter;
}
writer.addAlignment(rec);
}
void close() {
if (outputByReadGroup) {
writerMap.values().forEach(SAMFileWriter::close);
} else {
singleWriter.close();
}
}
}
/**
* Contains a map of sorters used when OUTPUT_BY_READGROUP=true
* and a single sorter used when OUTPUT_BY_READGROUP=false.
*/
private static class RevertSamSorter {
private final Map<String, SortingCollection<SAMRecord>> sorterMap = new HashMap<>();
private final SortingCollection<SAMRecord> singleSorter;
private final boolean outputByReadGroup;
RevertSamSorter(
final boolean outputByReadGroup,
final Map<String, SAMFileHeader> headerMap,
final SAMFileHeader singleOutHeader,
final int maxRecordsInRam) {
this.outputByReadGroup = outputByReadGroup;
if (outputByReadGroup) {
for (final Map.Entry<String, SAMFileHeader> entry : headerMap.entrySet()) {
final String readGroupId = entry.getKey();
final SAMFileHeader outHeader = entry.getValue();
final SortingCollection<SAMRecord> sorter = SortingCollection.newInstance(SAMRecord.class, new BAMRecordCodec(outHeader), new SAMRecordQueryNameComparator(), maxRecordsInRam);
sorterMap.put(readGroupId, sorter);
}
singleSorter = null;
} else {
singleSorter = SortingCollection.newInstance(SAMRecord.class, new BAMRecordCodec(singleOutHeader), new SAMRecordQueryNameComparator(), maxRecordsInRam);
}
}
void add(final SAMRecord rec) {
final SortingCollection<SAMRecord> sorter;
if (outputByReadGroup) {
sorter = sorterMap.get(rec.getReadGroup().getId());
} else {
sorter = singleSorter;
}
sorter.add(rec);
}
List<PeekableIterator<SAMRecord>> iterators() {
final List<PeekableIterator<SAMRecord>> iterators = new ArrayList<>();
if (outputByReadGroup) {
for (final SortingCollection<SAMRecord> sorter : sorterMap.values()) {
final PeekableIterator<SAMRecord> iterator = new PeekableIterator<>(sorter.iterator());
iterators.add(iterator);
}
} else {
final PeekableIterator<SAMRecord> iterator = new PeekableIterator<>(singleSorter.iterator());
iterators.add(iterator);
}
return iterators;
}
}
/**
* Methods used for validating parameters to RevertSam.
*/
static class ValidationUtil {
static void validateSanitizeSortOrder(final boolean sanitize, final SAMFileHeader.SortOrder sortOrder, final List<String> errors) {
if (sanitize && sortOrder != SAMFileHeader.SortOrder.queryname) {
errors.add("SORT_ORDER must be queryname when sanitization is enabled with SANITIZE=true.");
}
}
static void validateOutputParams(final boolean outputByReadGroup, final File output, final File outputMap, final List<String> errors) {
if (outputByReadGroup) {
validateOutputParamsByReadGroup(output, outputMap, errors);
} else {
validateOutputParamsNotByReadGroup(output, outputMap, errors);
}
}
static void validateOutputParamsByReadGroup(final File output, final File outputMap, final List<String> errors) {
if (output != null) {
if (!Files.isDirectory(output.toPath())) {
errors.add("When OUTPUT_BY_READGROUP=true and OUTPUT is provided, it must be a directory: " + output);
}
return;
}
// output is null if we reached here
if (outputMap == null) {
errors.add("Must provide either OUTPUT or OUTPUT_MAP when OUTPUT_BY_READGROUP=true.");
return;
}
if (!Files.isReadable(outputMap.toPath())) {
errors.add("Cannot read OUTPUT_MAP " + outputMap);
return;
}
final TabbedTextFileWithHeaderParser parser = new TabbedTextFileWithHeaderParser(outputMap);
if (!ValidationUtil.isOutputMapHeaderValid(parser.columnLabelsList())) {
errors.add("Invalid header: " + outputMap + ". Must be a tab-separated file with READ_GROUP_ID as first column and OUTPUT as second column.");
}
}
static void validateOutputParamsNotByReadGroup(final File output, final File outputMap, final List<String> errors) {
if (outputMap != null) {
errors.add("Cannot provide OUTPUT_MAP when OUTPUT_BY_READGROUP=false. Provide OUTPUT instead.");
}
if (output == null) {
errors.add("OUTPUT is required when OUTPUT_BY_READGROUP=false");
return;
}
if (Files.isDirectory(output.toPath())) {
errors.add("OUTPUT " + output + " should not be a directory when OUTPUT_BY_READGROUP=false");
}
}
/**
* If we are going to override SAMPLE_ALIAS or LIBRARY_NAME, make sure all the read
* groups have the same values.
*/
static void validateHeaderOverrides(
final SAMFileHeader inHeader,
final String sampleAlias,
final String libraryName) {
final List<SAMReadGroupRecord> rgs = inHeader.getReadGroups();
if (sampleAlias != null || libraryName != null) {
boolean allSampleAliasesIdentical = true;
boolean allLibraryNamesIdentical = true;
for (int i = 1; i < rgs.size(); i++) {
if (!rgs.get(0).getSample().equals(rgs.get(i).getSample())) {
allSampleAliasesIdentical = false;
}
if (!rgs.get(0).getLibrary().equals(rgs.get(i).getLibrary())) {
allLibraryNamesIdentical = false;
}
}
if (sampleAlias != null && !allSampleAliasesIdentical) {
throw new PicardException("Read groups have multiple values for sample. " +
"A value for SAMPLE_ALIAS cannot be supplied.");
}
if (libraryName != null && !allLibraryNamesIdentical) {
throw new PicardException("Read groups have multiple values for library name. " +
"A value for library name cannot be supplied.");
}
}
}
static void assertWritable(final File output, final boolean outputByReadGroup) {
if (outputByReadGroup) {
if (output != null) {
IOUtil.assertDirectoryIsWritable(output);
}
} else {
IOUtil.assertFileIsWritable(output);
}
}
static void assertAllReadGroupsMapped(final Map<String, File> outputMap, final List<SAMReadGroupRecord> readGroups) {
for (final SAMReadGroupRecord readGroup : readGroups) {
final String id = readGroup.getId();
final File output = outputMap.get(id);
if (output == null) {
throw new PicardException("Read group id " + id + " not found in OUTPUT_MAP " + outputMap);
}
}
}
static boolean isOutputMapHeaderValid(final List<String> columnLabels) {
return columnLabels.size() >= 2 &&
"READ_GROUP_ID".equals(columnLabels.get(0)) &&
"OUTPUT".equals(columnLabels.get(1));
}
}
} |
package pl;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import java.awt.GridBagLayout;
import javax.swing.JList;
import java.awt.GridBagConstraints;
import javax.swing.JButton;
import java.awt.Insets;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.LayoutStyle.ComponentPlacement;
import bl.Gadget;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class GadgetMasterFrame extends JFrame {
private JPanel contentPane;
//private JFrame gadgetDetailFrame;
/**
* Create the frame.
*/
public GadgetMasterFrame() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
JButton btnNewButton = new JButton("Gadget editieren");
JButton btnNewButton_1 = new JButton("Gadget erfassen");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//GadgetDetailFrame window = new GadgetDetailFrame(new Gadget(""));
}
});
JPanel panel = new JPanel();
GroupLayout gl_contentPane = new GroupLayout(contentPane);
gl_contentPane.setHorizontalGroup(
gl_contentPane.createParallelGroup(Alignment.TRAILING)
.addGroup(gl_contentPane.createSequentialGroup()
.addContainerGap()
.addGroup(gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(Alignment.TRAILING, gl_contentPane.createSequentialGroup()
.addComponent(btnNewButton_1)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(btnNewButton))
.addComponent(panel, GroupLayout.DEFAULT_SIZE, 428, Short.MAX_VALUE))
.addContainerGap())
);
gl_contentPane.setVerticalGroup(
gl_contentPane.createParallelGroup(Alignment.LEADING)
.addGroup(gl_contentPane.createSequentialGroup()
.addContainerGap()
.addGroup(gl_contentPane.createParallelGroup(Alignment.BASELINE)
.addComponent(btnNewButton)
.addComponent(btnNewButton_1))
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(panel, GroupLayout.DEFAULT_SIZE, 221, Short.MAX_VALUE)
.addContainerGap())
);
panel.setLayout(new BorderLayout(0, 0));
JList list = new JList();
panel.add(list, BorderLayout.CENTER);
contentPane.setLayout(gl_contentPane);
}
} |
package sssj.index;
import static sssj.base.Commons.forgettingFactor;
import it.unimi.dsi.fastutil.BidirectionalIterator;
import it.unimi.dsi.fastutil.doubles.DoubleArrayList;
import it.unimi.dsi.fastutil.ints.Int2DoubleMap.Entry;
import it.unimi.dsi.fastutil.ints.Int2ReferenceMap;
import it.unimi.dsi.fastutil.ints.Int2ReferenceOpenHashMap;
import it.unimi.dsi.fastutil.longs.Long2DoubleMap;
import it.unimi.dsi.fastutil.longs.Long2DoubleOpenHashMap;
import it.unimi.dsi.fastutil.longs.LongArrayList;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.math3.util.FastMath;
import sssj.base.ResidualList;
import sssj.base.Vector;
public class L2APIndex implements Index {
private final Int2ReferenceMap<L2APPostingList> idx = new Int2ReferenceOpenHashMap<>();
private final ResidualList resList = new ResidualList();
private final Long2DoubleOpenHashMap ps = new Long2DoubleOpenHashMap();
private final double theta;
private final double lambda;
private final Vector maxVectorInWindow;
private final Vector maxVectorInIndex; // \hat{c_w}
private int size = 0;
public L2APIndex(double theta, double lambda, Vector maxVector) {
this.theta = theta;
this.lambda = lambda;
this.maxVectorInWindow = maxVector;
this.maxVectorInIndex = new Vector();
}
@Override
public Map<Long, Double> queryWith(final Vector v, final boolean addToIndex) {
/* candidate generation */
Long2DoubleOpenHashMap accumulator = generateCandidates(v);
/* candidate verification */
Long2DoubleOpenHashMap matches = verifyCandidates(v, accumulator);
/* index building */
if (addToIndex) {
Vector residual = addToIndex(v);
resList.add(residual);
}
return matches;
}
private final Long2DoubleOpenHashMap generateCandidates(final Vector v) {
// int minSize = theta / rw_x; //TODO possibly size filtering (need to sort dataset by max row weight rw_x)
final Long2DoubleOpenHashMap accumulator = new Long2DoubleOpenHashMap();
double remscore = Vector.similarity(v, maxVectorInIndex); // rs3, enhanced remscore bound
double l2remscore = 1, // rs4
rst = 1, squaredQueryPrefixMagnitude = 1;
for (BidirectionalIterator<Entry> it = v.int2DoubleEntrySet().fastIterator(v.int2DoubleEntrySet().last()); it
.hasPrevious();) { // iterate over v in reverse order
final Entry e = it.previous();
final int dimension = e.getIntKey();
final double queryWeight = e.getDoubleValue();
final double rscore = Math.min(remscore, l2remscore);
squaredQueryPrefixMagnitude -= queryWeight * queryWeight;
L2APPostingList list;
if ((list = idx.get(dimension)) != null) {
// TODO possibly size filtering: remove entries from the posting list with |y| < minsize (need to save size in the posting list)
for (L2APPostingEntry pe : list) {
final long targetID = pe.getID();
if (accumulator.containsKey(targetID) || Double.compare(rscore, theta) >= 0) {
final double targetWeight = pe.getWeight();
final double additionalSimilarity = queryWeight * targetWeight; // x_j * y_j
accumulator.addTo(targetID, additionalSimilarity); // A[y] += x_j * y_j
final double l2bound = accumulator.get(targetID) + FastMath.sqrt(squaredQueryPrefixMagnitude)
* pe.magnitude; // A[y] + ||x'_j|| * ||y'_j||
if (Double.compare(l2bound, theta) < 0)
accumulator.remove(targetID); // prune this candidate (early verification)
}
}
remscore -= queryWeight * maxVectorInIndex.get(dimension); // rs_3 -= x_j * \hat{c_w}
rst -= queryWeight * queryWeight; // rs_t -= x_j^2
l2remscore = FastMath.sqrt(rst); // rs_4 = sqrt(rs_t)
}
}
return accumulator;
}
private final Long2DoubleOpenHashMap verifyCandidates(final Vector v, Long2DoubleOpenHashMap accumulator) {
Long2DoubleOpenHashMap matches = new Long2DoubleOpenHashMap();
for (Long2DoubleMap.Entry e : accumulator.long2DoubleEntrySet()) {
// TODO possibly use size filtering (sz_3)
final long candidateID = e.getLongKey();
if (Double.compare(e.getDoubleValue() + ps.get(candidateID), theta) < 0) // A[y] = dot(x, y'')
continue; // l2 pruning
Vector residual = resList.get(candidateID);
assert (residual != null);
final double dpscore = e.getDoubleValue() + Math.min(v.maxValue() * residual.size(), residual.maxValue() * v.size());
if (Double.compare(dpscore, theta) < 0)
continue; // dpscore, eq. (5)
final long deltaT = v.timestamp() - candidateID;
double score = e.getDoubleValue() + Vector.similarity(v, residual); // dot(x, y) = A[y] + dot(x, y')
score *= forgettingFactor(lambda, deltaT); // apply forgetting factor
if (Double.compare(score, theta) >= 0) // final check
matches.put(candidateID, score);
}
return matches;
}
private final Vector addToIndex(final Vector v) {
double b1 = 0, bt = 0, b3 = 0, pscore = 0;
boolean psSaved = false;
Vector residual = new Vector(v.timestamp());
for (Entry e : v.int2DoubleEntrySet()) {
int dimension = e.getIntKey();
double weight = e.getDoubleValue();
pscore = Math.min(b1, b3);
b1 += weight * maxVectorInWindow.get(dimension);
bt += weight * weight;
b3 = FastMath.sqrt(bt);
if (Double.compare(Math.min(b1, b3), theta) >= 0) {
if (!psSaved) {
assert (!ps.containsKey(v.timestamp()));
ps.put(v.timestamp(), pscore);
psSaved = true;
}
L2APPostingList list;
if ((list = idx.get(dimension)) == null) {
list = new L2APPostingList();
idx.put(dimension, list);
}
list.add(v.timestamp(), weight, b3);
size++;
} else {
residual.put(dimension, weight);
}
}
maxVectorInIndex.updateMaxByDimension(v);
return residual;
}
@Override
public int size() {
return size;
}
@Override
public String toString() {
return "L2APIndex [idx=" + idx + ", resList=" + resList + ", ps=" + ps + "]";
}
public static class L2APPostingList implements Iterable<L2APPostingEntry> {
private final LongArrayList ids = new LongArrayList();
private final DoubleArrayList weights = new DoubleArrayList();
private final DoubleArrayList magnitudes = new DoubleArrayList();
public void add(long vectorID, double weight, double magnitude) {
ids.add(vectorID);
weights.add(weight);
magnitudes.add(magnitude);
}
@Override
public String toString() {
return "[ids=" + ids + ", weights=" + weights + ", magnitudes=" + magnitudes + "]";
}
@Override
public Iterator<L2APPostingEntry> iterator() {
return new Iterator<L2APPostingEntry>() {
private final L2APPostingEntry entry = new L2APPostingEntry();
private int i = 0;
@Override
public boolean hasNext() {
return i < ids.size();
}
@Override
public L2APPostingEntry next() {
entry.setID(ids.getLong(i));
entry.setWeight(weights.getDouble(i));
entry.setMagnitude(magnitudes.getDouble(i));
i++;
return entry;
}
@Override
public void remove() {
i
ids.removeLong(i);
weights.removeDouble(i);
magnitudes.removeDouble(i);
}
};
}
}
public static class L2APPostingEntry {
protected long id;
protected double weight;
protected double magnitude;
public L2APPostingEntry() {
this(0, 0, 0);
}
public L2APPostingEntry(long id, double weight, double magnitude) {
this.id = id;
this.weight = weight;
this.magnitude = magnitude;
}
public void setID(long id) {
this.id = id;
}
public void setWeight(double weight) {
this.weight = weight;
}
public void setMagnitude(double magnitude) {
this.magnitude = magnitude;
}
public long getID() {
return id;
}
public double getWeight() {
return weight;
}
public double getMagnitude() {
return magnitude;
}
@Override
public String toString() {
return "[" + id + " -> " + weight + " (" + magnitude + ")]";
}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.